Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * #%L
   * JBossOSGi Framework
   * %%
   * Copyright (C) 2010 - 2012 JBoss by Red Hat
   * %%
   * This program is free software: you can redistribute it and/or modify
   * it under the terms of the GNU Lesser General Public License as
   * published by the Free Software Foundation, either version 2.1 of the
  * License, or (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Lesser Public License for more details.
  *
  * You should have received a copy of the GNU General Lesser Public
  * License along with this program.  If not, see
  * <http://www.gnu.org/licenses/lgpl-2.1.html>.
  * #L%
  */
 package org.jboss.osgi.framework.internal;
 
 import static org.jboss.osgi.framework.FrameworkMessages.MESSAGES;
 
 import java.io.File;
 import java.net.URL;
 import java.util.List;
 import java.util.Map;
 
The bundle native code plugin

Author(s):
thomas.diesler@jboss.com
David Bosschaert
Since:
11-Aug-2010
 
 public final class NativeCodeImpl implements NativeCode {

    
The string that is to be replaced with the absolute path of the native library as specified by the core spec with the org.osgi.framework.command.execpermission framework property.
 
     private static final String ABSPATH_VARIABLE = "${abspath}";

    
Maps an alias to an OSGi processor name
 
     private static Map<StringStringprocessorAlias = new HashMap<StringString>();
     static {
         .put("amd64""x86-64");
         .put("em64t""x86-64");
         .put("i386""x86");
         .put("i486""x86");
         .put("i586""x86");
         .put("i686""x86");
         .put("pentium""x86");
         .put("x86_64""x86-64");
     }

    
Maps an alias to an OSGi osname
 
     private static Map<StringStringosAlias = new HashMap<StringString>();
     static {
         .put("hp-ux""HPUX");
         .put("Mac OS""MacOS");
         .put("Mac OS X""MacOSX");
         .put("OS/2""OS2");
         .put("procnto""QNX");
         .put("SymbianOS""Epoc32");
         .put("Win2000""Windows2000");
         .put("Win2003""Windows2003");
        .put("Win32""Windows");
        .put("Win95""Windows95");
        .put("Win98""Windows98");
        .put("WinCE""WindowsCE");
        .put("Windows 2000""Windows2000");
        .put("Windows 2003""Windows2003");
        .put("Windows 7""Windows7");
        .put("Windows 95""Windows95");
        .put("Windows 98""Windows98");
        .put("Windows CE""WindowsCE");
        .put("Windows NT""WindowsNT");
        .put("Windows Server 2003""Windows2003");
        .put("Windows Vista""WindowsVista");
        .put("Windows XP""WindowsXP");
        .put("WinNT""WindowsNT");
        .put("WinVista""WindowsVista");
        .put("WinXP""WindowsXP");
    }
    private final BundleManagerPlugin bundleManager;
    public NativeCodeImpl(BundleManager bundleManager) {
        this. = BundleManagerPlugin.assertBundleManagerPlugin(bundleManager);
    }
    @Override
    public void deployNativeCode(Deployment dep) {
        // Core 4.2 spec section 3.9: a bundle can be installed if the Bundle-NativeCode code header
        // doesn't match. Errors are reported during the resolution phase.
        // Add NativeLibraryMetaData to the deployment as a marker that the deployment contains
        // Native Code which needs to be processed. The actual processing of it happens in the
        // resolveNativeCode() method.
        NativeLibraryMetaData nativeLibraries = new NativeLibraryMetaData();
        dep.addAttachment(NativeLibraryMetaData.classnativeLibraries);
    }
    @Override
    public void resolveNativeCode(XBundleRevision userRevthrows BundleException {
        OSGiMetaData metaData = userRev.getAttachment(OSGiMetaData.class);
        List<ParameterizedAttributeparams = metaData.getBundleNativeCode();
        if (params == null)
            throw .cannotFindNativeCodeHeader(userRev);
        // Find the matching parameters
        List<ParameterizedAttributematchedParams = new ArrayList<ParameterizedAttribute>();
        for (ParameterizedAttribute param : params) {
            if (matchParameter(param))
                matchedParams.add(param);
        }
        Deployment dep = userRev.getAttachment(Deployment.class);
        NativeLibraryMetaData nativeLibraries = dep.getAttachment(NativeLibraryMetaData.class);
        // If no native clauses were selected in step 1, this algorithm is terminated
        // and a BundleException is thrown if the optional clause is not present
        if (matchedParams.size() == 0) {
            if (params.size() > 0 && "*".equals(params.get(params.size() - 1).getAttribute())) {
                // This Bundle-NativeCode clause is optional but we're not selecting any native code clauses
                // so remove the marker deployment attachment
                dep.removeAttachment(NativeLibraryMetaData.class);
                return;
            }
            throw .noNativeCodeClauseSelected(params);
        }
        // The selected clauses are now sorted in the following priority order:
        // * osversion: floor of the osversion range in descending order, osversion not specified
        // * language: language specified, language not specified
        // * Position in the Bundle-NativeCode manifest header: lexical left to right
        // [TODO] sort the clauses
        for (ParameterizedAttribute param : matchedParams) {
            String libpath = param.getAttribute();
            NativeLibrary library = new NativeLibrary(libpath);
            nativeLibraries.addNativeLibrary(library);
        }
    }
    @SuppressWarnings({ "unchecked" })
    private List<StringgetCollection(Object value) {
        if (value == null)
            return Collections.emptyList();
        if (value instanceof Collection)
            return new ArrayList<String>((Collection<String>) value);
        return Collections.singletonList(value.toString());
    }
    private boolean matchParameter(ParameterizedAttribute paramthrows BundleException {
        // Only select the native code clauses for which the following expressions all evaluate to true
        // ('~=' stands for 'matches').
        // * osname ~= [org.osgi.framework.os.name]
        // * processor ~= [org.osgi.framework.processor]
        // * osversion range includes [org.osgi.framework.os.version] or osversion is not specified
        // * language ~= [org.osgi.framework.language] or language is not specified
        // * selection-filter evaluates to true when using the values of the system properties or selection-filter is not
        // specified
        // osname ~= [org.osgi.framework.os.name]
        Parameter osnameParam = param.getAttribute(.);
        BundleContext systemContext = .getSystemBundle().getBundleContext();
        boolean match = (osnameParam != null);
        if (match == true && osnameParam != null) {
            String fwOSName = systemContext.getProperty(.);
            boolean osmatch = false;
            Collection<StringosNames = getCollection(osnameParam.getValue());
            for (String osname : osNames) {
                osmatch = (osname.equalsIgnoreCase(fwOSName) || osname.equalsIgnoreCase(.get(fwOSName)));
                if (osmatch == true)
                    break;
            }
            match &= osmatch;
        }
        // processor ~= [org.osgi.framework.processor]
        Parameter procParam = param.getAttribute(.);
        match &= (procParam != null);
        if (match && procParam != null) {
            String fwProcessor = systemContext.getProperty(.);
            boolean procmatch = false;
            List<Stringprocessors = getCollection(procParam.getValue());
            for (String proc : processors) {
                procmatch = (proc.equals(fwProcessor) || proc.equals(.get(fwProcessor)));
                if (procmatch == true)
                    break;
            }
            match &= procmatch;
        }
        // osversion range includes [org.osgi.framework.os.version] or osversion is not specified
        Parameter osversionParam = param.getAttribute(.);
        if (match && osversionParam != null) {
            String fwOSVersion = systemContext.getProperty(.);
            boolean versionMatch = false;
            Version currentVersion = Version.parseVersion(fwOSVersion);
            for (String versionRange : getCollection(osversionParam.getValue())) {
                VersionRange vr;
                vr = VersionRange.parse(versionRange);
                if (vr.isInRange(currentVersion)) {
                    versionMatch = true;
                    break;
                }
            }
            match &= versionMatch;
        }
        // language ~= [org.osgi.framework.language] or language is not specified
        Parameter languageParam = param.getAttribute(.);
        if (match && languageParam != null) {
            String fwLanguage = systemContext.getProperty(.);
            boolean languageMatch = false;
            for (String language : getCollection(languageParam.getValue())) {
                if (language.equals(fwLanguage)) {
                    languageMatch = true;
                    break;
                }
            }
            match &= languageMatch;
        }
        // selection-filter evaluates to true when using the values of the system properties or selection-filter is not specified
        Parameter filterSelectionParam = param.getAttribute(.);
        if (match && filterSelectionParam != null) {
            boolean filterMatch = false;
            Dictionary<StringObjectframeworkProps = new Hashtable<StringObject>(.getProperties());
            for (String filterSpec : getCollection(filterSelectionParam.getValue())) {
                try {
                    Filter filter = FrameworkUtil.createFilter(filterSpec);
                    if (filter.match(frameworkProps)) {
                        filterMatch = true;
                        break;
                    }
                } catch (InvalidSyntaxException ex) {
                    throw .invalidFilterExpression(exfilterSpec);
                }
            }
            match &= filterMatch;
        }
        return match;
    }
    static class BundleNativeLibraryProvider implements NativeLibraryProvider {
        private final HostBundleState hostBundle;
        private final String libname;
        private final String libpath;
        private final URL libURL;
        private File libraryFile;
        BundleNativeLibraryProvider(HostBundleRevision hostrevString libnameString libpath) {
            this. = hostrev.getBundleState();
            this. = libpath;
            this. = libname;
            // If a native code library in a selected native code clause cannot be found
            // within the bundle or its fragments then the bundle must fail to resolve
            String path;
            String filename;
            int idx = libpath.lastIndexOf('/');
            if (idx >= 0) {
                path = libpath.substring(0, idx);
                filename = libpath.substring(idx + 1);
            } else {
                path = "";
                filename = libpath;
            }
            Enumeration<URLurls = hostrev.findResolvedEntries(pathfilenamefalse);
            if (urls == null || urls.hasMoreElements() == false)
                throw .illegalStateCannotFindNativeLibrary(libpath);
            this. = urls.nextElement();
        }
        @Override
        public String getLibraryName() {
            return ;
        }
        @Override
        public String getLibraryPath() {
            return ;
        }
        @Override
        public File getLibraryLocation() throws IOException {
            if ( == null) {
                // Create a unique local file location
                 = getUniqueLibraryFile();
                .deleteOnExit();
                // Copy the native library to the bundle storage area
                FileOutputStream fos = new FileOutputStream();
                VFSUtils.copyStream(.openStream(), fos);
                fos.close();
                handleExecPermission();
            }
            return ;
        }
        private void handleExecPermission() throws IOException {
            if (epProp == null)
                return;
            StringBuilder command = new StringBuilder(epProp);
            int idx = command.indexOf();
            if (idx >= 0) {
                command.replace(idxidx + .length(), .getAbsolutePath());
            }
            Process process = Runtime.getRuntime().exec(command.toString());
            try {
                process.waitFor();
            } catch (InterruptedException e) {
                // Move ahead when interrupted
            }
        }
        private File getUniqueLibraryFile(final UserBundleState userBundlefinal String libpath) {
            BundleStorage storagePlugin = userBundle.getFrameworkState().getBundleStorage();
            return storagePlugin.getDataFile(userBundle.getBundleId(), libpath);
        }
    }
New to GrepCode? Check out our FAQ X