As I seem to end up with the odd person dropping by the blog to look at IntelliJ keyboard Short cuts, I figured that it is probably worth pointing people towards the DZone IntelliJ Refcard which has a pretty good introduction to IntelliJ.
Archive for the ‘Java’ Category
Swing Text APIs
At Ephox we are pretty heavy users of the Java text APIs. In some respects the EditLive! team probably knows more about them than anyone in the world. In a Creative Coding Afternoon recently, I was doing some work on a cool plugin for EditLive! (it might make it into a future release of Enterprise Edition), and after spending time getting angry with the Swing document (some of the anger was justified). I had an epiphany. I expect that the actual revelation will not matter to any outside of Ephox (ok so people who want to work for ephox might be interested), but I'm going to share it anyway.
The Swing Document model != the DOM. Don't expect it to look like the DOM. Don't expect it to be the HTML DOM. The subclass HTMLDocument is not the DOM. While you can access all the information in the DOM, you should not expect there to be a direct mapping between concepts in the DOM and in the Swing Document model. You can expect all the information in the DOM to be available in the Swing Document model, but it isn't going to look exactly like the DOM. The Swing Document model is a generic model for presenting a document for us in a rich text editor, which means the DOM is transformed to work with the Swing Document model.
Once you can get your head around this, the Swing Text APIs can begin to make more sense (although I'm still grumpy about the lack of working with the java.util.collections properly).
JWhich in a line of code
Old skool java programmers will have almost certainly come across the tool JWhich (http://www.javaworld.com/javaworld/javatips/jw-javatip105.html). It's the classic tool for finding out which jar file contains a class. The following line of code has the same effect, and is slightly better than just trying to grep jar files.
com.ibm.websphere.management.AdminService.class. getClassLoader(). getResource( "com/ibm/websphere/management/AdminService.class");1
1 – after reading the source for JWhich I realised that I have just copied it exactly
↩
Programmatic Check for WebSphere Portal iFixes and Fixpacks
As the internet didn't seem to know how to programatically lookup the installed iFixes and Fixpacks for a PortalServer, I'm going to share my solution, it the hope that someone can point me to a better way.
What I was able to work out from trawling the net and poking around at the WebSphere portal installation is that the install history for iFixes and Fixpacks for Portal are stored in the directory %PORTAL_HOME%/version/history. This makes the process of finding the fix level a case of:
- Lookup the Portal home.
- List the files in the version history directory.
Lookup the Portal Home
To lookup the portal home, use the fact that there is a WPS_HOME environment variable set in the WebSphere environment. Unfortunately looking up values in the WebSphere environment is non-trivial. The WebSphere environment is not made directly available, to access it you need to go through the WebSphere Admin service, and the WebSphere management mbeans.
The code to do this is:
com.ibm.websphere.management.AdminService as = com.ibm.websphere.management.AdminServiceFactory.getAdminService(); String server = as.getProcessName(); javax.management.ObjectName serverName = new javax.management.ObjectName("*:*,type=AdminOperations,process=" + server); Set objectNames = as.queryNames(servName, null); javax.management.ObjectName objectName = (javax.management.ObjectName) objectNames.iterator().next(); Object[] args = new Object[] {"${WPS_HOME}"}; String[] signature = new String[] {"java.lang.String"}; String wpsHome = as.invoke(objectName,"expandVariable",args, signature);
The wpsHome variable will contain the string path to the websphere portal home directory.
List the Files in the Version History Directory
After retrieving the portal home, it is possible to lookup the fixpacks in the ${WPS_HOME}/version/history directory.
The following code does this:
File f = new File(wpsHome + File.separatorChar + "version" + File.separatorChar + "history"); String[] children = f.list(); for (int i=0;i<children.length;i++){ out.println(children[i]); }
In summary the full code snippet for this is:
com.ibm.websphere.management.AdminService as = com.ibm.websphere.management.AdminServiceFactory.getAdminService(); String server = as.getProcessName(); javax.management.ObjectName serverName = new javax.management.ObjectName("*:*,type=AdminOperations,process=" + server); Set objectNames = as.queryNames(servName, null); javax.management.ObjectName objectName = (javax.management.ObjectName) objectNames.iterator().next(); Object[] args = new Object[] {"${WPS_HOME}"}; String[] signature = new String[] {"java.lang.String"}; String wpsHome = as.invoke(objectName,"expandVariable",args, signature); File f = new File(wpsHome + File.separatorChar + "version" + File.separatorChar + "history"); String[] children = f.list(); for (int i=0;i<children.length;i++){ out.println(children[i]); }
The work of mapping file names to the installed fix packs/iFixes is left as an exercise for the reader.
Does anyone know if there is a better way of dong this?
Web Character Encoding
Making character encoding work well on the web can be a bit of a tricky task. There are many different layers to get right, and many different places in which things can go wrong.
At Ephox we have seen many of our clients experience problems with character encoding, and different fonts. We've actually created a variety of different articles to help people make there content editing environment work better:
http://liveworks.ephox.com/2007/05/15/why-international-characters-display-as-boxes/
http://liveworks.ephox.com/2007/05/08/solving-character-set-issues-with-legacy-systems/
http://liveworks.ephox.com/2007/09/03/character-encoding-and-special-characters/
http://liveworks.ephox.com/2008/03/11/url-encoding-and-character-sets/
http://liveworks.ephox.com/2008/02/05/controlling-entity-encoding
More recently I have been seeing some issues with encoding without EditLive! included. Sun proved to have a decent article talking about Character Conversions: http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/. This articles includes good details on how to setup your JSP/Servlet layers to support encodings well.
This proved to be the answer to my problems, and well worth viewing if you are having encoding related problems in a Java Web application.
Howto Learn an API
I recently have been learning a number of different APIs. After reflecting on my process for learning I have ended up with the following strategy for working with APIs.
- Find someone who has used the API in the past and get a brief introduction.
- Read documentation about the product (starting at the central documentation site for the product, include any tutorials and getting started guides). The goal from this first step is to get a general background understanding of what the product is about, the core concepts and jargon and principles of the product.
- Use the product without the APIs. If there is a gui to access to product that is available, ensure that you know this, and the jargon around the product. Try and ensure that the information you have from step 1 is grounded in reality.
- Read more documentation around the APIs. Make the top goal for this round to get enough of an understanding of what you can do.
- Explore the APIs to see what they expose of the feature. The set of features exposed by APIs often do not match up with what is exposed through the GUI. The most important spot to aim for is the subset of features that are supported by both the API and the GUI.
- Google (as usual it’s your friend). Sometimes there are some useful results in google that are missed elsewhere. Start with searching for the product name, try adding in API/howto/tutorial/getting started keywords to filter down content if you get too many results.
- Write some exploratory code to see how the APIs work, and what they do. This should enable you to know enough to actually write the code that you need.
All steps are required, as there are often features which are not easily discovered by just taking one of the above paths. One of the most important steps is ensure that you do understand the subset of what is supported by the API and the front-end. This helps to ensure that you are actually hitting the right part of the API.
From time to time there are options which are not well documented at all, and are only alluded to in technical documents. It can be worth contacting authors of documents if the feature is not clear. The coding and exploration of the system will need to continue after this. It should be expected to continue learning the APIs. At every stage there is value in talking to whatever experts/more experienced people you have available. Being able to quickly pickup a technology and move from no knowledge to confidence in using the API is a valuable tool for developers. Learning new technologies has been an important part of my job as a software engineer, and I expect that it will continue to be for many years to come.
TestDox IntelliJ Plugin Reviewed
I’ve recently started using the TestDox plugin with IntelliJ. It’s a nice little tool that fits in well with agile test driven development practices. It’s easy to get started with, either installing it from the IntelliJ plugins repository using your IDE, or downloading it directly from the plugins repository, and copying it into the plugins directory.
The premise on which the test dox plugin is based on is the idea that your test methods should be long sentences using CamelCase to break up words. By doing this your tests become your documentation. The plugin takes this premise, and exposes the following behaviour in IntelliJ:
- automatic translation of CamelCase test names to sentences. This is exposed through two different views, which, when coupled with nice navigation synchronisation options, makes it possible to use your tests to understand what the code is meant to do at a high level, and makes it easy to drill down to the specifics when needed.
- There is a simple mapping between classes and tests – TestDox knows that HelloWorldTest is the test for HelloWorld. This is configurable to suit your environment (test classname prefixes and suffixes can be specified, as well as test packages).
- documentation windows will be context sensitive, using the above mapping to show the appropriate documentation for the class/test currently being edited.
- alt-shift-t swapping between the test class and the base class – great for navigation
- alt-shift-t will prompt to create a test class if it doesn’t exist. Very cool fr the cases where you have created a class before the test (for whatever reason)
Overall this is a great little tool. There’s only a couple of minor tweaks I’d like to see made to the tool.
- The biggest that would be nice for the open source project, would be to make editing the source code of the IntelliJ plugin slightly easier. It would be cool to be able to make slight changes to the software, and help improve the project, but the cost of entry was slightly too high for me.
- It would be good for the alt-shift-t auto creation to work both ways. That is I want alt-shift-t to help me automatically create the class as well as the test.
- I saw a couple of minor screen repaint issues on 7.0.3 on OSX 10.5
TestDox is a good tool for IntelliJ, and you really should install it and use it.
Utility method for TDD of a SwingBorderLayout
I have been working with different ideas for Test Driven Swing code for a while now. Recently, Suneth and I came up with a new strategy for testing Swing BorderLayouts (unfortunately requiring reflection).
Here is what we did.
When using a border layout you are specifying the relative position of the components. To TDD this, you really want to say whether your component appears in the NORTH, SOUTH, EAST or west location.
Unfortunately this isn't exposed directly, hence the need for reflection.
Here is the method that we wrote to do this:
private JComponent getComponentAt(BorderLayout layout, String position) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException { Method method = BorderLayout.class. getDeclaredMethod("getChild", new Class[]{String.class, boolean.class}); method.setAccessible(true); return (JComponent) method.invoke(layout, new Object[]{position, Boolean.TRUE}); }
The layout is the layout containing the component, and the string position needs to be one from the BorderLayout constants (BorderLayout.NORTH etc).
The method will retrieve the component at the specified position using reflection, allowing you to write simple assertions around this.
Creating a Surround in Quote Live Template in IntelliJ
One of the features I like about TextMate is the smart insertion of characters, like when I’m typing text, highlight a word, and type ", TextMate will wrap the word in quotes. Unfortunately IntelliJ doesn’t have this behaviour by default, and makes surrounding some text in quotes messier than what would be preferred.
It is possible to make this task much easier, through the use of live templates. Here is how to do it.
- navigate to the add a live template screen via the following path: settings – live templates – add
- type "$SELECTION$" as the template text, ensure that the context is suitably broad, give it a meaningful name, and you are done. This can be seen in pictures.
You will now be able to access the template using the cmd-option (ctrl-alt) t "surround with" shortcut, making it easy to wrap text (code) in quotes using IntelliJ.
Fixing Intermittent Table Not Found Errors with JUnit when Using Hibernate SchemaExport and H2
As a part of my test suite, I run a series of tests using Hibernate and the h2 database (h2 seems to be the most lightweight java in memory database around at the moment). These tests run in memory and perform realively quickly, so are a part of my pre-commit build.
In order to move to a spot where the application upgrades work well, I’ve just removed the hbm2ddl.auto create-drop statements from my hibernate.xml file, and wanted to move to a programmatic use of the SchemaExport tool. This was more pain than expected, so I’m documenting what I had to do here.
From the javadoc, and Java Persistence with Hibernate, it looks like you can get away with the following code:
1 | 1: Configuration configuration = new Configuration().configure();<br /> 2: SchemaExport schemaExport = new SchemaExport(configuration);<br /> 3: schemaExport.create(false, true);<br /> |
Unfortunately I found that this didn’t quite work. It seems that the connection/transactionality/connection pool combination of concerns would cause this kind of code to fail at various degrees. After much gnashing of teeth I ended up with the following code:
1 | 1: Configuration configuration = new Configuration().configure();<br /> 2: SessionFactory sessionFactory = |
1 | configuration.buildSessionFactory();<br /> 3: Session session = sessionFactory.openSession();<br /> 4: Connection connection = session.connection();<br /> 5: SchemaExport schemaExport = |
1 | new SchemaExport(configuration, connection);<br /> 6: schemaExport.execute(false, true, false, true);<br /> 7: session.close(); |
the critical differences are:
In lines 2-4 we are obtaining a connection to the database which is then used by the schema export tool. In line 6 we do the export using the execute command, passing in a bunch of booleans. This tell it execute command:
- don’t output the sql to the console,
- do execute on the database,
- don’t execute drop statements, and
- do execute create statements.
Finally in line 7, we close the session, ensuring jdbc connection is released and cleaned up. Now any intermittent problems caused by using schema export with h2 database should be avoided.





