Pages

Friday, December 9, 2011

Sunday, October 23, 2011

Sublime: The Awesome Text Editor

What is your favorite text editor? Not only to edit text but also to write some code. Emacs? Vim? Notepad++ or SciTE? Yeah, for code you can use IDEs, but sometimes it is just too much.

Myself, I'm a long time Vim fan. I know emacs is really-really powerful, but I could not quite understand the ideology behind it. Sometimes I use Notepad++, just because it works really well for log files. Just recently I discovered Sublime. This is a really awesome piece of software!
Sublime is available for OS X, Linux and Windows. It feels really lightweight, and the UI is quite responsive. In Sublime's blog you will find nice tips and tricks on how to use the editor. And if you take a look at the support forum, it seems that the guys are quite busy making the editor even more awesome. This all together just makes you want to by a license! :)

The UI is rather minimalistic, and all the required windows and dialogs appear on demand by pressing a relevant shortcut. What I really like is the file outline on right (see the screenshot below).


Sublime comes with a huge number of code snippets available out of the box and you can define your own.


Regarding the features, you're almost able to use Sublime as a full-featured IDE, not as intelligent as IntelliJIDEA, but still - you can edit code quite efficiently, compile source and execute the apps. Also, Sublime is quite extensible - you can create your own plugins, customize the layout, shortcuts, etc.

I think, Sublime could be the new tool in my toolbox if I'd need to code something besides Java :)

Monday, August 29, 2011

What’s Cool In IntelliJIDEA. Part III: External Tools

Previous posts about IntelliJ
What’s Cool In IntelliJIDEA. Part I
What’s Cool In IntelliJIDEA. Part II: Live Templates


Although there is almost any kind of functionality available in IntelliJIDEA, either as a base functionality or via plugins, there's still a fraction of probability involved that you might want to do something that goes beyond the power of the IDE. For such rare cases you might want to take a look at External Tools in IntelliJ.

Just recently I've encountered such a case myself - I wanted to use an utility from JDK, but in a more flexible way than just switching to command line and navigating to the correct location. My idea was that I should just press an arbitrary shortcut and get the result. So I decided to give External Tools a try.

The utility I use a lot when studying Java is javap - the java class file disassembler. This is due I study the bytecode sometimes. And although there's ASM plugin available for IntelliJ that basically can provide me the result I needed, I still prefer to read the raw javap output.

To setup javap in Intellij as an External Tool go to Settings >> External Tools and press Add... . You can then define the location of the tool, the working directory, and the parameters.


The nice part of it is that IntelliJ provides some basic macros in order to dynamically resolve the parameters for the tool. So for javap it was enough to set $FileClass$ for the parameter, and $OutputPath$ as the working directory. And that's it - the tool is now ready for use.


You can also define a "group" which is then used to group the external tools in the popup menu. I use "jdk" as a group name for javap so here's what it looks after:


So that's cool but you might have noticed that it is not that comfortable to use - have to right-click the file, navigate to "jdk" group, expand it, and only then can execute javap. Well, shortcuts to the rescue! Browse to Settings >> Keymap, and there you can define any sortcut for the tool. The nice part of it is that IntelliJ detects if you select a conflicting shortcut and notifies you.


One more tweak left to do. Once I press the shortcut that I've assigned to javap, the result of decompilation is printed out to the IDE console, which is just below the source code. But it would be more convenient to see it side by side. For that, it is possible to drag-and-drop the Run window to the side panel in IntelliJ so the result can be observed right next to the source I'm currently working with.


The only thing that is probably missing is the syntax highlight for the javap output, but that is probably too much to wish.



Tuesday, August 2, 2011

Code Snippet: Redirecting Standard Output to File

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.PrintStream;


public class SystemOutRedirect {

  public static void main(String[] args) throws FileNotFoundException {
    System.setOut(new PrintStream(new FileOutputStream("stdout.txt")));
    System.setErr(new PrintStream(new FileOutputStream("error.txt")));

    System.out.println("hello");  //goes to stdout.txt
    System.err.println("error");  //goes to error.txt
  }

}

Wednesday, July 27, 2011

Using JRebel with MyEclipse Blue and WebSphere

Just recently ZeroTurnaround and Genuitec announce JRebel for MyEclipse. Here's what it looks like in combination with WebSphere application server. It is quite easy to install and configure.



JRebel 4.0.x

JRebel 4.0.3 was released just recently. The debugger support is maturing - some features are still missing, like expression evaluation support for the reloaded classes, but stepping functionality and breakpoints installation are quite well polished now.





See the press release.

Monday, July 25, 2011

JVM Language Summit 2011


Back from Santa Clara, CA where I've attended an awesome event - JVM Language Summit. Before the event I thought I know some Java, but it seems I was too self-confident :) The 3 days of technical sessions revealed to me a lot of new things in Java world, including the new features coming in the next versions of Java as well as some JVM-based languages that I didn't pay attention to previously.

Day 1


The event started with a short intro by Brian Goetz followed by a keynote speech by Cameron Purdy. Cameron presented an awesome wishlist for the upcoming versions of Java/JVM. Some of the features I liked the most on that list:

Immutability. The main concern was pretty much about how could Java get so far without immutability natively supported by the language?


Obvious Intrinsic Types are just missing from Java. And this is the major pain for the developers dealing with financial calculations whereas the rule of thumb is - never use double for operations on monetary values. Indeed, every Java programmer should see this presentation - How Java's Floating-Point Hurts Everyone Everywhere. The good news is, IEEE 754-2008 a.k.a. IEEE 754r – defines decimal types, the bad news, it is not yet implemented.


Alternative class format is something that tool implementers would definitely love - why inner classes aren't inner classes? why anonymous classes are not properties of a method where they are defined?. In fact, I was carrying the idea around with myself on why not to try to implement the class nesting into the VM? I was actually thinking it is a crazy idea of mine but it turns out other people do have same crazy ideas! :)


Tail Recursion / Tail Call Optimization is something that every developer, who tried some FP language, misses from Java. I've tried Erlang a while ago, and after a few weeks I really could live without this feature.


Cameron had plenty of other stuff on the list but I'd rather skip mentioning all the points. The presentation slides are available here.

Async .NET

It was quite an interesting presentation by Mads Torgersen. It is nice to know, what are the people working on the other major managed runtime come up with in a while. The main feature that Mads was talking about was the asynchronous task execution coming in C# 5. Basically it is similar to what Java has with Futures. The presentation slides are available here, and actually I've found a video on the same subject at Channel 9 - recommended!.

Indy FTW!

Now it was all about invokedynamic, method handles, call sites, etc. First, John Rose talked about Method Handles. And after that, Dan Heidinga talked about the method handles implementation in IBM J9.

These followed by the language implementers - demonstrating how invokedynamic and method handles can be used: Charles Nutter on JRuby, and Remi Forax on JSR-292 Cookbook. JRuby folks take a great advantage of the invokedynamic which allows a lot of optimizations hence improving the performance. Remi Forax presented a number of Method Handle usage tips. The collection can be found at https://code.google.com/p/jsr292-cookbook. One really cool thing I've got to know is the ClassValue which can serve as a metadata carrier that might be required for dynamic method invocation.

Day 2


The first half of day 2 was mostly related to all the same JSR-292 features: porting Smalltalk to JVM, new implementation of JavaScript on JVM, Jython&Indy.

Dynalink, presented by Attila Szegedi, is an interesting project for dynamic linking in Java - as far as I understand Dynalink could be used to implement invokedynamic behavior on JVM.

After all the dynamic fluff-and-stuff the statically typed languages came on stage.


Gosu. Honestly, I underestimated the language when I learned about it the first time. This time I was actually surprised by the features presented in Gosu, accompanied with compiler support and the open type system. A couple of years ago I used Drools and Groovy to implement the rules-based system. If I knew about Gosu at that time it would probably be my language of choice. Especially neat is that one can basically connect some XML or properties file to the type system and tell that this is a new type in Gosu, and get all the type-checking backed by the compiler. Just awesome!
Gosu doesn't seem to tackle any of the general-purpose language but it definitely has its niche - a statically-typed language for writing business rules.


Project Kotlin, presented by JetBrains developers, Andrey Breslav and Dmitry Jemerov, has definitely created a lot of buzz by now. According to the creators, Kotlin is designed to be nicier than Java, and simpler than Scala. Here're the slides from the presentation & the workshop. At first sight, the language is definitely nice to read and the syntax seems to be more friendly than in Scala, but going deeper into more advanced features, the claim tends to diminish. I noticed a lot of similarities with Scala, Groovy and C#, whereas C# features (i.e. non-virtual methods) do not seem as coherent with the other two languages. I do not have any strong opinion on the project yet - need to study it a bit and compare to other languages (read Scala) but one thing I quite sure about is that the IDE support should be top class. There are a lot of opinions currently, whether JetBrains should rather have contributed to Scala tooling, or Ceylon project.. don't know what is best - time will show. I do understand the scepsis of Scala fanboys regarding Kotlin, but it is quite stupid to underestimate this effort. IMHO, nothing replaces Java any time soon - it rather benefits of all the language experiments.

Day 3


On the day 3 there have been a few talks related to Java language itself.

Interface injection by Tobias Ivarsson, Extension Methods & Lambda Bytecode by Brian Goetz - awesome content and ideas presented. IMO, properly combined autoboxing, interface injection and extesion methods with lambdas could enable ruby-like syntax in Java, e.g. 5.times({ int x -> println(x); }. Neat, huh?

A very interesting project Graal, presented by Thomas Wuerthinger (one of the core developers on DCEVM. Graal includes a mechanism to execute the compiler outside of the HotSpot JVM which leads to "distributed compilation".

At the end Prashant Deva talked about the Chronon debugger. In fact, it turns out that Chronon isn't really a debugger but you can rather record the dataflow of your program execution and do "post-debugging" using the data recorded at runtime. It really looks as if you're debugging in the IDE, stepping through the lines of code and observing the values of variables. But technically, the plugin doesn't even connect via JVMTI - it rather emulates the program under inspection - executing queries to the recorded data set and jumping to the correct line of code in the IDE.

Summary


I think this was the most advanced and interesting Java-related event I've attended so far. I really feel myself being so dumb now - very motivating to finally take a look at some textbook on the compiler construction :)

Sunday, July 10, 2011

What’s Cool In IntelliJIDEA. Part II: Live Templates

In IntelliJ, I use Live Templates quite heavily and still think that these are underused. It is not only the standard number of templates that can make your life easier while typing yet another piece of code, but it is also the ability to define new templates with all the bells and whistles that are available in IntelliJ standard template list.

In the previous post I've covered the basics of Live Templates but I think that it would be cool to cover these in more details and to point out some less-known aspects of this functionality.

First of all, Ctrl+J is the shortcut to use in order to get a list of the available by default. But if you had time to practice, most likely you can remember the abbreviations by heart, like psvm, iter, psfs, soutv, etc.


One thing I do for sure before using Live Templates is that I change the default expansion key, which is Tab by default, to a Space key. It seems to me that it is more natural to use Space for this purpose as when you type you actually hit the Space key almost automatically.


Another cool feature of Live Templates is to surround a capable statement with a block of code - also covered in the previous post.


How do I define my own template?


IntelliJ provides a number of templates in its default distribution but obviously it doesn't cover all cases you might need. So here's the main purpose of this post - how to define a custom live template in IntelliJ. First, let's make up a use case - a situation where we'd like to have some means for typing faster but which isn't defined in the IDE by default.

For some reason, IntelliJ doesn't provide try-catch template by default. It only suggests this option if you'd like to surround an existing statement with the try-catch block, but not when you just want to create an empty one. Here's what we can do: open Settings window (Ctrl+Alt+S) and start typing 'Live Templates' - this will lead you to the templates' settings - and hit the "Add.." button on the right.

It is quite easy to create a simple template which just has to generate a defined text for the given keyword. For the empty try-catch block we just need to fill in the abbreviation and the code itself, and not to forget to bind it to Java context using the corresponding checkbox.


This is quite a dumb template, nothing intelligent here. But what if we'd like to suggest the exception type in the catch block? What if we'd like to position the cursor in some particular place after the template is applied? Let's make our brand new template a little smarter.

To ask IntelliJ for a type of the throwable in the catch block we can add a variable ($EXCEPTION$) and define its value using a special function provided by IntelliJ. Say, I'd like the type to be a subtype of java.lang.Exception class, hence I'm using the subtype(<type>) function:


You've probably noticed that I've used another variable, $END$, but there's no value defined in the dialog window. This is a predefined variable, meaning where should the cursor be positioned after the last choice made within the templates.

So now once I type 'try' and hit the space key, the template is expanded to the following:


First the cursor will be positioned inside the catch block in order to choose the type of the exception to be handled. Right after I make my mind about the type and hit the Enter key, the cursor will be positioned back into the try block.

Wednesday, June 29, 2011

What’s Cool In IntelliJIDEA. Part I

Eclipse or IntelliJ? NetBeans or Eclipse? IntelliJ or NetBeans? The dispute about the IDEs is the most popular among the software developers and hardly will ever end. I consider myself being a big IntelliJ fan, but I do realize that there are a lot of things that IntelliJ could do better and that NetBeans and Eclipse are better in some ways. In this post I’d like to make an overview of IntelliJ’s features which I like the most, and and beyond that. Also I’d like point out some of the aspects in which IntelliJ could do better.

UPDATE: due to the popularity of this blog post I took some time to combine my blog posts about IntelliJ IDEA into one big article, published at RebelLabs as Getting Started with IntelliJ IDEA as an Eclipse User. You will find it interesting, I'm sure :)


Other post in the series:
One of my friends said once:
I don't like IDEs. They help to write verbose code. In real life 90% of time I spend on code reading. Verbose code kills my productivity

I think he's wrong. The reality is that IDEs are used not only for writing/generating code, but to a greater extent IDEs are used to read and analyze the code. You might be a hard-core Emacs/Vim ninja but still, there are things that you just cannot do with the text editors.


Navigation


Navigation through the source code is one of the activities that programmer executes on a regular basis. Basically, it is not hard to navigate the code with Emacs or Vim, but it would limit you only to a basic navigation options. IDEs take navigation abilities one step further.

Let's see what are the navigation features in IntelliJ. First of all, "Open Type" which is executed via Ctrl+N:


The same can be achieved with Ctrl+Shift+T in Eclipse and the behavior is exactly the same.

Ctrl+Shift+N will help you to open any resource. Eclipse does the same with Ctrl+Shift+R.

And it could have been all but there's more - Ctrl+Shift+Alt+N will find you all the appearances of a specific symbol, e.g. a method name:


It doesn't mean IntelliJ will scan the code for the occurrence of the specific symbols but it rather will match the code structure and look for the elements in your code so you will get a list of method declarations but not just any appearance of the method name in the code. This is quite useful if your classes are not sharing the same hierarchy.

Often when you navigate the source code you jump over class hierarchies, browse different methods, open type declarations, etc. It is quite common that once in a while you would like to step several steps back in your navigation and proceed with some other direction. Ctrl+Alt+(left|right) arrow is a very useful shortcut for such purpose. Whenever a caret hits any place in the code this place is remembered and you can go back and forward in the your browsing history. This is quite cool as if you navigate a large code base you might not even remember which classes you actually opened just a second ago.

Actually you can get a list of the recently visited files by pressing Ctrl+E - also quite often used to reopen the recently closed files.

Navigating back in forward is the same in Eclipse (with Alt+(left|right)arrow shortcuts). But I failed to find a list of recently edited files there, while this can be done in IntelliJ by hitting Ctrl+Shift+E shortcut.

There are plenty of other feature that make your code browsing experience more pleasant. For instance, both IntelliJ and Eclipse provide a feature to quickly browse the location of the currently opened class - Alt+Home will popup a navigation bar with the path to the class.

The cool feature in IntelliJ for this navigation par is that it is possible to brows the content of any file with Ctrl+Shift+I without having to really open the file:


In Eclipse a similar feature is called "Browse in Breadcrumb" called via Alt+Shift+B. The difference is that in Eclipse it works only if a Java type is opened and it acts only as a navigation bar - no quick preview available. Also, I didn't find an easy way how to get rid of that "Breadcrumb" in Eclipse besides clicking a dedicated button on the toolbar.

Ctrl+Shift+I also works in IntelliJ for any symbol that you'd probably like to inspect. For instance, you may press this shortcut on any method call, and it will raise a popup that displays the methods source code:


Also, if you try to browse the code that maybe involved in the type hierarchy, it is possible to select the implementation by choosing the type in the very same quick view popup:


Talking about navigation on the hierarchy of classes, IntelliJ implements that also quite nicely - quick hierarchy view is available the same way as in Eclipse. The feature that distinguishes IntelliJ is the ability to easily navigate to implementation. For instance, from interface method declaration to any of the implementations. If there are multiple implementations of an interface method Ctrl+Alt+B will call a popup dialog with the list of implementations:


Saturday, April 16, 2011

Code Snippet. Intercepting "On Save" Action in IntelliJIDEA

1. Add the following to META-INF/plugin.xml of your plug-in:
<application-components>
   <component>
      <implementation-class>my.plugin.OnFileSaveComponent</implementation-class>
    </component>
 </application-components>

2. Implement com.intellij.openapi.components.ApplicationComponent:
package my.plugin;

import com.intellij.AppTopics;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManagerAdapter;
import com.intellij.util.messages.MessageBus;
import com.intellij.util.messages.MessageBusConnection;
import org.jetbrains.annotations.NotNull;

public class OnFileSaveComponent implements ApplicationComponent {
  @NotNull
  public String getComponentName() {
    return "My On-Save Component";
  }

  public void initComponent() {
    MessageBus bus = ApplicationManager.getApplication().getMessageBus();

    MessageBusConnection connection = bus.connect();

    connection.subscribe(AppTopics.FILE_DOCUMENT_SYNC, 
      new FileDocumentManagerAdapter() {
      @Override
      public void beforeDocumentSaving(Document document) {
         // create your custom logic here
      }
    });
  }

  public void disposeComponent() {
  }
}

That's it! :)

So how could it be used? If you'd like to perform some synchronization with a remote server on each file save in IntelliJ, probably, this code snippet would help you.

Wednesday, April 6, 2011

33rd Degree, 2011, Day 1


ZeroTurnaround is exhibiting at 33rd degree conference in Krakow. In fact, we are the only software product company at the tiny expo here. The others, Luxoft and Tieto are the outsourcing companies, so we feel a bit lonely in this situation. BTW, Luxof has the most meaningless booth I've ever seen - it is huge and it completely ineffective.


Anyways, we've met a lot of smart people asking a lot of smart questions about JRebel and it is tough to answer all kind of questions - I wish I could.

I didn't have much time to attend the sessions myself. However I've managed to escape from the expo area and to attend Ted Neward's talk Busy Developer's Guide to Scala: Patterns. I've got smarter in a way. I've learned about some Scala idioms that diminish some of the classical design patterns that you need to implement in Java from scratch. In fact, I realized that many of the design patterns become obsolete once the target language supports closures.

At the end of the day we've organized the beer party for all the conference attendees. It is a funny thing but people are more interested in JRebel if they're are served with the free beer :)

Friday, April 1, 2011

Just Some Java Reflection Madness

import java.lang.reflect.Field;

public class Test {

  public static void main(String[] args) throws Exception {
    doStuff();
    System.out.println("Hello".equals("World"));  // --> true
  }

  public static void doStuff() throws Exception {
    Field value = String.class.getDeclaredField("value");
    value.setAccessible(true);
    value.set("Hello", "World".toCharArray());
  }

}

http://www.javaspecialists.eu/talks/oslo09/ReflectionMadness.pdf

Tuesday, March 22, 2011

Presentation Slides: Java Bytecode Fundamentals I - Tech Talk for JUG.lv, March 2011


JRebel 4.0 M1 Released

JRebel 4.0-M1 was released. Grab it while it's hot!

The new features include integration with HotSwap, support for anonymous classes and adding new session beans to JBoss 4.2/5.1 and Glassfish 2/3.

For the new features, I would encourage everyone to give it a try! JRebel already provides the integration for JSF (Mojarra), JAX-RS (Jersey), CDI (Weld), and now the support for EJBs is extended! It is possible to create a JavaEE6 app with almost no redeploys already. Things are improving quite fast!

Sunday, March 6, 2011

Embedded Tomcat, The Minimal Version

Tomcat 7 has been improved a lot and along with all the features that it brings, a very nice feature is provided - the API for embedding tomcat into the application. The API was provided in earlier versions of Tomcat but it was quite cumbersome to use.

To to start the embedded version of Tomcat one may need to build the required JARs.


$> svn co https://svn.apache.org/repos/asf/tomcat/trunk tomcat
$> cd tomcat
$> ant embed-jars
$> ls -l output/embed
total 5092
-rw-r--r-- 1 anton None 56802 2011-03-06 17:09 LICENSE
-rw-r--r-- 1 anton None 1194 2011-03-06 17:09 NOTICE
-rw-r--r-- 1 anton None 1690519 2011-03-06 17:09 ecj-3.6.jar
-rw-r--r-- 1 anton None 234625 2011-03-06 17:09 tomcat-dbcp.jar
-rw-r--r-- 1 anton None 2402517 2011-03-06 17:09 tomcat-embed-core.jar
-rw-r--r-- 1 anton None 781989 2011-03-06 17:09 tomcat-embed-jasper.jar
-rw-r--r-- 1 anton None 34106 2011-03-06 17:09 tomcat-embed-logging-juli.jar


The following snippet demonstrates the embedded Tomcat usage with a deployed servlet instance.

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.Writer;

public class Main {

  public static void main(String[] args)
  throws LifecycleException, InterruptedException, ServletException {
    Tomcat tomcat = new Tomcat();
    tomcat.setPort(8080);

    Context ctx = tomcat.addContext("/", new File(".").getAbsolutePath());

    Tomcat.addServlet(ctx, "hello", new HttpServlet() {
      protected void service(HttpServletRequest req, HttpServletResponse resp) 
      throws ServletException, IOException {
        Writer w = resp.getWriter();
        w.write("Hello, World!");
        w.flush();
      }
    });
    ctx.addServletMapping("/*", "hello");

    tomcat.start();
    tomcat.getServer().await();
  }

}

The only two JARs required are tomcat-embed-core.jar and tomcat-embed-logging-juli.jar. It means that there will be no JSP support and pooling will also be disabled. But that's enough to start a servlet and in most cases that is what you probably need.

Wednesday, February 23, 2011

Java Bytecode Fundamentals. Part II. Passing parameters

Judging from the feedback, the first Java Bytecode Fundamentals was rather a success. So I though maybe it is worth to continue the series on some other aspects of the topic.

The interesting part of the bytecode is the one that covers method invocation and parameter passing. I have put up a full-blown post here: Java Bytecode Fundamentals: Using Objects and Calling Methods. The article covers how objects are created at the bytecode level, what the opcodes for method invocation are, how parameters are passed to the method invocations and how the return value is passed back. The important part to understand is how the stack is involved into the operations, along with the local variable table taking part in the game.

Just to reveal some parts of the full post, here's the slidecast demonstrating the parameter passing process in method invocation:

Jfokus 2011 in Pictures

Tuesday, February 1, 2011

Technology Radar 2011

ThoughWorks has published the brand new edition of Technology Radar for 2011. Honestly, some of the things look really weird compared to the previous editions. But also some of the technologies mentioned are rather surprising/positive.

Techniques


Real-time business intelligence. The radar says that batch jobs are the outdated form of data processing and business cannot rely on that if one aims to be on global markets. I can say that I have experienced that myself during last 5 years fighting for batch jobs performance for almost every project that I have worked on - the amount of data doesn't allow you to fit into the maintenance window. Moving to real-time or event-based systems/architectures is inevitable as there's the need to distribute the processing load in time. The only thing I wander is why is this still in the Assess phase? It should be Adopted already!

DevOps looks like the new hype to me. I think it will hardly happen at the full scale. It is hard to find good developers, it is hard to find ninja-sysadmins, where do you find good devops?

Automated database deployment - that's an interesting topic for the last few years already. I hardly believe the topic just made it to the radar.

Concurrency abstractions and patterns section mentions Clojure, Erlang, Retlang. That's interesting, as these languages hardly can take the niche of application programming languages like Java or C#, but specifically for concurrency - this is a very compelling alternative. My personal preference is Erlang, and I think it would be a good idea to take a look at Erjang as well.

Catagorization of technical debt. Oh yes, Captain Obvious!

Tools


The first thing I'm thinking of when I hear "Insfrastructure as Code", is Puppet! And what do you know, it is on the radar! :) Some interesting tools are mentioned as well - Vagrant, Deltacloud, Splunk, etc. I only wander why these tools are on the radar - I kind of doubt that these tools are unique.

The biggest surprise in the Tools section is the state of Subversion. AFAIK, Subversion was loosing popularity according to the last year radar's editions, and now it is in the Adopt phase again.

I wonder why JRebel isn't on the list?? :)

Languages


The report suggests that Ruby, JRuby, C# are mature enough to start using these language for production. Well, this somehow correlates with the job posts for JRuby that I have seen last months. Looks rather positive to me! :) On the other hand the report suggests to consider "Java language EOF". You know what - that's a speculation, even if Oracle owns Java now.

javaScript as first-class language? Noooooooooooooooooooooooo!

Scala and Groovy are in the Trial phase... Don't care really.

Domain-Specific Languages is an old technique that we think is significantly under-used.

It seems that the DSL hype is shrinking. Maybe it is partly because that a good API is a DSL in some sense? My opinion is, the biggest problem of DSLs is that they are mostly usable by their authors :)

Platforms


OpenStack looks quite interesting for infrastructure solution. Kind of surprising that KVM has made it right to the center of the radar's target.

Surprising is that GWT is on Hold while Node.js is in Assess phase according to the report. Node.js is probably the argument for having JavaScript as the first-class language. Well, I haven't tried it myself yet and feel quite doubtful about it. Maybe one day...

Heroku looks like an interesting PaaS for ruby devs. I think this is something worth trying if you do ruby development.

Not a surprise, Android has reached the center of the radar, I'd expect an exploading growth of jobs for Android devs despite the Google-Oracle law suite.

ThoughWorks radar is always an interesting read, but it seems to be a little biased as .NET world is almost unmentioned there (OK, C# and F# are on the list, but it is almost unnoticeable) and the most traction is still around the Java platform (yay!).

Sunday, January 16, 2011

Java snippet: get PID at runtime

package my.pid;

import java.lang.management.ManagementFactory;

public class MyPid {
  public static void main(String[] args) {
    String nameOfRunningVM = ManagementFactory.getRuntimeMXBean().getName();
    int p = nameOfRunningVM.indexOf('@');
    String pid = nameOfRunningVM.substring(0, p);
    System.out.println("Java app PID: " + pid);
  }
}

Sunday, January 2, 2011

Java Bytecode Fundamentals

Java bytecode is a bread and butter of JRebel, the productivity tool for Java developers. This is why I decided that it would be a good thing to write a blog post on this subject. This blog post is a summary of various sources that I've found while googling on the subject. Hopefully someone may find it relevant and useful. What is a little weird is that there's not much information on the subject, either books or articles. BTW, if you have anything to add or comment - don't hesitate to post to comments :)

UPDATE This blog post, along with many improvements is a part of my article for RebelLabs' report on Java Bytecode that can be found here: http://zeroturnaround.com/rebellabs/rebel-labs-report-mastering-java-bytecode-at-the-core-of-the-jvm/


The developers who use Java for application development, usually do not need to be aware of the bytecode that is being executed in the VM. However, those developers who implement the state-of-the-art frameworks, compilers, or even Java tooling - may need to understand and may even be using bytecode directly. While special libraries (like ASM, cglib, Javassist) do help regarding bytecode manipulation, it is still important to understand the fundamentals in order to make the effective use of those tools.


Let's start off with a simple example - a POJO, with one field, a getter and a setter.

public class Foo {
    private String bar;

    public String getBar(){ 
      return bar; 
    }

    public void setBar(String bar) {
      this.bar = bar;
    }
  }

First of all, one you compile the class using javac Foo.java, you'll have the Foo.class, which now contains the bytecode. Here's how it looks in the hex editor:


Each pair of hex numbers (a byte) is actually translatable to opcodes (mnemonics), but obviously it would be too brutal to start reading it in the binary format. Let's proceed to the mnemonical representation.

Executing javap -c Foo will print out the bytecode:
public class Foo extends java.lang.Object {
public Foo();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public java.lang.String getBar();
  Code:
   0:   aload_0
   1:   getfield        #2; //Field bar:Ljava/lang/String;
   4:   areturn

public void setBar(java.lang.String);
  Code:
   0:   aload_0
   1:   aload_1
   2:   putfield        #2; //Field bar:Ljava/lang/String;
   5:   return

}
The class is very simple and it is easy to see the relation between the sourced code and the generated bytecode. First of all we notice that in the bytecode version of the class the compiler inferred the default constructor (as promised by the JVM spec).

Disqus for Code Impossible