Archive for the ‘java’ Category

Prototype styled Google Analytics javascript snippet

Monday, August 11th, 2008

Recently I’ve created a prototype styled javascript snippet to enable google analytics on one of my sites. Save this code in google.analytics.js file and include it from the head tag of the page just after including of the prototype.js:

gaTrackerId = 'ss-ddddddd-d'; // insert your tracker id here

document.observe('dom:loaded', function() {
var gaJsHost = (
('https:' == document.location.protocol)
? 'https://ssl.'
: 'http://www.'
) + 'google-analytics.com/ga.js';
var script = new Element('script', { 'src': gaJsHost});
var gaTrack = function() {
if (
!script.readyState
|| /loaded|complete/.test(script.readyState)
) {
var pageTracker = _gat._getTracker(gaTrackerId);
pageTracker._trackPageview();
}
};
script.observe('load', gaTrack);
script.observe('readystatechange', gaTrack);
document.body.appendChild(script);
});

Copying nodes between XML documents with Java DOM

Thursday, June 26th, 2008

Today I had an atomic task of creating a most convenient way to copy nodes from one XML document to another with Java’s DOM implementation. Googling did not help me much in it, so I will share the solution here in case someone would be challenged too.

So, imagine you have multiple XML documents like this:

<document><section><node attribute="value" /></section></document>

…, another one like this:

<storage><sections /></storage>

… and you wish to read the multilple documents and to put the <section> nodes into the <sections> node of the second one respecting all the structure.

To do that you should:

1. Create the XML document builder:

DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();

2. Get the <sections> node of the target file:

File target;
Document targetDom = builder.parse(new InputSource(new FileReader(target));
Node targetSections = targetDom.getElementsByTagName("sections").item(0);
// TODO this is not the best way to use that.
// I advice XPath instead.

3. Iterate over the source files and get the <section> nodes:

File[] sources;
for (File source : sources) {
Node sourceSection = builder.parse(new InputSource(new FileReader(source))
.getElementsByTagName("section").item(0);
// [continued inside]
}

4. Copy the node into the target document:

targetDom.appendChild(targetDom.adoptNode(section.cloneNode(true)));
// 'true' means we want to clone children too

5. Write the target back to the file:

TransformerFactory.newInstance().newTransformer().transform(new DOMSource(targetDom)
, new StreamResult(new FileWriter(target)));

That’s it. Note, this code lacks error handling and probably won’t work directly after copy-paste, but just shows you the usage of the classes.

Nice Diagram Editor - yWorks’ yEd

Thursday, February 21st, 2008

Today I felt need in simple diagram editor in order to draw a comprehensive flow-chart diagram.

Previously I widely used Dia one, but it was always to painful to achieve acceptable with no constant mistakes and overall creation always took too long.

In the past I also several times evaluated Enterprise Architect, Visio and SmartDraw, but they were too heavy, not only from the package size and memory usage view, but also they required too much time to get used to them, and time is the most expensive resource, as you know.

So, today I’ve restarted the process of finding a simple and good diagram editor, and surprisingly, the first try give me the one, which caused me to stop immediately.

I won’t list here all yWorksyEd’s features and won’t compare it to anything else - Just try it, and I promise: you will be happy. The only thing to add is it’s very fast and light, despite the fact it’s java based.

Java Code Structure and Dependencies Analysis Tools for Eclipse

Friday, February 1st, 2008

One of my first assignments at the new company (remember, I left Zend previous week), was analysing existing projects structure. Which means distribution of classes into packages, package dependencies, libraries usage etc.

The results, I would say, were far from being perfect, but I can bet, most of large (and especially proprietary) projects would look similar or even worse. But this is not what I was going to say.

What I am going to say, is for this purpose I evaluated several analysis tools and I want to share my opinion about them.

Here they are (in order of evaluation).

1. Eclipse Metrics(1) (CPL)

Pros: Runs fast, provides tangle detector.

Cons: Dependencies graph is not usable with large projects. No text output of dependencies is available.

2. Eclipse Metrics(2) (CPL)

Pros: no.

Cons: Does not analyze dependencies.

2. JDepend

Pros: Nice and simple UI, fast analysis.

Cons: Provides neither graph nor detailed dependency cycles information, doesn’t provide links to source.

3. eDepend (Commercial)

Pros: Fully featured graphic dependency analyzer, allows filtering on dependency kind

Cons: Commercial, creates disproportedly wide graphs for large projects that are hard to maintain, very slow analyzing and graph creation, doesn’t provide info on elements which depend on selected element.

4. stan4j (Free Beta)

Pros: Fully featured graphic dependency analyzer, very cute GEF based UI, cycles and tangles visualizer, very convenient eclipse integration, report/graphics export ability.

Cons: Does not provide recursive dependency paths on selected elements, does not provide inter-package class dependencies information, non graphical views improvement is suggested.

Conclusion

In the end, in order to perform my task I’ve mostly used stan4j, sometimes switched to eDepend and once or twice times executed JDepend - each of them has its specific advantages.

Zend Studio for Eclipse Release & cetera

Tuesday, January 22nd, 2008

Dear diary,

I have 2 news for you today.

  1. Today we successfully released Zend Studio for Eclipse. My contribution to it, beyond PDT commitments, is Sebastian Bergmann’s PHPUnit testing framework integration plug-in, File Network support, Organize Includes and other parts of Refactoring engine, Code Coverage browser… well, it seems that’s it. Maybe several additional, but minor things. Enjoy, guys. This is really a great (and some say - the best) PHP IDE.
  2. Occasionally, these are my last days at Zend Technologies. Since next week I’m starting at Nielsen Online (BuzzMetrics) to do text-mining. If you ask why, the answer is simple - I got bored of Zend, where I spent last 6.5 years of my life, and wanted to do something really new and exciting. I hope it will work :) For now I’m planning to stay an Eclipse committer and continue to help my brothers at Zend to move on.

Source

Dependency Injections in Java 5

Saturday, December 22nd, 2007

Recently I’ve discovered a new “framework” which simplifies dependency injections in Java 5. It’s called Guice.

Well, what can I say. It indeed has sence. But what I’m wandering of is you need a framework for this thing. In PHP you can solve the problem in exactly x lines. And certainly don’t perform at lectures to explain the concept. :)

Grouped Completion (Content Assist) in PDT

Sunday, November 25th, 2007

Last Wednesday I was working on grouping of code completion (content assist) options. It’s now only exists in CVS and will be (hopefully) released with the build after the next one (the current is already finalized).

Overview

The main point of the feature is collapsing of multiple same-prefixed options into groups, instead of showing a long list of the options. For example if your application is based on Zend Framework or PEAR, most of library’s classes start with “Zend_” or “PEAR_”, and this is what you will get as a completion option. In addition, the grouped list doesn’t show common prefix if an user already typed it.

(Demo)

In general it’s applied to all the types of elements (classes, functions/methods, variables and constants) in all the possible contexts (general completion, doc blocks, new/instanceof etc.). The feature is disabled by default can can be found at:
Preferences->PHP->Editor->Code Assist->Group Completion Options

The logic of the grouping is very similar to completion of files in include statements in Zend Neon and is quite simple:

  1. If there are several options which share common prefix AND there are additional elements which do NOT have this prefix, the sibling elements are collapsed to groups with “…” suffix.
  2. After completion of a group, completion pops up immediately again to show elements with the typed prefix.
  3. If typed prefix has common prefix with proposed elements/groups, it’s collapsed with “…” prefix.

How it works

First, all the types of code completion options are created by objects which extend an abstract CompletionProposalGroup (View Source). The class’ work is to receive an array of CodeData’s and return an array of ICompletionOption’s. This is why the feature’s code is mostly aggregated in this class.
So, instead of just creating a completion option for each element, we should first create a tree of all elements, based on elements’ name chunks separated by “_”, then go over the tree and extract only the relevant elements and groups, and then create chopped completion options for groups and elements. And now in details -

Creating Tree of Elements

CompletionProposalGroup.buildCompletionTree()

Luckily, Eclipse platform provides two base components which made the implementation relatively simple. It’s IPath/Path couple, which provide a comfortable solution for handling abstract OS-like paths, and ElementTree, which is a recursive tree data structure which gives access to it’s nodes based on IPaths.
The first action item here is to create a path from element’s name – it’s done by replacing all delimiters with slashes and providing the result string to Path’s constructor. Then it’s time to recursively create the element – if the parent path is not in the tree, we’ll add it with null data attached (these nodes will represent element groups in the future). After the parents exist, we are adding the element itself to the tree with CodeData object attached.

Extracting relevant Elements and Groups

CompletionProposalGroup.treeRecursiveCreateElement()

In order to get the relevant elements and groups according to 3 rules mentioned above, we basically need to recursively get children of a tree node starting from the root. However if there are no children for current node or the node has sibling(s) - we don’t want to continue deeper inside, and just return the current node. As a result, we get list of elements and collapsed groups to create completion proposals from.

Creating Elements and Groups Completion

CompletionProposalGroup.calcCompletionProposals()

Afterwards, the only remaining thing is to create proposals. For element proposals there is a wrapper proxy PartialProposal for CodeDataCompletionProposal which cuts off matching segments of prefix, and for groups – there is a wrapper proxy TemporaryCompletionProposal for CompletionProposal created with cut prefixes,  which only ovverrides ICompletionProposal.apply() method to reactivate completion immediately group application.

That’s all it’s about.

Copying files the Eclipse way

Tuesday, November 6th, 2007

The tip on subject.

PDT CodeDataResolver and ContentAssistSupport Unit Testing

Sunday, October 21st, 2007

Just wrote the subject related article here.

The article explains the concept of editor caret position based Unit Testing of editor links and code completion in PDT.

  • You are currently browsing the archives for the java category.
  • Pages

  • Archives

  • Categories