brooklyn-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From neykov <...@git.apache.org>
Subject [GitHub] brooklyn-server pull request #485: `BundleMaker` utility routines making it ...
Date Fri, 16 Dec 2016 17:15:29 GMT
Github user neykov commented on a diff in the pull request:

    https://github.com/apache/brooklyn-server/pull/485#discussion_r92849732
  
    --- Diff: core/src/main/java/org/apache/brooklyn/util/core/osgi/BundleMaker.java ---
    @@ -0,0 +1,340 @@
    +/*
    + * Licensed to the Apache Software Foundation (ASF) under one
    + * or more contributor license agreements.  See the NOTICE file
    + * distributed with this work for additional information
    + * regarding copyright ownership.  The ASF licenses this file
    + * to you under the Apache License, Version 2.0 (the
    + * "License"); you may not use this file except in compliance
    + * with the License.  You may obtain a copy of the License at
    + *
    + *     http://www.apache.org/licenses/LICENSE-2.0
    + *
    + * Unless required by applicable law or agreed to in writing,
    + * software distributed under the License is distributed on an
    + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
    + * KIND, either express or implied.  See the License for the
    + * specific language governing permissions and limitations
    + * under the License.
    + */
    +package org.apache.brooklyn.util.core.osgi;
    +
    +import java.io.File;
    +import java.io.FileOutputStream;
    +import java.io.IOException;
    +import java.io.InputStream;
    +import java.io.InputStreamReader;
    +import java.util.Enumeration;
    +import java.util.Map;
    +import java.util.Set;
    +import java.util.jar.JarFile;
    +import java.util.jar.JarOutputStream;
    +import java.util.jar.Manifest;
    +import java.util.zip.ZipEntry;
    +import java.util.zip.ZipFile;
    +import java.util.zip.ZipOutputStream;
    +
    +import org.apache.brooklyn.api.mgmt.ManagementContext;
    +import org.apache.brooklyn.core.mgmt.internal.LocalManagementContext;
    +import org.apache.brooklyn.util.collections.MutableMap;
    +import org.apache.brooklyn.util.collections.MutableSet;
    +import org.apache.brooklyn.util.core.ResourceUtils;
    +import org.apache.brooklyn.util.exceptions.Exceptions;
    +import org.apache.brooklyn.util.net.Urls;
    +import org.apache.brooklyn.util.os.Os;
    +import org.apache.brooklyn.util.stream.Streams;
    +import org.apache.brooklyn.util.text.Strings;
    +import org.osgi.framework.Bundle;
    +import org.osgi.framework.Constants;
    +import org.osgi.framework.launch.Framework;
    +
    +import com.google.common.annotations.Beta;
    +import com.google.common.base.Predicate;
    +import com.google.common.base.Predicates;
    +import com.google.common.io.LineReader;
    +
    +public class BundleMaker {
    +
    +    final static String MANIFEST_PATH = JarFile.MANIFEST_NAME;
    +    private Framework framework;
    +    private ResourceUtils resources;
    +    private Class<?> optionalDefaultClassForLoading;
    +
    +    public BundleMaker(Framework f, ResourceUtils resources) {
    +        this.framework = f;
    +        this.resources = resources;
    +    }
    +    
    +    public BundleMaker(ManagementContext mgmt) {
    +        this( ((LocalManagementContext)mgmt).getOsgiManager().get().getFramework(), ResourceUtils.create()
);
    +    }
    +
    +    /** if set, this will be used to resolve relative classpath fragments */
    +    public void setDefaultClassForLoading(Class<?> optionalDefaultClassForLoading)
{
    +        this.optionalDefaultClassForLoading = optionalDefaultClassForLoading;
    +    }
    +    
    +    /** creates a ZIP in a temp file from the given classpath folder, 
    +     * by recursively taking everything in the referenced directories,
    +     * treating the given folder as the root,
    +     * respecting the MANIFEST.MF if present (ie putting it first so it is a valid JAR)
*/
    +    public File createJarFromClasspathDir(String path) {
    +        File f = Os.newTempFile(path, "zip");
    +        ZipOutputStream zout = null;
    +        try {
    +            if (Urls.getProtocol(path)==null) {
    +                // default if no URL is classpath
    +                path = Os.tidyPath(path);
    +                if (!path.startsWith("/") && optionalDefaultClassForLoading!=null)
{
    +                    path = "/"+optionalDefaultClassForLoading.getPackage().getName().replace('.',
'/') + "/" + path;
    +                }
    +                path = "classpath:"+path;
    +            }
    +            
    +            InputStream min = resources.getResourceFromUrl(Urls.mergePaths(path, MANIFEST_PATH));
    +            if (min==null) {
    +                addUrlItemRecursively(zout, path, path, Predicates.<String>alwaysTrue());
    +            } else {
    +                zout = new JarOutputStream(new FileOutputStream(f), new Manifest(min));
    +                addUrlItemRecursively(zout, path, path, Predicates.not(Predicates.equalTo(MANIFEST_PATH)));
    +            }
    +            
    +            Streams.closeQuietly(zout);
    +            
    +            return f;
    +            
    +        } catch (Exception e) {
    +            throw Exceptions.propagate("Error creating ZIP from classpath spec "+path,
e);
    +            
    +        } finally {
    +            Streams.closeQuietly(zout);
    +        }
    +    }
    +
    +    /** true iff given ZIP/JAR file contains a MANIFEST.MF file defining a bundle symbolic
name */
    +    public boolean hasOsgiManifest(File f) {
    +        Manifest mf = getManifest(f);
    +        if (mf==null) return false;
    +        String sn = mf.getMainAttributes().getValue(Constants.BUNDLE_SYMBOLICNAME);
    +        return Strings.isNonBlank(sn);
    +    }
    +
    +    /** returns the manifest in a JAR file, or null if no manifest contained therein
*/
    +    public Manifest getManifest(File f) {
    +        JarFile jf = null;
    +        try {
    +            jf = new JarFile(f);
    +            return jf.getManifest();
    +        } catch (IOException e) {
    +            throw Exceptions.propagate("Unable to read "+f+" when looking for manifest",
e);
    +        } finally {
    +            Streams.closeQuietly(jf);
    +        }
    +    }
    +    
    +    /** as {@link #copyAddingManifest(File, Manifest)} but taking manifest entries as
a map for convenience */
    +    public File copyAddingManifest(File f, Map<String,String> attrs) {
    +        Manifest mf = new Manifest();
    +        for (Map.Entry<String,String> attr: attrs.entrySet()) {
    +            mf.getMainAttributes().putValue(attr.getKey(), attr.getValue());
    +        }
    +        return copyAddingManifest(f, mf);
    +    }
    +    
    +    /** create a copy of the given ZIP as a JAR with the given manifest, returning the
new temp file */
    +    public File copyAddingManifest(File f, Manifest mf) {
    +        File f2 = Os.newTempFile(f.getName(), "zip");
    +        ZipOutputStream zout = null;
    +        ZipFile zf = null;
    +        try {
    +            zout = new JarOutputStream(new FileOutputStream(f2), mf);
    +            writeZipEntriesFromFile(zout, f, Predicates.not(Predicates.equalTo(MANIFEST_PATH)));
    +        } catch (IOException e) {
    +            throw Exceptions.propagate("Unable to read "+f+" when looking for manifest",
e);
    +        } finally {
    +            Streams.closeQuietly(zf);
    +            Streams.closeQuietly(zout);
    +        }
    +        return f2;
    +    }
    +    
    +    /** create a copy of the given ZIP as a JAR with the given entries added at the end
(removing any duplicates), returning the new temp file */
    +    public File copyAdding(File f, Map<ZipEntry,InputStream> entries) {
    +        return copyAdding(f, entries, Predicates.<String>alwaysTrue(), false);
    +    }
    +    
    +    /** create a copy of the given ZIP as a JAR with the given entries added at the end,
returning the new temp file */
    +    public File copyAddingAtEnd(File f, Map<ZipEntry,InputStream> entries) {
    +        return copyAdding(f, entries, Predicates.<String>alwaysTrue(), true);
    +    }
    +
    +    /** create a copy of the given ZIP as a JAR with the given entries removed, returning
the new temp file */
    +    public File copyRemoving(File f, final Set<String> itemsToRemove) {
    +        return copyRemoving(f, new Predicate<String>(){
    +            @Override
    +            public boolean apply(String input) {
    +                return !itemsToRemove.contains(input);
    +            }
    +        });
    +    }
    +    
    +    /** create a copy of the given ZIP as a JAR with the given entries removed, returning
the new temp file */
    +    public File copyRemoving(File f, Predicate<String> filter) {
    +        return copyAdding(f, MutableMap.<ZipEntry,InputStream>of(), filter, true);
    +    }
    +    
    +    private File copyAdding(File f, Map<ZipEntry,InputStream> entries, final Predicate<String>
filter, boolean addAtStart) {
    +        final Set<String> entryNames = MutableSet.of();
    +        for (ZipEntry ze: entries.keySet()) {
    +            entryNames.add(ze.getName());
    +        }
    +        
    +        File f2 = Os.newTempFile(f.getName(), "zip");
    +        ZipOutputStream zout = null;
    +        ZipFile zf = null;
    +        try {
    +            zout = new ZipOutputStream(new FileOutputStream(f2));
    +            
    +            if (addAtStart) {
    +                writeZipEntries(zout, entries);
    +            }
    +            
    +            writeZipEntriesFromFile(zout, f, new Predicate<String>() {
    +                @Override
    +                public boolean apply(String input) {
    +                    return filter.apply(input) && !entryNames.contains(input);
    +                }
    +            });
    +            
    +            if (!addAtStart) {
    +                writeZipEntries(zout, entries);
    +            }
    +
    +            return f2;
    +        } catch (IOException e) {
    +            throw Exceptions.propagate("Unable to read "+f+" when looking for manifest",
e);
    +        } finally {
    +            Streams.closeQuietly(zf);
    +            Streams.closeQuietly(zout);
    +        }
    +    }
    +
    +    private void writeZipEntries(ZipOutputStream zout, Map<ZipEntry, InputStream>
entries) throws IOException {
    +        for (Map.Entry<ZipEntry,InputStream> ze: entries.entrySet()) {
    +            zout.putNextEntry(ze.getKey());
    +            InputStream zin = ze.getValue();
    +            Streams.copy(zin, zout);
    +            Streams.closeQuietly(zin);
    +            zout.closeEntry();
    +        }
    +    }
    +
    +    private void writeZipEntriesFromFile(ZipOutputStream zout, File existingZip, Predicate<String>
filter) throws IOException {
    +        ZipFile zf = new ZipFile(existingZip);
    +        try {
    +            Enumeration<? extends ZipEntry> zfe = zf.entries();
    +            while (zfe.hasMoreElements()) {
    +                ZipEntry ze = zfe.nextElement();
    +                if (filter.apply(ze.getName())) {
    +                    zout.putNextEntry(ze);
    +                    InputStream zin = zf.getInputStream(ze);
    +                    Streams.copy(zin, zout);
    +                    Streams.closeQuietly(zin);
    +                    zout.closeEntry();
    +                }
    +            }
    +        } finally {
    +            Streams.closeQuietly(zf);
    +        }
    +    }
    +    
    +    /** installs the given JAR file as an OSGi bundle; all manifest info should be already
set up.
    +     * bundle-start semantics are TBD. */
    +    @Beta
    +    public Bundle installBundle(File f, boolean start) {
    +        try {
    +            Bundle b = Osgis.install( framework, "file://"+f.getAbsolutePath() );
    +            if (start) {
    +                // benefits of start:
    +                // a) we get wiring issues thrown here, and
    +                // b) catalog.bom in root will be scanned synchronously here
    +                // however drawbacks:
    +                // c) other code doesn't always do it (method above)
    +                // d) heavier-weight earlier
    +                // e) tests in IDE break (but mvn fine)
    +                b.start();
    +            }
    +            
    +            return b;
    +            
    +        } catch (Exception e) {
    +            throw Exceptions.propagate("Error starting bundle from "+f, e);
    +        }
    +    }
    +    
    +    private boolean addUrlItemRecursively(ZipOutputStream zout, String root, String item,
Predicate<String> filter) throws IOException {
    +        InputStream itemFound = null;
    +        try {
    +            itemFound = resources.getResourceFromUrl(item);
    --- End diff --
    
    Wow haven't realised it's possible to read the listing of a classpath path. Had to run
the test myself to make sure it works :)
    Is this standard, documented somewhere? Does it work in Karaf?


---
If your project is set up for it, you can reply to this email and have your
reply appear on GitHub as well. If your project does not have this feature
enabled and wishes so, or if the feature is enabled but not working, please
contact infrastructure at infrastructure@apache.org or file a JIRA ticket
with INFRA.
---

Mime
View raw message