You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@felix.apache.org by gn...@apache.org on 2009/04/30 11:10:06 UTC
svn commit: r770120 [2/3] - in /felix/trunk/karaf: ./ assembly/
assembly/src/main/descriptors/ assembly/src/main/filtered-resources/etc/
deployer/ deployer/blueprint/
deployer/blueprint/src/main/java/org/apache/servicemix/kernel/deployer/
deployer/blue...
Added: felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/FileMonitor.java
URL: http://svn.apache.org/viewvc/felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/FileMonitor.java?rev=770120&view=auto
==============================================================================
--- felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/FileMonitor.java (added)
+++ felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/FileMonitor.java Thu Apr 30 09:10:03 2009
@@ -0,0 +1,767 @@
+/**
+ *
+ * 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.servicemix.kernel.deployer.filemonitor;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Dictionary;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Hashtable;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.Set;
+import java.util.concurrent.Executor;
+import java.util.concurrent.Executors;
+import java.util.jar.Attributes;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.Bundle;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.BundleEvent;
+import org.osgi.framework.BundleException;
+import org.osgi.framework.BundleListener;
+import org.osgi.framework.Constants;
+import org.osgi.framework.InvalidSyntaxException;
+import org.osgi.framework.ServiceEvent;
+import org.osgi.framework.ServiceListener;
+import org.osgi.framework.ServiceReference;
+import org.osgi.service.cm.Configuration;
+import org.osgi.service.cm.ConfigurationAdmin;
+import org.osgi.service.packageadmin.PackageAdmin;
+import org.osgi.service.prefs.Preferences;
+import org.osgi.service.prefs.PreferencesService;
+import org.osgi.util.tracker.ServiceTracker;
+
+/**
+ * Watches a deploy directory for files that are added, updated or removed then
+ * processing them. Currently we support OSGi bundles, OSGi configuration files
+ * and expanded directories of OSGi bundles.
+ *
+ * @version $Revision: 1.1 $
+ */
+public class FileMonitor {
+
+ public final static String CONFIG_DIR = "org.apache.servicemix.filemonitor.configDir";
+ public final static String DEPLOY_DIR = "org.apache.servicemix.filemonitor.monitorDir";
+ public final static String GENERATED_JAR_DIR = "org.apache.servicemix.filemonitor.generatedJarDir";
+ public final static String SCAN_INTERVAL = "org.apache.servicemix.filemonitor.scanInterval";
+ public final static String PREFERENCE_KEY = "FileMonitor";
+
+ protected static final String ALIAS_KEY = "_alias_factory_pid";
+
+ private static final Log LOGGER = LogFactory.getLog(FileMonitor.class);
+
+ private FileMonitorActivator activator;
+ private File configDir;
+ private File deployDir;
+ private File generateDir;
+ private Scanner scanner = new Scanner();
+ private long scanInterval = 500L;
+ private boolean loggedConfigAdminWarning;
+ private List<Bundle> bundlesToStart = new ArrayList<Bundle>();
+ private List<Bundle> bundlesToUpdate = new ArrayList<Bundle>();
+ private Map<String, String> artifactToBundle = new HashMap<String, String>();
+ private final Set<String> pendingTransformationArtifacts = new HashSet<String>();
+ private final Set<Bundle> pendingStartBundles = new HashSet<Bundle>();
+ private ServiceListener deployerListener;
+ private BundleListener bundleListener;
+ private Executor executor;
+ private String pid;
+
+ public FileMonitor() {
+ String base = System.getProperty("servicemix.base", ".");
+ configDir = new File(base, "etc");
+ deployDir = new File(base, "deploy");
+ generateDir = new File(base, "data/generated-bundles");
+ }
+
+ @SuppressWarnings("unchecked")
+ public FileMonitor(FileMonitorActivator activator, Dictionary properties, String pid) {
+ this();
+
+ this.activator = activator;
+ this.pid = pid;
+
+ File value = getFileValue(properties, CONFIG_DIR);
+ if (value != null) {
+ configDir = value;
+ }
+ value = getFileValue(properties, DEPLOY_DIR);
+ if (value != null) {
+ deployDir = value;
+ }
+ value = getFileValue(properties, GENERATED_JAR_DIR);
+ if (value != null) {
+ generateDir = value;
+ }
+ Long i = getLongValue(properties, SCAN_INTERVAL);
+ if (i != null) {
+ scanInterval = i;
+ }
+ }
+
+ public void start() {
+ executor = Executors.newSingleThreadExecutor();
+ if (configDir != null) {
+ configDir.mkdirs();
+ }
+ deployDir.mkdirs();
+ generateDir.mkdirs();
+
+ List<File> dirs = new ArrayList<File>();
+ if (configDir != null) {
+ dirs.add(configDir);
+ }
+ dirs.add(deployDir);
+ scanner.setScanDirs(dirs);
+ scanner.setScanInterval(scanInterval);
+ // load the scan results for this monitor
+ loadScannerState();
+ scanner.addListener(new Scanner.BulkListener() {
+ public void filesChanged(List<String> filenames) throws Exception {
+ onFilesChanged(filenames);
+ }
+ });
+
+ LOGGER.info("Starting to monitor the deploy directory: " + deployDir + " every " + scanInterval
+ + " millis");
+ if (configDir != null) {
+ LOGGER.info("Config directory is at: " + configDir);
+ }
+ LOGGER.info("Will generate bundles from expanded source directories to: " + generateDir);
+
+ executor.execute(new Runnable() {
+ public void run() {
+ scanner.start();
+ }
+ });
+ }
+
+ public void stop() {
+ // first stop the scanner
+ scanner.stop();
+ // load the scan results for this monitor
+ saveScannerState();
+ }
+
+ // Properties
+ // -------------------------------------------------------------------------
+
+ public BundleContext getContext() {
+ return activator.getContext();
+ }
+
+ public FileMonitorActivator getActivator() {
+ return activator;
+ }
+
+ public void setActivator(FileMonitorActivator activator) {
+ this.activator = activator;
+ }
+
+ public File getConfigDir() {
+ return configDir;
+ }
+
+ public void setConfigDir(File configDir) {
+ this.configDir = configDir;
+ }
+
+ public File getDeployDir() {
+ return deployDir;
+ }
+
+ public void setDeployDir(File deployDir) {
+ this.deployDir = deployDir;
+ }
+
+ public File getGenerateDir() {
+ return generateDir;
+ }
+
+ public void setGenerateDir(File generateDir) {
+ this.generateDir = generateDir;
+ }
+
+ public long getScanInterval() {
+ return scanInterval;
+ }
+
+ public void setScanInterval(long scanInterval) {
+ this.scanInterval = scanInterval;
+ }
+
+ // Implementation methods
+ // -------------------------------------------------------------------------
+
+ protected synchronized void onFilesChanged(Collection<String> filenames) {
+ bundlesToStart.clear();
+ bundlesToUpdate.clear();
+ Set<File> bundleJarsCreated = new HashSet<File>();
+
+ for (String filename : filenames) {
+ File file = new File(filename);
+ try {
+ LOGGER.debug("File changed: " + filename);
+
+ // Handle config files
+ if (isValidConfigFile(file)) {
+ if (file.exists()) {
+ updateConfiguration(file);
+ } else {
+ deleteConfiguration(file);
+ }
+ continue;
+ }
+
+ // Handle exploded artifacts removal
+ if (!file.exists() && file.getName().equals("MANIFEST.MF")) {
+ File parentFile = file.getParentFile();
+ if (parentFile.getName().equals("META-INF")) {
+ File bundleDir = parentFile.getParentFile();
+ if (isValidBundleSourceDirectory(bundleDir)) {
+ undeployBundle(bundleDir);
+ continue;
+ }
+ }
+ }
+
+ // Handle exploded artifacts add
+ File jardir = getExpandedBundleRootDirectory(file);
+ if (jardir != null) {
+ if (bundleJarsCreated.contains(jardir)) {
+ continue;
+ }
+ bundleJarsCreated.add(jardir);
+ file = createBundleJar(jardir);
+ }
+
+ // Transformation step
+ if (file.exists()) {
+ File f = transformArtifact(file);
+ if (f == null) {
+ LOGGER.warn("Unsupported deployment: " + filename);
+ rescheduleTransformation(file);
+ continue;
+ }
+ file = f;
+ } else {
+ String transformedFile = artifactToBundle.get(filename);
+ if (transformedFile != null) {
+ file = new File(transformedFile);
+ if (file.exists()) {
+ file.delete();
+ }
+ }
+ }
+
+ // Handle final bundles
+ if (isValidArtifactFile(file)) {
+ if (file.exists()) {
+ deployBundle(file);
+ } else {
+ undeployBundle(file);
+ }
+ }
+ } catch (Exception e) {
+ LOGGER.warn("Failed to process: " + file + ". Reason: " + e, e);
+ }
+ }
+ refreshPackagesAndStartOrUpdateBundles();
+ }
+
+ private void rescheduleTransformation(File file) {
+ synchronized (pendingTransformationArtifacts) {
+ pendingTransformationArtifacts.add(file.getAbsolutePath());
+ }
+ if (deployerListener == null) {
+ try {
+ String filter = "(" + Constants.OBJECTCLASS + "=" + DeploymentListener.class.getName() + ")";
+ deployerListener = new ServiceListener() {
+ public void serviceChanged(ServiceEvent event) {
+ executor.execute(new Runnable() {
+ public void run() {
+ Set<String> files;
+ synchronized (pendingTransformationArtifacts) {
+ files = new HashSet<String>(pendingTransformationArtifacts);
+ pendingTransformationArtifacts.clear();
+ }
+ onFilesChanged(files);
+ }
+ });
+ }
+ };
+ getContext().addServiceListener(deployerListener, filter);
+ } catch (InvalidSyntaxException e) {
+ // Ignore
+ }
+ }
+ }
+
+ private File transformArtifact(File file) throws Exception {
+ // Check registered deployers
+ ServiceReference[] srvRefs = getContext().getAllServiceReferences(DeploymentListener.class.getName(),
+ null);
+ if (srvRefs != null) {
+ for (ServiceReference sr : srvRefs) {
+ try {
+ DeploymentListener deploymentListener = (DeploymentListener)getContext().getService(sr);
+ if (deploymentListener.canHandle(file)) {
+ File transformedFile = deploymentListener.handle(file, getGenerateDir());
+ artifactToBundle.put(file.getAbsolutePath(), transformedFile.getAbsolutePath());
+ return transformedFile;
+ }
+ } finally {
+ getContext().ungetService(sr);
+ }
+ }
+ }
+ JarFile jar = null;
+ try {
+ // Handle OSGi bundles with the default deployer
+ if (file.getName().endsWith("txt") || file.getName().endsWith("xml")
+ || file.getName().endsWith("properties")) {
+ // that's file type which is not supported as bundle and avoid
+ // exception in the log
+ return null;
+ }
+ jar = new JarFile(file);
+ Manifest m = jar.getManifest();
+ if (m.getMainAttributes().getValue(new Attributes.Name("Bundle-SymbolicName")) != null
+ && m.getMainAttributes().getValue(new Attributes.Name("Bundle-Version")) != null) {
+ return file;
+ }
+ } catch (Exception e) {
+ LOGGER.debug("Error transforming artifact " + file.getName(), e);
+ } finally {
+ if (jar != null) {
+ jar.close();
+ }
+ }
+ return null;
+ }
+
+ protected void deployBundle(File file) throws IOException, BundleException {
+ LOGGER.info("Deploying: " + file.getCanonicalPath());
+
+ InputStream in = new FileInputStream(file);
+
+ try {
+ Bundle bundle = getBundleForJarFile(file);
+ if (bundle != null) {
+ bundlesToUpdate.add(bundle);
+ } else {
+ bundle = getContext().installBundle(file.getCanonicalFile().toURI().toString(), in);
+ if (!isBundleFragment(bundle)) {
+ bundlesToStart.add(bundle);
+ }
+ }
+ } finally {
+ closeQuietly(in);
+ }
+ }
+
+ protected void undeployBundle(File file) throws BundleException, IOException {
+ LOGGER.info("Undeploying: " + file.getCanonicalPath());
+ Bundle bundle = getBundleForJarFile(file);
+
+ if (bundle == null) {
+ LOGGER.warn("Could not find Bundle for file: " + file.getCanonicalPath());
+ } else {
+ if (!isBundleFragment(bundle)) {
+ bundle.stop();
+ }
+ bundle.uninstall();
+ }
+ }
+
+ protected Bundle getBundleForJarFile(File file) throws IOException {
+ String absoluteFilePath = file.getAbsoluteFile().toURI().toString();
+ Bundle bundles[] = getContext().getBundles();
+ for (Bundle bundle : bundles) {
+ String location = bundle.getLocation();
+ if (filePathsMatch(absoluteFilePath, location)) {
+ return bundle;
+ }
+ }
+ return null;
+ }
+
+ protected static boolean filePathsMatch(String p1, String p2) {
+ p1 = normalizeFilePath(p1);
+ p2 = normalizeFilePath(p2);
+ return (p1 != null && p1.equalsIgnoreCase(p2));
+ }
+
+ protected static String normalizeFilePath(String path) {
+ if (path != null) {
+ path = path.replaceFirst("file:/*", "");
+ path = path.replaceAll("[\\\\/]+", "/");
+ }
+ return path;
+ }
+
+ protected void updateConfiguration(File file) throws IOException, InvalidSyntaxException {
+ ConfigurationAdmin configurationAdmin = activator.getConfigurationAdmin();
+ if (configurationAdmin == null) {
+ if (!loggedConfigAdminWarning) {
+ LOGGER.warn("No ConfigurationAdmin so cannot deploy configurations");
+ loggedConfigAdminWarning = true;
+ }
+ } else {
+ Properties properties = new Properties();
+ InputStream in = new FileInputStream(file);
+ try {
+ properties.load(in);
+ interpolation(properties);
+ closeQuietly(in);
+ String[] pid = parsePid(file);
+ Hashtable<Object, Object> hashtable = new Hashtable<Object, Object>();
+ hashtable.putAll(properties);
+ if (pid[1] != null) {
+ hashtable.put(ALIAS_KEY, pid[1]);
+ }
+
+ Configuration config = getConfiguration(pid[0], pid[1]);
+ if (config.getBundleLocation() != null) {
+ config.setBundleLocation(null);
+ }
+ config.update(hashtable);
+ } finally {
+ closeQuietly(in);
+ }
+ }
+ }
+
+ protected void interpolation(Properties properties) {
+ for (Enumeration e = properties.propertyNames(); e.hasMoreElements();) {
+ String key = (String)e.nextElement();
+ String val = properties.getProperty(key);
+ Matcher matcher = Pattern.compile("\\$\\{([^}]+)\\}").matcher(val);
+ while (matcher.find()) {
+ String rep = System.getProperty(matcher.group(1));
+ if (rep != null) {
+ val = val.replace(matcher.group(0), rep);
+ matcher.reset(val);
+ }
+ }
+ properties.put(key, val);
+ }
+ }
+
+ protected void deleteConfiguration(File file) throws IOException, InvalidSyntaxException {
+ String[] pid = parsePid(file);
+ Configuration config = getConfiguration(pid[0], pid[1]);
+ config.delete();
+ }
+
+ protected Configuration getConfiguration(String pid, String factoryPid) throws IOException,
+ InvalidSyntaxException {
+ ConfigurationAdmin configurationAdmin = activator.getConfigurationAdmin();
+ if (factoryPid != null) {
+ Configuration[] configs = configurationAdmin.listConfigurations("(|(" + ALIAS_KEY + "=" + pid
+ + ")(.alias_factory_pid="
+ + factoryPid + "))");
+ if (configs == null || configs.length == 0) {
+ return configurationAdmin.createFactoryConfiguration(pid, null);
+ } else {
+ return configs[0];
+ }
+ } else {
+ return configurationAdmin.getConfiguration(pid, null);
+ }
+ }
+
+ protected String[] parsePid(File file) {
+ String path = file.getName();
+ String pid = path.substring(0, path.length() - 4);
+ int n = pid.indexOf('-');
+ if (n > 0) {
+ String factoryPid = pid.substring(n + 1);
+ pid = pid.substring(0, n);
+ return new String[] {pid, factoryPid};
+ } else {
+ return new String[] {pid, null};
+ }
+ }
+
+ protected PackageAdmin getPackageAdmin() {
+ ServiceTracker packageAdminTracker = activator.getPackageAdminTracker();
+ if (packageAdminTracker != null) {
+ try {
+ return (PackageAdmin)packageAdminTracker.waitForService(5000L);
+ } catch (InterruptedException e) {
+ // ignore
+ }
+ }
+ return null;
+ }
+
+ protected boolean isBundleFragment(Bundle bundle) {
+ PackageAdmin packageAdmin = getPackageAdmin();
+ if (packageAdmin != null) {
+ return packageAdmin.getBundleType(bundle) == PackageAdmin.BUNDLE_TYPE_FRAGMENT;
+ }
+ return false;
+ }
+
+ protected void refreshPackagesAndStartOrUpdateBundles() {
+ for (Bundle bundle : bundlesToUpdate) {
+ try {
+ bundle.update();
+ LOGGER.info("Updated: " + bundle);
+ } catch (BundleException e) {
+ LOGGER.warn("Failed to update bundle: " + bundle + ". Reason: " + e, e);
+ }
+ }
+
+ for (Bundle bundle : bundlesToStart) {
+ try {
+ bundle.start();
+ LOGGER.info("Started: " + bundle);
+ } catch (BundleException e) {
+ LOGGER.warn("Failed to start bundle: " + bundle + ". Reason: " + e, e);
+ rescheduleStart(bundle);
+ }
+ }
+
+ PackageAdmin packageAdmin = getPackageAdmin();
+ if (packageAdmin != null) {
+ packageAdmin.refreshPackages(null);
+ }
+ }
+
+ private void rescheduleStart(Bundle bundle) {
+ synchronized (pendingStartBundles) {
+ pendingStartBundles.add(bundle);
+ if (bundleListener == null) {
+ bundleListener = new BundleListener() {
+ public void bundleChanged(BundleEvent event) {
+ if (event.getType() == BundleEvent.RESOLVED) {
+ executor.execute(new Runnable() {
+ public void run() {
+ retryPendingStartBundles();
+ }
+ });
+ } else if (event.getType() == BundleEvent.UNINSTALLED) {
+ // bundle was uninstalled meanwhile, so remove
+ // it from the list of pending bundles
+ pendingStartBundles.remove(event.getBundle());
+ }
+ }
+ };
+ getContext().addBundleListener(bundleListener);
+ }
+ }
+ }
+
+ protected void retryPendingStartBundles() {
+ synchronized (pendingStartBundles) {
+ Set<Bundle> bundles = new HashSet<Bundle>();
+ bundles.addAll(pendingStartBundles);
+ pendingStartBundles.clear();
+ boolean success = false;
+ for (Bundle bundle : bundles) {
+ try {
+ bundle.start();
+ LOGGER.info("Pending bundle started: " + bundle);
+ success = true;
+ } catch (BundleException e) {
+ LOGGER.info("Pending bundle not started: " + bundle);
+ pendingStartBundles.add(bundle);
+ }
+ }
+ if (success) {
+ PackageAdmin packageAdmin = getPackageAdmin();
+ if (packageAdmin != null) {
+ packageAdmin.refreshPackages(null);
+ }
+ }
+ }
+ }
+
+ protected File createBundleJar(File dir) throws BundleException, IOException {
+ File destFile = new File(generateDir, dir.getName() + ".jar");
+ if (destFile.exists()) {
+ undeployBundle(destFile);
+ destFile.delete();
+ }
+ JarUtil.jarDir(dir.getPath(), destFile.getPath());
+ return destFile;
+ }
+
+ /**
+ * Returns the root directory of the expanded OSGi bundle if the file is
+ * part of an expanded OSGi bundle or null if it is not
+ */
+ protected File getExpandedBundleRootDirectory(File file) throws IOException {
+ File parent = file.getParentFile();
+ if (file.isDirectory()) {
+ String rootPath = deployDir.getCanonicalPath();
+ if (file.getCanonicalPath().equals(rootPath)) {
+ return null;
+ }
+ if (containsManifest(file)) {
+ return file;
+ }
+ }
+ if (isValidBundleSourceDirectory(parent)) {
+ return getExpandedBundleRootDirectory(parent);
+ }
+ return null;
+ }
+
+ /**
+ * Returns true if the given directory is a valid child directory within the
+ * {@link #deployDir}
+ */
+ protected boolean isValidBundleSourceDirectory(File dir) throws IOException {
+ if (dir != null) {
+ String parentPath = dir.getCanonicalPath();
+ String rootPath = deployDir.getCanonicalPath();
+ return !parentPath.equals(rootPath) && parentPath.startsWith(rootPath);
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Returns true if the given directory is a valid child file within the
+ * {@link #deployDir} or a child of {@link #generateDir}
+ */
+ protected boolean isValidArtifactFile(File file) throws IOException {
+ if (file != null) {
+ String filePath = file.getParentFile().getCanonicalPath();
+ String deployPath = deployDir.getCanonicalPath();
+ String generatePath = generateDir.getCanonicalPath();
+ return filePath.equals(deployPath) || filePath.startsWith(generatePath);
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Returns true if the given directory is a valid child file within the
+ * {@link #configDir}
+ */
+ protected boolean isValidConfigFile(File file) throws IOException {
+ if (file != null && file.getName().endsWith(".cfg")) {
+ String filePath = file.getParentFile().getCanonicalPath();
+ String configPath = configDir.getCanonicalPath();
+ return filePath.equals(configPath);
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * Returns true if the given directory contains a valid manifest file
+ */
+ protected boolean containsManifest(File dir) {
+ File metaInfDir = new File(dir, "META-INF");
+ if (metaInfDir.exists() && metaInfDir.isDirectory()) {
+ File manifest = new File(metaInfDir, "MANIFEST.MF");
+ return manifest.exists() && !manifest.isDirectory();
+ }
+ return false;
+ }
+
+ @SuppressWarnings("unchecked")
+ protected File getFileValue(Dictionary properties, String key) {
+ Object value = properties.get(key);
+ if (value instanceof File) {
+ return (File)value;
+ } else if (value != null) {
+ return new File(value.toString());
+ }
+ return null;
+ }
+
+ @SuppressWarnings("unchecked")
+ protected Long getLongValue(Dictionary properties, String key) {
+ Object value = properties.get(key);
+ if (value instanceof Long) {
+ return (Long)value;
+ } else if (value != null) {
+ return Long.parseLong(value.toString());
+ }
+ return null;
+ }
+
+ protected void closeQuietly(Closeable in) {
+ try {
+ in.close();
+ } catch (IOException e) {
+ LOGGER.warn("Failed to close stream. " + e, e);
+ }
+ }
+
+ protected PreferencesService getPreferenceService() {
+ if (activator.getPreferenceServiceTracker() != null) {
+ try {
+ return (PreferencesService)activator.getPreferenceServiceTracker().waitForService(5000L);
+ } catch (InterruptedException e) {
+ // ignore
+ }
+ }
+ return null;
+ }
+
+ protected void saveScannerState() {
+ try {
+ Map<String, Long> results = scanner.getLastScanResults();
+ Preferences prefs = getPreferenceService().getUserPreferences(PREFERENCE_KEY).node(pid);
+ Iterator<String> it = results.keySet().iterator();
+ while (it.hasNext()) {
+ String key = it.next();
+ Long value = results.get(key);
+ prefs.putLong(key, value);
+ }
+ prefs.flush();
+ } catch (Exception e) {
+ LOGGER.error("Error persisting FileMonitor state", e);
+ }
+ }
+
+ protected void loadScannerState() {
+ try {
+ Preferences prefs = getPreferenceService().getUserPreferences(PREFERENCE_KEY).node(pid);
+ Map<String, Long> lastResult = new HashMap<String, Long>();
+ for (String key : prefs.keys()) {
+ lastResult.put(key, prefs.getLong(key, -1));
+ }
+ scanner.setLastScanResults(lastResult);
+ } catch (Exception e) {
+ LOGGER.error("Error loading FileMonitor state", e);
+ }
+ }
+}
Added: felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/FileMonitorActivator.java
URL: http://svn.apache.org/viewvc/felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/FileMonitorActivator.java?rev=770120&view=auto
==============================================================================
--- felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/FileMonitorActivator.java (added)
+++ felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/FileMonitorActivator.java Thu Apr 30 09:10:03 2009
@@ -0,0 +1,146 @@
+/**
+ *
+ * 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.servicemix.kernel.deployer.filemonitor;
+
+import java.util.Collection;
+import java.util.Dictionary;
+import java.util.HashMap;
+import java.util.Hashtable;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.framework.BundleActivator;
+import org.osgi.framework.BundleContext;
+import org.osgi.framework.Constants;
+import org.osgi.service.cm.ConfigurationAdmin;
+import org.osgi.service.cm.ConfigurationException;
+import org.osgi.service.cm.ManagedServiceFactory;
+import org.osgi.service.packageadmin.PackageAdmin;
+import org.osgi.service.prefs.PreferencesService;
+import org.osgi.util.tracker.ServiceTracker;
+
+/**
+ * Inspired by <a href="http://www.aqute.biz/Code/FileInstall">FileInstall</a>
+ * by Peter Kriens.
+ *
+ * @version $Revision: 1.1 $
+ */
+public class FileMonitorActivator implements BundleActivator, ManagedServiceFactory {
+ private static final Log LOGGER = LogFactory.getLog(FileMonitorActivator.class);
+
+ private BundleContext context;
+ private ServiceTracker packageAdminTracker;
+ private ServiceTracker configurationAdminTracker;
+ private ServiceTracker preferenceServiceTracker;
+ private Map<String, FileMonitor> fileMonitors = new HashMap<String, FileMonitor>();
+
+ // BundleActivator interface
+ // -------------------------------------------------------------------------
+ public void start(BundleContext context) throws Exception {
+ this.context = context;
+
+ Hashtable properties = new Hashtable();
+ properties.put(Constants.SERVICE_PID, getName());
+ context.registerService(ManagedServiceFactory.class.getName(), this, properties);
+
+ packageAdminTracker = new ServiceTracker(context, PackageAdmin.class.getName(), null);
+ packageAdminTracker.open();
+
+ configurationAdminTracker = new ServiceTracker(context, ConfigurationAdmin.class.getName(), null);
+ configurationAdminTracker.open();
+
+ preferenceServiceTracker = new ServiceTracker(context, PreferencesService.class.getName(), null);
+ preferenceServiceTracker.open();
+
+ Hashtable initialProperties = new Hashtable();
+ setPropertiesFromContext(initialProperties, FileMonitor.CONFIG_DIR, FileMonitor.DEPLOY_DIR,
+ FileMonitor.GENERATED_JAR_DIR, FileMonitor.SCAN_INTERVAL);
+ updated("initialPid", initialProperties);
+ }
+
+ public void stop(BundleContext context) throws Exception {
+ Collection<FileMonitor> fileMonitors = this.fileMonitors.values();
+ for (FileMonitor monitor : fileMonitors) {
+ try {
+ // stop the monitor
+ monitor.stop();
+ } catch (Exception e) {
+ // Ignore
+ }
+ }
+ this.fileMonitors.clear();
+
+ preferenceServiceTracker.close();
+ configurationAdminTracker.close();
+ packageAdminTracker.close();
+ }
+
+ // ManagedServiceFactory interface
+ // -------------------------------------------------------------------------
+ public String getName() {
+ return "org.apache.servicemix.kernel.deployer.filemonitor.FileMonitor";
+ }
+
+ public void updated(String pid, Dictionary properties) throws ConfigurationException {
+ deleted(pid);
+ FileMonitor monitor = new FileMonitor(this, properties, pid);
+ fileMonitors.put(pid, monitor);
+ monitor.start();
+ }
+
+ public void deleted(String pid) {
+ FileMonitor monitor = fileMonitors.remove(pid);
+ if (monitor != null) {
+ monitor.stop();
+ }
+ }
+
+ // Properties
+ // -------------------------------------------------------------------------
+ public BundleContext getContext() {
+ return context;
+ }
+
+ public ServiceTracker getConfigurationAdminTracker() {
+ return configurationAdminTracker;
+ }
+
+ public ServiceTracker getPackageAdminTracker() {
+ return packageAdminTracker;
+ }
+
+ public ConfigurationAdmin getConfigurationAdmin() {
+ return (ConfigurationAdmin)getConfigurationAdminTracker().getService();
+ }
+
+ public ServiceTracker getPreferenceServiceTracker() {
+ return preferenceServiceTracker;
+ }
+
+ // Implementation methods
+ // -------------------------------------------------------------------------
+ protected void setPropertiesFromContext(Hashtable properties, String... keys) {
+ for (String key : keys) {
+ Object value = context.getProperty(key);
+ if (value != null) {
+ properties.put(key, value);
+ }
+ }
+ }
+}
Added: felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/JarUtil.java
URL: http://svn.apache.org/viewvc/felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/JarUtil.java?rev=770120&view=auto
==============================================================================
--- felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/JarUtil.java (added)
+++ felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/JarUtil.java Thu Apr 30 09:10:03 2009
@@ -0,0 +1,122 @@
+/**
+ *
+ * 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.servicemix.kernel.deployer.filemonitor;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.util.Collections;
+import java.util.Set;
+import java.util.jar.JarFile;
+import java.util.jar.JarOutputStream;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipOutputStream;
+
+public class JarUtil {
+
+ /**
+ * Zip up a directory
+ *
+ * @param directory
+ * @param zipName
+ * @throws IOException
+ */
+ public static void zipDir(String directory, String zipName) throws IOException {
+ // create a ZipOutputStream to zip the data to
+ ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipName)));
+ String path = "";
+ zipDir(directory, zos, path, Collections.<String>emptySet());
+ // close the stream
+ zos.close();
+ }
+
+ /**
+ * Jar up a directory
+ *
+ * @param directory
+ * @param zipName
+ * @throws IOException
+ */
+ public static void jarDir(String directory, String zipName) throws IOException {
+ // create a ZipOutputStream to zip the data to
+ JarOutputStream zos = new JarOutputStream(new BufferedOutputStream(new FileOutputStream(zipName)));
+ String path = "";
+ File manFile = new File(directory, JarFile.MANIFEST_NAME);
+ if (manFile.exists()) {
+ byte[] readBuffer = new byte[8192];
+ FileInputStream fis = new FileInputStream(manFile);
+ try {
+ ZipEntry anEntry = new ZipEntry(JarFile.MANIFEST_NAME);
+ zos.putNextEntry(anEntry);
+ int bytesIn = fis.read(readBuffer);
+ while (bytesIn != -1) {
+ zos.write(readBuffer, 0, bytesIn);
+ bytesIn = fis.read(readBuffer);
+ }
+ } finally {
+ fis.close();
+ }
+ zos.closeEntry();
+ }
+ zipDir(directory, zos, path, Collections.singleton(JarFile.MANIFEST_NAME));
+ // close the stream
+ zos.close();
+ }
+
+ /**
+ * Zip up a directory path
+ * @param directory
+ * @param zos
+ * @param path
+ * @throws IOException
+ */
+ public static void zipDir(String directory, ZipOutputStream zos, String path, Set<String> exclusions) throws IOException {
+ File zipDir = new File(directory);
+ // get a listing of the directory content
+ String[] dirList = zipDir.list();
+ byte[] readBuffer = new byte[8192];
+ int bytesIn = 0;
+ // loop through dirList, and zip the files
+ for (int i = 0; i < dirList.length; i++) {
+ File f = new File(zipDir, dirList[i]);
+ if (f.isDirectory()) {
+ String filePath = f.getPath();
+ zipDir(filePath, zos, path + f.getName() + "/", exclusions);
+ continue;
+ }
+ String entry = path + f.getName();
+ if (!exclusions.contains(entry)) {
+ FileInputStream fis = new FileInputStream(f);
+ try {
+ ZipEntry anEntry = new ZipEntry(entry);
+ zos.putNextEntry(anEntry);
+ bytesIn = fis.read(readBuffer);
+ while (bytesIn != -1) {
+ zos.write(readBuffer, 0, bytesIn);
+ bytesIn = fis.read(readBuffer);
+ }
+ } finally {
+ fis.close();
+ }
+ }
+ }
+ }
+
+}
Added: felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/Scanner.java
URL: http://svn.apache.org/viewvc/felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/Scanner.java?rev=770120&view=auto
==============================================================================
--- felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/Scanner.java (added)
+++ felix/trunk/karaf/deployer/filemonitor/src/main/java/org/apache/servicemix/kernel/deployer/filemonitor/Scanner.java Thu Apr 30 09:10:03 2009
@@ -0,0 +1,455 @@
+//========================================================================
+//$Id: Scanner.java 2180 2007-10-31 04:01:26Z janb $
+//Copyright 2006 Mort Bay Consulting Pty. Ltd.
+//------------------------------------------------------------------------
+//Licensed 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.servicemix.kernel.deployer.filemonitor;
+
+import java.io.File;
+import java.io.FilenameFilter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.Timer;
+import java.util.TimerTask;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * Scanner
+ * <p/>
+ * Utility for scanning a directory for added, removed and changed files and
+ * reporting these events via registered Listeners.
+ * <p/>
+ * From the <a href="http://jetty.codehaus.org/">Jetty Util project</a>
+ *
+ * @version $Revision: 1.1 $
+ */
+public class Scanner {
+
+ private static Log logger = LogFactory.getLog(Scanner.class);
+ private long _scanInterval;
+ private List<Listener> _listeners = Collections.synchronizedList(new ArrayList<Listener>());
+ private Map<String, Long> _prevScan = new HashMap<String, Long>();
+ private FilenameFilter _filter;
+ private List<File> _scanDirs;
+ private volatile boolean _running = false;
+ private boolean _reportExisting = true;
+ private Timer _timer;
+ private TimerTask _task;
+
+ /**
+ * Listener
+ * <p/>
+ * Marker for notifications re file changes.
+ */
+ public interface Listener {
+ }
+
+ public interface DiscreteListener extends Listener {
+ public void fileChanged(String filename) throws Exception;
+
+ public void fileAdded(String filename) throws Exception;
+
+ public void fileRemoved(String filename) throws Exception;
+ }
+
+ public interface BulkListener extends Listener {
+ public void filesChanged(List<String> filenames) throws Exception;
+ }
+
+ /**
+ *
+ */
+ public Scanner() {
+ }
+
+ /**
+ * Get the scan interval
+ *
+ * @return interval between scans in millis
+ */
+ public long getScanInterval() {
+ return _scanInterval;
+ }
+
+ /**
+ * Set the scan interval
+ *
+ * @param scanInterval pause between scans in millis
+ */
+ public synchronized void setScanInterval(long scanInterval) {
+ this._scanInterval = scanInterval;
+
+ if (_running) {
+ stop();
+
+ _timer = newTimer();
+ _task = newTimerTask();
+
+ schedule(_timer, _task);
+ _running = true;
+ }
+ }
+
+ /**
+ * Set the location of the directory to scan.
+ *
+ * @param dir
+ * @deprecated use setScanDirs(List dirs) instead
+ */
+ public void setScanDir(File dir) {
+ _scanDirs = new ArrayList<File>();
+ _scanDirs.add(dir);
+ }
+
+ /**
+ * Get the location of the directory to scan
+ *
+ * @return
+ * @deprecated use getScanDirs() instead
+ */
+ public File getScanDir() {
+ return (_scanDirs == null ? null : (File)_scanDirs.get(0));
+ }
+
+ public void setScanDirs(List<File> dirs) {
+ _scanDirs = dirs;
+ }
+
+ public List<File> getScanDirs() {
+ return _scanDirs;
+ }
+
+ /**
+ * Apply a filter to files found in the scan directory. Only files matching
+ * the filter will be reported as added/changed/removed.
+ *
+ * @param filter
+ */
+ public void setFilenameFilter(FilenameFilter filter) {
+ this._filter = filter;
+ }
+
+ /**
+ * Get any filter applied to files in the scan dir.
+ *
+ * @return
+ */
+ public FilenameFilter getFilenameFilter() {
+ return _filter;
+ }
+
+ /**
+ * Whether or not an initial scan will report all files as being added.
+ *
+ * @param reportExisting if true, all files found on initial scan will be
+ * reported as being added, otherwise not
+ */
+ public void setReportExistingFilesOnStartup(boolean reportExisting) {
+ this._reportExisting = reportExisting;
+ }
+
+ /**
+ * Add an added/removed/changed listener
+ *
+ * @param listener
+ */
+ public synchronized void addListener(Listener listener) {
+ if (listener == null) {
+ return;
+ }
+
+ _listeners.add(listener);
+ }
+
+ /**
+ * Remove a registered listener
+ *
+ * @param listener the Listener to be removed
+ */
+ public synchronized void removeListener(Listener listener) {
+ if (listener == null) {
+ return;
+ }
+ _listeners.remove(listener);
+ }
+
+ /**
+ * Start the scanning action.
+ */
+ public synchronized void start() {
+ if (_running) {
+ return;
+ }
+
+ _running = true;
+
+ if (_reportExisting) {
+ // if files exist at startup, report them
+ scan();
+ } else {
+ // just register the list of existing files and only report changes
+ _prevScan = scanFiles();
+ }
+
+ _timer = newTimer();
+ _task = newTimerTask();
+
+ schedule(_timer, _task);
+ }
+
+ public TimerTask newTimerTask() {
+ return new TimerTask() {
+ public void run() {
+ scan();
+ }
+ };
+ }
+
+ public Timer newTimer() {
+ return new Timer(true);
+ }
+
+ public void schedule(Timer timer, TimerTask task) {
+ if (timer == null) {
+ throw new IllegalArgumentException("Timer is null");
+ }
+ if (task == null) {
+ throw new IllegalArgumentException("TimerTask is null");
+ }
+
+ if (getScanInterval() > 0) {
+ timer.scheduleAtFixedRate(task, getScanInterval(), getScanInterval());
+ }
+ }
+
+ /**
+ * Stop the scanning.
+ */
+ public synchronized void stop() {
+ if (_running) {
+ _running = false;
+ _timer.cancel();
+ _task.cancel();
+ _task = null;
+ _timer = null;
+ }
+ }
+
+ /**
+ * Perform a pass of the scanner and report changes
+ */
+ public void scan() {
+ Map<String, Long> currentScan = scanFiles();
+ reportDifferences(currentScan, _prevScan);
+ _prevScan = currentScan;
+ }
+
+ /**
+ * Recursively scan all files in the designated directories.
+ *
+ * @return Map of name of file to last modified time
+ */
+ public Map<String, Long> scanFiles() {
+ if (_scanDirs == null) {
+ return Collections.emptyMap();
+ }
+
+ HashMap<String, Long> scanInfo = new HashMap<String, Long>();
+ Iterator<File> itor = _scanDirs.iterator();
+ while (itor.hasNext()) {
+ File dir = (File)itor.next();
+
+ if ((dir != null) && (dir.exists())) {
+ scanFile(dir, scanInfo);
+ }
+ }
+
+ return scanInfo;
+ }
+
+ /**
+ * Report the adds/changes/removes to the registered listeners
+ *
+ * @param currentScan the info from the most recent pass
+ * @param oldScan info from the previous pass
+ */
+ public void reportDifferences(Map<String, Long> currentScan, Map<String, Long> oldScan) {
+ List<String> bulkChanges = new ArrayList<String>();
+
+ Set<String> oldScanKeys = new HashSet<String>(oldScan.keySet());
+ Iterator<Map.Entry<String, Long>> itor = currentScan.entrySet().iterator();
+ while (itor.hasNext()) {
+ Map.Entry<String, Long> entry = itor.next();
+ if (!oldScanKeys.contains(entry.getKey())) {
+ logger.debug("File added: " + entry.getKey());
+ reportAddition(entry.getKey());
+ bulkChanges.add(entry.getKey());
+ } else if (!oldScan.get(entry.getKey()).equals(entry.getValue())) {
+ logger.debug("File changed: " + entry.getKey());
+ reportChange(entry.getKey());
+ oldScanKeys.remove(entry.getKey());
+ bulkChanges.add(entry.getKey());
+ } else {
+ oldScanKeys.remove(entry.getKey());
+ }
+ }
+
+ if (!oldScanKeys.isEmpty()) {
+
+ Iterator<String> keyItor = oldScanKeys.iterator();
+ while (keyItor.hasNext()) {
+ String filename = keyItor.next();
+ logger.debug("File removed: " + filename);
+ reportRemoval(filename);
+ bulkChanges.add(filename);
+ }
+ }
+
+ if (!bulkChanges.isEmpty()) {
+ reportBulkChanges(bulkChanges);
+ }
+ }
+
+ /**
+ * Get last modified time on a single file or recurse if the file is a
+ * directory.
+ *
+ * @param f file or directory
+ * @param scanInfoMap map of filenames to last modified times
+ */
+ private void scanFile(File f, Map<String, Long> scanInfoMap) {
+ try {
+ if (!f.exists()) {
+ return;
+ }
+
+ if (f.isFile()) {
+ if ((_filter == null)
+ || ((_filter != null) && _filter.accept(f.getParentFile(), f.getName()))) {
+ String name = f.getCanonicalPath();
+ long lastModified = f.lastModified();
+ scanInfoMap.put(name, new Long(lastModified));
+ }
+ } else if (f.isDirectory()) {
+ File[] files = f.listFiles();
+ for (int i = 0; i < files.length; i++) {
+ scanFile(files[i], scanInfoMap);
+ }
+ }
+ } catch (IOException e) {
+ logger.warn("Error scanning watched files", e);
+ }
+ }
+
+ /**
+ * Report a file addition to the registered FileAddedListeners
+ *
+ * @param filename
+ */
+ private void reportAddition(String filename) {
+ Iterator<Listener> itor = _listeners.iterator();
+ while (itor.hasNext()) {
+ try {
+ Listener l = itor.next();
+ if (l instanceof DiscreteListener) {
+ ((DiscreteListener)l).fileAdded(filename);
+ }
+ } catch (Exception e) {
+ logger.warn(e);
+ } catch (Error e) {
+ logger.warn(e);
+ }
+ }
+ }
+
+ /**
+ * Report a file removal to the FileRemovedListeners
+ *
+ * @param filename
+ */
+ private void reportRemoval(String filename) {
+ Iterator<Listener> itor = _listeners.iterator();
+ while (itor.hasNext()) {
+ try {
+ Listener l = itor.next();
+ if (l instanceof DiscreteListener) {
+ ((DiscreteListener)l).fileRemoved(filename);
+ }
+ } catch (Exception e) {
+ logger.warn(e);
+ } catch (Error e) {
+ logger.warn(e);
+ }
+ }
+ }
+
+ /**
+ * Report a file change to the FileChangedListeners
+ *
+ * @param filename
+ */
+ private void reportChange(String filename) {
+ Iterator<Listener> itor = _listeners.iterator();
+ while (itor.hasNext()) {
+ try {
+ Listener l = itor.next();
+ if (l instanceof DiscreteListener) {
+ ((DiscreteListener)l).fileChanged(filename);
+ }
+ } catch (Exception e) {
+ logger.warn(e);
+ } catch (Error e) {
+ logger.warn(e);
+ }
+ }
+ }
+
+ private void reportBulkChanges(List<String> filenames) {
+ Iterator<Listener> itor = _listeners.iterator();
+ while (itor.hasNext()) {
+ try {
+ Listener l = itor.next();
+ if (l instanceof BulkListener) {
+ ((BulkListener)l).filesChanged(filenames);
+ }
+ } catch (Exception e) {
+ logger.warn(e);
+ } catch (Error e) {
+ logger.warn(e);
+ }
+ }
+ }
+
+ protected Map<String, Long> getLastScanResults() {
+ Map<String, Long> result = new HashMap<String, Long>();
+ synchronized (_prevScan) {
+ result.putAll(_prevScan);
+ }
+ return result;
+ }
+
+ protected void setLastScanResults(Map<String, Long> results) {
+ synchronized (_prevScan) {
+ _prevScan.clear();
+ _prevScan.putAll(results);
+ }
+ }
+}
Added: felix/trunk/karaf/deployer/filemonitor/src/test/java/org/apache/servicemix/kernel/deployer/filemonitor/BundlePackerTest.java
URL: http://svn.apache.org/viewvc/felix/trunk/karaf/deployer/filemonitor/src/test/java/org/apache/servicemix/kernel/deployer/filemonitor/BundlePackerTest.java?rev=770120&view=auto
==============================================================================
--- felix/trunk/karaf/deployer/filemonitor/src/test/java/org/apache/servicemix/kernel/deployer/filemonitor/BundlePackerTest.java (added)
+++ felix/trunk/karaf/deployer/filemonitor/src/test/java/org/apache/servicemix/kernel/deployer/filemonitor/BundlePackerTest.java Thu Apr 30 09:10:03 2009
@@ -0,0 +1,45 @@
+/**
+ *
+ * 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.servicemix.kernel.deployer.filemonitor;
+
+import java.io.File;
+
+import junit.framework.TestCase;
+import org.apache.commons.io.FileUtils;
+
+/**
+ * @version $Revision: 1.1 $
+ */
+public class BundlePackerTest extends TestCase {
+ public void testFiles() throws Exception {
+ File bundleDir = new File("target/deploy");
+ File unpackDir = new File("target/data");
+ FileUtils.deleteDirectory(unpackDir);
+
+ bundleDir.mkdirs();
+ unpackDir.mkdirs();
+
+ FileUtils.copyDirectory(new File("src/test/data"), unpackDir);
+
+/*
+ FileMonitor packer = new FileMonitor(bundleDir, unpackDir);
+ packer.scan();
+*/
+ }
+
+}
Added: felix/trunk/karaf/deployer/filemonitor/src/test/java/org/apache/servicemix/kernel/deployer/filemonitor/FileMonitorTest.java
URL: http://svn.apache.org/viewvc/felix/trunk/karaf/deployer/filemonitor/src/test/java/org/apache/servicemix/kernel/deployer/filemonitor/FileMonitorTest.java?rev=770120&view=auto
==============================================================================
--- felix/trunk/karaf/deployer/filemonitor/src/test/java/org/apache/servicemix/kernel/deployer/filemonitor/FileMonitorTest.java (added)
+++ felix/trunk/karaf/deployer/filemonitor/src/test/java/org/apache/servicemix/kernel/deployer/filemonitor/FileMonitorTest.java Thu Apr 30 09:10:03 2009
@@ -0,0 +1,100 @@
+/**
+ *
+ * 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.servicemix.kernel.deployer.filemonitor;
+
+import junit.framework.TestCase;
+import org.apache.servicemix.kernel.deployer.filemonitor.FileMonitor;
+
+/**
+ * FileMonitor Tester.
+ *
+ * @author <Authors name>
+ * @version 1.0
+ * @since <pre>07/02/2008</pre>
+ */
+public class FileMonitorTest extends TestCase {
+
+ public FileMonitorTest(String name) {
+ super(name);
+ }
+
+ public void setUp() throws Exception {
+ super.setUp();
+ }
+
+ public void tearDown() throws Exception {
+ super.tearDown();
+ }
+
+ public void testFilePathsMatch() throws Exception {
+ assertTrue(FileMonitor.filePathsMatch(
+ "C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt",
+ "C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt"));
+
+ assertTrue(FileMonitor.filePathsMatch(
+ "C:\\Apps\\apache-servicemix-kernel-1.0.0-rc1\\src\\README.txt",
+ "C:\\Apps\\apache-servicemix-kernel-1.0.0-rc1\\src\\README.txt"));
+
+ assertTrue(FileMonitor.filePathsMatch(
+ "C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt",
+ "C:\\Apps\\apache-servicemix-kernel-1.0.0-rc1\\src\\README.txt"));
+
+ assertTrue(FileMonitor.filePathsMatch(
+ "file:/C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt",
+ "C:\\Apps\\apache-servicemix-kernel-1.0.0-rc1\\src\\README.txt"));
+
+ assertTrue(FileMonitor.filePathsMatch(
+ "file://C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt",
+ "C:\\Apps\\apache-servicemix-kernel-1.0.0-rc1\\src\\README.txt"));
+ }
+
+ public void testNormalizeFilePath() throws Exception {
+ assertEquals(
+ "C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt",
+ FileMonitor.normalizeFilePath("C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt"));
+
+ assertEquals(
+ "C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt",
+ FileMonitor.normalizeFilePath("C:/Apps//apache-servicemix-kernel-1.0.0-rc1////src/////README.txt"));
+
+ assertEquals(
+ "C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt",
+ FileMonitor.normalizeFilePath("C:\\Apps\\apache-servicemix-kernel-1.0.0-rc1\\src\\README.txt"));
+
+ assertEquals(
+ "C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt",
+ FileMonitor.normalizeFilePath("C:\\\\Apps\\\\apache-servicemix-kernel-1.0.0-rc1\\\\src\\\\README.txt"));
+
+ assertEquals(
+ "C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt",
+ FileMonitor.normalizeFilePath("C:\\Apps\\//apache-servicemix-kernel-1.0.0-rc1\\/\\src///\\\\README.txt"));
+
+ assertEquals(
+ "C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt",
+ FileMonitor.normalizeFilePath("file:C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt"));
+
+ assertEquals(
+ "C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt",
+ FileMonitor.normalizeFilePath("file:/C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt"));
+
+ assertEquals(
+ "C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt",
+ FileMonitor.normalizeFilePath("file://C:/Apps/apache-servicemix-kernel-1.0.0-rc1/src/README.txt"));
+ }
+
+}
Added: felix/trunk/karaf/deployer/pom.xml
URL: http://svn.apache.org/viewvc/felix/trunk/karaf/deployer/pom.xml?rev=770120&view=auto
==============================================================================
--- felix/trunk/karaf/deployer/pom.xml (added)
+++ felix/trunk/karaf/deployer/pom.xml Thu Apr 30 09:10:03 2009
@@ -0,0 +1,43 @@
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <!--
+
+ 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.
+ -->
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <parent>
+ <groupId>org.apache.servicemix.kernel</groupId>
+ <artifactId>kernel</artifactId>
+ <version>1.2.0-SNAPSHOT</version>
+ </parent>
+
+ <groupId>org.apache.servicemix.kernel.deployer</groupId>
+ <artifactId>deployer</artifactId>
+ <packaging>pom</packaging>
+ <version>1.2.0-SNAPSHOT</version>
+ <name>Apache ServiceMix Kernel :: Deployer</name>
+
+ <modules>
+ <module>filemonitor</module>
+ <module>spring</module>
+ <module>blueprint</module>
+ <module>features</module>
+ </modules>
+
+</project>
\ No newline at end of file
Modified: felix/trunk/karaf/deployer/spring/pom.xml
URL: http://svn.apache.org/viewvc/felix/trunk/karaf/deployer/spring/pom.xml?rev=770120&r1=770090&r2=770120&view=diff
==============================================================================
--- felix/trunk/karaf/deployer/spring/pom.xml (original)
+++ felix/trunk/karaf/deployer/spring/pom.xml Thu Apr 30 09:10:03 2009
@@ -27,8 +27,8 @@
<version>1.2.0-SNAPSHOT</version>
</parent>
- <groupId>org.apache.servicemix.kernel</groupId>
- <artifactId>org.apache.servicemix.kernel.spring</artifactId>
+ <groupId>org.apache.servicemix.kernel.deployer</groupId>
+ <artifactId>org.apache.servicemix.kernel.deployer.spring</artifactId>
<packaging>bundle</packaging>
<version>1.2.0-SNAPSHOT</version>
<name>Apache ServiceMix Kernel :: Spring Deployer</name>
@@ -46,8 +46,8 @@
<artifactId>spring-osgi-core</artifactId>
</dependency>
<dependency>
- <groupId>org.apache.servicemix.kernel</groupId>
- <artifactId>org.apache.servicemix.kernel.filemonitor</artifactId>
+ <groupId>org.apache.servicemix.kernel.deployer</groupId>
+ <artifactId>org.apache.servicemix.kernel.deployer.filemonitor</artifactId>
</dependency>
<dependency>
<groupId>org.apache.servicemix.bundles</groupId>
Added: felix/trunk/karaf/deployer/spring/src/main/java/org/apache/servicemix/kernel/deployer/spring/SpringDeploymentListener.java
URL: http://svn.apache.org/viewvc/felix/trunk/karaf/deployer/spring/src/main/java/org/apache/servicemix/kernel/deployer/spring/SpringDeploymentListener.java?rev=770120&view=auto
==============================================================================
--- felix/trunk/karaf/deployer/spring/src/main/java/org/apache/servicemix/kernel/deployer/spring/SpringDeploymentListener.java (added)
+++ felix/trunk/karaf/deployer/spring/src/main/java/org/apache/servicemix/kernel/deployer/spring/SpringDeploymentListener.java Thu Apr 30 09:10:03 2009
@@ -0,0 +1,80 @@
+/**
+ *
+ * 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.servicemix.kernel.deployer.spring;
+
+import java.io.File;
+import java.io.FileOutputStream;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+
+import org.w3c.dom.Document;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.servicemix.kernel.deployer.filemonitor.DeploymentListener;
+
+/**
+ * A deployment listener that listens for spring xml applications
+ * and creates bundles for these.
+ */
+public class SpringDeploymentListener implements DeploymentListener {
+
+ private static final Log LOGGER = LogFactory.getLog(SpringDeploymentListener.class);
+
+ private DocumentBuilderFactory dbf;
+
+ public boolean canHandle(File artifact) {
+ try {
+ if (artifact.isFile() && artifact.getName().endsWith(".xml")) {
+ Document doc = parse(artifact);
+ String name = doc.getDocumentElement().getLocalName();
+ String uri = doc.getDocumentElement().getNamespaceURI();
+ if ("beans".equals(name) && "http://www.springframework.org/schema/beans".equals(uri)) {
+ return true;
+ }
+ }
+ } catch (Exception e) {
+ LOGGER.error("Unable to parse deployed file " + artifact.getAbsolutePath(), e);
+ }
+ return false;
+ }
+
+ public File handle(File artifact, File tmpDir) {
+ try {
+ File destFile = new File(tmpDir, artifact.getName() + ".jar");
+ FileOutputStream os = new FileOutputStream(destFile);
+ SpringTransformer.transform(artifact.toURL(), os);
+ os.close();
+ return destFile;
+ } catch (Exception e) {
+ LOGGER.error("Unable to build spring application bundle", e);
+ return null;
+ }
+ }
+
+ protected Document parse(File artifact) throws Exception {
+ if (dbf == null) {
+ dbf = DocumentBuilderFactory.newInstance();
+ dbf.setNamespaceAware(true);
+ }
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ return db.parse(artifact);
+ }
+
+}
Added: felix/trunk/karaf/deployer/spring/src/main/java/org/apache/servicemix/kernel/deployer/spring/SpringTransformer.java
URL: http://svn.apache.org/viewvc/felix/trunk/karaf/deployer/spring/src/main/java/org/apache/servicemix/kernel/deployer/spring/SpringTransformer.java?rev=770120&view=auto
==============================================================================
--- felix/trunk/karaf/deployer/spring/src/main/java/org/apache/servicemix/kernel/deployer/spring/SpringTransformer.java (added)
+++ felix/trunk/karaf/deployer/spring/src/main/java/org/apache/servicemix/kernel/deployer/spring/SpringTransformer.java Thu Apr 30 09:10:03 2009
@@ -0,0 +1,249 @@
+/**
+ *
+ * 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.servicemix.kernel.deployer.spring;
+
+import java.io.BufferedReader;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.net.URL;
+import java.util.Enumeration;
+import java.util.Properties;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.jar.JarFile;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.zip.ZipEntry;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.transform.Result;
+import javax.xml.transform.Source;
+import javax.xml.transform.Transformer;
+import javax.xml.transform.TransformerFactory;
+import javax.xml.transform.dom.DOMSource;
+import javax.xml.transform.stream.StreamResult;
+import javax.xml.transform.stream.StreamSource;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+import org.osgi.framework.Constants;
+
+public class SpringTransformer {
+
+ static Transformer transformer;
+ static DocumentBuilderFactory dbf;
+ static TransformerFactory tf;
+
+
+ public static void transform(URL url, OutputStream os) throws Exception {
+ // Build dom document
+ Document doc = parse(url);
+ // Heuristicly retrieve name and version
+ String name = url.getPath();
+ int idx = name.lastIndexOf('/');
+ if (idx >= 0) {
+ name = name.substring(idx + 1);
+ }
+ String[] str = extractNameVersionType(name);
+ // Create manifest
+ Manifest m = new Manifest();
+ m.getMainAttributes().putValue("Manifest-Version", "2");
+ m.getMainAttributes().putValue(Constants.BUNDLE_MANIFESTVERSION, "2");
+ m.getMainAttributes().putValue(Constants.BUNDLE_SYMBOLICNAME, str[0]);
+ m.getMainAttributes().putValue(Constants.BUNDLE_VERSION, str[1]);
+ m.getMainAttributes().putValue("Spring-Context", "*;publish-context:=false;create-asynchronously:=true");
+ String importPkgs = getImportPackages(analyze(new DOMSource(doc)));
+ if (importPkgs != null && importPkgs.length() > 0) {
+ m.getMainAttributes().putValue(Constants.IMPORT_PACKAGE, importPkgs);
+ }
+ m.getMainAttributes().putValue(Constants.DYNAMICIMPORT_PACKAGE, "*");
+ // Extract manifest entries from the DOM
+ NodeList l = doc.getElementsByTagName("manifest");
+ if (l != null) {
+ for (int i = 0; i < l.getLength(); i++) {
+ Element e = (Element) l.item(i);
+ String text = e.getTextContent();
+ Properties props = new Properties();
+ props.load(new ByteArrayInputStream(text.trim().getBytes()));
+ Enumeration en = props.propertyNames();
+ while (en.hasMoreElements()) {
+ String k = (String) en.nextElement();
+ String v = props.getProperty(k);
+ m.getMainAttributes().putValue(k, v);
+ }
+ e.getParentNode().removeChild(e);
+ }
+ }
+
+ JarOutputStream out = new JarOutputStream(os);
+ ZipEntry e = new ZipEntry(JarFile.MANIFEST_NAME);
+ out.putNextEntry(e);
+ m.write(out);
+ out.closeEntry();
+ e = new ZipEntry("META-INF/");
+ out.putNextEntry(e);
+ e = new ZipEntry("META-INF/spring/");
+ out.putNextEntry(e);
+ out.closeEntry();
+ e = new ZipEntry("META-INF/spring/" + name);
+ out.putNextEntry(e);
+ // Copy the new DOM
+ if (tf == null) {
+ tf = TransformerFactory.newInstance();
+ }
+ tf.newTransformer().transform(new DOMSource(doc), new StreamResult(out));
+ out.closeEntry();
+ out.close();
+ }
+
+ private static final String DEFAULT_VERSION = "0.0.0";
+
+ private static final Pattern ARTIFACT_MATCHER = Pattern.compile("(.+)(?:-(\\d+)(?:\\.(\\d+)(?:\\.(\\d+))?)?(?:[^a-zA-Z0-9](.*))?)(?:\\.([^\\.]+))", Pattern.DOTALL);
+ private static final Pattern FUZZY_MODIFIDER = Pattern.compile("(?:\\d+[.-])*(.*)", Pattern.DOTALL);
+
+ public static String[] extractNameVersionType(String url) {
+ Matcher m = ARTIFACT_MATCHER.matcher(url);
+ if (!m.matches()) {
+ return new String[] { url, DEFAULT_VERSION };
+ }
+ else {
+ //System.err.println(m.groupCount());
+ //for (int i = 1; i <= m.groupCount(); i++) {
+ // System.err.println("Group " + i + ": " + m.group(i));
+ //}
+
+ StringBuffer v = new StringBuffer();
+ String d1 = m.group(1);
+ String d2 = m.group(2);
+ String d3 = m.group(3);
+ String d4 = m.group(4);
+ String d5 = m.group(5);
+ String d6 = m.group(6);
+ if (d2 != null) {
+ v.append(d2);
+ if (d3 != null) {
+ v.append('.');
+ v.append(d3);
+ if (d4 != null) {
+ v.append('.');
+ v.append(d4);
+ if (d5 != null) {
+ v.append(".");
+ cleanupModifier(v, d5);
+ }
+ } else if (d5 != null) {
+ v.append(".0.");
+ cleanupModifier(v, d5);
+ }
+ } else if (d5 != null) {
+ v.append(".0.0.");
+ cleanupModifier(v, d5);
+ }
+ }
+ return new String[] { d1, v.toString(), d6 };
+ }
+ }
+
+ private static void cleanupModifier(StringBuffer result, String modifier) {
+ Matcher m = FUZZY_MODIFIDER.matcher(modifier);
+ if (m.matches()) {
+ modifier = m.group(1);
+ }
+ for (int i = 0; i < modifier.length(); i++) {
+ char c = modifier.charAt(i);
+ if ((c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == '-') {
+ result.append(c);
+ }
+ }
+ }
+
+ public static Set<String> analyze(Source source) throws Exception {
+ if (transformer == null) {
+ if (tf == null) {
+ tf = TransformerFactory.newInstance();
+ }
+ Source s = new StreamSource(SpringTransformer.class.getResourceAsStream("extract.xsl"));
+ transformer = tf.newTransformer(s);
+ }
+
+ Set<String> refers = new TreeSet<String>();
+
+ ByteArrayOutputStream bout = new ByteArrayOutputStream();
+ Result r = new StreamResult(bout);
+ transformer.transform(source, r);
+
+ ByteArrayInputStream bin = new ByteArrayInputStream(bout.toByteArray());
+ bout.close();
+
+ BufferedReader br = new BufferedReader(new InputStreamReader(bin));
+
+ String line = br.readLine();
+ while (line != null) {
+ line = line.trim();
+ if (line.length() > 0) {
+ String parts[] = line.split("\\s*,\\s*");
+ for (int i = 0; i < parts.length; i++) {
+ int n = parts[i].lastIndexOf('.');
+ if (n > 0) {
+ refers.add(parts[i].substring(0, n));
+ }
+ }
+ }
+ line = br.readLine();
+ }
+ br.close();
+ return refers;
+ }
+
+ protected static String getImportPackages(Set<String> packages) {
+ StringBuilder sb = new StringBuilder();
+ for (String pkg : packages) {
+ if (sb.length() > 0) {
+ sb.append(",");
+ }
+ sb.append(pkg);
+ }
+ return sb.toString();
+ }
+
+ protected static Document parse(URL url) throws Exception {
+ if (dbf == null) {
+ dbf = DocumentBuilderFactory.newInstance();
+ dbf.setNamespaceAware(true);
+ }
+ DocumentBuilder db = dbf.newDocumentBuilder();
+ return db.parse(url.toString());
+ }
+
+ protected static void copyInputStream(InputStream in, OutputStream out) throws Exception {
+ byte[] buffer = new byte[4096];
+ int len = in.read(buffer);
+ while (len >= 0) {
+ out.write(buffer, 0, len);
+ len = in.read(buffer);
+ }
+ }
+}
Added: felix/trunk/karaf/deployer/spring/src/main/java/org/apache/servicemix/kernel/deployer/spring/SpringURLHandler.java
URL: http://svn.apache.org/viewvc/felix/trunk/karaf/deployer/spring/src/main/java/org/apache/servicemix/kernel/deployer/spring/SpringURLHandler.java?rev=770120&view=auto
==============================================================================
--- felix/trunk/karaf/deployer/spring/src/main/java/org/apache/servicemix/kernel/deployer/spring/SpringURLHandler.java (added)
+++ felix/trunk/karaf/deployer/spring/src/main/java/org/apache/servicemix/kernel/deployer/spring/SpringURLHandler.java Thu Apr 30 09:10:03 2009
@@ -0,0 +1,97 @@
+/**
+ *
+ * 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.servicemix.kernel.deployer.spring;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.osgi.service.url.AbstractURLStreamHandlerService;
+
+/**
+ * A URL handler that will transform a JBI artifact to an OSGi bundle
+ * on the fly. Needs to be registered in the OSGi registry.
+ */
+public class SpringURLHandler extends AbstractURLStreamHandlerService {
+
+ private static Log logger = LogFactory.getLog(SpringURLHandler.class);
+
+ private static String SYNTAX = "spring: spring-xml-uri";
+
+ private URL springXmlURL;
+
+ /**
+ * Open the connection for the given URL.
+ *
+ * @param url the url from which to open a connection.
+ * @return a connection on the specified URL.
+ * @throws IOException if an error occurs or if the URL is malformed.
+ */
+ @Override
+ public URLConnection openConnection(URL url) throws IOException {
+ if (url.getPath() == null || url.getPath().trim().length() == 0) {
+ throw new MalformedURLException ("Path can not be null or empty. Syntax: " + SYNTAX );
+ }
+ springXmlURL = new URL(url.getPath());
+
+ logger.debug("Spring xml URL is: [" + springXmlURL + "]");
+ return new Connection(url);
+ }
+
+ public URL getSpringXmlURL() {
+ return springXmlURL;
+ }
+
+ public class Connection extends URLConnection {
+
+ public Connection(URL url) {
+ super(url);
+ }
+
+ @Override
+ public void connect() throws IOException {
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException {
+ try {
+ final File f = File.createTempFile("smx", "xml");
+ FileOutputStream os = new FileOutputStream(f);
+ SpringTransformer.transform(springXmlURL, os);
+ os.close();
+ return new FileInputStream(f) {
+ public void close() throws IOException {
+ super.close();
+ f.delete();
+ }
+ };
+ } catch (Exception e) {
+ logger.error("Error opening spring xml url", e);
+ throw (IOException) new IOException("Error opening spring xml url").initCause(e);
+ }
+ }
+ }
+
+}
Modified: felix/trunk/karaf/deployer/spring/src/main/resources/META-INF/spring/spring-deployer.xml
URL: http://svn.apache.org/viewvc/felix/trunk/karaf/deployer/spring/src/main/resources/META-INF/spring/spring-deployer.xml?rev=770120&r1=770090&r2=770120&view=diff
==============================================================================
--- felix/trunk/karaf/deployer/spring/src/main/resources/META-INF/spring/spring-deployer.xml (original)
+++ felix/trunk/karaf/deployer/spring/src/main/resources/META-INF/spring/spring-deployer.xml Thu Apr 30 09:10:03 2009
@@ -29,17 +29,17 @@
http://www.springframework.org/schema/osgi
http://www.springframework.org/schema/osgi/spring-osgi.xsd">
- <bean id="springDeploymentListener" class="org.apache.servicemix.kernel.spring.SpringDeploymentListener">
+ <bean id="springDeploymentListener" class="org.apache.servicemix.kernel.deployer.spring.SpringDeploymentListener">
</bean>
<osgi:service ref="springDeploymentListener">
<osgi:interfaces>
- <value>org.apache.servicemix.kernel.filemonitor.DeploymentListener</value>
+ <value>org.apache.servicemix.kernel.deployer.filemonitor.DeploymentListener</value>
</osgi:interfaces>
</osgi:service>
- <bean id="springHandler" class="org.apache.servicemix.kernel.spring.SpringURLHandler" />
+ <bean id="springHandler" class="org.apache.servicemix.kernel.deployer.spring.SpringURLHandler" />
<osgi:service ref="springHandler" interface="org.osgi.service.url.URLStreamHandlerService">
<osgi:service-properties>
Added: felix/trunk/karaf/deployer/spring/src/main/resources/org/apache/servicemix/kernel/deployer/spring/extract.xsl
URL: http://svn.apache.org/viewvc/felix/trunk/karaf/deployer/spring/src/main/resources/org/apache/servicemix/kernel/deployer/spring/extract.xsl?rev=770120&view=auto
==============================================================================
--- felix/trunk/karaf/deployer/spring/src/main/resources/org/apache/servicemix/kernel/deployer/spring/extract.xsl (added)
+++ felix/trunk/karaf/deployer/spring/src/main/resources/org/apache/servicemix/kernel/deployer/spring/extract.xsl Thu Apr 30 09:10:03 2009
@@ -0,0 +1,79 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+
+ 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.
+
+-->
+<xsl:stylesheet version="1.0"
+ xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
+ xmlns:beans="http://www.springframework.org/schema/beans"
+ xmlns:aop="http://www.springframework.org/schema/aop"
+ xmlns:context="http://www.springframework.org/schema/context"
+ xmlns:jee="http://www.springframework.org/schema/jee"
+ xmlns:jms="http://www.springframework.org/schema/jms"
+ xmlns:lang="http://www.springframework.org/schema/lang"
+ xmlns:osgi-compendium="http://www.springframework.org/schema/osgi-compendium"
+ xmlns:osgi="http://www.springframework.org/schema/osgi"
+ xmlns:tool="http://www.springframework.org/schema/tool"
+ xmlns:tx="http://www.springframework.org/schema/tx"
+ xmlns:util="http://www.springframework.org/schema/util"
+ xmlns:webflow-config="http://www.springframework.org/schema/webflow-config">
+
+ <xsl:output method="text" />
+
+ <xsl:template match="/">
+
+ <!-- Match all attributes that holds a class or a comma delimited
+ list of classes and print them -->
+
+ <xsl:for-each select="
+ //beans:bean/@class
+ | //beans:*/@value-type
+ | //aop:*/@implement-interface
+ | //aop:*/@default-impl
+ | //context:load-time-weaver/@weaver-class
+ | //jee:jndi-lookup/@expected-type
+ | //jee:jndi-lookup/@proxy-interface
+ | //jee:remote-slsb/@ejbType
+ | //jee:*/@business-interface
+ | //lang:*/@script-interfaces
+ | //osgi:*/@interface
+ | //util:list/@list-class
+ | //util:set/@set-class
+ | //util:map/@map-class
+ | //webflow-config:*/@class
+ ">
+ <xsl:value-of select="." />
+ <xsl:text>
+ </xsl:text>
+ </xsl:for-each>
+
+ <!-- This seems some magic to get extra imports? -->
+
+ <xsl:for-each select="//beans:bean[@class='org.springframework.osgi.service.exporter.support.OsgiServiceFactoryBean'
+ or @class='org.springframework.osgi.service.importer.support.OsgiServiceProxyFactoryBean']">
+ <xsl:for-each select="beans:property[@name='interfaces']">
+ <xsl:value-of select="@value" />
+ <xsl:text>
+ </xsl:text>
+ </xsl:for-each>
+ </xsl:for-each>
+
+ </xsl:template>
+
+
+</xsl:stylesheet>
+