Monday Nov 28, 2011

Build Open JDK 7 on Mac OSX (TOTD #172)




The complete requirements, pre-requisites, and steps to build OpenJDK 7 port on Mac OSX are described here. The steps are very clearly explained and here are the exact ones I followed on my MacBook Pro 10.7.2:
  1. Confirm the version of pre-installed Java as:
    > java -version
    java version "1.6.0_26"
    Java(TM) SE Runtime Environment (build 1.6.0_26-b03-383-11A511c)
    Java HotSpot(TM) 64-Bit Server VM (build 20.1-b02-383, mixed mode)
  2. Download and install Mercurial from mercurial.berkwood.com (zip bundle for 10.7 is here). It gets installed in the /usr/local/bin directory.
  3. Get the source code as (commands highlighted in bold):

    hg clone http://hg.openjdk.java.net/macosx-port/macosx-port
    destination directory: macosx-port
    requesting all changes
    adding changesets
    adding manifests
    adding file changes
    added 437 changesets with 364 changes to 33 files
    updating to branch default
    31 files updated, 0 files merged, 0 files removed, 0 files unresolved
    cd macosx-port
    chmod 7555 get_source.sh
    ./get_source.sh
    # Repos:  corba jaxp jaxws langtools jdk hotspot
    Starting on corba
    Starting on jaxp
    Starting on jaxws
    Starting on langtools
    Starting on jdk
    Starting on hotspot
    # hg clone http://hg.openjdk.java.net/macosx-port/macosx-port/corba corba
    requesting all changes
    adding changesets
    adding manifests
    adding file changes
    added 396 changesets with 3275 changes to 1379 files

    . . .

    # exit code 0
    # cd ./corba && hg pull -u
    pulling from http://hg.openjdk.java.net/macosx-port/macosx-port/corba
    searching for changes
    no changes found
    # exit code 0
    # cd ./jaxp && hg pull -u
    pulling from http://hg.openjdk.java.net/macosx-port/macosx-port/jaxp
    searching for changes
    no changes found
    # exit code 0
  4. Install Xcode from the App Store. Include /Developer/usr/bin in PATH.

    Note: JDK 1.6.0_26 ame pre-installed on my laptop and I installed Xode after that. The compilation went fine and there was no need to re-install the Java for Mac OS X as mentioned in the original steps.
  5. Build the code as:

    make ALLOW_DOWNLOADS=true SA_APPLE_BOOT_JAVA=true
    ALWAYS_PASS_TEST_GAMMA=true ALT_BOOTDIR=`/usr/libexec/java_home -v
    1.6` HOTSPOT_BUILD_JOBS=`sysctl -n hw.ncpu`

    The final output is shown as:

    >>>Finished making images @ Sat Nov 19 00:59:04 WET 2011 ...
    >>>Finished making images @ Sat Nov 19 00:59:04 WET 2011 ...
    ########################################################################
    ##### Leaving jdk for target(s) sanity all docs images #####
    ########################################################################
    ##### Build time 00:17:42 jdk for target(s) sanity all docs images #####
    ########################################################################

    ## Build times ##########
    Target all_product_build
    Start 2011-11-19 00:32:40
    End 2011-11-19 00:59:04
    00:01:46 corba
    00:04:07 hotspot
    00:00:51 jaxp
    00:01:21 jaxws
    00:17:42 jdk
    00:00:37 langtools
    00:26:24 TOTAL
    #########################
  6. Change the directory and verify the version:

    >cd build/macosx-universal/j2sdk-image/1.7.0.jdk/Contents/Home/bin
    >./java -version
    openjdk version "1.7.0-internal"
    OpenJDK Runtime Environment (build 1.7.0-internal-arungup_2011_11_19_00_32-b00)
    OpenJDK 64-Bit Server VM (build 21.0-b17, mixed mode)

Now go fix some bugs, file new bugs, or discuss at the macosx-port-dev mailing list.

Wednesday Aug 10, 2011

TOTD #169: Multi-catch - Using Java 7 in Java EE 6/GlassFish

Project Coin introduces a small set of changes to the Java language making your everyday programming easier. The TOTD #167 explained how to use Automatic Resource Management particularly for a Java EE 6 application. The TOTD #168 showed how to use "String switch statement" for a RESTful Web service. This Tip Of The Day (TOTD) will explain a scenario where multi-catch can be used in Java EE 6 applications.

Consider the following piece of code:

protected void doPost(HttpServletRequest request, HttpServletResponse response){
    PrintWriter out = null;
    try {
        response.setContentType("text/html;charset=UTF-8");
        out = response.getWriter();
        out.println("<html><head><title>Servlet TestServlet</title></head>");
        out.println("<body>");
        out.println("<h1>Sending email from " + request.getContextPath () + "</h1>");
        
        for (Part p : request.getParts()) {
            // save the parts locally
            System.out.println(p.getName() + " saved");
        }  
       Message message = new MimeMessage(session);        message.setFrom(new InternetAddress(from));        InternetAddress[] address = {new InternetAddress(to)};         message.setRecipients(Message.RecipientType.TO, address);         message.setSubject("File upload successful.");         message.setSentDate(new Date());         message.setText("File has been successfully saved.");         Transport.send(message);
        out.println("</body>");         out.println("</html>");     } catch (ServletException ex) {         Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);     } catch (MessagingException ex) {         Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);     } catch (IOException ex) {         Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);     } finally {         out.close();     } }


If you are familiar with Java EE 6 then you'll understand that this fragment is from a Servlet responding to a POST request. This fragment receives a multi-part message such as a file, saves it locally, and then sends a confirmation email. The fields used for sending an email are initialized in the "init" method of the Servlet (not shown here for brevity).

If you notice then there are 3 "catch" blocks and each one of them is executing the same code, printing a log message. Using JDK7 multi-catch block, the different "catch" blocks can be combined together and rewritten as (highlighted in bold):

    out.println("</body>");
    out.println("</html>");
} catch (ServletException | MessagingException | IOException ex) {
    Logger.getLogger(TestServlet.class.getName()).log(Level.SEVERE, null, ex);
} finally {            
    out.close();
}

If you have configured NetBeans 7.0.1 for the JDK7 Source/Binary format then it will show you a hint as shown below:

The catch parameter of a multi-catch clause is regarded as implicitly final. An explicit final modifier will be redundant and one more way JDK7 enables more concise syntax.

How are you using JDK7 features in Java EE 6 applications ?

 

Sunday Aug 07, 2011

TOTD #168: String switch statement - Using Java 7 in Java EE 6/GlassFish


Project Coin introduces a small set of changes to the Java language making your everyday programming easier. TOTD #167 explained Automatic Resource Management (ARM) and this Tip Of The Day (TOTD) will explain how to use Strings in switch statements.

Prior to JDK7, switch statement worked on byte, short, char, and int primitive data types and enum. It took us about 16 years to realize that java.lang.String is also a constant and add it to the list of data types supported by a switch statement :-)

Consider the following RESTful endpoint that responds with the color of a fruit:

@Path("fruits")
public class FruitResource {

@GET
@Produces("application/json")
@Path("{name}")
public String getJson(@PathParam("name")String name) {
if (name.equals("apple") || name.equals("cherry") || name.equals("strawberry"))
return "Red";
else if (name.equals("banana") || name.equals("papaya"))
return "Yellow";
else if (name.equals("kiwi") || name.equals("grapes") || name.equals("guava"))
return "Green";
else if (name.equals("clementine") || name.equals("persimmon"))
return "Orange";
else
return "Unknown";
}
Using JDK 7's String switch statement this code can be easily re-written as:

@Path("fruits")
public class FruitResource {

@GET
@Produces("application/json")
@Path("{name}")
public String getJson(@PathParam("name")String name) {
switch (name) {
case "apple":
case "cherry":
case "strawberry":
return "Red";
case "banana":
case "papaya":
return "Yellow";
case "kiwi":
case "grapes":
case "guava":
return "Green";
case "clementine":
case "persimmon":
return "Orange";
default:
return "Unknown";
}
}

The number of characters is pretty similar (669 using switch and 674 without) but the code is much more readable, no chained if-else statements, and slightly better performance (not measured). Couple of things to keep in mind:
  • Check for null before the switch
  • Check for different case letters before the switch

NetBeans 7.0.1 provide a hint if you have a chained if-else statement to take advantage of the JDK7 features. Have you downloaded it yet ? Check out screencast #35 highlighting Project Coin features in NetBeans.

NetBeans 7.0.1 provide complete tooling around JDK7 and GlassFish 3.1.1 allow you to leverage JDK7 features in your Java EE 6 applications.

How are you using JDK7 features in your Java EE 6 applications ?


Thursday Aug 04, 2011

TOTD #167: Automatic Resource Management or try-with-resources - Using Java 7 in Java EE 6/GlassFish


Java 7 is now available, NetBeans 7.0.1 provide complete tooling around it, and GlassFish 3.1.1 allow you to leverage JDK7 features in your Java EE 6 applications. This Tip Of The Day (TOTD) will explain a new feature introduced in JDK7 and how it can be used to simplify your Java EE 6 application code.

Automatic Resource Management (ARM) or try-with-resources is one of the functionality coming from Project Coin as part of Java 7. It simplifies working with external resources such as JDBC connection/statement and xxxInput/OutputStream which need to be explicitly closed in case of an error or successful completion of a code block.

The code originally published in TOTD #164 is given below:

@javax.annotation.PostConstruct
void startup() {
   Connection c = null;
   Statement s = null;
   try {
     InitialContext ctx = new InitialContext();
     DataSource ds = (DataSource)ctx.lookup("jdbc/__default");
     c = ds.getConnection();
     s = c.createStatement();

// invoke SQL here

   } catch (SQLException ex) {
     System.err.println("ouch!");
   } catch (NamingException ex) {
     System.err.println("ouch!");
   } finally {
     try {
       if (s != null)
         s.close();
       if (c != null)
         c.close();
     } catch (SQLException ex) {
       System.err.println("ouch!");;
     }
   }
}
This is a lot of boilerplate code, couple of specific points to note here:
  • Because Connection and Statement need to be closed in "finally" block, they need to be declared outside of the "try" block.
  • "s.close()" and "c.close()" can further throw an SQLException and so there is a nested exception in the "finally" block.
 This code can also be rewritten as:
@Resource(name="jdbc/sample")
DataSource ds;

@javax.annotation.PostConstruct
void startup() {
   Connection c = null;
   Statement s = null;
   try {
     c = ds.getConnection();
     s = c.createStatement();

     // invoke SQL here

   } catch (SQLException ex) {
     System.err.println("ouch!");
   } finally {
     try {
       if (s != null)
         s.close();
       if (c != null)
         c.close();
     } catch (SQLException ex) {
       System.err.println("ouch!");;
     }
   }
}
It still has tons of boilerplate code. This can be easily simplified using JDK 7 Automatic Resource Management by changing the code to:

@Resource(name="jdbc/sample")
DataSource ds;

@javax.annotation.PostConstruct
void startup() {
try (Connection c = ds.getConnection();
     Statement s = c.createStatement())

       // invoke SQL here
     } catch (SQLException ex) {
       System.err.println("ouch!");;
     }
   }
}

The resources defined in the "try" block are automatically closed as they get out of scope and there is no boilerplate code here. The code is much more semantically readable and contains 285 characters instead of 629 in the first version.

NOTE: The code fragments in this blog are updated because throwing a checked exception from a @PostConstruct method is not permitted by the Managed Beans specification. See the comments below for more detailed discussion.

How does this all work under the hood ?

A new java.lang.Autocloseable API has been added to the platform which has a single "close()" method that automatically closes the resource. The java.io.Closeable extends this new API ensuring that xxxInputStream and xxxOutputStream are candidates for ARM. Any resource implementing this interface can be used for ARM so if there are any custom resources in your project then they can leverage this functionality as well.

NetBeans 7.0.1 provide hints to take advantage of JDK7 features. Have you downloaded it yet ? Check out screencast #35 highlighting Project Coin features in NetBeans.

How are you using JDK7 features in your Java EE 6 applications ?

Saturday Jul 09, 2011

JDK7 Launch and Java EE 6/GlassFish in Goiania

Keep reading for report on my Brazil trip so far (FISL12, Java Noroeste, Brasilia) ...

Goiania is a small city about 200km from Brasilia and the enthusiasm of the local Java community is extremely high. The JUG leaders, architects, developers, administrators, IT directors, and everybody else is always excited to showcase their work.

Instead of taking the flight, Paulo Jeronimo drove me to Goiania. He is an extremely passionate GlassFish fan, presented at local conferences on GlassFish 3.1, and even recorded screencasts that are available on GlassFishVideos (part 1, 2, and 3). He has helped the local community in architecture and performance tuning of applications running on GlassFish. He is certainly a great local resource if you are interested in GlassFish support in Brazil.

I met a customer that has been using GlassFish since 2006 and have multiple instances running all around Brazil. In all these years, GlassFish has never been the source of their problems, ever. Their instances are a mix of 2.1 and 3.1 and the migration from 2.1 -> 3.1 was seamless, no issues at all. Generally customer visits are a mix of happy/not-so-happy items but this particular visit was quite a breeze :-)

On Jul 7, the day of JDK7 launch, I talked about the new features in JDK 7 to three different set of audience concluding at the Goiania JUG. And there were customer visits in between so the day was pretty exhausting but very exciting. The JUG meeting particularly ended by celebrating JDK 7 launch and watch the following two short videos for that:






Thank you Paulo, Raphael, Marcelo, Filipe, Alessandra, and everybody else for helping me with everything in Goiania! My Portuguese <-> English translator in the JUG meeting was also excellent so consider her if you are in the neighborhood.

Check out some pictures from Goiania ....











I managed to get couple of runs with Marcelo in a nearby park and here is one of them:
And, as always, the evolving album:



And this report comes from the Sao Paulo Guarulhos Airport while waiting for my flight!

Next, and concluding, blog in this series about TDC 2011 Sao Paulo!


Monday Jul 04, 2011

JDK 7 and Java EE 6/GlassFish at Java Noroeste




Simon Ritter and I presented on JDK 7/8/9 and Java EE 6/7 at Java Noroeste, the Java User Group in Sao Jose do Rio Preto, Brazil.

As characteristic of Brazilian hospitality, we were given a very warm welcome at the airport by about 8 JUG members. About 60+ attendees missed a local soccer (or football as called in Brazil) game on a Sunday evening which was very humbling. Some of the attendees even traveled over 100km to attend the talk. This absolute craze for Java can only happen in Brazil :-)

Simon talked about how Oracle is committed to make Java successful for everybody, the new features coming in JDK 7 and plans for JDK 8 and 9. I talked about Java EE 6 and GlassFish and showed how a web application can be easily created using NetBeans. The usual "kilobyte and miliseconds" deployment of Java EE 6 applications on GlassFish was very well appreciated by the Spring users who have to wait a LONG time for deployment of three-digit MB WARs.

Thiago Gonzaga, an ex-Sun Campus Ambassador, did an excellent job translating from English -> Portuguese for both of us. He is also arranging a Java Day for the local community so talk to him or post a message on their page if you'd like to participate or sponsor.

After the event concluded about 9:30, we had dinner at a local restaurant which was very relaxing.

Some pictures from the event ...





And the evolving album ...


Next stop Brasilia ...

And one of the most amazing thing is that a local Java developer, Paulo Jeronimo, has organized a community run at 6:30am tomorrow morning. He even planned the entire course starting at Golden Tulip Hotel:



So I think its going to be a good start of the day. And for all the runners (hopefully), I got Odwalla bars ... so be sure to be there and run together :-)

Thursday Feb 24, 2011

TOTD #156: JDK 7 Developer Preview Now Available!

JDK 7 developer preview build is now available.
java -version
java version "1.7.0-ea"
Java(TM) SE Runtime Environment (build 1.7.0-ea-b130)
Java HotSpot(TM) Client VM (build 21.0-b02, mixed mode, sharing)

This is milestone 12 (all milestones), build #130 and has 456 bugs fixed since feature complete about a month ago. Download it today and try your applications and provide us feedback via forums and/or file a bug/rfe.

For sanity, I could easily download/install it on Windows 7, run NetBeans 7.0 Beta 2 and GlassFish 3.1 b41, create a simple Java EE 6 Web application and run it on GlassFish. And also encountered bug 195254 which is totally unrelated to JDK7 though ;-)

And if you are interested, screencast #35 showed how to use Project Coin features in NetBeans 7. The video is available below again for your reference:

Today NetBeans has the most comprehensive support for JDK 7 but its also coming in IntelliJ 10.5 and Eclipse.

JDK 7 will be released on the supported set of platforms (Windows, Solaris SPARC, Solaris x86, and Linux) first and then will be released on OSX later. You can also find some more details on community-led JDK 7 builds on Mac OSX.

Technorati: totd jdk7 javase

Sunday Nov 21, 2010

Screencast #35: JDK 7 Project Coin Features in NetBeans IDE 7.0 Beta

NetBeans IDE 7.0 Beta was released last week - download here. JDK 7 build 118 was released last week as well - download here. The New and Noteworthy page of NetBeans 7.0 highlights the support for some of the Project Coin features. This screencast highlights how to get started with JDK 7 in NetBeans IDE and use some of the Project Coin features, specifically:

  • Strings in switch
  • Binary integer literals and underscores in numeric literals
  • Multi-catch
  • Improved type inference for generic instance creation (diamond operator)
  • Automatic resource management

Enjoy!

Share feedback about Project Coin at coin-dev and about NetBeans at NetBeans Forums.

Technorati: screencast netbeans jdk7 project coin

About

profile image
Arun Gupta is a technology enthusiast, a passionate runner, author, and a community guy who works for Oracle Corp.


Java EE 7 Samples

Stay Connected

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today