コード例 #1
0
  @Override
  protected void setUp() throws Exception {
    tmp = IO.getFile("generated/tmp");
    tmp.mkdirs();

    configuration = new HashMap<String, Object>();
    configuration.put(
        Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    configuration.put(Constants.FRAMEWORK_STORAGE, new File(tmp, "fwstorage").getAbsolutePath());
    configuration.put(
        Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.4");
    framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration);
    framework.init();
    framework.start();
    BundleContext context = framework.getBundleContext();

    String[] bundles = {
      "../cnf/repo/osgi.cmpn/osgi.cmpn-4.3.1.jar", "testdata/slf4j-simple-1.7.12.jar",
      "testdata/slf4j-api-1.7.12.jar", "testdata/org.apache.aries.util-1.1.0.jar",
      "testdata/org.apache.aries.jmx-1.1.1.jar", "generated/biz.aQute.remote.test.jmx.jar"
    };

    for (String bundle : bundles) {
      String location = "reference:" + IO.getFile(bundle).toURI().toString();
      Bundle b = context.installBundle(location);
      if (!bundle.contains("slf4j-simple")) {
        b.start();
      }
    }

    super.setUp();
  }
コード例 #2
0
 @Override
 protected void tearDown() throws Exception {
   framework.stop();
   framework.waitForStop(10000);
   IO.delete(tmp);
   super.tearDown();
 }
コード例 #3
0
  @Override
  protected void setUp() throws Exception {
    tmp = IO.getFile("generated/tmp");
    tmp.mkdirs();
    IO.copy(IO.getFile("testdata/ws"), tmp);
    workspace = Workspace.getWorkspace(tmp);
    workspace.refresh();

    InfoRepository repo = workspace.getPlugin(InfoRepository.class);
    t1 = create("bsn-1", new Version(1, 0, 0));
    t2 = create("bsn-2", new Version(1, 0, 0));

    repo.put(new FileInputStream(t1), null);
    repo.put(new FileInputStream(t2), null);
    t1 = repo.get("bsn-1", new Version(1, 0, 0), null);
    t2 = repo.get("bsn-2", new Version(1, 0, 0), null);
    repo.put(new FileInputStream(IO.getFile("generated/biz.aQute.remote.launcher.jar")), null);

    workspace.getPlugins().add(repo);

    File storage = IO.getFile("generated/storage-1");
    storage.mkdirs();

    configuration = new HashMap<String, Object>();
    configuration.put(
        Constants.FRAMEWORK_STORAGE_CLEAN, Constants.FRAMEWORK_STORAGE_CLEAN_ONFIRSTINIT);
    configuration.put(Constants.FRAMEWORK_STORAGE, storage.getAbsolutePath());

    configuration.put(
        Constants.FRAMEWORK_SYSTEMPACKAGES_EXTRA, "org.osgi.framework.launch;version=1.2");

    framework = new org.apache.felix.framework.FrameworkFactory().newFramework(configuration);
    framework.init();
    framework.start();
    context = framework.getBundleContext();
    location = "reference:" + IO.getFile("generated/biz.aQute.remote.agent.jar").toURI().toString();
    agent = context.installBundle(location);
    agent.start();

    thread =
        new Thread() {
          @Override
          public void run() {
            try {
              Main.main(
                  new String[] {
                    "-s", "generated/storage", "-c", "generated/cache", "-p", "1090", "-et"
                  });
            } catch (Exception e) {
              e.printStackTrace();
            }
          }
        };
    thread.setDaemon(true);
    thread.start();

    super.setUp();
  }
コード例 #4
0
 @Override
 protected void tearDown() throws Exception {
   super.tearDown();
   framework.stop();
   IO.delete(tmp);
   Main.stop();
   IO.delete(IO.getFile("generated/cache"));
   IO.delete(IO.getFile("generated/storage"));
   framework.waitForStop(100000);
   super.tearDown();
 }
コード例 #5
0
 Object setContextFinder() {
   if (!SET_TCCL) return Boolean.FALSE;
   Thread currentThread = Thread.currentThread();
   ClassLoader previousTCCL = currentThread.getContextClassLoader();
   ClassLoader contextFinder = framework.getContextFinder();
   if (previousTCCL != contextFinder) {
     currentThread.setContextClassLoader(framework.getContextFinder());
     return previousTCCL;
   }
   return Boolean.FALSE;
 }
コード例 #6
0
 /**
  * @return specific nodes resources file path for the project, based on the
  *     framework.nodes.file.name property
  */
 public static String getNodesResourceFilePath(IRundeckProject project, Framework framework) {
   if (project.hasProperty(ProjectNodeSupport.PROJECT_RESOURCES_FILE_PROPERTY)) {
     return new File(project.getProperty(ProjectNodeSupport.PROJECT_RESOURCES_FILE_PROPERTY))
         .getAbsolutePath();
   }
   if (null != framework) {
     File etcDir = new File(framework.getFrameworkProjectsBaseDir(), project.getName() + "/etc/");
     if (framework.hasProperty(Framework.NODES_RESOURCES_FILE_PROP)) {
       return new File(etcDir, framework.getProperty(Framework.NODES_RESOURCES_FILE_PROP))
           .getAbsolutePath();
     } else {
       return new File(etcDir, ProjectNodeSupport.NODES_XML).getAbsolutePath();
     }
   } else {
     return null;
   }
 }
コード例 #7
0
  /**
   * Remove a service listener. The listener is removed from the context bundle's list of listeners.
   * See {@link #getBundle() getBundle()} for a definition of context bundle.
   *
   * <p>If this method is called with a listener which is not registered, then this method does
   * nothing.
   *
   * @param listener The service listener to remove.
   * @exception java.lang.IllegalStateException If the bundle context has stopped.
   */
  public void removeServiceListener(ServiceListener listener) {
    checkValid();

    if (listener == null) {
      throw new IllegalArgumentException();
    }
    framework.getServiceRegistry().removeServiceListener(this, listener);
  }
コード例 #8
0
  /**
   * Add a service listener with a filter. {@link ServiceListener}s are notified when a service has
   * a lifecycle state change. See {@link #getServiceReferences(String, String)
   * getServiceReferences} for a description of the filter syntax. The listener is added to the
   * context bundle's list of listeners. See {@link #getBundle() getBundle()} for a definition of
   * context bundle.
   *
   * <p>The listener is called if the filter criteria is met. To filter based upon the class of the
   * service, the filter should reference the "objectClass" property. If the filter paramater is
   * <code>null</code>, all services are considered to match the filter.
   *
   * <p>If the Java runtime environment supports permissions, then additional filtering is done.
   * {@link AbstractBundle#hasPermission(Object) Bundle.hasPermission} is called for the bundle
   * which defines the listener to validate that the listener has the {@link ServicePermission}
   * permission to <code>"get"</code> the service using at least one of the named classes the
   * service was registered under.
   *
   * @param listener The service listener to add.
   * @param filter The filter criteria.
   * @exception InvalidSyntaxException If the filter parameter contains an invalid filter string
   *     which cannot be parsed.
   * @see ServiceEvent
   * @see ServiceListener
   * @exception java.lang.IllegalStateException If the bundle context has stopped.
   */
  public void addServiceListener(ServiceListener listener, String filter)
      throws InvalidSyntaxException {
    checkValid();

    if (listener == null) {
      throw new IllegalArgumentException();
    }
    framework.getServiceRegistry().addServiceListener(this, listener, filter);
  }
コード例 #9
0
  /** Destroy the wrapper. This is called when the bundle is stopped. */
  protected void close() {
    valid = false; /* invalidate context */

    final ServiceRegistry registry = framework.getServiceRegistry();

    registry.removeAllServiceListeners(this);
    framework.removeAllListeners(this);

    /* service's registered by the bundle, if any, are unregistered. */
    registry.unregisterServices(this);

    /* service's used by the bundle, if any, are released. */
    registry.releaseServicesInUse(this);

    synchronized (contextLock) {
      servicesInUse = null;
    }
  }
コード例 #10
0
  /**
   * Retrieve the value of the named environment property.
   *
   * @param key The name of the requested property.
   * @return The value of the requested property, or <code>null</code> if the property is undefined.
   */
  public String getProperty(String key) {
    SecurityManager sm = System.getSecurityManager();

    if (sm != null) {
      sm.checkPropertyAccess(key);
    }

    return (framework.getProperty(key));
  }
コード例 #11
0
  private static PermissionInfo[] getPermissionInfos(URL resource, Framework framework) {
    if (resource == null) return null;
    PermissionInfo[] info = EMPTY_PERM_INFO;
    DataInputStream in = null;
    try {
      in = new DataInputStream(resource.openStream());
      ArrayList permissions = new ArrayList();
      BufferedReader reader;
      try {
        reader = new BufferedReader(new InputStreamReader(in, "UTF8")); // $NON-NLS-1$
      } catch (UnsupportedEncodingException e) {
        reader = new BufferedReader(new InputStreamReader(in));
      }

      while (true) {
        String line = reader.readLine();
        if (line == null) /* EOF */ break;
        line = line.trim();
        if ((line.length() == 0)
            || line.startsWith("#")
            || line.startsWith("//")) /* comments */ // $NON-NLS-1$ //$NON-NLS-2$
        continue;

        try {
          permissions.add(new PermissionInfo(line));
        } catch (IllegalArgumentException iae) {
          /* incorrectly encoded permission */
          if (framework != null)
            framework.publishFrameworkEvent(FrameworkEvent.ERROR, framework.getBundle(0), iae);
        }
      }
      int size = permissions.size();
      if (size > 0) info = (PermissionInfo[]) permissions.toArray(new PermissionInfo[size]);
    } catch (IOException e) {
      // do nothing
    } finally {
      try {
        if (in != null) in.close();
      } catch (IOException ee) {
        // do nothing
      }
    }
    return info;
  }
コード例 #12
0
  /**
   * Get a service's service object. Retrieves the service object for a service. A bundle's use of a
   * service is tracked by a use count. Each time a service's service object is returned by {@link
   * #getService}, the context bundle's use count for the service is incremented by one. Each time
   * the service is release by {@link #ungetService}, the context bundle's use count for the service
   * is decremented by one. When a bundle's use count for a service drops to zero, the bundle should
   * no longer use the service. See {@link #getBundle()} for a definition of context bundle.
   *
   * <p>This method will always return <code>null</code> when the service associated with this
   * reference has been unregistered.
   *
   * <p>The following steps are followed to get the service object:
   *
   * <ol>
   *   <li>If the service has been unregistered, <code>null</code> is returned.
   *   <li>The context bundle's use count for this service is incremented by one.
   *   <li>If the context bundle's use count for the service is now one and the service was
   *       registered with a {@link ServiceFactory}, the {@link ServiceFactory#getService
   *       ServiceFactory.getService} method is called to create a service object for the context
   *       bundle. This service object is cached by the framework. While the context bundle's use
   *       count for the service is greater than zero, subsequent calls to get the services's
   *       service object for the context bundle will return the cached service object. <br>
   *       If the service object returned by the {@link ServiceFactory} is not an <code>instanceof
   *       </code> all the classes named when the service was registered or the {@link
   *       ServiceFactory} throws an exception, <code>null</code> is returned and a {@link
   *       FrameworkEvent} of type {@link FrameworkEvent#ERROR} is broadcast.
   *   <li>The service object for the service is returned.
   * </ol>
   *
   * @param reference A reference to the service whose service object is desired.
   * @return A service object for the service associated with this reference, or <code>null</code>
   *     if the service is not registered.
   * @exception java.lang.SecurityException If the caller does not have {@link ServicePermission}
   *     permission to "get" the service using at least one of the named classes the service was
   *     registered under and the Java runtime environment supports permissions.
   * @exception java.lang.IllegalStateException If the bundle context has stopped.
   * @see #ungetService
   * @see ServiceFactory
   */
  public <S> S getService(ServiceReference<S> reference) {
    checkValid();
    if (reference == null)
      throw new NullPointerException("A null service reference is not allowed."); // $NON-NLS-1$
    synchronized (contextLock) {
      if (servicesInUse == null)
        // Cannot predict how many services a bundle will use, start with a small table.
        servicesInUse = new HashMap<ServiceRegistrationImpl<?>, ServiceUse<?>>(10);
    }

    @SuppressWarnings("unchecked")
    S service =
        (S) framework.getServiceRegistry().getService(this, (ServiceReferenceImpl<S>) reference);
    return service;
  }
コード例 #13
0
  /**
   * Remove a framework listener. The listener is removed from the context bundle's list of
   * listeners. See {@link #getBundle() getBundle()} for a definition of context bundle.
   *
   * <p>If this method is called with a listener which is not registered, then this method does
   * nothing.
   *
   * @param listener The framework listener to remove.
   * @exception java.lang.IllegalStateException If the bundle context has stopped.
   */
  public void removeFrameworkListener(FrameworkListener listener) {
    checkValid();
    if (listener == null) {
      throw new IllegalArgumentException();
    }

    if (Debug.DEBUG_EVENTS) {
      String listenerName =
          listener.getClass().getName()
              + "@"
              + Integer.toHexString(System.identityHashCode(listener)); // $NON-NLS-1$
      Debug.println(
          "removeFrameworkListener["
              + bundle
              + "]("
              + listenerName
              + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    }

    framework.removeFrameworkListener(listener, this);
  }
コード例 #14
0
  /**
   * Bottom level event dispatcher for the BundleContext.
   *
   * @param originalListener listener object registered under.
   * @param l listener to call (may be filtered).
   * @param action Event class type
   * @param object Event object
   */
  public void dispatchEvent(Object originalListener, Object l, int action, Object object) {
    // save the bundle ref to a local variable
    // to avoid interference from another thread closing this context
    AbstractBundle tmpBundle = bundle;
    Object previousTCCL = setContextFinder();
    try {
      if (isValid()) /* if context still valid */ {
        switch (action) {
          case Framework.BUNDLEEVENT:
          case Framework.BUNDLEEVENTSYNC:
            {
              BundleListener listener = (BundleListener) l;

              if (Debug.DEBUG_EVENTS) {
                String listenerName =
                    listener.getClass().getName()
                        + "@"
                        + Integer.toHexString(System.identityHashCode(listener)); // $NON-NLS-1$
                Debug.println(
                    "dispatchBundleEvent["
                        + tmpBundle
                        + "]("
                        + listenerName
                        + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
              }

              BundleEvent event = (BundleEvent) object;
              switch (event.getType()) {
                case Framework.BATCHEVENT_BEGIN:
                  {
                    if (listener instanceof BatchBundleListener)
                      ((BatchBundleListener) listener).batchBegin();
                    break;
                  }
                case Framework.BATCHEVENT_END:
                  {
                    if (listener instanceof BatchBundleListener)
                      ((BatchBundleListener) listener).batchEnd();
                    break;
                  }
                default:
                  {
                    listener.bundleChanged((BundleEvent) object);
                  }
              }
              break;
            }

          case ServiceRegistry.SERVICEEVENT:
            {
              ServiceEvent event = (ServiceEvent) object;

              ServiceListener listener = (ServiceListener) l;
              if (Debug.DEBUG_EVENTS) {
                String listenerName =
                    listener.getClass().getName()
                        + "@"
                        + Integer.toHexString(System.identityHashCode(listener)); // $NON-NLS-1$
                Debug.println(
                    "dispatchServiceEvent["
                        + tmpBundle
                        + "]("
                        + listenerName
                        + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
              }
              listener.serviceChanged(event);

              break;
            }

          case Framework.FRAMEWORKEVENT:
            {
              FrameworkListener listener = (FrameworkListener) l;

              if (Debug.DEBUG_EVENTS) {
                String listenerName =
                    listener.getClass().getName()
                        + "@"
                        + Integer.toHexString(System.identityHashCode(listener)); // $NON-NLS-1$
                Debug.println(
                    "dispatchFrameworkEvent["
                        + tmpBundle
                        + "]("
                        + listenerName
                        + ")"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
              }

              listener.frameworkEvent((FrameworkEvent) object);
              break;
            }
          default:
            {
              throw new InternalError();
            }
        }
      }
    } catch (Throwable t) {
      if (Debug.DEBUG_GENERAL) {
        Debug.println(
            "Exception in bottom level event dispatcher: " + t.getMessage()); // $NON-NLS-1$
        Debug.printStackTrace(t);
      }
      // allow the adaptor to handle this unexpected error
      framework.adaptor.handleRuntimeError(t);
      publisherror:
      {
        if (action == Framework.FRAMEWORKEVENT) {
          FrameworkEvent event = (FrameworkEvent) object;
          if (event.getType() == FrameworkEvent.ERROR) {
            break publisherror; // avoid infinite loop
          }
        }

        framework.publishFrameworkEvent(FrameworkEvent.ERROR, tmpBundle, t);
      }
    } finally {
      if (previousTCCL != Boolean.FALSE)
        Thread.currentThread().setContextClassLoader((ClassLoader) previousTCCL);
    }
  }
コード例 #15
0
 public ServiceReference<?>[] getAllServiceReferences(String clazz, String filter)
     throws InvalidSyntaxException {
   checkValid();
   return framework.getServiceRegistry().getServiceReferences(this, clazz, filter, true);
 }
コード例 #16
0
  public DispatcherResult dispatch(
      final ExecutionContext context, final ExecutionItem item, final Dispatchable toDispatch)
      throws DispatcherException {
    final NodesSelector nodesSelector = context.getNodeSelector();
    INodeSet nodes = null;
    try {
      nodes =
          framework.filterAuthorizedNodes(
              context.getFrameworkProject(),
              new HashSet<String>(Arrays.asList("read", "run")),
              framework.filterNodeSet(
                  nodesSelector, context.getFrameworkProject(), context.getNodesFile()));
    } catch (NodeFileParserException e) {
      throw new DispatcherException(e);
    }
    if (nodes.getNodes().size() < 1) {
      throw new DispatcherException("No nodes matched");
    }
    boolean keepgoing = context.isKeepgoing();

    context
        .getExecutionListener()
        .log(4, "preparing for sequential execution on " + nodes.getNodes().size() + " nodes");
    final HashSet<String> nodeNames = new HashSet<String>(nodes.getNodeNames());
    final HashMap<String, Object> failures = new HashMap<String, Object>();
    FailedNodesListener failedListener = context.getExecutionListener().getFailedNodesListener();
    if (null != failedListener) {
      failedListener.matchedNodes(nodeNames);
    }
    boolean interrupted = false;
    final Thread thread = Thread.currentThread();
    boolean success = true;
    final HashMap<String, StatusResult> resultMap = new HashMap<String, StatusResult>();
    final Collection<INodeEntry> nodes1 = nodes.getNodes();
    // reorder based on configured rank property and order
    final String rankProperty =
        null != context.getNodeRankAttribute() ? context.getNodeRankAttribute() : "nodename";
    final boolean rankAscending = context.isNodeRankOrderAscending();
    final INodeEntryComparator comparator = new INodeEntryComparator(rankProperty);
    final TreeSet<INodeEntry> orderedNodes =
        new TreeSet<INodeEntry>(rankAscending ? comparator : Collections.reverseOrder(comparator));
    orderedNodes.addAll(nodes1);
    for (final Object node1 : orderedNodes) {
      if (thread.isInterrupted()
          || thread instanceof ExecutionServiceThread
              && ((ExecutionServiceThread) thread).isAborted()) {
        interrupted = true;
        break;
      }
      final INodeEntry node = (INodeEntry) node1;
      context
          .getExecutionListener()
          .log(
              Constants.DEBUG_LEVEL,
              "Executing command on node: " + node.getNodename() + ", " + node.toString());
      try {

        if (thread.isInterrupted()
            || thread instanceof ExecutionServiceThread
                && ((ExecutionServiceThread) thread).isAborted()) {
          interrupted = true;
          break;
        }
        final StatusResult result;
        final ExecutionContext interimcontext =
            new ExecutionContextImpl.Builder(context)
                .nodeSelector(SelectorUtils.singleNode(node.getNodename()))
                .build();
        if (null != item) {
          result = framework.getExecutionService().interpretCommand(interimcontext, item, node);
        } else {
          result = toDispatch.dispatch(interimcontext, node);
        }
        if (null != result) {
          resultMap.put(node.getNodename(), result);
        }
        if (null == result || !result.isSuccess()) {
          success = false;
          //                    context.getExecutionListener().log(Constants.ERR_LEVEL,
          //                        "Failed execution for node " + node.getNodename() + ": " +
          // result);
          if (null != result) {
            failures.put(node.getNodename(), result);
          } else {
            failures.put(node.getNodename(), "Failed execution, result was null");
          }
          if (!keepgoing) {
            break;
          }
        } else {
          nodeNames.remove(node.getNodename());
        }
      } catch (Throwable e) {
        success = false;
        failures.put(
            node.getNodename(), "Error dispatching command to the node: " + e.getMessage());
        context
            .getExecutionListener()
            .log(
                Constants.ERR_LEVEL,
                "Failed dispatching to node " + node.getNodename() + ": " + e.getMessage());

        final StringWriter stringWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(stringWriter));
        context
            .getExecutionListener()
            .log(
                Constants.DEBUG_LEVEL,
                "Failed dispatching to node "
                    + node.getNodename()
                    + ": "
                    + stringWriter.toString());

        if (!keepgoing) {
          if (failures.size() > 0 && null != failedListener) {
            // tell listener of failed node list
            failedListener.nodesFailed(failures);
          }
          throw new DispatcherException(
              "Failed dispatching to node " + node.getNodename() + ": " + e.getMessage(), e, node);
        }
      }
    }
    if (keepgoing && nodeNames.size() > 0) {
      if (null != failedListener) {
        // tell listener of failed node list
        failedListener.nodesFailed(failures);
      }
      // now fail
      // XXX: needs to change from exception
      throw new NodesetFailureException(failures);
    } else if (null != failedListener && failures.isEmpty() && !interrupted) {
      failedListener.nodesSucceeded();
    }
    if (interrupted) {
      throw new DispatcherException("Node dispatch interrupted");
    }

    final boolean status = success;
    return new DispatcherResult() {
      public Map<String, ? extends StatusResult> getResults() {
        return resultMap;
      }

      public boolean isSuccess() {
        return status;
      }

      @Override
      public String toString() {
        return "DispatcherResult{"
            + "status="
            + isSuccess()
            + ", "
            + "results="
            + getResults()
            + "}";
      }
    };
  }
コード例 #17
0
 public Bundle getBundle(String location) {
   return framework.getBundleByLocation(location);
 }
コード例 #18
0
  /**
   * Unget a service's service object. Releases the service object for a service. If the context
   * bundle's use count for the service is zero, this method returns <code>false</code>. Otherwise,
   * the context bundle's use count for the service is decremented by one. See {@link #getBundle()}
   * for a definition of context bundle.
   *
   * <p>The service's service object should no longer be used and all references to it should be
   * destroyed when a bundle's use count for the service drops to zero.
   *
   * <p>The following steps are followed to unget the service object:
   *
   * <ol>
   *   <li>If the context bundle's use count for the service is zero or the service has been
   *       unregistered, <code>false</code> is returned.
   *   <li>The context bundle's use count for this service is decremented by one.
   *   <li>If the context bundle's use count for the service is now zero and the service was
   *       registered with a {@link ServiceFactory}, the {@link ServiceFactory#ungetService
   *       ServiceFactory.ungetService} method is called to release the service object for the
   *       context bundle.
   *   <li><code>true</code> is returned.
   * </ol>
   *
   * @param reference A reference to the service to be released.
   * @return <code>false</code> if the context bundle's use count for the service is zero or if the
   *     service has been unregistered, otherwise <code>true</code>.
   * @exception java.lang.IllegalStateException If the bundle context has stopped.
   * @see #getService
   * @see ServiceFactory
   */
  public boolean ungetService(ServiceReference<?> reference) {
    checkValid();

    return framework.getServiceRegistry().ungetService(this, (ServiceReferenceImpl<?>) reference);
  }
コード例 #19
0
  /**
   * Creates a <code>File</code> object for a file in the persistent storage area provided for the
   * bundle by the framework. If the adaptor does not have file system support, this method will
   * return <code>null</code>.
   *
   * <p>A <code>File</code> object for the base directory of the persistent storage area provided
   * for the context bundle by the framework can be obtained by calling this method with the empty
   * string ("") as the parameter. See {@link #getBundle()} for a definition of context bundle.
   *
   * <p>If the Java runtime environment supports permissions, the framework the will ensure that the
   * bundle has <code>java.io.FilePermission</code> with actions "read","write","execute","delete"
   * for all files (recursively) in the persistent storage area provided for the context bundle by
   * the framework.
   *
   * @param filename A relative name to the file to be accessed.
   * @return A <code>File</code> object that represents the requested file or <code>null</code> if
   *     the adaptor does not have file system support.
   * @exception java.lang.IllegalStateException If the bundle context has stopped.
   */
  public File getDataFile(String filename) {
    checkValid();

    return (framework.getDataFile(bundle, filename));
  }
コード例 #20
0
 /**
  * Retrieve the bundle that has the given location.
  *
  * @param location The location string of the bundle to retrieve.
  * @return A Bundle object, or <code>null</code> if the location doesn't match any installed
  *     bundle.
  */
 public AbstractBundle getBundleByLocation(String location) {
   return (framework.getBundleByLocation(location));
 }
コード例 #21
0
 /**
  * Retrieve the bundle that has the given unique identifier.
  *
  * @param id The identifier of the bundle to retrieve.
  * @return A Bundle object, or <code>null</code> if the identifier doesn't match any installed
  *     bundle.
  */
 public Bundle getBundle(long id) {
   return framework.getBundle(this, id);
 }
コード例 #22
0
 /**
  * Retrieve a list of all installed bundles. The list is valid at the time of the call to
  * getBundles, but the framework is a very dynamic environment and bundles can be installed or
  * uninstalled at anytime.
  *
  * @return An array of {@link AbstractBundle} objects, one object per installed bundle.
  */
 public Bundle[] getBundles() {
   return framework.getBundles(this);
 }
コード例 #23
0
 /**
  * Register a service with multiple names. This method registers the given service object with the
  * given properties under the given class names. A {@link ServiceRegistration} object is returned.
  * The {@link ServiceRegistration} object is for the private use of the bundle registering the
  * service and should not be shared with other bundles. The registering bundle is defined to be
  * the context bundle. See {@link #getBundle()} for a definition of context bundle. Other bundles
  * can locate the service by using either the {@link #getServiceReferences getServiceReferences}
  * or {@link #getServiceReference getServiceReference} method.
  *
  * <p>A bundle can register a service object that implements the {@link ServiceFactory} interface
  * to have more flexiblity in providing service objects to different bundles.
  *
  * <p>The following steps are followed to register a service:
  *
  * <ol>
  *   <li>If the service parameter is not a {@link ServiceFactory}, an <code>
  *       IllegalArgumentException</code> is thrown if the service parameter is not an <code>
  *       instanceof</code> all the classes named.
  *   <li>The service is added to the framework's service registry and may now be used by other
  *       bundles.
  *   <li>A {@link ServiceEvent} of type {@link ServiceEvent#REGISTERED} is synchronously sent.
  *   <li>A {@link ServiceRegistration} object for this registration is returned.
  * </ol>
  *
  * @param clazzes The class names under which the service can be located. The class names in this
  *     array will be stored in the service's properties under the key "objectClass".
  * @param service The service object or a {@link ServiceFactory} object.
  * @param properties The properties for this service. The keys in the properties object must all
  *     be Strings. Changes should not be made to this object after calling this method. To update
  *     the service's properties call the {@link ServiceRegistration#setProperties
  *     ServiceRegistration.setProperties} method. This parameter may be <code>null</code> if the
  *     service has no properties.
  * @return A {@link ServiceRegistration} object for use by the bundle registering the service to
  *     update the service's properties or to unregister the service.
  * @exception java.lang.IllegalArgumentException If one of the following is true:
  *     <ul>
  *       <li>The service parameter is null.
  *       <li>The service parameter is not a {@link ServiceFactory} and is not an <code>instanceof
  *           </code> all the named classes in the clazzes parameter.
  *     </ul>
  *
  * @exception java.lang.SecurityException If the caller does not have {@link ServicePermission}
  *     permission to "register" the service for all the named classes and the Java runtime
  *     environment supports permissions.
  * @exception java.lang.IllegalStateException If the bundle context has stopped.
  * @see ServiceRegistration
  * @see ServiceFactory
  */
 public ServiceRegistration<?> registerService(
     String[] clazzes, Object service, Dictionary<String, ?> properties) {
   checkValid();
   return framework.getServiceRegistry().registerService(this, clazzes, service, properties);
 }
コード例 #24
0
  private void _setupScope() {
    if (_inScopeSetup) return;

    final Scope saveTLPref = _scope.getTLPreferred();
    _scope.setTLPreferred(null);

    final Scope saveTL = Scope.getThreadLocal();
    _scope.makeThreadLocal();

    _inScopeSetup = true;

    try {
      Object fo = getConfigObject("framework");

      if (fo != null) {

        Framework f = null;

        if (fo instanceof JSString) {
          f = Framework.byName(fo.toString(), null); // we allow people to just specify name
          _logger.info("Setting framework by name [" + fo.toString() + "]");
        } else if (fo instanceof JSObjectBase) {

          JSObjectBase obj = (JSObjectBase) fo;

          if (obj.containsKey("name")) {

            String s = obj.getAsString("version");

            f = Framework.byName(obj.getAsString("name"), s);
            _logger.info("Setting framework by name [" + obj.getAsString("name") + "]");
          } else if (obj.containsKey("custom")) {

            Object o = obj.get("custom");

            if (o instanceof JSObjectBase) {
              f = Framework.byCustom((JSObjectBase) o);
              _logger.info("Setting framework by custom [" + o + "]");
            } else {
              throw new RuntimeException("Error - custom framework wasn't an object [" + o + "]");
            }
          } else if (obj.containsKey("classname")) {
            f = Framework.byClass(obj.getAsString("classname"));
            _logger.info("Setting framework by class [" + obj.getAsString("classname") + "]");
          }
        }

        if (f == null) {
          throw new RuntimeException("Error : can't find framework [" + fo + "]");
        }

        f.install(this);
      }

      _runInitFiles(INIT_FILES);

      if (_adminContext != null) {
        _adminContext._scope.set("siteScope", _scope);
        _adminContext._setLocalObject(_localObject);
      }

      _lastScopeInitTime = _getScopeTime();
    } catch (RuntimeException re) {
      _scopeInited = false;
      throw re;
    } catch (Exception e) {
      _scopeInited = false;
      throw new RuntimeException(e);
    } finally {
      _inScopeSetup = false;
      _scope.setTLPreferred(saveTLPref);

      if (saveTL != null) saveTL.makeThreadLocal();

      this.approxSize(_rootContextReachable);
    }
  }
コード例 #25
0
  /**
   * Get a service reference. Retrieves a {@link ServiceReference} for a service which implements
   * the named class.
   *
   * <p>This reference is valid at the time of the call to this method, but since the framework is a
   * very dynamic environment, services can be modified or unregistered at anytime.
   *
   * <p>This method is provided as a convenience for when the caller is interested in any service
   * which implements a named class. This method is the same as calling {@link #getServiceReferences
   * getServiceReferences} with a <code>null</code> filter string but only a single {@link
   * ServiceReference} is returned.
   *
   * @param clazz The class name which the service must implement.
   * @return A {@link ServiceReference} object, or <code>null</code> if no services are registered
   *     which implement the named class.
   * @see #getServiceReferences
   */
  public ServiceReference<?> getServiceReference(String clazz) {
    checkValid();

    return framework.getServiceRegistry().getServiceReference(this, clazz);
  }
コード例 #26
0
 public Bundle installBundle(String location, InputStream in) throws BundleException {
   checkValid();
   // note AdminPermission is checked after bundle is loaded
   return framework.installBundle(location, in, this);
 }