Example usage for java.util.jar JarFile JarFile

List of usage examples for java.util.jar JarFile JarFile

Introduction

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

Prototype

public JarFile(File file) throws IOException 

Source Link

Document

Creates a new JarFile to read from the specified File object.

Usage

From source file:org.dspace.installer_edm.InstallerCrosswalk.java

/**
 * Se comprueba que exista el archivo XXXCrosswalk.java y se pueda modificar
 * Se comprueba que exista el archivo de la api de oai de dspace y se pueda leer y se copia al directorio de trabajo del instalador
 *
 * Se abre el jar de la api de oai de dsapce y se comprueba si ya existe el archivo de la clase XXXCrosswalk.class y se pregunta si se sustituye.
 * Se configura, se escribe el java, se compila y se introduce en el jar de la api de oai de dspace.
 *
 * Se modifica oai.properties para aadir el crosswalk
 *//* w w w . jav a  2  s. c o  m*/
public void configure() {
    try {
        // comprueba que exista el archivo EDMCrosswalk.java y se pueda modificar. Comprueba que exista el archivo de la api de oai de dspace y se pueda leer
        if (checkEdmCrowssWalk() && checkOaiApiJar()) {
            edmCrossWalkName = edmCrossWalkFile.getName();
            edmCrossWalkClass = "org/dspace/app/oai/" + edmCrossWalkName.replaceFirst("\\.java", ".class");

            // copia al directorio de trabajo del instalador
            oaiApiJarWorkFile = new File(myInstallerWorkDirPath + fileSeparator + oaiApiJarFile.getName());
            copyDspaceFile2Work(oaiApiJarFile, oaiApiJarWorkFile, "configure.edmcrosswalk.oaiapijar");
            oaiApiJarName = oaiApiJarWorkFile.getAbsolutePath();

            // abre el jar de la api de oai de dsapce
            oaiApiJarJarFile = new JarFile(oaiApiJarWorkFile);
            // comprueba si ya existe el archivo de la clase EDMCrosswalk.class
            ZipEntry edmOaiApiEdmCrossWalkZipentry = oaiApiJarJarFile.getEntry(edmCrossWalkClass);
            if (edmOaiApiEdmCrossWalkZipentry != null) {
                // se pregunta si se sustituye
                String response = null;
                do {
                    installerEDMDisplay.showQuestion(currentStepGlobal, "configure.exists.class",
                            new String[] { edmCrossWalkClass, oaiApiJarFile.getAbsolutePath() });
                    response = br.readLine();
                    if (response == null)
                        continue;
                    response = response.trim();
                    if (!response.isEmpty() && response.equalsIgnoreCase(answerYes)) {
                        break;
                    } else
                        return;
                } while (true);
            }
            installerEDMDisplay.showLn();
            installerEDMDisplay.showQuestion(currentStepGlobal, "configure.edmcrosswalk.conf.begin",
                    new String[] { edmCrossWalkName });
            installerEDMDisplay.showLn();
            // se lee el java y se recoge el contenido en edmCrossWalkContent
            readCrossWalk2String();
            configureCrosswalk();
            installerEDMDisplay.showQuestion(currentStepGlobal, "configure.edmcrosswalk.conf.compile");
            // compila
            if (compileEDMCrossWalk()) {
                installerEDMDisplay.showQuestion(currentStepGlobal, "configure.edmcrosswalk.conf.updatejar",
                        new String[] { oaiApiJarWorkFile.getAbsolutePath() });
                // se introduce en el jar de la api de oai de dspace
                writeNewJar();
                org.apache.commons.io.FileUtils
                        .deleteDirectory(new File(myInstallerWorkDirPath + fileSeparator + "org"));
                oaiApiJarJarFile = new JarFile(oaiApiJarWorkFile);
                edmOaiApiEdmCrossWalkZipentry = oaiApiJarJarFile.getEntry(edmCrossWalkClass);
                if (edmOaiApiEdmCrossWalkZipentry != null) {
                    // modifica oai.properties para aadir el crosswalk
                    if (confOaiCatProperties()) {
                        installerEDMDisplay.showLn();
                        installerEDMDisplay.showQuestion(currentStepGlobal, "configure.edmcrosswalk.conf.ok",
                                new String[] { oaiApiJarWorkFile.getName() });
                    } else
                        installerEDMDisplay.showQuestion(currentStepGlobal, "configure.edmcrosswalk.conf.nok");
                } else
                    installerEDMDisplay.showQuestion(currentStepGlobal, "configure.edmcrosswalk.conf.nok");
                oaiApiJarJarFile.close();
            } else
                installerEDMDisplay.showQuestion(currentStepGlobal, "configure.edmcrosswalk.conf.nok");
        }
    } catch (IOException e) {
        showException(e);
        installerEDMDisplay.showQuestion(currentStepGlobal, "configure.edmcrosswalk.conf.nok");
    }
}

From source file:com.tasktop.c2c.server.hudson.configuration.service.HudsonServiceConfiguratorTest.java

@Test
public void testUpdateZipfile() throws Exception {

    // First, set up our zipfile test.

    // Create a manifest with a random header so that we can ensure it's preserved by the configurator.
    Manifest mf = new Manifest();
    Attributes.Name mfTestHeader = Attributes.Name.IMPLEMENTATION_VENDOR;
    String mfTestValue = "someCrazyValue";
    mf.getMainAttributes().put(mfTestHeader, mfTestValue);

    // Why do you need to add this header? See http://tech.puredanger.com/2008/01/07/jar-manifest-api/ - if you
    // don't add it, your manifest will be blank.
    mf.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
    assertEquals(mfTestValue, mf.getMainAttributes().getValue(mfTestHeader));

    File testWar = File.createTempFile("HudsonServiceConfiguratorTest", ".war");
    configurator.setWarTemplateFile(testWar.getAbsolutePath());

    try {//from   w w  w  .  java 2  s  . c om
        JarOutputStream jarOutStream = new JarOutputStream(new FileOutputStream(testWar), mf);

        String specialFileName = "foo/bar.xml";
        String fileContents = "This is a file within our JAR file - it contains an <env-entry-value></env-entry-value> which should be filled by the configurator only if this is the 'special' file.";

        // Make our configurator replace this file within the JAR.
        configurator.setWebXmlFilename(specialFileName);

        // Create several random files in the zip.
        for (int i = 0; i < 10; i++) {
            JarEntry curEntry = new JarEntry("folder/file" + i);
            jarOutStream.putNextEntry(curEntry);
            IOUtils.write(fileContents, jarOutStream);
        }

        // Push in our special file now.
        JarEntry specialEntry = new JarEntry(specialFileName);
        jarOutStream.putNextEntry(specialEntry);
        IOUtils.write(fileContents, jarOutStream);

        // Close the output stream now, time to do the test.
        jarOutStream.close();

        // Configure this configurator with appropriate folders for testing.
        String expectedHomeDir = "/some/silly/random/homeDir";
        String webappsTarget = FileUtils.getTempDirectoryPath() + "/webapps/";
        File webappsTargetDir = new File(webappsTarget);
        if (webappsTargetDir.exists()) {
            FileUtils.deleteDirectory(webappsTargetDir);
        }
        String expectedDestFile = webappsTarget + "s#test#hudson.war";
        HudsonWarNamingStrategy warNamingStrategy = new HudsonWarNamingStrategy();
        warNamingStrategy.setPathPattern(webappsTarget + "s#%s#hudson.war");
        configurator.setHudsonWarNamingStrategy(warNamingStrategy);
        configurator.setTargetHudsonHomeBaseDir(expectedHomeDir);
        ProjectServiceConfiguration config = new ProjectServiceConfiguration();
        config.setProjectIdentifier("test123");

        Map<String, String> m = new HashMap<String, String>();
        m.put(ProjectServiceConfiguration.PROJECT_ID, "test");
        m.put(ProjectServiceConfiguration.PROFILE_BASE_URL, "https://qcode.cloudfoundry.com");
        config.setProperties(m);
        config.setProjectIdentifier("test");

        // Now, run it against our test setup
        configurator.configure(config);

        // Confirm that the zipfile was updates as expected.
        File configuredWar = new File(expectedDestFile);
        assertTrue(configuredWar.exists());

        try {
            JarFile configuredWarJar = new JarFile(configuredWar);
            Manifest extractedMF = configuredWarJar.getManifest();
            assertEquals(mfTestValue, extractedMF.getMainAttributes().getValue(mfTestHeader));

            // Make sure all of our entries are present, and contain the data we expected.
            JarEntry curEntry = null;
            Enumeration<JarEntry> entries = configuredWarJar.entries();
            while (entries.hasMoreElements()) {
                curEntry = entries.nextElement();

                // If this is the manifest, skip it.
                if (curEntry.getName().equals("META-INF/MANIFEST.MF")) {
                    continue;
                }

                String entryContents = IOUtils.toString(configuredWarJar.getInputStream(curEntry));

                if (curEntry.getName().equals(specialFileName)) {
                    assertFalse(fileContents.equals(entryContents));
                    assertTrue(entryContents.contains(expectedHomeDir));
                } else {
                    // Make sure our content was unchanged.
                    assertEquals(fileContents, entryContents);
                    assertFalse(entryContents.contains(expectedHomeDir));
                }
            }
        } finally {
            // Clean up our test file.
            configuredWar.delete();
        }
    } finally {
        // Clean up our test file.
        testWar.delete();
    }
}

From source file:org.apache.torque.generator.configuration.ClasspathConfigurationProvider.java

public Collection<String> getOutletConfigurationNames() throws ConfigurationException {
    String outletConfigurationSubdir = getConfigResourceBase() + "/" + configurationPaths.getOutletDirectory();
    outletConfigurationSubdir = outletConfigurationSubdir.replace('\\', '/');

    URL dirUrl = getClass().getClassLoader().getResource(outletConfigurationSubdir);
    if (dirUrl == null) {
        log.error("Could not open Directory " + outletConfigurationSubdir + " in classpath");
        throw new ConfigurationException("outletConfigurationSubdir not found");
    }//from   w  w  w . j  a v a2 s  . c  o m
    String dirUrlString = dirUrl.toExternalForm();
    if (dirUrlString.startsWith("jar")) {
        String jarFilePath = dirUrl.getFile();
        if (jarFilePath.startsWith(FILE_URL_PREFIX)) {
            jarFilePath = jarFilePath.substring(FILE_URL_PREFIX.length());
        }
        jarFilePath = jarFilePath.substring(0, jarFilePath.indexOf("!"));
        if (log.isDebugEnabled()) {
            log.debug("outlet configuration located in jar file" + jarFilePath);
        }
        JarFile jarFile;
        try {
            jarFile = new JarFile(jarFilePath);
        } catch (IOException e) {
            log.error("Could not open jar File " + jarFilePath);
            throw new ConfigurationException(e);
        }

        String outletConfigurationDirectory = dirUrlString.substring(dirUrlString.lastIndexOf("!") + 1);
        if (outletConfigurationDirectory.startsWith("/")) {
            outletConfigurationDirectory = outletConfigurationDirectory.substring(1);
        }
        return JarConfigurationProvider.getOutletConfigurationNames(jarFile, outletConfigurationDirectory);
    }
    File directory = new File(dirUrl.getFile());
    if (!directory.exists()) {
        throw new ConfigurationException("Could not read outlet directory " + outletConfigurationSubdir
                + " in classpath; directory URL is " + dirUrl + " file is " + dirUrl.getFile());
    }
    String[] filenames = directory.list();

    List<String> result = new ArrayList<String>();
    for (String filename : filenames) {
        File file = new File(filename);
        if (file.isDirectory()) {
            continue;
        }
        String rawName = file.getName();
        if (!rawName.endsWith(".xml")) {
            continue;
        }
        result.add(filename);
    }
    return result;
}

From source file:ie.deri.unlp.javaservices.topicextraction.topicextractor.gate.TopicExtractorGate.java

/**
 * // w  w  w .j  a  va 2s  . c  om
 * Extract a directory in a JAR on the classpath to an output folder.
 * 
 * Note: User's responsibility to ensure that the files are actually in a JAR.
 * 
 * @param classInJar A class in the JAR file which is on the classpath
 * @param resourceDirectory Path to resource directory in JAR
 * @param outputDirectory Directory to write to  
 * @return String containing the path to the outputDirectory
 * @throws IOException
 */
private static String extractDirectoryFromClasspathJAR(Class<?> classInJar, String resourceDirectory,
        String outputDirectory) throws IOException {

    resourceDirectory = StringUtils.strip(resourceDirectory, "\\/") + File.separator;

    URL jar = classInJar.getProtectionDomain().getCodeSource().getLocation();
    JarFile jarFile = new JarFile(new File(jar.getFile()));

    byte[] buf = new byte[1024];
    Enumeration<JarEntry> jarEntries = jarFile.entries();
    while (jarEntries.hasMoreElements()) {
        JarEntry jarEntry = jarEntries.nextElement();
        if (jarEntry.isDirectory() || !jarEntry.getName().startsWith(resourceDirectory)) {
            continue;
        }

        String outputFileName = FilenameUtils.concat(outputDirectory, jarEntry.getName());
        //Create directories if they don't exist
        new File(FilenameUtils.getFullPath(outputFileName)).mkdirs();

        //Write file
        FileOutputStream fileOutputStream = new FileOutputStream(outputFileName);
        int n;
        InputStream is = jarFile.getInputStream(jarEntry);
        while ((n = is.read(buf, 0, 1024)) > -1) {
            fileOutputStream.write(buf, 0, n);
        }
        is.close();
        fileOutputStream.close();
    }
    jarFile.close();

    String fullPath = FilenameUtils.concat(outputDirectory, resourceDirectory);
    return fullPath;
}

From source file:org.ebayopensource.turmeric.eclipse.resources.util.SOAIntfUtil.java

/**
 * Load metadata props.//from  ww w  .  j  a v a  2s . co m
 *
 * @param assetLocation the asset location
 * @param serviceName the service name
 * @return the properties
 * @throws Exception the exception
 */
public static Properties loadMetadataProps(String assetLocation, final String serviceName) throws Exception {
    if (SOALogger.DEBUG)
        logger.entering(assetLocation, serviceName);
    Properties props = null;
    if (assetLocation != null && serviceName != null) {
        if (assetLocation.endsWith(SOAProjectConstants.JAR_EXT)) {
            final JarFile file = new JarFile(assetLocation);
            logger.info("loading service_metadata.properties from the service jar->", assetLocation);
            props = loadMetadataProps(new JarFile[] { file }, serviceName);
        } else {
            IPath path = new Path(assetLocation);
            props = loadMetadataProps(path, serviceName);
        }
    }
    if (SOALogger.DEBUG)
        logger.exiting(props);
    return props;
}

From source file:com.liferay.ide.server.util.ServerUtil.java

public static Properties getAllCategories(IPath portalDir) {
    Properties retval = null;//from  www.j  av a2  s  .  co m

    File implJar = portalDir.append("WEB-INF/lib/portal-impl.jar").toFile(); //$NON-NLS-1$

    if (implJar.exists()) {
        try {
            JarFile jar = new JarFile(implJar);
            Properties categories = new Properties();
            Properties props = new Properties();
            props.load(jar.getInputStream(jar.getEntry("content/Language.properties"))); //$NON-NLS-1$
            Enumeration<?> names = props.propertyNames();

            while (names.hasMoreElements()) {
                String name = names.nextElement().toString();

                if (name.startsWith("category.")) //$NON-NLS-1$
                {
                    categories.put(name, props.getProperty(name));
                }
            }

            retval = categories;
            jar.close();
        } catch (IOException e) {
            LiferayServerCore.logError(e);
        }
    }

    return retval;
}

From source file:net.adamcin.granite.client.packman.validation.PackageValidatorTest.java

private void expectReasonForCheckExtensions(File file, List<String> forbiddenExtensions,
        ValidationResult.Reason reason) throws IOException {
    ValidationResult result = PackageValidator.checkForbiddenExtensions(new JarFile(file), forbiddenExtensions);
    assertEquals(String.format("expect reason for forbidden extensions {} in file {}",
            forbiddenExtensions != null ? forbiddenExtensions : "", file), reason, result.getReason());
}

From source file:com.kaylerrenslow.armaDialogCreator.updater.tasks.AdcVersionCheckTask.java

private String getCurrentJarVersion() throws Exception {
    setStatusText("Updater.getting_current_version");
    if (!adcJarSave.exists()) {
        return "";
    }/*ww w. j a  va 2 s  . c  o m*/
    Manifest m = new JarFile(adcJarSave).getManifest();
    Attributes manifestAttributes = m.getMainAttributes();
    return manifestAttributes.getValue("Specification-Version");
}

From source file:io.joynr.util.JoynrUtil.java

public static void copyDirectoryFromJar(String jarName, String srcDir, File tmpDir) throws IOException {

    JarFile jf = null;/* w ww.  jav  a 2 s.  c om*/
    JarInputStream jarInputStream = null;

    try {
        jf = new JarFile(jarName);
        JarEntry je = jf.getJarEntry(srcDir);
        if (je.isDirectory()) {
            FileInputStream fis = new FileInputStream(jarName);
            BufferedInputStream bis = new BufferedInputStream(fis);
            jarInputStream = new JarInputStream(bis);
            JarEntry ze = null;
            while ((ze = jarInputStream.getNextJarEntry()) != null) {
                if (ze.isDirectory()) {
                    continue;
                }
                if (ze.getName().contains(je.getName())) {
                    InputStream is = jf.getInputStream(ze);
                    String name = ze.getName().substring(ze.getName().lastIndexOf("/") + 1);
                    File tmpFile = new File(tmpDir + "/" + name); //File.createTempFile(file.getName(), "tmp");
                    tmpFile.deleteOnExit();
                    OutputStream outputStreamRuntime = new FileOutputStream(tmpFile);
                    copyStream(is, outputStreamRuntime);
                }
            }
        }
    } finally {
        if (jf != null) {
            jf.close();
        }
        if (jarInputStream != null) {
            jarInputStream.close();
        }
    }
}

From source file:com.tobedevoured.solrsail.SolrConfig.java

/**
 * Install Solr Config t the local file system by extracting from the
 * SolrSail jar/*  ww  w  .j  ava  2  s  . com*/
 * 
 * @param jar File
 * @throws IOException
 */
public void installFromJar(File jar) throws IOException {
    logger.info("Installing config from Jar to {}", this.getSolrHome());
    logger.debug("Opening Jar {}", jar.toString());

    JarFile jarFile = new JarFile(jar);

    for (Enumeration<JarEntry> enumeration = jarFile.entries(); enumeration.hasMoreElements();) {
        JarEntry entry = enumeration.nextElement();

        if (!entry.getName().equals("solr/") && entry.getName().startsWith("solr/")) {
            StringBuilder dest = new StringBuilder(getSolrHome()).append(File.separator)
                    .append(entry.getName().replaceFirst("solr/", ""));

            File file = new File(dest.toString());

            if (entry.isDirectory()) {
                file.mkdirs();
            } else {
                if (file.getParentFile() != null) {
                    file.getParentFile().mkdirs();
                }

                logger.debug("Copying {} to {}", entry.getName(), dest.toString());

                InputStream input = jarFile.getInputStream(entry);
                Writer writer = new FileWriter(file.getAbsoluteFile());
                IOUtils.copy(input, writer);

                input.close();

                writer.close();
            }
        }
    }
}