Locate and process license agreement and information files within a jar

@param esa
@param resource
@throws IOException
353866
protected void processLAandLI(File archive, RepositoryResourceWritable resource,
                                  Manifest manifest) throws RepositoryException, IOException {
        Attributes attribs = manifest.getMainAttributes();
        String LAHeader = attribs.getValue(LA_HEADER_PRODUCT);
        String LIHeader = attribs.getValue(LI_HEADER_PRODUCT);
        processLAandLI(archive, resource, LAHeader, LIHeader);
    }
280799
@Override
    public void execute()
            throws MojoExecutionException
    {

        boolean withExtensions = CollectionUtils.isNotEmpty( jnlpExtensions );

        if ( withExtensions )
        {
            prepareExtensions();
            findDefaultJnlpExtensionTemplateURL();
        }

        checkInput();

        getLog().debug( "using work directory " + getWorkDirectory() );
        getLog().debug( "using library directory " + getLibDirectory() );

        IOUtil ioUtil = getIoUtil();

        // ---
        // prepare layout
        // ---

        ioUtil.makeDirectoryIfNecessary( getWorkDirectory() );
        ioUtil.makeDirectoryIfNecessary( getLibDirectory() );

        try
        {
            ioUtil.copyResources( getResourcesDirectory(), getWorkDirectory() );

            artifactWithMainClass = null;

            processDependencies();

            if ( jnlp.isRequireMainClass() && artifactWithMainClass == null )
            {
                throw new MojoExecutionException(
                        "didn't find artifact with main class: " + jnlp.getMainClass() + ". Did you specify it? " );
            }

            if ( withExtensions )
            {
                processExtensionsDependencies();
            }

            // ---
            // Process native libs (FIXME)
            // ---

            processNativeLibs();

            if ( ( isPack200() || getSign() != null ) && getLog().isDebugEnabled() )
            {
                logCollection(
                        "Some dependencies may be skipped. Here's the list of the artifacts that should be signed/packed: ",
                        getModifiedJnlpArtifacts() );
            }

            // ---
            // Process collected jars
            // ---

            signOrRenameJars();

            // ---
            // Generate jnlp file
            // ---

            generateJnlpFile( getWorkDirectory() );

            // ---
            // Generate jnlp extension files
            // ---

            if ( withExtensions )
            {
                generateJnlpExtensionsFile( getWorkDirectory() );
            }

            // ---
            // Generate archive file if required
            // ---

            if ( makeArchive )
            {
                // package the zip. Note this is very simple. Look at the JarMojo which does more things.
                // we should perhaps package as a war when inside a project with war packaging ?

                ioUtil.makeDirectoryIfNecessary( archive.getParentFile() );

                ioUtil.deleteFile( archive );

                verboseLog( "Will create archive at location: " + archive );

                ioUtil.createArchive( getWorkDirectory(), archive );

                if ( attachArchive )
                {
                    // maven 2 version 2.0.1 method
                    projectHelper.attachArtifact( getProject(), "zip", archive );
                }
            }
        }
        catch ( MojoExecutionException e )
        {
            throw e;
        }
        catch ( Exception e )
        {
            throw new MojoExecutionException( "Failure to run the plugin: ", e );
        }
    }
767859
public static boolean isJavaArtifact(IResource resource) {
        if (resource == null || (resource.getType() != IResource.FILE)) {
            return false;
        }
        String ex = resource.getFileExtension();
        if ("java".equalsIgnoreCase(ex) || "class".equalsIgnoreCase(ex)) {
            return true;
        }
        String name = resource.getName();
        return Archive.isArchiveFileName(name);
    }
1257573
@Override
    public T addAsLibrary(URL resource, ArchivePath target) throws IllegalArgumentException {
        Validate.notNull(resource, "Resource must be specified");
        Validate.notNull(target, "Target must be specified");

        File resourceFile = new File(resource.getFile());
        if (!resourceFile.exists()) {
            return addAsLibrary(new UrlAsset(resource), target);
        }

        if (resourceFile.isFile()) {
            return addAsLibrary(new UrlAsset(resource), target);
        }

        if (resourceFile.listFiles().length == 0) {
            return addAsLibrary(new UrlAsset(resource), target);
        }

        for (File file : resourceFile.listFiles()) {
            addAsLibrary(file, new BasicPath(target, file.getName()));
        }

        return covarientReturn();
    }
862566
public Set<InstallLicense> getFeatureLicense(String esaLocation, Locale locale) throws InstallException {
        Set<InstallLicense> licenses = new HashSet<InstallLicense>();
        ArrayList<InstallAsset> installAssets = new ArrayList<InstallAsset>();
        getResolveDirector().resolve(esaLocation, "", product.getInstalledFeatures(), installAssets, 10, 40);
        if (installAssets.isEmpty()) {
            return licenses;
        }

        Map<String, InstallLicenseImpl> licenseIds = new HashMap<String, InstallLicenseImpl>();
        for (InstallAsset installAsset : installAssets) {
            if (installAsset.isFeature()) {
                ESAAsset esa = (ESAAsset) installAsset;
                LicenseProvider lp = esa.getLicenseProvider(locale);
                String licenseId = esa.getLicenseId();
                if (licenseId != null && !licenseId.isEmpty()) {
                    InstallLicenseImpl ili = licenseIds.get(licenseId);
                    if (ili == null) {
                        ili = new InstallLicenseImpl(licenseId, null, lp);
                        licenseIds.put(licenseId, ili);
                    }
                    ili.addFeature(esa.getProvideFeature());
                }
            }
        }
        licenses.addAll(licenseIds.values());
        return licenses;
    }
1051444
@Override
    public T addAsLibrary(File resource, ArchivePath target) throws IllegalArgumentException {
        Validate.notNull(resource, "Resource must be specified");
        Validate.notNull(target, "Target must be specified");

        if (resource.isFile()) {
            return addAsLibrary(new FileAsset(resource), target);
        }

        if (resource.listFiles().length == 0) {
            return addAsLibrary(new FileAsset(resource), target);
        }

        for (File file : resource.listFiles()) {
            addAsLibrary(file, new BasicPath(target, file.getName()));
        }
        return covarientReturn();
    }
116810
private void findJarFile() throws IOException {
        if (getUseCaches()) {
            synchronized (jarCache) {
                jarFile = jarCache.get(jarFileURL);
            }
            if (jarFile == null) {
                JarFile jar = openJarFile();
                synchronized (jarCache) {
                    jarFile = jarCache.get(jarFileURL);
                    if (jarFile == null) {
                        jarCache.put(jarFileURL, jar);
                        jarFile = jar;
                    } else {
                        jar.close();
                    }
                }
            }
        } else {
            jarFile = openJarFile();
        }

        if (jarFile == null) {
            throw new IOException();
        }
    }
168318
protected void initZipOutputStream(ZipOutputStream zOut) throws IOException, BuildException 
    {
        if (manifestFiles.size() != 0)
        {
            //
            // Create a default (empty) manifest
            //
            Manifest mergeManifest = Manifest.getDefaultManifest();

            //
            // Iterate through each found manifest file, merging its contents into the
            // merge manifest
            //
            for (File manifestFile : manifestFiles)
            {
                FileInputStream fis = null;
                try
                {
                    fis = new FileInputStream(manifestFile);
                    Manifest resourceManifest = new Manifest(new InputStreamReader(fis));
                    mergeManifest.merge(resourceManifest);
                }
                catch (IOException ioe)
                {
                    throw new BuildException("Unable to read manifest file:" + manifestFile, ioe);
                }
                catch (ManifestException me)
                {
                    throw new BuildException("Unable to process manifest file: "+ manifestFile, me);
                }
                finally 
                {
                    if (fis != null) fis.close();
                }
            }

            //
            // Set the merge manifest as the 'configured' manifest.   This will treat its
            // contents as if they had been included inline with the <jar> task, with
            // similar precedence rules.
            //
            try
            {
                addConfiguredManifest(mergeManifest);
            }
            catch (ManifestException me)
            {
                throw new BuildException("Unable to add new manifest entries:" + me);
            }
        }

        super.initZipOutputStream(zOut);
    }
950518
public void setImage(Resource resource)
    {
        ImageIcon image = null;
        if (resource != null && resource.exists())
        {
            try
            {
                image = new ImageIcon(resource.getURL());
            }
            catch (IOException e)
            {
                logger.warn("Error reading resource: " + resource);
                throw new RuntimeException("Error reading resource " + resource, e);
            }
        }
        setImage(image);
    }
1242821
public static LicenseApi licenseApiFactory()
    {
        String licensePath = System.getProperty("user.dir") + "/" + licenseFileName;
        LicenseApi licenseApi = MiscUtils.licenseApiFactory(licensePath);
        if (licenseApi == null) {
            try {
                // Get location of jar file
                String jarLoc = VoltDB.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath();
                // Strip of file name
                int lastSlashOff = jarLoc.lastIndexOf("/");
                if (lastSlashOff == -1) {
                    // Jar is at root directory
                    licensePath = "/" + licenseFileName;
                }
                else {
                    licensePath = jarLoc.substring(0, lastSlashOff+1) + licenseFileName;
                }
                licenseApi = MiscUtils.licenseApiFactory(licensePath);
            }
            catch (URISyntaxException e) {
            }
        }
        if (licenseApi == null) {
            licensePath = System.getProperty("user.home") + "/" + licenseFileName;
            licenseApi = MiscUtils.licenseApiFactory(licensePath);
        }
        if (licenseApi != null) {
            hostLog.info("Searching for license file located " + licensePath);
        }
        return licenseApi;
    }
832135
public void associateTypeJndiResource(JNDIResourceModel resource, String type)
    {
        if (type == null || resource == null)
        {
            return;
        }

        if (StringUtils.equals(type, "javax.sql.DataSource") && !(resource instanceof DataSourceModel))
        {
            DataSourceModel ds = GraphService.addTypeToModel(this.getGraphContext(), resource, DataSourceModel.class);
        }
        else if (StringUtils.equals(type, "javax.jms.Queue") && !(resource instanceof JmsDestinationModel))
        {
            JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);
            jms.setDestinationType(JmsDestinationType.QUEUE);
        }
        else if (StringUtils.equals(type, "javax.jms.QueueConnectionFactory") && !(resource instanceof JmsConnectionFactoryModel))
        {
            JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);
            jms.setConnectionFactoryType(JmsDestinationType.QUEUE);
        }
        else if (StringUtils.equals(type, "javax.jms.Topic") && !(resource instanceof JmsDestinationModel))
        {
            JmsDestinationModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsDestinationModel.class);
            jms.setDestinationType(JmsDestinationType.TOPIC);
        }
        else if (StringUtils.equals(type, "javax.jms.TopicConnectionFactory") && !(resource instanceof JmsConnectionFactoryModel))
        {
            JmsConnectionFactoryModel jms = GraphService.addTypeToModel(this.getGraphContext(), resource, JmsConnectionFactoryModel.class);
            jms.setConnectionFactoryType(JmsDestinationType.TOPIC);
        }
    }
670453
public void extractResources() throws IOException {
        if (!cacheDir.isDirectory()) {
            if (!cacheDir.mkdirs()) {
                //debug("Failed to create cachedJar dir for dependent resources: " + cachedir);
            }
        }
        if (null != resourcesList) {
            //debug("jar manifest lists resources: " + resourcesList + " for file: " + pluginJar);

            extractJarContents(resourcesList, cacheDir);
            for (final String s : resourcesList) {
                File libFile = new File(cacheDir, s);
                libFile.deleteOnExit();
            }
        } else {
            //debug("using resources dir: " + resDir + " for file: " + pluginJar);
            ZipUtil.extractZip(zipFile.getAbsolutePath(), cacheDir, resourcesBasedir, resourcesBasedir);
        }
    }
183355
public static EsaSubsystemFeatureDefinitionImpl constructInstance(File esa) throws ZipException, IOException {
        // Find the manifest - case isn't guaranteed so do a search
        ZipFile zip = new ZipFile(esa);
        Enumeration<? extends ZipEntry> zipEntries = zip.entries();
        ZipEntry subsystemEntry = null;
        while (zipEntries.hasMoreElements()) {
            ZipEntry nextEntry = zipEntries.nextElement();
            if ("OSGI-INF/SUBSYSTEM.MF".equalsIgnoreCase(nextEntry.getName())) {
                subsystemEntry = nextEntry;
            }
        }
        return new EsaSubsystemFeatureDefinitionImpl(zip.getInputStream(subsystemEntry), zip);
    }
909054
public static InputStream getResourceAsStream(String resource) throws IOException {
    InputStream in = null;
    ClassLoader loader = ResourcesUtils.class.getClassLoader();
    if (loader != null) {
      in = loader.getResourceAsStream(resource);
    }
    if (in == null) {
      in = ClassLoader.getSystemResourceAsStream(resource);
    }
    if (in == null) {
      throw new IOException("Could not find resource " + resource);
    }
    return in;
  }
393970
@Override
    protected AssetInformation extractInformationFromAsset(final File archive, ArtifactMetadata metadata) throws PrivilegedActionException, ProductInfoParseException, IOException {
        AssetInformation assetInformation = new AssetInformation();
        JarFile jarFile = null;
        try {
            jarFile = AccessController.doPrivileged(new PrivilegedExceptionAction<JarFile>() {

                @Override
                public JarFile run() throws IOException {
                    return new JarFile(archive);
                }

            });
            Manifest manifest = jarFile.getManifest();
            Attributes mainAttributes = manifest.getMainAttributes();
            String archiveRoot = mainAttributes.getValue("Archive-Root");
            archiveRoot = archiveRoot != null ? archiveRoot : "";
            assetInformation.addProductInfos(jarFile, archiveRoot, archive);

            // See what type of archive this is
            String contentType = mainAttributes.getValue("Archive-Content-Type");
            ResourceType type = getType(contentType, archive);
            assetInformation.type = type;
            assetInformation.provideFeature = mainAttributes.getValue("Provide-Feature");

            if (type.equals(ResourceType.ADDON)) {
                // Only needed for addon, not product
                assetInformation.requireFeature = mainAttributes.getValue("Require-Feature");
                assetInformation.appliesTo = mainAttributes.getValue("Applies-To");
            }
            assetInformation.laLocation = mainAttributes.getValue(LA_HEADER_PRODUCT);
            assetInformation.liLocation = mainAttributes.getValue(LI_HEADER_PRODUCT);
            assetInformation.fileWithLicensesIn = archive;
        } finally {
            if (jarFile != null) {
                jarFile.close();
            }
        }
        return assetInformation;
    }
171420
private void addPackage(Resource resource) throws DroolsParserException, IOException {
        if (pmmlCompiler != null) {
            if (pmmlCompiler.getResults().isEmpty()) {
                addPMMLPojos(pmmlCompiler, resource);
                if (pmmlCompiler.getResults().isEmpty()) {
                    List<PackageDescr> packages = getPackageDescrs(resource);
                    if (packages != null && !packages.isEmpty()) {
                        for (PackageDescr descr : packages) {
                            this.kbuilder.addPackage(descr);
                        }
                    }
                }
            }
        }
    }
638495
public static boolean isFile(Resource resource) {
        Node node = resource.adaptTo(Node.class);
        if (node != null) {
            try {
                NodeType type = node.getPrimaryNodeType();
                if (type != null) {
                    String typeName = type.getName();
                    switch (typeName) {
                        case TYPE_FILE:
                            return true;
                        case TYPE_RESOURCE:
                        case TYPE_UNSTRUCTURED:
                            try {
                                Property mimeType = node.getProperty(PROP_MIME_TYPE);
                                if (mimeType != null && StringUtils.isNotBlank(mimeType.getString())) {
                                    node.getProperty(ResourceUtil.PROP_DATA);
                                    // PathNotFountException if not present
                                    return true;
                                }
                            } catch (PathNotFoundException pnfex) {
                                // ok, was a check only
                            }
                            break;
                    }
                }
            } catch (RepositoryException e) {
                LOG.error(e.getMessage(), e);
            }
        }
        return false;
    }