-[UIViewController _loadViewFromNibNamed:bundle:] loaded the “X” nib but the view outlet was not set.

If you get such an error while starting your iPhone Application:

-[UIViewController _loadViewFromNibNamed:bundle:] loaded the “X” nib but the view outlet was not set.

You may have changed the content of you view. And because of that the nib has lost its view element.

To fix this error open you nib and select the ‘File’s Owner’ entry as you see below.

Within the utilities you can define the necessary view.

Restart and the error will be gone.

be happy until cancelled,
Your Codescale’s

Inspect the magic of Eclipse Fragments

In the post ‘Basics about OSGi Classloading’ we have learned the fundamental knowledge how Classes are defined and loaded within OSGi.
And we have worked with ‘pure’ OSGi Bundles. But there is another ‘type’ of a Bundle, called Fragment. Basically a Fragment is an extension to its Host-Bundle.

And because such a Fragment will lead to a ‘special’ kind of Classloading within Equinox, we will take a look at what happens if we load a Class out of a Fragment.

This is our test setup (get it from git@github.com:codescale/osgi-playground.git):

designfragmentclassloading-2011-04-14-23-21.png

Our starting point is a Console Service to control the test executions. This Bundle does have a dependency to ‘org.codescale.bundle.a’ which does have the Fragment ‘org.codescale.fragment.a’. This Fragment does define another dependency to ‘org.codescale.bundle.b’.

To learn about the behavior of OSGi and Fragments we will go through these six parts:

  1. Load a Class from the Fragment whereat the package is only exported by the Bundle A
  2. Load a Class from the Fragment whereat the package is also exported by the Fragment
  3. Load a Class from Bundle A whereat the package is only exported by the Fragment
  4. Load a Class from Bundle B from a Class inside of the Bundle A at what this bundle does not have the necessary dependency
  5. Load a resource from Bundle A from within a Class of Bundle A
  6. Load a resource from the Fragment from within a Class of Bundle A

Let’s start…

If you have setup a workspace in Eclipse with the source from git@github.com:codescale/osgi-playground.git you can start an OSGi Framework using the prepared launcher from the project ‘org.eclipse.console’.

Now we start an OSGi Framework with all the four bundles started.

Part 1
Enter ‘loadClass org.codescale.bundle.a.PublicBundleClass‘ into the console. After executing this command you will see the following output:

Load the class 'org.codescale.bundle.a.PublicBundleClass', called by bundle 'org.codescale.console'.
The class was loaded by 'org.codescale.bundle.a' instance '64212394'.
...

In the first line we see that the ‘Console Bundle’ is going to load a class which seems to be ‘Bundle A’. Let’s have a look at this bundle.

eclipse3-2011-04-14-23-21.png

There is not such a Class. But let’s take a look at the fragment.

eclipse2-2011-04-14-23-21.png

Here it is Ok what happens? As we’ve learned, the place to step into is the ‘BundleLoader#findClassInternal’.
(1) The first Bundle-ClassLoader which will be checked is the one of the ‘Console Bundle’, of course. (2) There the required ‘Bundle A’ is identified to be a possibility to load the Class, because this bundle does export the necessary package. (3) Within this bundle, firstly the ClasspathManager tries to load the class from the bundle itself, then (if this approach fails) all the fragments are called.

eclipse2-2011-04-14-23-211.png

This is the code that does iterate through all the fragments and tries to load the class.

for (int i = 0; i < fragments.length; i++) {
 ClasspathEntry[] fragEntries = fragments[i].getEntries();
 for (int j = 0; j < fragEntries.length; j++) {
  result = findClassImpl(classname, fragEntries[j], hooks);
  if (result != null)
   return result;
 }
}

That’s how it happens, that the class will be loaded by ‘Bundle A’.

Part 2
Enter loadClass org.codescale.fragment.a.PublicFragmentClass into the console to get a class loaded whose package is exported by the fragment. The output will be:

Load the class 'org.codescale.fragment.a.PublicFragmentClass', called by bundle 'org.codescale.console'.
The class was loaded by 'org.codescale.bundle.a' instance '1762688005'.
...

O.K. the class is once again loaded by ‘Bundle A’. How?
Stepping through the ‘BundleLoader’ we see that the ‘Bundle A’ does have all his exported packages, plus the one of the Fragment. That’s the key point! The Bundle description of ‘Bundle A’ and its Fragment are merged. This will happen in ‘org.eclipse.osgi.internal.module.ResolverBundle’ e.g. #getExportedPackages().
With the help of the ‘PackageAdmin’ Service we can get some infos out of ‘Bundle A’.

Symbolic-Name: org.codescale.bundle.a
The bundle exported packages:
 > org.codescale.bundle.a
 > org.codescale.fragment.a
 > org.codescale.bundle.internal.a
The bundle does have 1 fragments:
 > org.codescale.fragment.a

There you see, that ‘Bundle A’ does have three exported packages, merged together by the bundle itself an its Fragment.

Part 3
Enter loadClass org.codescale.bundle.internal.a.InternalBundleClass into the console to get a class loaded from ‘Bundle A’ even though the package is exported by its Fragment.

Because of the previous recognition we now know that this will work. See the output:

Load the class 'org.codescale.bundle.internal.a.InternalBundleClass', called by bundle 'org.codescale.console'.
The class was loaded by 'org.codescale.bundle.a' instance '744919514'.

Both Bundle descriptions are merged, so the ‘Bundle A’ does export the necessary package through the definition by its Fragment.

Part 4
Now we’re going to load a class from ‘Bundle B’ by a class of ‘Bundle A’. This scenario is equal to the previous Part 2 and 3. The Fragment does extend the Bundle-Description of ‘Bundle A’ with an additional dependency to ‘Bundle B’.

You can step through this by entering instance org.codescale.bundle.internal.a.InternalBundleClass into the console.

Part 5
Enter instance org.codescale.bundle.internal.a.InternalBundleClass into the console to get a stream of a resource which is located in ‘Bundle A’. This will be the output:

Instantiate the class 'org.codescale.bundle.internal.a.InternalBundleClass', called by bundle 'org.codescale.console'.
The class was loaded by 'org.codescale.bundle.a' instance '2052558331'.
Created instance of org.codescale.bundle.internal.a.InternalBundleClass
The resource /resources/bundle.file was found.
Content > Hi I'm the bundle.file

First of all the Class will be loaded (as we’ve done previously) then we create an instance of it. Within the constructor a resource will be loaded.

URL url = getClass().getResource("/resources/bundle.file");

This scenario is not so special – we’ve just requested a resource within the same bundle as the class lives. Anyway let’s have a look at the ‘BundleLoader’ (this time the method ‘findResource(String, boolean)’) to get the default behavior known.

eclipse-2011-04-14-23-21.png

As you see it’s not so different to Part 1 where we’ve looked at the Stacktrace of Classloading. We also end up at the ‘ClasspathManager’.

Part 6
If you enter instance org.codescale.fragment.a.PublicFragmentClass into the console a resource from the Fragment should be loaded by a class of ‘Bundle A’. As we see in the output, the resource is loaded as well:

Instantiate the class 'org.codescale.fragment.a.PublicFragmentClass', called by bundle 'org.codescale.console'.
The class was loaded by 'org.codescale.bundle.a' instance '1609377764'.
Created instance of org.codescale.bundle.internal.a.InternalBundleClass
The resource /resources/fragment.file was found.
Content > Hi I'm the fragment.file

One more time the implementation of the ‘ClasspathManager’ does the trick.

private URL findLocalResourceImpl(String resource, int classPathIndex) {
 ...
 // look in fragments
 for (int i = 0; i &lt; fragments.length; i++) {
  ClasspathEntry[] fragEntries = fragments[i].getEntries();
  for (int j = 0; j &lt; fragEntries.length; j++) {
   result = findResourceImpl(resource, fragEntries[j].getBundleFile(), curIndex);
   if (result != null &amp;&amp; (classPathIndex == -1 || classPathIndex == curIndex))
    return result;
   curIndex++;
   }
  }

Conclusion
Now we know how a fragment does behave in a OSGi environment. A Fragment can help you to interact directly with its Host-Bundle ‘without borders’. This can be helpful if you have to test the internal implementation of a Bundle. Another imaginable region is to extend a third party library (because of this Bundle-Description merge). But be aware you can’t ‘overwrite’ a Class of your Host-Bundle. A Class will be loaded first from its own Bundle, then from the Fragments!

Finally I leave you with a question. We add a Fragment to ‘Bundle B’, add a dependency from ‘Bundle A’ to ‘Bundle B’ and (as we’ve done in Part 6) load a resource from a Class in ‘Bundle A’ out of this Fragment. Will it work?

be happy until cancelled,
Your Codescale’s

Text and image ‘Slideup Boxes’ with CSS3 (not one line of javascript)

The basic idea is very similar to these sliding boxes that are animated with JQuery. The difference is, that I will not use one line of javascript (nor JQuery) but CSS3.
OK, that’s also not completely new. But ;) I do have the requirement to let flow out a box with text inside as well as an image.

View Demo

Download Source

Find the OSGi bundle that does contain this Class

Hi,

Just a quick tip.

If you need to find the bundle which does contain a specific Class, use FrameworkUtil#getBundle(java.lang.Class classFromBundle)

In equinox it does reside in the bundle org.eclipse.osgi.

Then you can get all the information you may require from the bundle.
E.g. you can use this to get your bundles’ context and register or request an OSGi Service.
Or start the bundle which does contain the specific class.

be happy until cancelled,
Your Codescale’s

Get your callers class as fast as possible

If you have to dive into the java stacktrace, you can use three possible functions to do so.

  1. Use a Throwable
  2. Create a SecurityManager and get his ClassContext
  3. Or do the trick with Reflection API (thanks to Heinz’s advise)

Here are the three solutions written down:

        private String getCallerClassFromThrowable() {
                Throwable trace = new Throwable();
                return trace.getStackTrace()[1].getClassName();
        }
—————————–
        private static class MySecurityManager extends SecurityManager {
                @Override
                public Class<?>[] getClassContext() {
                        return super.getClassContext();
                }
        }
        private String getCallerClassFromSecurityManager() {
                Class<?>[] classContext = new MySecurityManager().getClassContext();
                return classContext[1].getName();
        }
—————————–
        private String getCallerClassFromReflection() {
                return Reflection.getCallerClass(2).getName();
        }

The result of a tiny performance test shows…

        private void doMeasurement(int counter) {
                if (counter == 0) {

                        long time1 = System.currentTimeMillis();
                        for (int i = 0; i < REPEATS; i++) {
                                getCallerClassFromThrowable();
                        }
                        time1 = System.currentTimeMillis() – time1;
                        System.out.println(“time1 = “ + time1 + “ms”);

                        long time2 = System.currentTimeMillis();
                        for (int i = 0; i < REPEATS; i++) {
                                getCallerClassFromSecurityManager();
                        }
                        time2 = System.currentTimeMillis() – time2;
                        System.out.println(“time2 = “ + time2 + “ms”);

                        long time3 = System.currentTimeMillis();
                        for (int i = 0; i < REPEATS; i++) {
                                getCallerClassFromReflection();
                        }
                        time3 = System.currentTimeMillis() – time3;
                        System.out.println(“time3 = “ + time3 + “ms”);
                        return;
                }

                doMeasurement(–counter);
        }

        private static void test() {
                PerformanceTest test = new PerformanceTest();
                for (int i = 1; i < 1025; i *= 2) {
                        System.out.println(“doMeasurement(“ + i + “)”);
                        test.doMeasurement(i);
                }
        }

… that the reflection hack really does the trick.

doMeasurement(1024)
time1 = 36598ms
time2 = 4924ms
time3 = 0ms

be happy until cancelled,
Your Codescale’s

Log the Ant output to the Eclipse console

Have you ever written an Eclipse Plug-In that has to call an Ant-Script? OK, I’m sure you get this done. Maybe then you’ve ask yourself (or someone else ;-) ): “How do I get the Ant output into the console of Eclipse?” So, I have and also was asked.

My spontaneous and innocent answer: “Just call ‘addBuildLogger’ on your AntRunner.”

The Logger has to look like that:

public class EclipseAntLogger extends DefaultLogger {

private IOConsole console = new IOConsole(&quot;Ant&quot;, null);
private IOConsoleOutputStream outputStream = console.newOutputStream();

public EclipseAntLogger() {
 ConsolePlugin.getDefault().getConsoleManager().addConsoles(new IConsole[] { console });
}

@Override
protected void printMessage(String message, PrintStream stream, int priority) {
 super.printMessage(message, stream, priority);
 try {
  outputStream.write(message + &quot;\n&quot;);
 } catch (IOException e) {
  e.printStackTrace();
 }
}

The problem I’ve got with that was a ClassNotFound exception of my logger class. Of course! My AntRunner uses a different VM and with that a totally different ClassPath than the one of Eclipse.

How to put your logger class onto the AntRunner ClassPath?
-> Setup the custom classpath of the AntRunner.

// get the default custom classpath from the preferences
AntCorePreferences corePreferences = AntCorePlugin.getPlugin().getPreferences();
URL[] urls = corePreferences.getURLs();

// get the location of the plugin jar
File bundleFile = FileLocator.getBundleFile(myPlugin.getBundle());
URL url = bundleFile.toURI().toURL();

// bond urls to complete classpath
List<URL> classpath = new ArrayList<URL>();
classpath.addAll(Arrays.asList(urls));
classpath.add(url);

// set custom classpath
antRunner.setCustomClasspath(classpath.toArray(new URL[classpath.size()]));

Not too nice in my opinion. Another possibility is to use an extension.

<extension point="org.eclipse.ant.core.extraClasspathEntries">
 <extraClasspathEntry library="ant/logger.jar">
 </extraClasspathEntry>
</extension>

You have to put the logger class into another jar and add it to the extra classpath of the eclipse ant classpath.

Better! But I wasn’t almost happy with this solution.
After some days of work there was the flash of genius – or something like that :-)

You know the laucher from the Eclipse-UI where you can create a new ‘External Tools Configurations…’?

In your code you have to use ‘ILaunchConfigurationType’ to create a new configuration. My solution looks like this:

ILaunchManager launchManager = DebugPlugin.getDefault().getLaunchManager();
ILaunchConfigurationType lcType = launchManager.getLaunchConfigurationType(IAntLaunchConstants.ID_ANT_LAUNCH_CONFIGURATION_TYPE);

String name = launchManager.generateLaunchConfigurationName(&quot;Run Ant&quot;);
ILaunchConfigurationWorkingCopy wc = lcType.newInstance(null, name);
wc.setAttribute(ILaunchManager.ATTR_PRIVATE, true);
wc.setAttribute(IExternalToolConstants.ATTR_LOCATION, buildFile.toString());
wc.setAttribute(IAntLaunchConstants.ATTR_ANT_TARGETS, &quot;run&quot;);

wc.launch(ILaunchManager.RUN_MODE, null);

It’s based on the new API that will be introduced with Eclipse 3.6 and requires at least these bundles:

  • org.eclipse.debug.core
  • org.eclipse.ant.launching
  • org.eclipse.core.externaltools

It works beautiful I think? So what do you?

Do you have another suggestion how to solve the problem? Let me know.

be happy until cancelled,
Your Codescale’s

Second day at Eclipse Summit Europe 2009

Once again e4 (exactly what’s in) was on the agenda. And i will have to say once more that a deeper look to e4 is required :)

Another topic was about JPicus. An I/O Analyser made by SAP. You can inject JPicus into the JVM of your application by adding JPicus as a java-agent (“-javaagent:jpicus.jar”).
Very interesting to me was the discovery that equinox holds up the FileHandler to the Bundle-Jar until the OSGi Environment gets closed. This maybe results in a data leak and you can run out of memory. There is a property called “osgi.equinox.bundle.file” which reduces the amount of FileHandlers.

Later on i’ve attend the Buckminster talk given by Henrik, Thomas and Filip Hrbek.
There was a large audience listened to them. They have explained how Buckminster will create a p2 repository by defining a so called cquery. And this will equally work headless.
There is even more you will get out of an cquery. You can let Buckminster create a dependency graph named BOM (bill of material).
Beside of building a p2 repository you will get this repository as a maven repository as well. Isn’t that fantastic?
So take a look at the Buckminster book and setup up your build based on models (i will do so ;-) ).


First day at eclipse summit europe 2009 with OSGi and e4

Today i’ve participated in the OSGi Meeting which was launched at the early beginning of eclipse summit.

The first topic on this session was the “new” released OSGi Spec. 4.2.

And in context of that, the OSGi Service Notation was announced. Not very special but important to know. First of all to bring the communication to a more comprehensible and uniform one.

Then the new Service Hook possibility was announced. In basic meaning you can compare it (if you know) to the classloading hook. With this model you can “hack” the default behavior of how Bundles are found, Service-Events are delivered and Service-Listener can interact. Of course i needn’t mention that these possibilities shouldn’t be the first idea to solve a problem. But in context of a framework (for example with the usage of a service proxy) a Service Hook can solve a problem and provide a great opportunity.

Also the Remote (old named delayed) Services were announced. The main parts of this technology came from Spring. One thing i will mention is that these Remote Services are defined by property convention. But if you are interested in more detail i will refer you to the OSGi Spec. One thing i will append is a (maybe called) “Remote Services Proxy Pattern”.

For example in a framework you can use a Service Hook to implement a Service Proxy which hides the dynamic of Remote Services.

The next part of the OSGi Meeting took a presentation about lessons learned during the Apache Sling project and OSGi. In their opinion Spring contains a too static Descriptor and it’s also not really dynamic. So they have setup their execution environment with the implementation of Apache Felix.

The main problem during the project was the thinking of developers. It doesn’t match in deed with the dynamic approach of OSGi. So their statement was, that a developer requires about half a year to realize and “think” in the way OSGi expected it.

Later in the afternoon five representatives of four implementations of OSGi sit together and talk about Felix, Knopperfish, Prosys (i thought it was named) and Equinox. It was a very interesting discussion. And one topic was present every time – Tooling Issue.

—————-

The e4 symposium was the second big part I have participated in today. In my opinion it’s a very interesting topic and it requires more space than i can actually give. Some keywords i can give:

  • e4 setup a new abstraction layer upon SWT and the Workbench Model
  • one major goal is to remove all static accessors inside of e4 UI (for example IWorkbench)
  • The Renderer, CSSEngine and Workbench Model are decoupled
  • you can extend the default UI-Metamodel delivered with e4
  • declarative UI
  • Dependency-Injection instead of static accessor


Arrived at Ludwigsburg to attend Eclipse Summit Europe 2009

Tonight i’ve been arrived at Ludwigsburg to attend Eclipse Summit Europe 2009 from tomorrow 27. until Thursday 29. October.
There is a big program launched and I’m looking forward to attend in a few presentations during the next days.

27. Oct
OSGi Meeting – Parallel to the Eclipse Summit Europe there is the first OSGi Meeting organize by OSGi User Forum Europe.
e4 Symposium
Symposium on Eclipse Foundation 2.0

28. Oct
Taking Functional Programming Into the Mainstream
What’s in e4
How about I/O?
Climb the Babel Tower
OSGi Best Practices
OSGi Versioning and Testing
Web meets Eclipse
From source to automated builds with Buckminster and p2

29. Oct
Open Source Maturity Curve and Ecosystems Interactions – Lessons Learned
Stop the Architecture Erosion
WebTools Incubator: Creating Web Services with JAXWS
Building Equinox OSGi Applications with EclipseLink–-Even Better in Galileo!
The e4 Toolkit Model – A new view on UIs
ReviewClipse – Continuous Code Reviews within the Eclipse IDE
The p2 provisioning platform

After a day full of presentations, ideas and innovations ;) I will look to give you a sum-up. Also you can ask for your special concern which i have to enter in my sum-up. Or you can setup a question about a presentation i’ve participated in.

Be happy until canceled,

Your CodeScale’s


Lazy activation and registration of a declarative service

The org.eclipse.equinox.ds bundle released with Eclipse Galileo supports lazy activation of declarative services.

The source code of org.eclipse.equinox.ds is located at dev.eclipse.org/cvsroot/rt/org.eclipse.equinox/compendium/
bundles/org.eclipse.equinox.ds

And there we will find the following source code lines:

public final void bundleChanged(BundleEvent event) {
 long start = 0l;
 if (Activator.PERF) {
  start = System.currentTimeMillis();
  log.info(NLS.bind(Messages.PROCESSING_BUNDLE_EVENT, event));
 }
 int type = event.getType();
 if (type == BundleEvent.STOPPING) {
  stoppingBundle(event.getBundle());
 } else if (type == BundleEvent.STARTED) {
  startedBundle(event.getBundle());
 } else if (type == BundleEvent.LAZY_ACTIVATION) {
  startedBundle(event.getBundle());
 } else if (type == BundleEvent.UNINSTALLED && Activator.DBSTORE) {
  storage.deleteComponentDefinitions(event.getBundle().getBundleId());
 }
 if (Activator.PERF) {
  start = System.currentTimeMillis() - start;
  log.info(NLS.bind(Messages.PROCESSED_BUNDLE_EVENT, event, new Long(start)));
  // ... 

Important is the check if the bundle is in the LAZY_ACTIVATION state. In this case the bundle will also be started in the meaning of the DS implementation. This starting invokes the registration of the OSGi-Service. But, and that’s important, the bundle will not be activated and the Activator (if one exists) will not be instantiated. And this is pretty damn lazy :D No single class must be loaded!!!

Follow

Get every new post delivered to your Inbox.