Thursday, December 20, 2012

Conditional menu contribution relying on java code

Context

Last few days I need to build a contextual menu on a TreeViewer provides by antother plugin. This TreeView containing EClass instance (comming from ecore and genmodel).

What I want to do is implement functions allowing  :
  • the create a new Resource containing a particular selected object
  • to absord the contend of a ressource containing a particular selected object
To build those functions, I rely on a provide popup menu (comming from EMF Client Plateform : ECP)

Developments

So I add :
  • command (extension org.eclipse.ui.commands)
  • menu entries using contributionItems (extension org.eclipse.ui.menus)
    • contribution item refers a command 
  • handler (extension org.eclipse.ui.handlers)
    • refers a command
    • describs "visiblewhen" using 
      • iterate
        • and
          • instanceof
          • test refers a propertyTester
      • count
  • propertyTester (extension org.eclipse.core.expressions.propertyTesters)

Plugin.xml fragment

here I just show how to detect that the selected "MyObject" is not already in a particular resource.

Command


<extension
         point="org.eclipse.ui.commands">
      <command
            id="franckys.gui.command.makeFragment"
            name="Make fragment">
      </command>
   </extension>

Contribution item


   <extension
         point="org.eclipse.ui.menus">
       <menuContribution
            allPopups="false"
            locationURI="popup:org.eclipse.emf.ecp.navigator.viewer?after=additions">
         <command
               commandId="franckys.gui.command.makeFragment"
               style="push">
         </command>
      </menuContribution>
   </extension>


handler

Here the expected behavior is obtain using "test" in java and "instanceof" checking.

   <extension point="org.eclipse.ui.handlers">
  <handler
   class="franckys.gui.handlers.MakeFragment"
   commandId="franckys.gui.command.makeFragment">
   <enabledWhen>
    <with variable="selection">
     <iterate>
      <and>
       <instanceof
       value="franckys.model.MyObject">
       </instanceof>
       <test
       property="franckys.isFragment"
       value="false">
       </test>
      </and>
     </iterate>
     <count
      value="1">
     </count>
    </with>
   </enabledWhen>
  </handler>
 </extension>


propertyTester


   <extension
         point="org.eclipse.core.expressions.propertyTesters">
      <propertyTester
            class="franckys.propertytester.IsFragmentTester"
            id="franckys.propertytester.isfragment"
            namespace="franckys"
            properties="isFragment"
            type="org.eclipse.emf.ecore.EObject">
      </propertyTester>
   </extension>


source code


propertyTester


import org.eclipse.core.expressions.PropertyTester;

import franckys.model.MyObject;

public class IsFragmentTester extends PropertyTester {

 public IsFragmentTester() {
 }

 @Override
 public boolean test(Object receiver, String property, Object[] args,
  Object expectedValue) {
 if (receiver instanceof MyObject) {
  MyObject myo = (MyObject) receiver;
  if("isFragment".equals(property)) {
   Boolean value = (Boolean)expectedValue;
   boolean bool = myo.eResource() == myo.eContainer().eResource();
   if(value.booleanValue()==false) {
    return bool;
   } else {
    return !bool;
   }
  }
 }
 return false;
 }
}


Handler


public class MakeFragment extends AbstractHandler {
 @Override
 public Object execute(ExecutionEvent event) throws ExecutionException {
 //Do the job in emf transaction
 }
}

Thursday, October 18, 2012

Eclipse update timeout

A reminder for eclipse update timeout...


If your eclipse environment produce timeout when installing or upgrading a plugin you could try to add in you eclipse.ini:


-Dorg.eclipse.ecf.provider.filetransfer.retrieve.closeTimeout={value time in millisecond, default is 1000}

-Dorg.eclipse.ecf.provider.filetransfer.retrieve.readTimeout={value time in millisecond, default is 1000}


Tuesday, September 18, 2012

XML configuration is not bad


I write this post because I red more and more post or article  that promote annotations simply clamming or suggesting  that XML is bad, unusefull... It is not for me the right way to present things.

XML and annotations are complementary technics, each adresses differents problematics.  This point of view rely on work with differents frameworks or product like Spring, CDI, guice, eclipse DS (Inversion relying on OSGI waving mecanisms), Hibernate, Jaxb, Service Mix ... where one could find many xml, annotated or source configurations...

As I agree to say that annotations are usefull in some cases, I'm not agree to replace all XML configurations by annotation only on assertions like:

  • It's less XML centric; does I should think that's XML centralization is bad ???
  • You generally have one implementation per Java interface, so even if a best practise in OO is "think in inteface terms"  I am septical when I red this point. 
    • If I observes, at the end of my conception, that I have one implementation for each interface, I should ask to myself for each interface : "should I have, reasonnably,  during the product lifecycle changes here" and then I delete or not this inteface to simplify the system.
    • Justify the use of annotations because each interface bind the only one existing implementation with no source dependency  is ok for me in the case that the answer to the previous question is  : "no changes in the future". But in  the opposite case ? You should add a sort of "routing mecanism" to point the write implementation in the considered case. So it's the same thing  as writing a configuration (in java or XML) or writing  a switch / case / new ....


In fact my purpose is not to say "annotation is evil".... IT IS NOT. Annotation is an efficient paradigm.  I just want to explain why I think that XML stays a valid technical choice dependending of the context.

Let me expose a real case :
I had to install an open source product for my client. This client wanted to use his prefered RDBMS system. The problem here, is : this RDBMS is not validated with this product.... Anyway I install both, did the configuration and saw that AUTO-INCREMENT is not supported here, as the too much long association name. At this point I though ok, no problem, let have a look to the "xml mapping files" to change this... but there no... there only annotation in source code....
So I had to get the source code, make a full search to find annotations for RDBMS, make changes, compiled sources, package and redeploy....
If I could find XML centric mapping, I should do the job, changing only XML mapping file.... more secure, more efficient in my point of view...
In this case, Xml centric configuration is good... beacause in this way, you doesn't have to :

  • modify source code
  • compile
  • package

In some case it could be expensive to do that depending of system criticity, development norms and so one...
And in some case not ....

Other thing I coul read about this point :

  • Java developpers are developers not XML editors, Ok and so what ? If the context imply XML file configuration usage, you should hire a new XML editor ? 
  • xml configuration is too verbose ? Ok it is a fact but it is sometimes veru usefull to have few human readable configuration. I currently work on a system with five hundred classes and interfaces and it's nice to be have to see the whole sytem configuration with a couple of XML files opposes with "distributes (in source code) configuration" offers by annotations uses


At the end of this post my position is :
"Annotations" and "XML configuration" are both efficient and not exclusive.



Thursday, September 6, 2012

redirecting system.out for purpose testing

In a test I had verify an output on system.out. At first I use slf4j and after reflexion I think about redirecting System.out... It gave the next lines


static private PrintStream currentSystemOut = System.out;
static private List listchar = new ArrayList(); 


....
@BeforeClass static public void setup() {
....
  //redirect system.out  to listchar
  PrintStream printStream;
  OutputStream outs = new OutputStream() {
   @Override
   public void write(int b) throws IOException {
   char c = (char)b;
   listchar.add(new Character(c));
   }
  };
  printStream = new PrintStream(outs);
  System.setOut(printStream);
 }
 
@AfterClass static public void teardown() {
  //revert setting
  System.setOut(currentSystemOut);
 }
 
private static String getOutContent() {
  String res = "";
  for(Character aChar:  listchar ) {
   res = res.concat( aChar +"");
  }
  return res;
 }
...

Adding contextual help to an Eclipse Wirzard plugin

Just a useful link that works for doing that here.

Another thing if eclipse help system is very slow when browsing page, on winXP and behind a proxy, check your connexion settings (verify bypass for local adress)


Wednesday, June 13, 2012

Rich editor in eclipse RCP (Part 1)

Rich editor in eclipse RCP (Part2)

Why this post... because I 'm looking about a rich text editor in an eclipse RCP application... After few readings I saw that is not so obvious.


You could find more info at : git@github.com:franckys/TutorialSamples.git
In the tinymceTest folder. 
This repo does not contain tinyMce so you have to download your own to make it work.


At the end I found (and use) an interresting approach : Integrate a well known (In my case) javascript rich text editor, relying on SWT browser (http://www.vogella.com/blog/2009/12/21/javascript-swt/) capabilities.... The result :

As the integraton is not an "heavy one" I decided to do my own...
These are the steps required for this integration :
  1. I download the last Tinymce version. In my case the 3.5.2 (download here)
  2. Build an HTML page containing required  :
    • CSS
    • Javascript
    • textarea html element
  3. Use your favorite tools for debuging (In my case chrome + web developers tools) to customize tinymce contents (plugins, buttons, css...)
  4. Optional : Build a specific tinymce plugin to allow contextual floating menu content managment. For this I simply :
    • take the example, 
    • follows Tinymce guide line
    • remove all unecessary code 
    • add this code :
      init : function(ed, url) {
       ed.onInit.add(function(ed, e){
       ed.plugins.contextmenu.onContextMenu.add(function(th, menu, event) {
          menu.removeAll();
          menu.add({title : 'advanced.paste_desc', icon : 'paste', cmd : 'Paste'});
          menu.add({title : 'paste.paste_word_desc', icon : 'pasteword', cmd : 'mcePasteWord'});
       ed.plugins.paste.pasteAsPlainText = 1;
        });
       });
      },
      
  5. write a java plugin :
    • providing a composite Class containing  (and presenting) "org.eclipse.swt.browser.Browser"
    • initializing this browser with an URL ponting on the previous HTML page
    • providing a setEditorContent (inject in textarea the desired and HTML/JS formated code)
    • In java
      public void setEditorContent(String htmlText) {
         String jscript = " setEditorText('" + formatEditorText(htmlText) + "');";
         if (!browser.execute(jscript)) {
           throw new UnsupportedOperationException("JavaScript was not executed.");
         }
      }
      In js
      function setEditorText(editcontent) {
         var textarea = document.getElementById('textarea');
         textarea.value = editcontent;
      }
    • providing a getEditorContent using for example 
    • In java
      public String getEditorContent() {
          Object o = browser.evaluate("return getEditorText()");
          return (String) o;
         }}
      in js
      function getEditorText() {
          var tmce = tinyMCE.get('textarea');
          return tmce.getContent();
      }
You could find more info at : git@github.com:franckys/TutorialSamples.git
In the tinymceTest folder. 
This repo does not contain tinyMce so you have to download your own to make it work.

Rich editor in eclipse RCP (Part2)

Wednesday, May 30, 2012

Installing Rational Quality Manager for testing purpose

Objectives :

  • Evaluate if Rational Quality Manager capabilities could fit our needs in a couple of days
  • Build a test using a java.jar, injecting references datas, collecting results and evaluate this results. 


This install is a trial  Jazz Team server bundle.

Donwloading and installing
  • As I already have installed Rational Functional Tester I have an IBM Installer Manager. So I download the 1,5 Go zip file on jazz.net.
  • I unzip and register the result in the Installation manager.
  • I install all elements
After this you have a tomcat server installed in:
${YOUR_PATH}/IBM/JazzTeamServer/server

run
sudo ./repotools-qm.sh -clean

Start this server
./server.startup.sh (add a tail -f on log file to see what happened....)
Open a browser and go to
https://localhost:9443/jts/setup

you will have a setup screen :

  • Configure URI : in my case I use "https://localhost:9443/jts"  (testing purpose)
  • Configure Database : let Derby's configuration
  • Enable E-mail notification : disabled
Problems
At this point I have to stop my server because I couldn't discover properly application to register qm, ccm, etc.
After looking in logs I found a problem :
'too many file open' 
this problem sound like familiar as a friend  has the same problem on alfresco... so after looking here, modifying and restarting I could continue.

So I login as ADMIN (https://localhost:9443/jts/setup) and finish setting process. It was a long list of "next","wait", "next","wait"....  (setting for jts, qm, ccm, admin and rm)

And finally you have a success setup screen that allows you to create users or create lifcyle project....

I can now set role and permissions, create project areas and so on....

Create a command line script
After a "set up" phase :

  • test environnement, 
  • test case 
  • machines
  • users
  • and so on...
Now I would like to create a commandLine script and I block on adapter selection.... after a few reading and ggogling I found that :

  • Command Line Adapter is deliver with RQM
  • In my case it's a zip file
  • The readme.txt show how to run this adapter to allow RQM to propose this adapter in a selection list.
At the end I found this link https://jazz.net/library/article/809. This link explain a lot of things....
And this one https://jazz.net/library/article/755









Starting dev on ubuntu 12.04 LTS : GTK (part 02)

Now we have our C launcher I'd like to see how it could work with Python.
Writing the next script give the same result as in C :

main.py :
#!/usr/bin/env python

import sys
import gtk
    
class TestProg:
    def on_window_destroy(self, widget, data=None):
        gtk.main_quit()
     
    def __init__(self):
    
        builder = gtk.Builder()
        builder.add_from_file("test.xml") 
        
        self.window = builder.get_object("window1")
        builder.connect_signals(self)       
    
if __name__ == "__main__":
    prog = TestProg()
    prog.window.show()
    gtk.main()


the next step is : how to react to my button...

Friday, May 25, 2012

Starting dev on ubuntu 12.04 LTS : GTK (part 01)

After few reading and googling I choose to use glade and GTK (see http://glade.gnome.org/  and http://www.gtk.org)

Before starting I do some installations :
apt-get install  glade

apt-get install gnome-core-devel build-essential


And I start with the tutorial.. (http://developer.gnome.org/gtk-tutorial/stable/c39.html)

and then I start building my own GUI :


After few reading I saw that there is a GTK+ 3 ... Then I install it :
sudo apt-get install libgtk-3-0 libgtk-3-0-dbg libgtk-3-bin libgtk-3-common libgtk-3-dev libgtk-3-doc


To see the version and the includes path use (more explanation could be found at : http://www.micahcarrick.com/gtk-glade-tutorial-part-3.html)
pkg-config --modversion gtk+-2.0

pkg-config --cflags gtk+-3.0

Now I want to run my app... so i need to
  • write a "launcher" (I chose to write it in C)
  • compile
The launcher :

#include <gtk/gtk.h>

void 
on_window_destroy (GObject *object, gpointer user_data)
{
        gtk_main_quit();
}

int
main (int argc, char *argv[])
{
        GtkBuilder              *builder;
        GtkWidget               *window;
        
        gtk_init (&argc, &argv);
        
        builder = gtk_builder_new ();
        gtk_builder_add_from_file (builder, "test.xml", NULL);

        window = GTK_WIDGET (gtk_builder_get_object (builder, "window1"));
        gtk_builder_connect_signals (builder, NULL);          
        g_object_unref (G_OBJECT (builder));
        
        gtk_widget_show (window);       
        gtk_main ();
        
        return 0;
}

To  compile :

gcc -Wall -g -o testProg main.c -export-dynamic `pkg-config --cflags --libs gtk+-3.0`


The first running does not work...I have to 
  • change from GtkGrid to GtkTable
  • change from to 
  • change from to
  • change values attach to right_attach and bottom_attach
  • change from GtkPaned to GtkHPaned
At the end I saw :


Ok, I have something but it's not exactly what I want... 


Materials
  • gcc proxypass.c -o proxypass `pkg-config --cflags --libs gtk+-2.0`
  • http://www.micahcarrick.com/gtk-glade-tutorial-part-3.html
  • http://www.micahcarrick.com/gtk-glade-tutorial-part-1.html
  • http://www.gtk.org/documentation.php
  • sudo apt-get install libgtk2.0-dev sudo apt-get install libgtk2.0-doc devhelp

Thursday, May 24, 2012

resizing virtualbox machine disk on Ubuntu 12.04 LTS guest

Before starting do a backup and verify it works ....!


  • First use vboxmanage  (I want to changemy VM size from 8Go to 15 Go dynamic size): 

VBoxManage modifyhd  yourpath\yourMachine.vdi --resize 15360


you will see something like that  :

0%...10%...20%...30%...40%...50%...60%...70%...80%...90%...100%



  • Then add in the VM settings an ubuntu live CD  (containing gparted) and then boot on it. After boot, run gparted. In my case, before extend my partition, I have to move extended partition containing swap. 
  • Finally extend your partition.

At the end if you have moved your SWAP partition you'll probably change its UUID (see here). Use the next command to see your current and in use swap UUID :
cat /etc/fstab 

And use 
blkid | grep -i swap 

to see if UUID are the same.... Make correction if needed in fstab. 

Friday, April 27, 2012

Usefull eclipse application startup parameters


Mainly because I do not remember extacly all small things I put them here...


Program arguments :
  • -consoleLog
  • -clean

VM arguments :
  • -Dosgi.requiredJavaVersion=1.5
  • -Dosgi.clean=true
  • -Dosgi.console


The most usefull parameter is for me the last one. It allows use of osgi console. 
This command line console active in console log. This console allow :


  • Controlling the OSGi framework
  • Controlling Bundles
  • Displaying Status
  • Extras
  • Controlling Start Level
  • Controlling the Profiling
  • Eclipse Runtime commands
  • Service Component Runtime
  • ...


To get more information, use 
osgi> help
gives :

Exemples  
osgi> ss (Short Status)
gives :

  
osgi> bundle number
provides view on : 


  • Id, 
  • Status,
  • Location,
  • Registered services,
  • Services in use,
  • Exported packages,
  • Imported packages,
  • Host bundles,
  • Class spaces,
  • Required bundles.


Tuesday, April 10, 2012

OSGI Maven bundle for Eclipse (Part 1)

Context
I have a maven project uses many dependencies. I want to use this project as an OSGI bundle. This bundle have to export all its package and dependencies packages, and includes the physical jars.
My first approach was to use apache Felix, maven-copy-dependency and maven-eclipse-plugin.

  • apache felix maven-bundle-plugin for MANIFEST.MF building (including dependencies export)
  • maven-dependency-plugin for jars copy
  • maven-eclipse-plugin for eclipse files update (.classpath and .project)
  • maven-clean-plugin for deleting temporary files.

I finally leave this approch because I could not managed to set up maven plugins producing  the result targeted.

At the end my solution was :

  • apache felix maven-bundle-plugin for MANIFEST.MF building (including dependencies export)
  • maven-dependency-plugin for jars copy
  • specific maven plugin for files update (.classpath)
  • maven-clean-plugin for deleting temporary files.
This solution produces : 
  • a MANISFEST.MF including export package for all maven dependencies
  • a jar including jar dependencies 
  • an eclipse .classpath including all copied dependencies 
Usefull information could be found at  :
My satisfying configuration is giving below (see excerpt).


<project...>
...
  <build>
 <plugins>
   <plugin>
  <groupId>org.apache.felix</groupId>
  <artifactId>maven-bundle-plugin</artifactId>
  <version>2.3.7</version>
  <extensions>true</extensions>
  <configuration>
    <manifestLocation>META-INF</manifestLocation>
    <instructions>
   <_nouses>true</_nouses>
   <unpackBundle>true</unpackBundle>
   <Bundle-SymbolicName>${bundle.symbolicName}</Bundle-SymbolicName>
   <Bundle-Version>${project.version}</Bundle-Version>
   <Bundle-RequiredExecutionEnvironment>J2SE-1.5</Bundle-RequiredExecutionEnvironment>
   <Import-Package>!*</Import-Package>
   <Export-Package>!target.*,*;-noimport:=true</Export-Package>
   <Embed-Dependency>*;scope=compile|runtime;inline=false</Embed-Dependency>
   <Embed-Transitive>true</Embed-Transitive>
   <Embed-Directory>${dependency.outputdirectory}</Embed-Directory>
   <Embed-StripVersion>false</Embed-StripVersion>
   <Bundle-ClassPath>.,{maven-dependencies}</Bundle-ClassPath>
    </instructions>
  </configuration>
  <executions>
    <execution>
   <id>bundle-manifest</id>
   <phase>process-classes</phase>
   <goals>
     <goal>manifest</goal>
   </goals>
    </execution>
  </executions>
   </plugin>
   <plugin>
  <artifactId>maven-clean-plugin</artifactId>
  <version>2.4.1</version>
  <configuration>
    <filesets>
   <fileset>
     <directory>${basedir}/META-INF</directory>
     <includes>
    <include>**/*.MF</include>
     </includes>
     <followSymlinks>false</followSymlinks>
   </fileset>
   <fileset>
     <directory>${dependency.outputdirectory}</directory>
     <includes>
    <include>**/*.jar</include>
     </includes>
     <followSymlinks>false</followSymlinks>
   </fileset>
    </filesets>
  </configuration>
   </plugin>
   <plugin> 
  <artifactId>maven-dependency-plugin</artifactId> 
  <configuration> 
    <excludeTransitive>false</excludeTransitive> 
  </configuration> 
  <executions> 
    <execution> 
   <id>copy-dependencies</id> 
   <phase>process-classes</phase>
   <goals> 
     <goal>copy-dependencies</goal> 
   </goals> 
   <configuration> 
     <excludeScope>provided</excludeScope> 
     <outputDirectory>${dependency.outputdirectory}</outputDirectory> 
     <overWriteReleases>false</overWriteReleases> 
     <overWriteSnapshots>false</overWriteSnapshots> 
     <overWriteIfNewer>true</overWriteIfNewer> 
   </configuration> 
    </execution> 
  </executions> 
   </plugin> 
   <plugin>
  <groupId>fr.eclipse.plugin</groupId>
  <artifactId>maven-pdeAdapter-plugin</artifactId>
    <version>0.0.1-SNAPSHOT</version>
  <configuration />
  <executions>
    <execution>
   <id>managed-classpath-file</id>
   <phase>prepare-package</phase>
   <goals>
     <goal>process-classpath</goal>
   </goals>
    </execution>
  </executions>
   </plugin>
 </plugins>
  </build>
</project>