Thursday Jul 18, 2013

Java EE 7 Samples Galore


The Java EE 7 SDK provides a comprehensive set of samples for different technologies - both new and updated. They are very nicely documented, runs using Maven + using Cargo, and demonstrate a good usage of the different APIs.

The question I get typically asked is "how do you learn all these APIs and technologies ?".

The SDK samples, reading specifications, and whitboarding with specification leads is indeed a big source of my learning. But I need to write my own code, simple "hello world" style samples that demonstrates point usage of different APIs. I truly believe in "let the code talk" and have given several slide-free code-driven session on Java EE 7 around the world. The source for these talks is about 100+ samples I've written over the past few months.

All of these samples are now available at: github.com/arun-gupta/javaee7-samples

They are all Maven-based projects and have no documentation at all. However they are logically arranged by technologies and I've tried to give intuitive names to the directories. I don't intend to write any documentation so please don't ask for it ;-) But at least now you've access to all the samples.

Here is the complete list of samples at this time:

javaee7-samples
  + batch-samples
    + batchlet-simple
    + chunk-checkpoint
    + chunk-exception
    + chunk-mapper
    + chunk-optional-processor
    + chunk-partition
    + chunk-simple
    + decision
    + flow
    + batch-listeners
    + multiple-steps
    + split
    + chunk-simple-nobeans
  + concurrency-samples
    + dynamicproxy
    + executor
    + schedule
    + threads
  + ejb-samples
    + embeddable
    + timer
    + lifecycle
    + el-samples
    + standalone
  + javamail-samples
    + definition
  + jaxrs-samples
    + async-client
    + async-server
    + beanvalidation
    + jaxrs-client
    + dynamicfilter
    + endpoint
    + filter
    + filter-interceptor
    + interceptor
    + invocation
    + invocation-async
    + link
    + readerwriter
    + readerwriter-json
    + server-sent-event
    + jsonp
    + moxy
  + jms-samples
    + send-receive-simple
    + send-receive
    + temp-destination
    + jmscontext-cdi
  + jpa-samples
    + criteria
    + entitygraph
    + jpa-listeners
    + multiple-pu
    + schema-gen
    + storedprocedure
    + jndi-context
    + locking-optimistic
    + schema-gen-scripts
  + jta-samples
    + transactional
    + transaction-scope
    + user-transaction
    + tx-exception
  + jsf-samples
    + contracts
    + contracts-library
    + flows-simple
    + flows-mixed
    + flows-programmatic
    + flows-declarative
    + passthrough
    + radio-buttons
    + viewscoped
    + file-upload
    + components
    + bean-validation
  + json-samples
    + object-builder
    + object-reader
    + streaming-generate
    + streaming-parser
  + servlet-samples
    + nonblocking
    + protocol-handler
    + servlet-security
    + metadata-complete
    + validation
    + methods
  + websocket-samples
    + binary
    + chat
    + encoder
    + encoder-client
    + encoder-programmatic
    + endpoint
    + endpoint-async
    + endpoint-javatypes
    + endpoint-programmatic
    + endpoint-programmatic-async
    + endpoint-programmatic-injection
    + endpoint-security
    + httpsession
    + injection
    + javase-client
    + messagesize
    + parameters
    + properties
    + websocket-vs-rest
    + subprotocol
    + websocket-client
    + websocket-client-config
    + websocket-client-programmatic
    + websocket-client-programmatic-config
    + websocket-client-programmatic-encoders
    + whiteboard


Will continue to add more as I dig into other pieces. I gave a 3-hour presentation explaining some of these samples at UberConf and captured the screen during the session. Those two-part videos are available.

The first part covers:
  • WebSocket 1.0
  • Batch 1.0
  • JSON Processing 1.0
  • Java Persistence API 2.1



The second part covers:
  • JavaServer Faces 2.2
  • Java API for RESTful Web Services 2.0
  • Java Message Service 2.0
  • Java Transaction API 1.2
  • Bean Vaildation 1.1
  • Concurrency Utilities for Java EE 1.0



Enjoy!

Friday Jun 28, 2013

Java EE 7 Launch Replay


Java EE 7 was released final on Jun 12, 2013. A complete replay of Strategy and Technical Keynote can be seen below:



All the Technical Breakout sessions are now available on GlassFishVideos@YouTube and can be viewed in the following playlist:



Ready to try out Java EE 7 ?

Download Binaries

Tools

Docs


Do you feel enabled and empowered to start building Java EE 7 applications ?

Just download Java EE 7 SDK that contains GlassFish Server Open Source Edition 4.0, tutorial, samples, documentation and much more.

Enjoy!

Thursday Jun 27, 2013

Java EE 7 support in Eclipse 4.3




Eclipse Kepler (4.3) features 71 different open source projects and over 58 million LOC. One of the main themes of the release is the support for Java EE 7. Kepler specifically added support for the features mentioned below:
  • Create Java EE 7 Eclipse projects or using Maven
  • New facets for JPA 2.1, JSF 2.2, Servlet 3.1, JAX-RS 2.0, EJB 3.2
  • Schemas and descriptors updated for Java EE 7 standards (web.xml, application.xml, ejb-jar.xml, etc)
  • Tolerance for JPA 2.1 such as features can be used without causing invalidation and content assist for UI (JPA 2.1)
  • Support for NamedStoredProcedureQuery (JPA 2.1)
  • Schema generation configuration in persistence.xml (JPA 2.1)
  • Updates to persistence.xml editor with the new JPA 2.1 properties
  • Existing features support EE7 (Web Page Editor, Palette, EL content assist, annotations, JSF tags, Facelets, etc)
  • Code generation wizards tolerant of EE7 (New EJB, Servlet, JSP, etc.)

A comprehensive list of features added in this release is available in Web Tools Platform 3.5 - New and Noteworthy.

Download Eclipse 4.3 and Java EE 7 SDK and start playing with Java EE 7!

Oracle Enterprise Pack for Eclipse was released recently that uses Eclipse Kepler RC3 but will be refreshed soon to include the final bits.

Wednesday Jun 26, 2013

Java EE 7 support in NetBeans 7.3.1


NetBeans IDE provide tools, templates, and samples for building Java EE 7 applications. NetBeans 7.3.1 specifically added support for the features mentioned below:

  • Support for creating Java EE 7 projects using Maven and Ant
  • Develop, Deploy, and Debug using GlassFish 4
  • Bundled Java EE 7 javadocs
  • CDI is enabled by default for new Java EE 7 projects (CDI 1.1)
  • Create database scripts from Entity Classes (JPA 2.1)
  • Java Persistence Query Language (JPQL) testing tool (JPA 2.1)
  • RESTful Java client creation using JAX-RS 2.0 Client APIs (JAX-RS 2.0)
  • New templates for JAX-RS 2 Filter and Interceptor (JAX-RS 2.0)
  • New templates for WebSocket endpoints (WebSocket 1.0)
  • JMS messages are sent using JMS 2 simplified API (JMS 2.0)
  • Pass-through attributes are supported during Facelet page editing (JSF 2.2)
  • Resource Library Contracts(JSF 2.2)
  • @FlowScoped beans from editor and wizards (JSF 2.2)
  • Support for EL 3.0 syntax in editor (EL 3.0)
  • JSON APIs can be used with code completion (JSON 1.0)

A comprehensive list of features added in this release is available in NetBeans 7.3.1 New and Noteworthy.

Watch the screencast below to get a quick overview of the features and capabilities:



Download Netbeans 7.3.1 and start playing with Java EE 7!

Tuesday Jun 25, 2013

JMSContext, @JMSDestinationDefintion, DefaultJMSConnectionFactory with simplified JMS API: TOTD #213


"What's New in JMS 2.0" Part 1 and Part 2 provide comprehensive introduction to new messaging features introduced in JMS 2.0. The biggest improvement in JMS 2.0 is introduction of the "new simplified API". This was explained in the Java EE 7 Launch Technical Keynote. You can watch a complete replay here.

Sending and Receiving a JMS message using JMS 1.1 requires lot of boilerplate code, primarily because the API was designed 10+ years ago. Here is a code that shows how to send a message using JMS 1.1 API:

@Stateless
public class ClassicMessageSender {

@Resource(lookup = "java:comp/DefaultJMSConnectionFactory")
ConnectionFactory connectionFactory;

@Resource(mappedName = "java:global/jms/myQueue")
Queue demoQueue;

public void sendMessage(String payload) {
  Connection connection = null;
    try {
      connection = connectionFactory.createConnection();
      connection.start();
      Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
      MessageProducer messageProducer = session.createProducer(demoQueue);
      TextMessage textMessage = session.createTextMessage(payload);
      messageProducer.send(textMessage);
    } catch (JMSException ex) {
      ex.printStackTrace();
    } finally {
      if (connection != null) {
        try {
          connection.close();
        } catch (JMSException ex) {
          ex.printStackTrace();
        }
      }
    }
  }
}

There are several issues with this code:
  • A JMS ConnectionFactory needs to be created in a application server-specific way before this application can run.
  • Application-specific destination needs to be created in an application server-specific way before this application can run.
  • Several intermediate objects need to be created to honor the JMS 1.1 API, e.g. ConnectionFactory -> Connection -> Session -> MessageProducer -> TextMessage.
  • All APIs throw checked exceptions and so try/catch block must be specified.
  • Connection need to be explicitly started and closed, and that bloats even the finally block.
The new JMS 2.0 simplified API code looks like:


@Stateless
public class SimplifiedMessageSender {

  @Inject
  JMSContext context;

  @Resource(mappedName="java:global/jms/myQueue")
  Queue myQueue;

  public void sendMessage(String message) {
    context.createProducer().send(myQueue, message);
  }
}

The code is significantly improved from the previous version in the following ways:
  • The JMSContext interface combines in a single object the functionality of both the Connection and the Session in the earlier JMS APIs.  You can obtain a JMSContext object by simply injecting it with the @Inject annotation. This of course works only in Java EE Web or EJB applications and does not apply in Java SE-based applications where injection is not available.
  • No need to explicitly specify a ConnectionFactory. A default ConnectionFactory under the JNDI name of
    java:comp/DefaultJMSConnectionFactory
    is used if no explicit ConnectionFactory is specified.
  • The destination can be easily created using newly introduced @JMSDestinationDefinition as:
    @JMSDestinationDefinition(name = "java:global/jms/myQueue",
            interfaceName = "javax.jms.Queue")

    It can be specified on any Java EE component and the destination is created during deployment.
  • Creating JMSConsumer also starts the connection so there is no need to explicitly start it.
  • JMSContext, Session, Connection, JMSProducer and JMSConsumer objects are now AutoCloseable. This means that these resources are closed automatically by the management of try-with-resources statement.
  • New simplified API throws a new unchecked exception, JMSRuntimeException. This means try/catch blocks are not required.
  • Method chaining on JMSProducers allows to use builder patterns.
  • No need to create separate Message object, you can specify the message body as an argument to the send() method instead.

Want to try this code ? Download source code!

Download Java EE 7 SDK and install.
Start GlassFish: bin/asadmin start-domain
Build the WAR (in the unzipped source code directory): mvn package
Deploy the WAR: bin/asadmin deploy <source-code>/jms/target/jms-1.0-SNAPSHOT.war

And access the application at http://localhost:8080/jms-1.0-SNAPSHOT/index.jsp to send and receive a message using classic and simplified API.

A replay of JMS 2.0 session from Java EE 7 Launch Webinar provides complete details on what's new in this specification:



Enjoy!

Wednesday Jun 12, 2013

Java EE 7 SDK and GlassFish Server Open Source Edition 4.0 Now Available


Java EE 7 (JSR 342) is now final!

I've delivered numerous talks on Java EE 7 and related technologies all around the world for past several months. I'm loaded with excitement to share that the Java EE 7 platform specification and implementation is now in the records.

The platform has three major themes:



  • Deliver HTML5 Dynamic Scalable Applications
    • Reduce response time with low latency data exchange using WebSocket
    • Simplify data parsing for portable applications with standard JSON support
    • Deliver asynchronous, scalable, high performance RESTful Service
  • Increase Developer Productivity
    • Simplify application architecture with a cohesive integrated platform
    • Increase efficiency with reduced boiler-plate code and broader use of annotations
    • Enhance application portability with standard RESTful web service client support
  • Meet the most demanding enterprise requirements
    • Break down batch jobs into manageable chunks for uninterrupted OLTP performance
    • Easily define multithreaded concurrent tasks for improved scalability
    • Deliver transactional applications with choice and flexibility
This "pancake" diagram of the major components helps understand how the components work with each other to provide a complete, comprehensive, and integrated stack for building your enterprise and web applications. The newly added components are highlighted in the orange color:




In this highly transparent and participatory effort, there were 14 active JSRs:
  • 342: Java EE 7 Platform
  • 338: Java API for RESTful Web Services 2.0
  • 339: Java Persistence API 2.1
  • 340: Servlet 3.1
  • 341: Expression Language 3.0
  • 343: Java Message Service 2.0
  • 344: JavaServer Faces 2.2
  • 345: Enteprise JavaBeans 3.2
  • 346: Contexts and Dependency Injection 1.1
  • 349: Bean Validation 1.1
  • 352: Batch Applications for the Java Platform 1.0
  • 353: Java API for JSON Processing 1.0
  • 356: Java API for WebSocket 1.0
  • 236: Concurrency Utilities for Java EE 1.0

The newly added components are highlighted in bold.

And 9 Maintenance Release JSRs:

  • 250: Common Annotations 1.2
  • 322: Connector Architecture 1.7
  • 907: Java Transaction API 1.2
  • 196: Java Authentication Services for Provider Interface for Containers
  • 115: Java Authorization for Contract for Containers
  • 919: JavaMail 1.5
  • 318: Interceptors 1.2
  • 109: Web Services 1.4
  • 245: JavaServer Pages 2.3

Ready to get rolling ?

Binaries

Tools

Docs


A few articles have already been published on OTN:

And more are coming!

This blog has also published several TOTD on Java EE 7:


All the JSRs have been covered in the Java Spotlight podcast:

The latest issue of Java Magazine is also loaded with tons of Java EE 7 content:



Media coverage has started showing as well ...
And you can track lot more here.

You can hear the latest and greatest on Java EE 7 by watching replays from the launch webinar:



This webinar consists of:
  • Strategy Keynote
  • Technical Keynote
  • 16 Technical Breakouts with JSR Specification Leads
  • Customer, partner, and community testimonials
  • And much more
Do you feel enabled and empowered to start building Java EE 7 applications ?

Just download Java EE 7 SDK that contains GlassFish Server Open Source Edition 4.0, tutorial, samples, documentation and much more.

Enjoy!

Sunday May 19, 2013

Java EE 7 Launch Webcast: Jun 12th, Register Now


The Java EE 7 Platform JSR was approved a few days ago and is ready to be released ...ta da!

Want to learn the latest and the greatest improvements in the platform from the best ?

Mark the date for webinars in two different time zones:

Jun 12, 2013, 9am PT
Jun 12, 2013, 9pm PT

Register now!

What will you see in this online event ?
  • Business Keynote (Hasan Rizvi and Cameron Purdy)
  • Technical Keynote (Linda DeMichiel)
  • Breakout Sessions on different JSRs by specification leads
  • Live Chat
  • Lots of Demos
  • Community, Partner, and Customer video testimonials

Feel free to use any of the following images to promote the launch webcast on your blog, website, social media, or elsewhere. You can also copy/paste the code fragment shown next to them:

<a
href="https://event.on24.com/eventRegistration/EventLobbyServlet?target=registration.jsp&eventid=615713&sessionid=1&key=453EBA948F6408FE613E61903CBAEBFA&partnerref=Java_EE7_Launch_glassfishblogs_06122013&sourcepage=register"><img
alt=""
src="https://blogs.oracle.com/arungupta/resource/javaee7-launch-jun12-185x225.png"
border="0" height="225" width="185"></a>



<a
href="https://event.on24.com/eventRegistration/EventLobbyServlet?target=registration.jsp&eventid=615713&sessionid=1&key=453EBA948F6408FE613E61903CBAEBFA&partnerref=Java_EE7_Launch_glassfishblogs_06122013&sourcepage=register"><img
alt=""
src="https://blogs.oracle.com/arungupta/resource/javaee7-launch-jun12-403x403.png"
border="0" height="403" width="403"></a>

Don't forget to register!

Get ready to drink from the fire hose, no throttle!

Wednesday Apr 17, 2013

Suggestions for Java EE and Cloud Track at JavaOne 2013: CFP ends Apr 23




JavaOne Call for Papers has been extended and now will close on April 23. There are eight tracks to submit your talks:
  • Client and Embedded Development with JavaFX
  • Core Java Platform
  • Edge Computing with Java in Embedded, Smart Card, and IoT applications
  • Emerging Languages and the Java Virtual Machine
  • Securing Java
  • Java Development Tools and Techniques
  • Java EE Web Profile and Platform Technologies
  • Java Web Services and the Cloud

A complete description of each track is provided here. Five different kind of sessions can be submitted for each track:

  • Conference Session: A 60-minute session presented by Oracle, customers, partners, developers, and/or user group members
  • Panel: A 60-minute session presented in a panel format by multiple speakers consisting of Oracle, customers, partners, developers, and/or user group members
  • Tutorials: A 2 hour speaker led session where the presenter literally show attendees a live "How to" tutorial, and attendees can ask questions to the presenter during this. It doesn't require the attendee to have any equipment whatsoever. Ideally, the attendee should be listening and taking notes.
  • Birds of a Feather (BOFs): A  60-minute session that allows a closer interaction with the speakers and attendees focusing on a particular aspect of technology.
  • Hands-on Lab (HOL): A two-hour hands-on, interactive lab session
We've seen a good response to paper submission so far and really thankful for that!

You've a few more days to submit your talks. As a track co-lead for Java EE and Cloud tracks, here are some talks that I'd like to see there:
  • Anything related to WebSocket, JSON, Concurrency, Batch, HTML5, Persistence, Dependency Injection, Transactions ?
  • Do you have a creative use of Java EE technologies in your applications ?
  • Are you an extreme believer in Java EE and use most of the components for creating world-class applications ?
  • Are you using multiple application servers in your deployment environment ?
  • Do you have any experience of migrating from earlier versions of J2EE to Java EE ? Tutorials here would be nice.
  • Do you want to show value of standards-based application development over proprietary frameworks ?
  • Are you building support for Java EE 7 in your applications already ?
  • Performance, monitoring, testing, development, deployment strategies ?
  • Any other enterprise Java technologies from the ecosystem ?
  • Real case studies on how Java EE helped you deliver on time, within budget, and stay competitive
And now some suggestions for the Cloud track:
  • How are your Java services powering web and cloud ?
  • Anything related to REST/SOAP Web services and design patterns ?
  • How is Service Oriented Architecture (SOA) helping you realize the benefits ?
  • Do you have an interesting deployment topology across your private and public cloud ?
  • Do you have a case study showing why a particular deployment scenario works ?
  • Are you exposing services at IaaS, PaaS, and SaaS layers and share guidelines on them ?
  • How are you simplifying DevOps ?
  • How are you using BigData in development and deployment ?
  • Anything related to NoSQL ? Using a mix of NoSQL and RDBMS ?
Keep the job of Content Review Committe interesting, demanding, and challenging. Submit as many sessions as you can before April 23rd 11:50pm PT.

Read the content review process and tips for submission from 2 years ago to improve your chances of getting a paper selected.

Submit now!

Thursday Apr 04, 2013

WebSocket Client and Server Endpoint: Annotated and Programmatic (TOTD #212)


JSR 356 defines Java API for WebSocket 1.0. It defines a standard-based programming model for creating WebSocket client and server endpoint. Both kind of endpoints can be created programmatically or using annotations. This Tip Of The Day (TOTD) provide short snippets of how to write a WebSocket client and server endpoint programmatically or using annotations.

The complete source code in this sample can be downloaded from here.

Lets start with annotation-based server endpoint.

@ServerEndpoint("/websocket")
public class MyEndpoint {
   
  @OnMessage
  public String echoText(String name) {
    return name;
  }
}

@ServerEndpoint marks the POJO as a WebSocket server endpoint. URI of the deployed endpoint is as value attribute of the annotation.  echoText method is invoked whenever a message with text payload is received by this endpoint. Payload of the message is mapped to the parameter name. A synchronous response is returned to the client using the return value.

Programmatic server endpoint can be defined as:

public class MyEndpoint extends Endpoint {

  @Override
  public void onOpen(final Session session, EndpointConfig ec) {
    session.addMessageHandler(new MessageHandler.Whole<String>() {

      @Override
      public void onMessage(String text) {
        try {
          session.getBasicRemote().sendText(text);
        } catch (IOException ex) {
          Logger.getLogger(MyEndpoint.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
  });
}

A programmatic server endpoint is defined by extending Endpoint abstract class. onOpen method is overridden to be notified of when a new conversation has started. Session captures the other end of the conversation. EndpointConfig identifies the configuration object used to configure this endpoint. Multiple MessageHandlers are registered to handle text, binary, and pong messages. The first parameter of onOpen captures the other end of the conversation. A synchronous response to the client is sent by calling getBasicRemote().sendText(...) method.

Programmatic server endpoint needs to be configured using ServerApplicationConfig.

public class MyApplicationConfig implements ServerApplicationConfig {

  @Override
  public Set<ServerEndpointConfig> getEndpointConfigs(Set<Class<? extends Endpoint>> set) {
    return new HashSet<ServerEndpointConfig>() {
      {
        add(ServerEndpointConfig.Builder
            .create(MyEndpoint.class, "/websocket")
            .build());
      }
    };
  }

  @Override
  public Set<Class<?>> getAnnotatedEndpointClasses(Set<Class<?>> set) {
    return Collections.emptySet();
  }
}

WebSocket runtime scans the WAR file with all implementations of ServerApplicationConfig and registers the endpoint returned from getEndpointConfigs and getAnnotatedEndpointClasses. The URI of the server endpoint is published using ServerEndpointConfig.Builder.

Now lets take a look at annotated client endpoint.

@ClientEndpoint
public class MyClient {
  @OnOpen
  public void onOpen(Session session) {
    try {
      String name = "Duke";
      System.out.println("Sending message to endpoint: " + name);
      session.getBasicRemote().sendText(name);
    } catch (IOException ex) {
      Logger.getLogger(MyClient.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}

@ClientEndpoint marks the POJO as a WebSocket client endpoint. onOpen method is invoked whenever a new WebSocket connection is opened and is identified by @OnOpen annotation. Session captures the other end of the conversation. A synchronous message is sent to the server using session.getBasicRemote.sendText() method.

This client can connect to the endpoint as:

WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://localhost:8080" + request.getContextPath() + "/websocket";
container.connectToServer(MyClient.class, URI.create(uri));

And finally programmatic client endpoint.

public class MyClient extends Endpoint {
  @Override
  public void onOpen(final Session session, EndpointConfig ec) {
    session.addMessageHandler(new MessageHandler.Whole<String>() {

      @Override
      public void onMessage(String text) {
        System.out.println("Received response in client from endpoint: " + text);
      }
  });
  try {
    String name = "Duke";
      System.out.println("Sending message from client -> endpoint: " + name);
      session.getBasicRemote().sendText(name);
    } catch (IOException ex) {
      Logger.getLogger(MyClient.class.getName()).log(Level.SEVERE, null, ex);
    }
  }
}


The first parameter of onOpen captures the other end of the conversation.  EndpointConfig identifies the configuration object used to configure this endpoint. Multiple MessageHandlers are registered to handle text, binary, and pong messages. onMessage method is called whenever a message is received from the endpoint. A synchronous request to the server is sent by calling getBasicRemote().sendText(...) method.

This client can connect to the endpoint as:

WebSocketContainer container = ContainerProvider.getWebSocketContainer();
String uri = "ws://localhost:8080" + request.getContextPath() + "/websocket";
container.connectToServer(MyClient.class,
                null,
                URI.create(uri));

Now go download your GlassFish b82, samples source code, and run them.


Friday Mar 22, 2013

Introducing Kids to Java Programming Using Minecraft


Minecraft is a wildly popular game among elementary and middle schoolers. The game allows players to build constructions of textured cubes in a 3D world.

My son has been playing the game for about a year, lets say addicted to it. Last Fall he told me that the game is corrupted because the JAR file snapshot has messed up the configuration. And that right away rang a bell in me as a Java Evangelist at Oracle.

I learned from him that the game is written in Java, has a trial version that runs as an applet in the browser, and downloaded as a JAR file for desktop. The game is modular where the players travel through a world and chunks are loaded and unloaded to keep the memory footprint small. Something unique about the game is the ability to modify the game from what it was originally designed for. In Minecraft language, this is called as a "mod" - short for modifications. For example, a mod can add new characters to the game, change look-and-feel of the play field, or make it easy to build new structures.

The game has a server and a client component. This allows the game to be played in a single player mode where a player connects to a server using a client and plays the game. Alternatively multiple players, using different clients across platforms, can connect to a server and play with each other collaboratively. Its very common to have a server run with multiple mods. There are almost an infinite number of mods someone could do to make Minecraft a more amusing game to play. There is no official API to create these mods but there are several third-party vendors that provide that capability; Bukkit is one such API. The ability to write mods and alter the game play gives players more control over the game and gets them more excited.

My son expressed his desire to write a mod and so we started exploring further. Then onwards, he started teaching me Minecraft vocabulary and I taught him the Java programming concepts. Our discussions in the car, on the dinner table, during the breakfast preparation, and elsewhere changed to reflect that as well. He already played with Scratch and Greenfoot last Summer and that was extremely helpful during this learning curve. We set up a goal to build a mod during Christmas break. After understanding the basic concepts and building a few mods, we decided to share the knowledge with a broader set of Minecrafters. And that's where the concept of doing a Minecraft Workshop was born.

My son came up with a list of his minecraft buddies and we announced a date for the workshop. Everybody invited for the workshop confirmed their presence right away. I found out that both the invited kids and their parents were equally excited. One friend could not attend because of a prior commitment and was extremely disappointed. On the day of the workshop, some kids were eager to come even before the formal start of the workshop.

The workshop was attended by 10 kids with age ranging from 10-14 years. Most of the kids had no programming experience, let alone Java. However there was high Minecraft experience in the group with some kids playing for about 2 years and up to 2 hours every day. When given the topic of Minecraft, the small group would talk excitedly about different aspects of the game, constantly using hundreds of game-specific terms and phrases as if speaking a different language. My goal was to leverage their passion and introduce them to Java programming.


The challenge for me was to introduce programming to these kids using analogies from the daily life. Using a car, features, capabilities, types, and car dealers and correlating with class, properties, methods, instances, and packages seem to work. Fruits and different methods of peeling, eating, and planting was used to introduce the concept of Interface in Java. I asked, “What can you do with a watermelon?” the first answer was obvious, “you can eat it.” The second one was a little less so, “You can chuck in a trash can.” The response was greeted with scattered laughter. I used that to explain the concept of Exceptions in Java.

Short anecdotes and side-conversations kept the livelihood of the group going throughout the five hour programming session. There are almost an infinite number of mods someone could do to make Minecraft a more amusing game to play. But all these mods hold the same basic framework that we set up for any future work on making game-specific mods. By the end of the session, we had worked out an entire framework for making a mod. A Maven archetype to create a template Bukkit plugin allowed the attendees to avoid writing boilerplate code. A lower bar to get started and simplicity was the key for this audience. The mod built in the workshop added a new server-side command and printed a trivial message.

Although the goal of the workshop was to get an introduction on programming and make a Minecraft mod, I believe the attendees learned much more than that. I think the informal set up helped them discover that programming can be fun and useful to add to gaming experience. Programming is a vast field and we barely scratched the surface. But most importantly, the attendees had a good time and learned their first lesson of Java programming to start off an interest in it.


"Fun", "Easy", "Quick", "Awesome", "Short", and "Intuitive" described attendees' one word summary of building and running their first Hello World application using NetBeans.

All the instructions followed in the workshop, including a lot more pictures, are available at java4kids.java.net/minecraft-workshop.

For me, it was quite a humbling and learning experience. I've delivered multiple workshops all around the world but mostly to professional developers. I realized how the instructions need to be completely spelled out in order for the attendees of this age to make progress. Something as simple as "Hit Enter after entering the command", yes, that is required. Anyway I plan this to be the first of many more workshops aimed to introduce the world of Java programming to school students.

One of the lessons learned during the workshop was to simplify the installation experience. All the kids had JDK and NetBeans set up already, pretty straight forward. However I wonder why Maven insists on JAVA_HOME variable instead of figuring it out. I need to investigate how to seamlessly install JDK, NetBeans, and Maven in a platform independent way. This will allow to focus more on building the actual mod rather than the multi-step installations.



This workshop was not possible without mentoring support from Allen Dutra and other parents. A huge shout out to my family who helped validate and calibrate my strategy for the audience. My nephews feedback from the lab is incorporated into this blog. Thanks to Oracle for sponsoring the snacks!

Thank you @notch for using Java to build the game! You've provided a great platform for young kids to learn Java and truly enabled Make The Future Java ...

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