Over a million developers have joined DZone.

Building Java applications that use .NET components on JRebel

DZone's Guide to

Building Java applications that use .NET components on JRebel

· Integration Zone ·
Free Resource

WSO2 is the only open source vendor to be named a leader in The Forrester Wave™: API Management Solutions, Q4 2018 Report. Download the report now or try out our product for free.

What are we up to


The main purpose of this article is to take the combination of Java and .NET one more step towards productivity with JRebel.

For those not familiar with the latter, let me give you a quick introduction. JRebel is a tool designed to boost productivity of Java developers and teams. It’s distributed as a JVM plugin or java agent which monitors changes made to your source code and deploys it on the fly.

It’s like JVM Hot Swap, only better as it allows you to update not only java classes but resources as well.

So, the proof of concept we are targeting here is to be able to build a web application written in Java which will be using a .NET third party library for creating MS Office Documents called DocX and making use of JRebel features to see the changes live with no server restart. 

Sounds ambitious, so let’s get our hands on it as soon as   possible.


PoC description


The application scenario is quite simple: we’ll build a Spring MVC web application that shows a simple form to create a MS Word document: header, footer and a paragraph will be sufficient for the moment.

Then we will introduce a mistake, a tiny error, that in an ordinary development cycle would force us to tear down the server, make the change, package our app, and re-deploy it again. We’ll point out how JRebel saves us from that hustle.

Regarding the MS Office document itself, we will appreciate how easy it is to establish a collaboration between Java and a third party .NET library using  javonet.

As a building tool we’ll use Maven and Jetty as a dev server.

Setting things up

In order to save us some time, let’s start by instantiating an existing project using a Maven archetype. @kolorobot created a simple, well organized, one and published it on GitHub. 

lifesaver tip: if you don’t feel like going through every step I have attached the sample project for you to tweak and play. 

  1. Create your Maven project
  2.   Go to https://github.com/kolorobot/spring-mvc-quickstart-archetype and follow the instructions.  
  3. Download and install a standalone version of JRebel here
  4. Assuming you unzipped it in “C:\jrebel\” activate your license by issuing this command

  5. C:\jrebel\bin> activate.cmd jrebel.lic
    JRebel successfully activated!
    License type: Evaluation
    Licensee name: Fer Troya
  6. Add the jrebel maven plugin configuration to your pom.xml file

  7. <plugin>
  8. Run mvn jrebel:generate from your project’s directory and copy the generated rebel.xml file into src/main/resources. In build time, this file will end up under WEB-INF/classes which is where it’s supposed to be.
  10. Download javonet  and install it into your local repository (you can find detailed instructions here http://java.dzone.com/articles/melting-down-jdknet-barrier)
  11. Add javonet’s dependency to your pom file.
  12. Add jetty plugin to your pom file.

  13. <plugin>
  14. Download DocX from http://docx.codeplex.com/, the .NET library for developing Microsoft Office documents written by Cathal Coffey. 
  15. Copy DocX.dll on the root of your project (next to the pom file is good). 

That’s it! We’re all setup with the tools we need. Now after running mvn jetty:run we should have our application running on http://localhost:8080. On your IDE the project should look like this:


It’s time now to develop our document editor, by simply adding the Spring MVC components we need.


Let’s code it


The first thing we need is something that represents our document, a simple bean we can share between server and client. I’ve named it DocXForm.

public class DocXForm {
  private static final String NOT_BLANK_MESSAGE = "{notBlank.message}";
  @NotBlank(message = DocXForm.NOT_BLANK_MESSAGE)
  private String header;
  @NotBlank(message = DocXForm.NOT_BLANK_MESSAGE)
  private String body;
  public String getHeader() {
    return header;
  public void setHeader(String header) {
    this.header = header;
  public String getBody() {
    return body;
  public void setBody(String body) {
    this.body = body;
As you can see is a simple POJO with validation annotations.

Let’s take a look at our controller now. This is the key component of our application.

public class DocXController {

  private static final String TEMP_DIR = System.getProperty("java.io.tmpdir");
  private static final String DOCX_VIEW_NAME = "docx/docx";
  private UserService userService;

  @RequestMapping(value = "docx")
  public String createDocX(Model model) {
    model.addAttribute(new DocXForm());
    return DOCX_VIEW_NAME;

  @RequestMapping(value = "docx", method = RequestMethod.POST)
  public String createDocX(@Valid @ModelAttribute DocXForm docXForm,
      Errors errors, RedirectAttributes ra) throws JavonetException {
    if (errors.hasErrors()) {
      return DOCX_VIEW_NAME;

     * License key can be obtained at http://www.javonet.com - trials
     * available
    try {
      Javonet.activate("xxxx@yyyy.com", "YOUR-LICENSE-KEY", JavonetFramework.v40);
    } catch (JavonetException e) {
      // Javonet already activated, ignoring (you can avoid this step by
      // using javonet.xml activation.

    String fileName = "Test.docx";
    NObject doc = Javonet.getType("DocX").invoke("Create",
        TEMP_DIR + "/" + fileName);
    NObject header = doc.get("Headers");
    NObject defaultHeader = header.get("odd");
    NObject p1 = defaultHeader.invoke("InsertParagraph");
    p1.invoke("Append", docXForm.getHeader());

    return "redirect:/files/" + fileName;

  @RequestMapping(value = "/files/{file_name}", method = RequestMethod.GET, produces = MediaType.APPLICATION_OCTET_STREAM_VALUE)
  public FileSystemResource getFile(@PathVariable("file_name") String fileName) {
    return new FileSystemResource(TEMP_DIR + "/" + fileName);

What’s going on here? Well let’s see. This is a Spring MVC   controller; as such, it defines routes which specify a path and the HTTP method   we’re handling. Besides that you can ask the Spring container to inject the model   that contains your data into the method that processes it. Pretty   straightforward! 

Looking closer to the createDocX method we can see there’s a try catch there. We’re using this to activate javonet with the credentials we got on the set-up phase; as this is a one-time only operation we’re catching the exception thrown the second time to avoid our app from crashing. Javonet provides an XML activation descriptor that can save you from this hustle; I took the liberty to use   this way for simplicity. 

Moving on! We have to import our DLL library. That’s as simple as adding the reference to its location, as you can remember we simply put it into the root folder of our project. Javonet allows to read references from the GAC as well, so that’s another possibility.

The next few lines create the .docx document itself using the data we’ve sent from our html form with just 6 lines. That’s all you need to create, edit and save a native MS Office document using a .NET dll library from Java if you go with javonet.    

For the sake of simplicity, I’m skipping the html side of things; there’s nothing to fear in that area and if you feel like trying I’m attaching the complete source code for this sample. 

Finally, the last method let’s you see Spring MVC showing off its gloriousness: serving the file we've just created to the client in a one-liner.


The JRebel boost


Before running your server for the first time, we should instruct the JVM where to locate the JRebel agent. That’s where the magic happens, whenever you save a file in your source code it will replace it live on your server. This is valid for classes, resources and of course, for our document editor code as well including the javonet link to the dll code.

C:\>SET REBEL_HOME=C:\jrebel\
C:\>set MAVEN_OPTS=-noverify -javaagent:%REBEL_HOME%\jrebel.jar
C:\>mvn jetty:run

That’s it, you don need to restart your server anymore. You can go to your DocXController class, add, remove, edit code and your changes will be reflected on your site on the fly.


Your turn!

I know we were going to introduce an error and then fix it with no redeploys or server restarts, but instead of sharing lots of screenshots or a video with my not so lovely voice, I’d rather let you go and try it yourself, do you dare? 

Go ahead and start coding Java web applications that can interact .NET  dll’s with no server restarts or redeploys.

Should you face any problems with javonet, their quickstart guide and awesome labs are at the rescue. Also jrebel docs have plenty of resources to mitigate any possible errors.

Happy coding!

IAM is now more than a security project. It’s an enabler for an integration agile enterprise. If you’re currently evaluating an identity solution or exploring IAM, join this webinar.


Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}