private String createUriFromBundle(Bundle cl, String ref) {
   URL url = cl.getResource(ref);
   if (url == null && ref.startsWith("/")) {
     url = cl.getResource(ref.substring(1));
   }
   if (url == null) {
     throw new RuntimeException("reference " + ref + " not found on bundle " + cl);
   }
   return "uri:" + url.toString().replaceFirst(ref + "$", "");
 }
 @Override
 public URL getRootUrl(Bundle b, String location) {
   if (location.lastIndexOf('/') > 0) {
     location = location.substring(0, location.lastIndexOf('/'));
   }
   return b.getResource(location);
 }
  @Test
  public void testFragmentAttachOrder() throws Exception {

    Bundle fragE1 = installBundle(getFragmentE1());
    Bundle fragE2 = installBundle(getFragmentE2());
    Bundle hostE = installBundle(getHostE());
    Bundle hostF = installBundle(getHostF());

    hostE.start();

    assertTrue(fragE1.getBundleId() < fragE2.getBundleId());

    // Load class provided by the fragment
    assertLoadClass(hostE, FragE1Class.class.getName());
    assertLoadClass(hostE, FragE2Class.class.getName());

    // Tests that if a classpath entry cannot be located in the bundle, then the
    // Framework attempts to locate the classpath entry in each attached
    // fragment bundle. The attached fragment bundles are searched in ascending
    // bundle id order.
    URL resourceURL = hostE.getResource("resource.txt");
    BufferedReader br = new BufferedReader(new InputStreamReader(resourceURL.openStream()));
    assertEquals("fragE1", br.readLine());

    hostF.uninstall();
    hostE.uninstall();
    fragE2.uninstall();
    fragE1.uninstall();
  }
  /**
   * Load the class and break on first found match. TODO: Should this throw a different exception or
   * warn if multiple classes were found? Naming collisions can and do happen in OSGi...
   */
  @Override
  protected URL findResource(String name) {
    if (resourceCache.containsKey(name)) {
      return resourceCache.get(name);
    }

    for (Bundle bundle : bundles) {
      try {
        final URL resource = bundle.getResource(name);
        if (resource != null) {
          resourceCache.put(name, resource);
          return resource;
        }
      } catch (Exception ignore) {
      }
    }

    for (ClassLoader classLoader : classLoaders) {
      try {
        final URL resource = classLoader.getResource(name);
        if (resource != null) {
          resourceCache.put(name, resource);
          return resource;
        }
      } catch (Exception ignore) {
      }
    }

    // TODO: Error?
    return null;
  }
  @Test
  public void testFragmentOnly() throws Exception {
    Bundle fragA = installBundle(getFragmentA());
    assertBundleState(Bundle.INSTALLED, fragA.getState());

    URL entryURL = fragA.getEntry("resource.txt");
    assertEquals("bundle", entryURL.getProtocol());
    assertEquals("/resource.txt", entryURL.getPath());

    BufferedReader br = new BufferedReader(new InputStreamReader(entryURL.openStream()));
    assertEquals("fragA", br.readLine());

    URL resourceURL = fragA.getResource("resource.txt");
    assertNull("Resource URL null", resourceURL);

    try {
      fragA.start();
      fail("Fragment bundles can not be started");
    } catch (BundleException e) {
      assertBundleState(Bundle.INSTALLED, fragA.getState());
    }

    fragA.uninstall();
    assertBundleState(Bundle.UNINSTALLED, fragA.getState());
  }
Beispiel #6
0
  private void addEditableLookups(MDSProcessorOutput output, Bundle bundle) {

    URL lookupsResource = bundle.getResource(MDS_LOOKUPS_JSON);

    if (lookupsResource != null) {

      try (InputStream stream = lookupsResource.openStream()) {

        String lookupsJson = IOUtils.toString(stream);

        if (StringUtils.isNotBlank(lookupsJson)) {

          EntityLookups[] entitiesLookups = GSON.fromJson(lookupsJson, EntityLookups[].class);

          for (EntityLookups entityLookups : entitiesLookups) {
            addEditableEntityLookups(output, entityLookups);
          }
        } else {
          LOGGER.info(EMPTY_JSON, bundle.getSymbolicName());
        }
      } catch (IOException e) {
        LOGGER.error(e.getMessage(), e);
      }
    }
  }
 void createPage0() {
   try {
     xmlEditor = new XMLEditor();
     int index = addPage(xmlEditor, getEditorInput());
     setPageText(index, xmlEditor.getTitle() + " (Xml View)");
     IDocument inputDocument =
         xmlEditor.getDocumentProvider().getDocument(xmlEditor.getEditorInput());
     String documentContent = inputDocument.get();
     if (documentContent.isEmpty()) {
       documentContent = "";
       Bundle bundle = Platform.getBundle("reprotool.ide.txtspec");
       URL url = bundle.getResource("schema/default.txtspec.xml");
       try {
         InputStream ir = url.openStream();
         InputStreamReader isr = new InputStreamReader(ir);
         BufferedReader br = new BufferedReader(isr);
         String append;
         if ((documentContent = (br.readLine())) != null) ;
         while ((append = (br.readLine())) != null) documentContent += ("\n" + append);
         br.close();
       } catch (Exception e) {
         System.err.println(e.getMessage() + " " + e.getCause().toString());
       }
       documentContent = documentContent.trim();
       xmlEditor.setDocument(documentContent);
     }
   } catch (PartInitException e) {
     ErrorDialog.openError(
         getSite().getShell(), "Error creating xml text editor", null, e.getStatus());
   }
 }
 /** Calculates the contents of page 2 when the it is activated. */
 protected void pageChange(int newPageIndex) {
   super.pageChange(newPageIndex);
   if (newPageIndex == 1) {
     IDocument inputDocument =
         xmlEditor.getDocumentProvider().getDocument(xmlEditor.getEditorInput());
     String documentContent = inputDocument.get();
     TSEditor.setDocument(documentContent);
   } else if (newPageIndex == 0) {
     IDocument inputDocument =
         xmlEditor.getDocumentProvider().getDocument(xmlEditor.getEditorInput());
     String documentContent = inputDocument.get();
     if (documentContent.isEmpty()) {
       documentContent = "";
       Bundle bundle = Platform.getBundle("reprotool.ide.txtspec");
       URL url = bundle.getResource("schema/default.txtspec.xml");
       try {
         InputStream ir = url.openStream();
         InputStreamReader isr = new InputStreamReader(ir);
         BufferedReader br = new BufferedReader(isr);
         String append;
         if ((documentContent = (br.readLine())) != null) ;
         while ((append = (br.readLine())) != null) documentContent += ("\n" + append);
         br.close();
       } catch (Exception e) {
         System.err.println(e.getMessage() + " " + e.getCause().toString());
       }
       documentContent = documentContent.trim();
     }
     xmlEditor.setDocument(documentContent);
   }
 }
  @Test
  public void testAttachedFragment() throws Exception {
    Bundle hostA = installBundle(getHostA());
    assertBundleState(Bundle.INSTALLED, hostA.getState());

    Bundle fragA = installBundle(getFragmentA());
    assertBundleState(Bundle.INSTALLED, fragA.getState());

    hostA.start();
    assertBundleState(Bundle.ACTIVE, hostA.getState());
    assertBundleState(Bundle.RESOLVED, fragA.getState());

    URL entryURL = hostA.getEntry("resource.txt");
    assertNull("Entry URL null", entryURL);

    URL resourceURL = hostA.getResource("resource.txt");
    assertEquals("bundle", resourceURL.getProtocol());
    assertEquals("/resource.txt", resourceURL.getPath());

    BufferedReader br = new BufferedReader(new InputStreamReader(resourceURL.openStream()));
    assertEquals("fragA", br.readLine());

    // Load class provided by the fragment
    assertLoadClass(hostA, FragBeanA.class.getName());

    // Load a private class from host
    assertLoadClass(hostA, SubBeanA.class.getName());

    // PackageAdmin.getBundleType
    PackageAdmin pa = getPackageAdmin();
    assertEquals("Bundle type", 0, pa.getBundleType(hostA));
    assertEquals("Bundle type", PackageAdmin.BUNDLE_TYPE_FRAGMENT, pa.getBundleType(fragA));

    // PackageAdmin.getHosts
    Bundle[] hosts = pa.getHosts(hostA);
    assertNull("Not a fragment", hosts);

    hosts = pa.getHosts(fragA);
    assertNotNull("Hosts not null", hosts);
    assertEquals("Hosts length", 1, hosts.length);
    assertEquals("Hosts equals", hostA, hosts[0]);

    // PackageAdmin.getFragments
    Bundle[] fragments = pa.getFragments(fragA);
    assertNull("Not a host", fragments);

    fragments = pa.getFragments(hostA);
    assertNotNull("Fragments not null", fragments);
    assertEquals("Fragments length", 1, fragments.length);
    assertEquals("Fragments equals", fragA, fragments[0]);

    hostA.uninstall();
    assertBundleState(Bundle.UNINSTALLED, hostA.getState());
    assertBundleState(Bundle.RESOLVED, fragA.getState());

    fragA.uninstall();
    assertBundleState(Bundle.UNINSTALLED, fragA.getState());
  }
 @Override
 public Object findTemplateSource(String name) throws IOException {
   for (Bundle bundle : ctx.getBundles()) {
     URL src = bundle.getResource(path + name);
     if (src != null) {
       return src;
     }
   }
   return null;
 }
  public URL getResource(String resourceName) {
    if (LOGGER.isDebugEnabled()) {
      LOGGER.debug("getResource( " + resourceName + " )");
    }

    if (resourceName.startsWith(mountPoint)) {
      resourceName = resourceName.substring(mountPoint.length());
    }
    return bundle.getResource(resourceName);
  }
  @Test
  public void shouldReturnIconWhenGivenBundleName() {
    setupBundleRetrieval();
    when(bundle.getResource("icon.gif")).thenReturn(getDefaultIconUrl(DEFAULT_PATH + DEFAULT_ICON));

    BundleIcon bundleIcon = bundleIconService.getBundleIconByName(BUNDLE_NAME, null);
    byte[] expectedIcon = readDefaultIcon(DEFAULT_PATH + DEFAULT_ICON);

    assertArrayEquals(expectedIcon, bundleIcon.getIcon());
    assertEquals(ICON_MIME, bundleIcon.getMime());
  }
  @Test
  public void testResourceNotAvailableOnInstall() throws Exception {
    Bundle bundleC = installBundle(getLogServiceArchive());
    assertBundleState(Bundle.INSTALLED, bundleC.getState());
    try {
      String resPath = LogService.class.getName().replace('.', '/') + ".class";
      URL resURL = bundleC.getResource(resPath);
      assertNull("Resource not found", resURL);
      assertBundleState(Bundle.RESOLVED, bundleC.getState());

      Bundle cmpd = installBundle("bundles/org.osgi.compendium.jar");
      try {
        resURL = bundleC.getResource(resPath);
        assertNotNull("Resource found", resURL);
      } finally {
        cmpd.uninstall();
      }
    } finally {
      bundleC.uninstall();
    }
  }
Beispiel #14
0
 /**
  * Uses the plugin bundle's class loader to find a resource.
  *
  * @return A InputStream object or null if no resource with this name is found.
  */
 public InputStream getResourceAsStream(String name) throws IOException {
   // We always use the plugin bundle's class loader to access the resource.
   // getClass().getResource() would fail for generic plugins (plugin bundles not containing a
   // plugin
   // subclass) because the core bundle's class loader would be used and it has no access.
   URL url = pluginBundle.getResource(name);
   if (url != null) {
     return url.openStream();
   } else {
     return null;
   }
 }
 private static Map<String, Version> readBundleActivationFile(
     Bundle bundle, String bundleActivationFileName) throws IOException {
   Map<String, Version> bundleMap = new HashMap<String, Version>();
   URL bundleFileUrl = bundle.getResource(bundleActivationFileName);
   Properties bundleProperties = new Properties();
   bundleProperties.load(bundleFileUrl.openStream());
   for (Map.Entry<Object, Object> entry : bundleProperties.entrySet()) {
     String symbolicName = (String) entry.getKey();
     Version version = new Version((String) entry.getValue());
     bundleMap.put(symbolicName, version);
   }
   return bundleMap;
 }
 private static String getFile(Bundle bundle, String path) {
   String fileURL;
   try {
     fileURL = FileLocator.toFileURL(bundle.getEntry(path)).getPath();
   } catch (Exception ex) {
     try {
       fileURL = FileLocator.toFileURL(bundle.getResource(path)).getPath();
     } catch (Exception ex2) {
       fileURL = FileLocator.find(bundle, new Path(path), null).getPath();
     }
   }
   return fileURL;
 }
 @Override
 protected URL findResource(String name) {
     for (Bundle delegate : delegates) {
         try {
             URL resource = delegate.getResource(name);
             if (resource != null) {
                 return resource;
             }
         } catch (IllegalStateException _) {
         }
     }
     return null;
 }
  @Test
  public void shouldReturnIcon() throws IOException {
    setupBundleRetrieval();
    byte[] expectedIcon = readDefaultIcon(DEFAULT_PATH + DEFAULT_ICON);
    when(bundle.getResource("icon.gif")).thenReturn(getDefaultIconUrl(DEFAULT_PATH + DEFAULT_ICON));

    BundleIcon bundleIcon = bundleIconService.getBundleIconById(BUNDLE_ID, null);

    assertArrayEquals(expectedIcon, bundleIcon.getIcon());
    assertEquals(expectedIcon.length, bundleIcon.getContentLength());
    assertEquals(ICON_MIME, bundleIcon.getMime());
    verify(bundleContext).getBundle(BUNDLE_ID);
    verify(bundle).getResource("icon.gif");
  }
 @Test
 @Ignore("still working it out")
 public void testCallGetResourceOnADifferentBundle() throws Exception {
   // find bundles
   Bundle[] bundles = bundleContext.getBundles();
   for (int i = 1; i < bundles.length; i++) {
     Bundle bundle = bundles[i];
     logger.debug(
         "calling #getResource on bundle " + OsgiStringUtils.nullSafeNameAndSymName(bundle));
     URL url = bundle.getResource(LOCATION);
     if (!OsgiBundleUtils.isFragment(bundle))
       assertNotNull(
           "bundle " + OsgiStringUtils.nullSafeNameAndSymName(bundle) + " contains no META-INF/",
           url);
   }
 }
 /**
  * Gets the icon.
  *
  * @param e IConfigurationElement
  * @param attribute name of icon
  * @return icon of algorithm
  */
 private static Image getIcon(IConfigurationElement e, String attribute) {
   try {
     Bundle bundle = Platform.getBundle(e.getContributor().getName());
     if (bundle != null) {
       URL resource = bundle.getResource(attribute);
       if (resource != null) {
         return new Image(Display.getDefault(), resource.openStream());
       }
     }
   } catch (InvalidRegistryObjectException e1) {
     e1.printStackTrace();
   } catch (IOException e1) {
     e1.printStackTrace();
   }
   return null;
 }
 public Properties getResourceAsProperties(Bundle loader, String path) throws IOException {
   URL resourceUrl = loader.getResource(path);
   if (null == resourceUrl) {
     return null;
   }
   InputStream in = resourceUrl.openStream();
   try {
     Properties rv = new Properties();
     rv.load(in);
     return rv;
   } finally {
     if (null != in) {
       in.close();
     }
   }
 }
  /**
   * This will try and load a ResourceBundle for the given qualified name.
   *
   * @param qualifiedName Name if the resource bundle we need to load.
   * @return The loaded resource bundle.
   */
  public synchronized ResourceBundle getResourceBundle(String qualifiedName) {
    MissingResourceException originalException = null;

    // shortcut evaluation in case this properties file can be found in the current classloader.
    try {
      ResourceBundle bundle = ResourceBundle.getBundle(qualifiedName);
      return bundle;
    } catch (MissingResourceException e) {
      originalException = e;
    }

    if (changedContributions.size() > 0) {
      refreshContributions();
    }

    /*
     * We'll iterate over the bundles that have been installed from the workspace, search for one that
     * exports a package of the name we're looking for, then try and load the properties file from this
     * bundle's class loader (bundle.getResource()). If the resource couldn't be found in that bundle, we
     * loop over to the next.
     */
    for (Map.Entry<IPluginModelBase, Bundle> entry : workspaceInstalledBundles.entrySet()) {
      final Bundle bundle = entry.getValue();
      URL propertiesResource =
          bundle.getResource(qualifiedName.replace('.', '/') + ".properties"); // $NON-NLS-1$
      if (propertiesResource != null) {
        InputStream stream = null;
        try {
          stream = propertiesResource.openStream();
          // make sure this stream is buffered
          stream = new BufferedInputStream(stream);
          return new PropertyResourceBundle(stream);
        } catch (IOException e) {
          // Swallow this, we'll throw the original MissingResourceException
        } finally {
          try {
            if (stream != null) {
              stream.close();
            }
          } catch (IOException e) {
            // Swallow this, we'll throw the original MissingResourceException
          }
        }
      }
    }
    throw originalException;
  }
Beispiel #23
0
  @Test
  public void testDOMParser() throws Exception {

    OSGiTestSupport.changeStartLevel(context, 4, 10, TimeUnit.SECONDS);

    bundle.start();

    DocumentBuilder domBuilder = getDocumentBuilder();
    URL resURL = bundle.getResource("example-xml-parser.xml");
    Document dom = domBuilder.parse(resURL.openStream());
    assertNotNull("Document not null", dom);

    Element root = dom.getDocumentElement();
    assertEquals("root", root.getLocalName());

    Node child = root.getFirstChild();
    assertEquals("child", child.getLocalName());
    assertEquals("content", child.getTextContent());
  }
  @Test
  public void testHostOnly() throws Exception {
    Bundle hostA = installBundle(getHostA());
    assertBundleState(Bundle.INSTALLED, hostA.getState());

    hostA.start();
    assertBundleState(Bundle.ACTIVE, hostA.getState());

    URL entryURL = hostA.getEntry("resource.txt");
    assertNull("Entry URL null", entryURL);

    URL resourceURL = hostA.getResource("resource.txt");
    assertNull("Resource URL null", resourceURL);

    // Load a private class
    assertLoadClass(hostA, SubBeanA.class.getName());

    hostA.uninstall();
    assertBundleState(Bundle.UNINSTALLED, hostA.getState());
  }
  @Test
  @SuppressWarnings("unchecked")
  public void testUnmarshaller() throws Exception {

    JAXBContext jaxbContext =
        JAXBContext.newInstance(
            ObjectFactory.class.getPackage().getName(), ObjectFactory.class.getClassLoader());
    Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
    URL resURL = bundle.getResource("booking.xml");
    JAXBElement<CourseBooking> rootElement =
        (JAXBElement<CourseBooking>) unmarshaller.unmarshal(resURL.openStream());
    assertNotNull("root element not null", rootElement);

    CourseBooking booking = rootElement.getValue();
    assertNotNull("booking not null", booking);

    CompanyType company = booking.getCompany();
    assertNotNull("company not null", company);
    assertEquals("ACME Consulting", company.getName());
  }
  @Override
  public BundleIcon getBundleIcon(long bundleId) {
    BundleIcon bundleIcon = null;
    Bundle bundle = getBundle(bundleId);

    for (String iconLocation : ICON_LOCATIONS) {
      URL iconURL = bundle.getResource(iconLocation);
      if (iconURL != null) {
        bundleIcon = loadBundleIcon(iconURL);
        break;
      }
    }

    if (bundleIcon == null) {
      URL defaultIconURL = getClass().getResource(DEFAULT_ICON);
      bundleIcon = loadBundleIcon(defaultIconURL);
    }

    return bundleIcon;
  }
  private static void addCloneSourceProvider(
      List<CloneSourceProvider> cloneSourceProvider, IConfigurationElement[] config, int index) {
    try {
      int myIndex = index;
      String label = config[myIndex].getAttribute("label"); // $NON-NLS-1$
      boolean hasFixLocation =
          Boolean.valueOf(config[myIndex].getAttribute("hasFixLocation"))
              .booleanValue(); //$NON-NLS-1$

      String iconPath = config[myIndex].getAttribute("icon"); // $NON-NLS-1$
      ImageDescriptor icon = null;
      if (iconPath != null) {
        Bundle declaringBundle =
            Platform.getBundle(config[myIndex].getDeclaringExtension().getNamespaceIdentifier());
        icon = ImageDescriptor.createFromURL(declaringBundle.getResource(iconPath));
      }
      myIndex++;
      IConfigurationElement serverProviderElement = null;
      if (myIndex < config.length
          && config[myIndex].getName().equals("repositoryServerProvider")) { // $NON-NLS-1$
        serverProviderElement = config[myIndex];
        myIndex++;
      }
      IConfigurationElement pageElement = null;
      if (myIndex < config.length
          && config[myIndex].getName().equals("repositorySearchPage")) { // $NON-NLS-1$
        pageElement = config[myIndex];
        myIndex++;
      }
      cloneSourceProvider.add(
          new CloneSourceProvider(label, serverProviderElement, pageElement, hasFixLocation, icon));
      if (myIndex == config.length) return;
      addCloneSourceProvider(cloneSourceProvider, config, myIndex);
    } catch (Exception e) {
      Activator.logError(
          "Could not create extension provided by "
              + //$NON-NLS-1$
              Platform.getBundle(config[index].getDeclaringExtension().getNamespaceIdentifier()),
          e);
    }
  }
  /**
   * Finds component descriptors based on descriptor location.
   *
   * @param bundle bundle to search for descriptor files
   * @param descriptorLocation descriptor location
   * @return array of descriptors or empty array if none found
   */
  static URL[] findDescriptors(final Bundle bundle, final String descriptorLocation) {
    if (bundle == null || descriptorLocation == null || descriptorLocation.trim().length() == 0) {
      return new URL[0];
    }

    // for compatibility with previoues versions (<= 1.0.8) use getResource() for non wildcarded
    // entries
    if (descriptorLocation.indexOf("*") == -1) {
      final URL descriptor = bundle.getResource(descriptorLocation);
      if (descriptor == null) {
        return new URL[0];
      }
      return new URL[] {descriptor};
    }

    // split pattern and path
    final int lios = descriptorLocation.lastIndexOf("/");
    final String path;
    final String filePattern;
    if (lios > 0) {
      path = descriptorLocation.substring(0, lios);
      filePattern = descriptorLocation.substring(lios + 1);
    } else {
      path = "/";
      filePattern = descriptorLocation;
    }

    // find the entries
    final Enumeration entries = bundle.findEntries(path, filePattern, false);
    if (entries == null || !entries.hasMoreElements()) {
      return new URL[0];
    }

    // create the result list
    List urls = new ArrayList();
    while (entries.hasMoreElements()) {
      urls.add(entries.nextElement());
    }
    return (URL[]) urls.toArray(new URL[urls.size()]);
  }
 ////////////////////////////////////////////////////////////////////////////
 //
 // Deployment
 //
 ////////////////////////////////////////////////////////////////////////////
 public static void deployIfNeededAndLoad() {
   if (!m_initialized) {
     try {
       // extract
       Bundle bundle = Platform.getBundle("com.google.gdt.eclipse.designer.hosted.2_0.webkit");
       URL resource = FileLocator.resolve(bundle.getResource("WebKit.zip"));
       ZipFile zipFile = new ZipFile(resource.getPath());
       try {
         if (deployNeeded(zipFile)) {
           extract(zipFile);
         }
       } finally {
         zipFile.close();
       }
       load();
       m_available = true;
     } catch (Throwable e) {
       // ignore
     }
     m_initialized = true;
   }
 }
  protected void collectPortletPreferences(
      ServiceReference<Portlet> serviceReference, com.liferay.portal.model.Portlet portletModel) {

    String defaultPreferences =
        GetterUtil.getString(serviceReference.getProperty("javax.portlet.preferences"));

    if ((defaultPreferences != null) && defaultPreferences.startsWith("classpath:")) {

      Bundle bundle = serviceReference.getBundle();

      URL url = bundle.getResource(defaultPreferences.substring("classpath:".length()));

      if (url != null) {
        try {
          defaultPreferences = StringUtil.read(url.openStream());
        } catch (IOException ioe) {
          _log.error(ioe, ioe);
        }
      }
    }

    portletModel.setDefaultPreferences(defaultPreferences);
  }