Thứ Năm, 8 tháng 5, 2014

Video Review: Building an Application with CoffeeScript

Darko Bozhinovski's video course Building an Application with CoffeeScript was published last month by Packt Publishing. In this post, I review this video course on CoffeeScript (described on its main web page as "a little language that compiles into JavaScript" that is "an attempt to expose the good parts of JavaScript in a simple way").
Building an Application with CoffeeScript runs in the same web browser-based Packt Video Player used by other video courses from Packt Publishing that I've previously reviewed: HTML5 Game Development, jQuery UI Development, and JBoss EAP Configuration, Deployment, and Administration. The player runs completely in a web browser and features short video segments (ranging from 1 minute to 9 minutes each) divided into eight sections (chapters) with between 2 and 3 videos per section.
Section 1: CoffeeScript 101
The first section of Building an Application with CoffeeScript includes three videos and the initial video is the longest of the entire video course with a duration of almost 9 minutes. This initial video's summary includes three bullets and provides a link to additional references for more details. The video introduces CoffeeScript via the CoffeeScript site. In describing how CoffeeScript allows the best parts of JavaScript to be used, the video author also references Douglas Crockford's JavaScript site. Much of this first video uses examples on the CoffeeScript site to compare and contrast CoffeeScript with JavaScript. The site shows CoffeeScript and equivalent JavaScript code side-by-side and the video author shows these same CoffeeScript-to-JavaScript comparisons in the web-based JavaScript-to-CoffeeScript compiler js2coffee. As he narrates, he shows how subtle changes to the CoffeeScript or the JavaScript impact the other language in the js2coffee tool. One slightly distracting issue with the first video is the presence of "Topic 3" text at the end of a bullet on the first slide; I suspect this was template text that should have been removed when the bullet was added.
The second video demonstrates how to download and install the CoffeeScript compiler via download of Node.js. The video demonstrates using the command-line compiler to compile a "Hello, World" example written in CoffeeScript to JavaScript and then shows that JavaScript rendered in a web browser.
Section 1's third video introduces cake, described in the CoffeeScript site as, "a (very) simple build system similar to Make and Rake." Bozhinovski demonstrates writing a Cake task that compiles all CoffeeScript files in a given directory to their CoffeeScript equivalents and then demonstrates running that Cake task.
Section 2: Head-first Application Development
Section 2 features three video snippets that cover concepts such as object-oriented programming, inheritance, classes, and MVC. The first video of Section 2 is the one that really started to pique my interest in CoffeeScript. Although I liked some of the conciseness that CoffeeScript offers over JavaScript as shown in earlier video snippets, it was the support for class-based object-oriented programming in CoffeeScript that really caught my attention. The narrator demonstrates using js2coffee that classes in CoffeeScript are functions in JavaScript and one cannot help but notice how much more readable the CoffeeScript classes are than the JavaScript functions. The author also uses this first video of Section 2 to introduce his project with code examples that are used in the course.
The second video snippet of Section 2 focuses on Model-View-Controller and begins this focus with a reference to the Wikipedia page on MVC. Bozhinovski returns to his Github project coffeescript-course again and makes a short detour to advertise benefits of Github and how to start with Github. He then shows that the files in his project are empty and explains that he will populate them as part of the video course. At that point, he creates base model, controller, and view classes.
The third video of Section 2 begins with a focus on class-based inheritance in CoffeeScript. This coverage includes referencing the CoffeeScript site and demonstrating extending the base classes written in the previous video. A significant portion of this video highlights more resources available to viewers interested in CoffeeScript at the CoffeeScript site, via JavaScript frameworks, and at the http://todomvc.com/ site.
Section 3: The Storage Layer – Models and Data Persistence
There are only two video snippets in Section 3, but the section's overall duration is among the highest of the video course. The first video in this section discusses Web/DOM storage and which browser versions support this feature. The author points out advantage of local (web) storage such as its better support among common web browsers as compared to alternatives such as IndexDB and Web SQL Database.
Section 3's first video demonstrates use of localStorage by opening a web brower's console and running JavaScript-based examples using localStorage in that console (brief discussion on how to open this console in different browsers is included). The examples are then shown in js2coffee so that use of localStorage can be seen both directly in JavaScript and in CoffeeScript.
The second video in Section 3 is "the fun part" and begins with a demonstration of writing a class in CoffeeScript that encapsulates persisting and retrieving data values to localStorage. The example highlights the ability to specify static methods on a CoffeeScript class with the @ symbol and demonstrates how these static methods would be called by clients. Section 3's second video also demonstrates completing and persisting the model classes. JSON.parse and JSON.stringify are demonstrated within CoffeeScript as well.
Section 4: Routing and Views
Section 4 is composed of three video snippets. The first video in this section reviews the roles of controller, view, and model and then introduces the concept of routing. The video demonstrates building a routing class for the example application, but the narrator explains the basic theory behind routers and points out third-party routing micro frameworks that are already available for use. The author's examples are relatively simple, associating routes with controllers' methods, but the author points out that more elaborate routing is possible.
The second video of Section 4 builds on the section's first video to cover routers and controllers in more detail. The author demonstrates writing new controller methods and demonstrates more concretely the association between controllers and routers.
Section 4's final video is the longest of the section and introduces views. Along the way, this video demonstrates some more CoffeeScript features such as its constructor method, its multi-line string support, and its for-of loop. The example application at this point has HTML tags added to its rendering portion of its view classes and jQuery is used here as well.
Section 5: Interactions and Event Handling – Using JQuery with CoffeeScript
Using jQuery was mentioned very briefly a couple times in earlier sections, but the two-video Section 5 makes the use of jQuery with CoffeeScript a central theme. The first of the section's two videos demonstrates how to prevent a hypertext action in the example application from going to a newly served page and instead be routed via the router built in Section 4. This is key to implementing a single-page application. This video also demonstrates additional CoffeeScript/jQuery binding concepts and demonstrates CoffeeScript's switch/when statement.
Section's final second and final video starts by revisiting the hash change support in modern browsers. The author also mentions the pushState API. Demonstration of writing a global Event Emitter based on Backbone.js's Backbone.Events class is also demonstrated and it is explained that this approach allows for less tight coupling than using direct calls between views and controllers.
Section 6: Extending Our Application – Manipulating Stored Data
There are three video snippets in Section 6 and all three use creation and enhancement of the example applications category and document concepts to illustrate organization of data and of additional CoffeeScript code in practice. These are code-heavy videos that illustrate practical implementation of new features for the example application.
Section 7: Extending Our Application – Add an External Library
The first video of Section 7 introduces the idea of using Summernote in the example application to support rich text editing. The second video demonstrates integrating Summernote with the example application, including saving the rich text.
The second video also introduces jsPDF and the third video of Section 7 demonstrates integrating jsPDF with the example application so that the example application can export PDF from HTML.
Section 8: Publishing and Real-world Usage for Our Documents
The final section has three videos. The first of these three demonstrates using the Blob API to allow the example application to export documents in text and HTML formats. The second video demonstrates how to allow a user of the example application to publish the document to a WordPress blog. The third and final video of this section (and final video of the course) talks about ways that viewers could customize and enhance the example application built during the course. The author outlines other possible applications that could be built from it and talks about other ways to change it.
General Observations
  • The title "Building an Application with CoffeeScript" articulates well what this video course is. Although the video course is often introductory in nature, it is organized around demonstration of building an application using CoffeeScript and incidentally providing introductory information along the way. This is different than being organized as an introduction to CoffeeScript that happens to build an example application along the way. Instead of providing lengthy lists of features and syntax examples (which is what a course focused on introduction over application building might do), this video course provides just enough introductory coverage of required features and syntax to allow the work of building an example application to take place.
  • Numerous online references are shown and discussed in this video course, making it easier for the viewer to identify sources of additional details and background information. These online resources help the narrator to explain the topic and showing them to the viewer allows the viewer to directly access them after being introduced to them. The video course makes it even easier to find these resources by listing the URLs for most of them in the summary area of each section.
  • There are several occurrences in the video course when the author references the associated GitHub project ("coffeescript-course") for additional or deeper details than covered in the video. This allows the video presentation to avoid getting too deep in details while at the same time allowing viewers to learn more details as desired after finishing the video.
  • Viewers of Building an Application with CoffeeScript will be best served if they have basic familiarity with JavaScript. This is because many of the examples teach CoffeeScript via comparison to JavaScript and because basic familiarity with JavaScript allows the viewer to more quickly appreciate what CoffeeScript offers in its place.
  • I liked that several popular JavaScript frameworks were used in the example application built in this video course. Specific examples of frameworks used in the example application include jQuery, BackBone, and Bootstrap-based Summernote.
  • I liked that several features of modern web browsers were used in the example application built in this video course.
Conclusion
Building an Application with CoffeeScript delivers on what its title promises: demonstration and explanation of building a simple application with CoffeeScript. This video is most likely going to appeal most strongly to developers who have basic JavaScript familiarity and want to get a quick overview of what CoffeeScript offers and how it can ease some of the burdens of JavaScript development.

Thứ Sáu, 2 tháng 5, 2014

Book Review: Java EE 7 with GlassFish 4 Application Server

David R. Heffelfinger's Java EE 7 with GlassFish 4 Application Server has been published by Packt Publishing. The subtitle of this book is "A practical guide to install and configure the GlassFish 4 application server and develop Java EE 7 applications to be deployed to this server."

The Preface of Java EE 7 with GlassFish 4 Application Server states that JDK 7 (or newer), GlassFish 4.0, and Maven are needed to build and run the examples in this book. The Preface also expects that readers are expected to have "familiarity with the Java language" and that the book is intended for Java developers wanting to learn Java EE or current Java EE developers wanting to learn about the newest specification.

Chapter 1: Getting Started with GlassFish

The first chapter of Java EE 7 with GlassFish 4 Application Server begins by briefly describing GlassFish and by providing a high-level overview of the new features of Java EE 7. The new Java EE 7 specifications covered at this high level are JavaServer Faces (JSF) 2.2, Java Persistence API (JPA) 2.1, Java API for RESTful Web Services (JAX-RS) 2.0, Java Message Service (JMS) 2.0, Java API for JSON Processing (JSON-P) 1.0, and Java API for WebSocket 1.0.

Chapter 1 lists two of the primary advantages of using GlassFish as a Java EE application server: it being the reference implementation and, as such, it providing implementations of the latest and newest Java EE features. There is no mention of what I perceive to be GlassFish 4's biggest disadvantage: Oracle has declined to provide commercial support for GlassFish 4.

The initial chapter demonstrates how to download GlassFish 4 and mentions that it is also available bundled with NetBeans IDE ("Java EE" or "All" bundles) since version 7.4. The chapter shows the basics of installing the downloaded GlassFish and assumes that JDK 1.7 or later (note there have been rumors of GlassFish 4 not working well on JDK 8 yet) has been installed and that the Java application launcher is available from the environment's path.

Starting GlassFish from the command-line using the well-known (to previous users of GlassFish) asadmin start-domain command is demonstrated in Chapter 1. The chapter shows bringing up a web browser with the URL http://localhost:8080 to verify that GlassFish is running and then demonstrates using the web-based administrative console at URL http://localhost:4848 to deploy a WAR (simpleapp.war) provided on the book's Packt Publishing site. This chapter also demonstrates using the web-based Administrative Console to undeploy the web application as well before demonstrating two ways to deploy the WAR from the command line (by copying the WAR into the autodeploy directory and by using the asadmin deploy command).

Chapter 1 introduces GlassFish domains as a concept and then explains how to work with them using appropriate asadmin domain commands create-domain, delete-domain, and stop-domain.

This meaty first chapter concludes with a demonstration of how to configure GlassFish to use a JDBC driver for working with a relational database. The example specifically demonstrates configuration of a MySQL database driver and datasource, but the author points out that the examples in the rest of the book that work with relational databases use the Apache Derby-based JavaDB that comes bundled with GlassFish.

Nothing in this first chapter on downloading, installing, deploying to, and configuring a data source for GlassFish seems different to me from previous versions of GlassFish. I believe that experienced GlassFish users who are reading Java EE 7 with GlassFish 4 Application Server to learn the new Java EE 7 features and new GlassFish 4 features could skip most of the introductory chapter with the exception of the section providing concisely worded high-level overviews of the new Java EE 7 features. For readers entirely new to GlassFish, this chapter provides a nice starting point for everything you need to do to get GlassFish up and running for use with examples later in the book.

Chapter 2: JavaServer Faces

The second chapter of Java EE 7 with GlassFish 4 Application Server focuses on JavaServer Faces (JSF), which it describes as "the standard component framework of the Java EE platform." This chapter's coverage includes discussion of Facelets as now (as of Java EE 6/JSF 2.0) JSF's "preferred view technology." The chapter describes how adhering to JSF's expected conventions can lead to minimal required configuration.

Chapter 2 continues its JSF coverage with an example XHTML-based Facelet that is described in detailed text. Along the way, the author explains how to use JSF 2.0 project stages and explains how to specify a project stage to GlassFish as a JNDI resource.

JSF's "built-in input validation capabilities" are covered next. A table of standard JSF validators is provided and there is minor discussion on using Bean Validation with JSF. The chapter also includes discussion on creation of custom validators. The example illustrating custom validators uses Apache Commons Validator. When the chapter includes an example of implementing custom validation methods on Named Beans, it makes use of Apache Commons StringUtils.

After Chapter 2 covers customization of message styles and text, it moves onto a section called "Ajax-enabling JSF applications." This section points out that "JSF 2.0 standardized Ajax support by introducing the <f:ajax> tag" and then provides an example of using that new tag. There is thorough coverage of the Ajax tag, how it works, and what its other options are.

The parts of JSF 2.2 that interest me most and which I looked forward most to reading about in this book are JSF 2.2's HTML5 support and JSF 2.2's Faces Flows. Both subjects are covered well in this chapter with examples and descriptions of those examples.

Chapter 3: Object Relational Mapping with JPA

Chapter 3 is dedicated to Java Persistence API and most of the chapter covers basics of JPA that have been in place well before Java EE 7. The chapter describes JPA as "the standard Java EE Object Relational Mapping (ORM) tool" and provides examples and discussion on using JPA with one-to-one relationships, one-to-many relationships, many-to-many relationships, and composite primary keys. The chapter also introduces Java Persistence Query Language (JPQL).

The third chapter discusses how the Criteria API limitations of JPQL. It also introduces JPA 2.1 (Java EE 7) enhancements to the Criteria API that allow "for updating database data via the CriteriaUpdate interface" because Criteria API could only be used for reading data previously.

Chapter 4: Enterprise JavaBeans

The fourth chapter's focus is Enterprise JavaBeans (EJB), which are introduced as "server side components that encapsulate business logic of an application" and "simplify application development by automatically managing transaction management and security." Two types of EJBs (session beans and message-driven beans) are discussed. Although not necessary anymore, it was interesting (or a walk down memory lane) to read the historical information about how session and entity beans have changed since the days of J2EE.

The examples and discussions regarding Session Enterprise JavaBeans include invocation of these deployed beans from a standalone client using appclient and from a web client using JSF and CDI. The examples also involve JPA, making them very inclusive of the significant Java EE specifications.

This fourth chapter covers several other EJB topics include security, the Timer Service, transactions, and the EJB lifecycle. None of these concepts are new to Java EE 7, but EJBs are of course a significant part of many Java EE applications.

Chapter 5: Contexts and Dependency Injection

Contexts and Dependency Injection (CDI), introduced with Java EE 6, is the subject of Chapter 5. The coverage includes named beans, dependency injection, CDI Qualifiers, and CDI named bean scopes (with particular emphasis on conversation scope).

Chapter 6: JSON Processing with JSON-P

Chapter 6 of Java EE 7 with GlassFish 4 Application Server is about Java API for JSON Processing (JSON-P, JSR 353), a specification new to Java EE 7. The chapter begins by introducing JavaScript Object Notation (JSON) as "a human-readable data interchange format ... derived from JavaScript."

The sixth chapter states that "JSON-P includes two APIs for processing JSON - the Model API and the Streaming API" and covers generating JSON and parsing JSON with each of these two APIs. The examples include code and text descriptions as well as brief descriptions of the advantages and disadvantages of JSON Model API versus JSON Streaming API.

Chapter 7: WebSockets

Like Chapter 6, Chapter 7 covers a specification and feature new to Java EE 7 with its coverage of Java API for WebSocket (JSR 356). The chapter covers development of WebSocket endpoints, development of JavaScript-based WebSocket clients, and development of Java-based WebSocket clients. Significant details regarding JSON-P are covered in this chapter and the author refers the read to the Tyrus User Guide for additional details (Tyrus is the "open source JSR 356 reference implementation").

Chapter 8: The Java Message Service

Chapter 8 of Java EE 7 with GlassFish 4 Application Server continues the streak of chapters covering new Java EE 7 specifications by covering Java Message Service (JMS) 2.0.

This is one of the chapters of Java EE 7 with GlassFish 4 Application Server that includes GlassFish-specific coverage within the topic of a general Java EE 7 specification. In this case, the chapter indicates how to configure GlassFish to use JMS by setting up "a JMS Connection Factory, a message queue, and a message topic." Like Chapter 4 on EJBs, this chapter on JMS also demonstrates using the GlassFish-specific applclient.

Chapter 8 coverage of JMS includes sending and receiving messages to/from queues and topics. It also includes an examples of browsing message queues and creating durable subscribers.

Chapter 9: Securing Java EE Applications

The ninth chapter of Java EE 7 with GlassFish 4 Application Server is on securing Java EE applications with Java Authentication and Authorization Service (JAAS) API and GlassFish. The chapter describes using security realms and covers both preconfigured realms (file, admin-realm, and certificate) and "defining additional realms" (with examples including an LDAP realm, a JDBC realm, and custom realms).

Chapter 10: Web Services with JAX-WS

The final two chapters of Java EE 7 with GlassFish 4 Application Server are on using web services with Java EE and Chapter 10 specifically covers working with SOAP-based web services using Java API for XML Web Services (JAX-WS). Chapter 10 defines web services as "application programming interfaces that can be invoked remotely" and that "can be invoked from clients written in any programming language."

Chapter 10 describes using JAX-WS to develop web services, to develop clients of web services, to add attachments to web services calls, to expose EJBs as web services, and to secure web services. The chapter looks at WSDLs and generating Java from WSDLs using GlassFish's wsimport.

Chapter 11: Developing RESTful Web Services with JAX-RS

The final chapter of Java EE 7 with GlassFish 4 Application Server covers REST-based web services support in Java EE as provided by Java API for RESTful Web Services (JAX-RS). Although this was originally added to enterprise Java with Java EE 6, Java EE 7 introduces JAX-RS 2.0.

Chapter 11 introduces REST and covers basic support for REST-based web services that was added with Java EE 6. This discussion covers basic JAX-RS annotations, using GlassFish logs to analyze working functionality, using curl as a client, and using JAXB for Java/XML binding. The chapter then moves onto discussion of Java EE 7's introduction of "a standard client-side API that we can use to easily develop RESTful web service clients." The chapter concludes with a discussion on query parameters and path parameters (@QueryParam and @PathParam).

Other Observations
  • Java EE 7 with GlassFish 4 Application Server liberally uses full color (in the PDF version I reviewed) screen snapshots that have sufficient resolution to be easy on the eyes and to nicely illustrate the concepts. This was particularly the case in the first chapter on installing and configuring GlassFish 4 and in other chapters dealing with the GlassFish web admin console.
  • I like that Java EE 7 with GlassFish 4 Application Server includes code examples that not only illustrate the points being made, but also include common and useful third-party libraries.
  • Heffelfinger has written other Packt Publishing books on J2EE/Java EE topics and portions of those books are the same across the books. For example, portions of Java EE 7 with GlassFish 4 Application Server are also available in Enterprise JavaBeans, Java EE 5 Development using GlassFish Application Server, and Java EE 6 with GlassFish 3 Application Server. Indeed, Java EE 7 with GlassFish 4 Application Server can be viewed as the third edition of the latter two of those books (it says as much by stating that it was "first published" in October 2007, had a "Second Edition" in July 2010, and the "Third Edition" in March 2014). Much of the Java EE and GlassFish content is the same with this edition adding in Java EE 7 new features and GlassFish 4 coverage. As a third edition, this book is as polished as one expects third editions to be.
  • Although Java EE 7 with GlassFish 4 Application Server explicitly covers GlassFish 4, there is not much that I can see in Java EE 7 with GlassFish 4 Application Server that is unique to GlassFish 4 other than its support for the newly added Java EE 7 specifications. The book is really more focused on Java EE in general and Java EE 7 in particular with GlassFish as the Java EE implementation used to demonstrate the examples. This is a great book for someone wanting to learn new Java EE 7 features and for someone wanting to learn how to use basic GlassFish features in Java EE development. The majority of GlassFish 4's new features are implementations of the new Java EE 7 specifications, so it's not surprising that the differences in this edition are more about Java EE 7 than about GlassFish 4.
  • Java EE 7 with GlassFish 4 Application Server's coverage of Java EE 7 covers it cumulatively rather than covering only features new to Java EE with Java EE 7.
Conclusion

Java EE 7 with GlassFish 4 Application Server provides a polished presentation of Java EE as it stands today with its recently included Java EE 7 specifications. GlassFish 4 is the application server used to demonstrate these Java EE concepts.

Thứ Ba, 29 tháng 4, 2014

Book Review: NetBeans Platform for Beginners

The recent Leanpub publication NetBeans Platform for Beginners: Modular Application Development for the Java Desktop by Jason Wexbridge and Walter Nyland provides an introduction to and coverage of the NetBeans Platform. I review the PDF version of NetBeans Platform for Beginners that was last updated on 26 March 2014 in this post.

NetBeans Platform for Beginners features over 350 pages of content divided into ten chapters and three major parts. Although the authors address NetBeans 7.4 specifically, the material in this book should be appropriate for several future versions of NetBeans as well. No prior NetBeans experience is assumed, but familiarity with Java is assumed. Although I've used Java and NetBeans IDE for years, my experience with NetBeans Platform has been minimal, making a book focused on NetBeans Platform for Beginners attractive to me.

Part 1: Core

Part 1 of NetBeans Platform for Beginners consists of four chapters focusing on "the mandatory core features of the NetBeans Platform." The initial chapter provides an overview of NetBeans Platform and demonstrates wizard-based creation and modification of simple NetBeans Platform-based applications. Although I don't have any significant experience with NetBeans Platform, this chapter was an easy-to-understand introduction, especially because much of what is covered consists of variations of approaches very familiar to anyone who has used NetBeans IDE extensively. This first chapter also outlines many advantages and features of NetBeans Platform.

The second, third, and fourth chapters of NetBeans Platform for Beginners respectively cover the Module System, File System, and Lookup features of the NetBeans Platform (three of Geertjan Wielenga's top four NetBeans Platform APIs).

The second chapter's coverage of the NetBeans Platform Module System describes benefits and trade-offs of modularity in general and discusses several details related to NetBeans Platform Module System such as use of manifest files, NBM files, and how to split an application into modules. The third chapter's coverage of the NetBeans Platform File System includes System FileSystem (see also related slides), module layers, FileObjects, FileObject attributes and DataObjects.

The fourth chapter (and final chapter in Part 1) begins with an introduction of why high cohesion and low coupling are architecturally desirable and states that "Lookup is a generic mechanism for loose coupling" in NetBeans Platform. The authors discuss the general JDK ServiceLoader mechanism as a foundation for understanding the NetBeans Lookup mechanism. They then compare the two approaches and list advantages of using NetBeans Lookup with applications based on NetBeans Platform. There are quite a few pages in this chapter devoted to introducing and demonstrating use of various approaches one can use to leverage the Lookup mechanism and the @ServiceProvider annotation.

Part 2: GUIs

Part 2 of NetBeans Platform for Beginners contains three chapters focusing on GUI components of the NetBeans Platform. Chapter 5 covers the Action System, Chapter 6 covers the Window System, and Chapter 7 covers Nodes and Explorers.

Chapter 5 introduces the NetBeans Platform Action System and introduces the ActionListener annotations @ActionID, @ActionRegistration, and @ActionReference. The chapter covers presenters such as menus, toolbars, keyboard shortcuts, and mnemonics.

The sixth chapter of NetBeans Platform for Beginners is focused on the NetBeans Platform Window System. There is quite a bit of content packed into this chapter including coverage of the benefits of the Window System as well as coverage of specific conceptual details such as describing components, registering components, component lifecycle, docking components, undoing changes within components, and lookup. The advanced section of this chapter's concept coverage was useful in understanding some of the material prior to the advanced section. For example, I understood Modes better after reading the advanced section on Modes than I did after reading the earlier section that briefly described Modes. One particularly interesting aspect of this chapter is highlighting of the internally (to NetBeans) developed Simple Validation API.

NetBeans Platform's Nodes and Explorer Views are the subject of Chapter 7 of NetBeans Platform for Beginners. The authors emphasize that "Nodes are a layer of indirection between a data model" before delving into coverage of specific types of Node classes. For example, the authors explain how a BeanNode is an adapter that wraps an underlying data-centric JavaBean/POJO with properties for presentation purposes. Other types of covered Node classes include DataNode (wraps file access), FilterNode (decorates another node in memory), and AbstractNode (suitable for extending for most custom Node implementations).

The authors also discuss explorer views in Chapter 7: "The Explorer & Property Sheet API consists of a set of GUI components, known as explorer views or explorers, that render Nodes."

Part 3: Extras

The first two parts of NetBeans Platform for Beginners ("Core" and "GUI") covered commonly used features of the NetBeans Platform. Part 3 focuses on NetBeans Platform features that are less commonly used.

Chapter 8 begins with an introduction of NetBeans Visual Library and NetBeans Platform Component Palette. Its initial paragraph on NetBeans Visual Library is essentially that provided on the library's main page:

The NetBeans Visual Library provides a set of reusable, predefined, and extensible Java components, called "widgets". Each widget has, built into it, various features, such as actions, layouts, and borders. When you compose widgets together, you can quickly and easily visualize data to the user. Combined with other NetBeans APIs, the NetBeans Visual Library lets you create interactive UIs, with drag-and-drop features commonly found in designer software.

The NetBeans Platform Palette and NetBeans Platform Widgets are covered in Chapter 8.

The ninth chapter of NetBeans Platform for Beginners introduces the NetBeans Platform "project type" and defines it as "a group of folders and files that should be treated as a single unit." There is significant detail in this chapter on using various APIs available on a NetBeans Platform project.

Chapter 10 is a "Miscellaneous" chapter that begins with a table of NetBeans APIs listed in alphabetical order. Text detailing each of these APIs follows the table. Most of the chapters prior to this one covered concepts first (basic and then advanced) before covering application of those concepts in the "Getting Started" section of each chapter. Chapter 10 is different in that the concepts and application are largely covered (briefly) together.

Other Observations
  • NetBeans Platform for Beginners makes use of numerous color (in the PDF version) screen snapshots. This makes visualizing what is being described more pleasant and makes reading and understanding the material easier.
  • I appreciate the color coded syntax applied to the code listings in PDF version of NetBeans Platform for Beginners. Using editors and IDEs that provide color coded syntax for years has spoiled me and I find it much easier to read code in a book when it has syntax coloring. Code samples in books are still not as readable as in IDEs but color syntax is far easier to read than syntax with no color highlighting. Some of the code listings don't seem completed color coded (some keywords are color coded in some listings but not others), but I appreciate the effort to get most of them color coded.
  • The PDF version of NetBeans Platform for Beginners that I reviewed has embedded links in text that references other parts of the book. This is very convenient and much easier to use to navigate throughout the text than trying to find a referenced subtitle or page number. Hyperlinks are a big part of the reason for the ubiquity of the web and I'm a bit surprised that more electronic books don't apply the concept as it is a major advantage over printed books.
  • I like that NetBeans Platform for Beginners often provides keyboard shortcuts for various actions in addition to explaining how to specify actions with mouse clicks.
  • There aren't many typos or spelling errors in the version (March 2014) of NetBeans Platform for Beginners that I reviewed. One exception to this is in Section 7.1.6.1.2 ("JPA"), which defines the JPA acronym as "Java Persistence Annotation specification" rather than as the "Java Persistence API specification." None of the typos I saw affected the accuracy of the information in a meaningful way as far as I could tell.
  • Although the "for Beginners" portion of its title suggests its introductory nature, NetBeans Platform for Beginners has enough detail in it to be useful as a reference as well. In fact, I think there are portions of the book that I'd better appreciate once I had more familiarity and practical experience with NetBeans Platform. Geertjan Wielenga, who is very familiar with the NetBeans Platform and has read multiple books on the NetBeans Platform, has written about NetBeans Platform for Beginners: "I think 'NetBeans Platform for Beginners' is a fantastic resource for NetBeans Platform developers, all the more so in combination with Leanpub.com, which is a simply wonderful authoring/publishing platform."
  • Most chapters in NetBeans Platform for Beginners covered concepts first and then illustrated those concepts with realistic code examples. In some cases, I found this enhanced my learning and in other cases I found I needed the code examples to clear up my interpretation of the descriptions of the concepts.
Conclusion

NetBeans Platform for Beginners provides a comprehensive introduction to the NetBeans Platform (version 7.4 specifically, though most of its content will apply to versions before and after that). It begins with "core" information that is easily learned by someone new to NetBeans Platform and the other two parts add increasingly deep information regarding the NetBeans Platform.

Thứ Bảy, 26 tháng 4, 2014

Book Review: Web Development with Jade

Packt Publishing recently published Web Development with Jade by Sean Lang. The subtitle of this book is "Utilize the advanced features of Jade to create dynamic web pages and significantly decrease development time."

Web Development with Jade is a relatively short book coming in at under 60 pages of main content divided into eight chapters and a one-page appendix. As is the case with most Packt Publishing books, the Preface contains useful information for people trying to decide whether to purchase the book. The Preface describes Jade as "a templating engine for Node.js" that is a "new, simplified language that compiles into HTML and is extremely useful for web developers." About Web Development with Jade, the Preface states, "This book is an introduction to Jade, and it will provide readers a with faster and cleaner way to write HTML that is more maintainable and automates redundant markup."

The Preface of Web Development with Jade states that the book is designed for "web developers with at least a basic understanding of HTML and JavaScript" and that readers of the book should have access to Node.js and a text editor.

Chapter 1: What is Jade?

The initial chapter of Web Development with Jade introduces Jade as "a templating language and a shorter, more elegant way to write HTML." The chapter discusses preprocessors in general before describing use Jade preprocessing specifically. The early part of this chapter also compares Jade to potential alternates HAML, PHP, Jinja2, and Mustache.

The first chapter moves to discussion of installing Jade by downloading Node.js and using the Node.js Package Manager (npm) to install Jade from the command line. With Jade installed, the chapter concludes with examples of compiling Jade template code into JavaScript and HTML.

Chapter 2: Basic Syntax

The second chapter of Web Development with Jade begins coverage of Jade syntax by explaining that indentation is used in Jade rather than opening and closing tags and braces like some other languages and templating tools use. This chapter does a nice job of presenting the basics of Jade syntax in an approachable manner. Seeing is believing and it's this chapter filled with simple examples that really "sells" one on the expressiveness of Jade better than any amount of descriptive text could.

Chapter 3: Feeding Data into Templates

Web Development with Jade's third chapter begins by demonstrating that JavaScript code can be executed within Jade templates by prefixing the JavaScript code with a hyphen and a space. The chapter describes and illustrates with examples how to use interpolation and escaping in Jade. The chapter also discusses and demonstrates providing data to a Jade template being compiled via compiler argument using --obj and via programmatic application of client-side Jade utilities in runtime.js.

Chapter 4: Logic in Templates

Chapter 4 of Web Development with Jade begins by introducing JavaScript-based logic (if/else, for, etc.) added to Jade templates. The chapter then moves to coverage of built-in Jade logical operators (if/else/else if, unless, cases, each, while) that read cleaner than embedded JavaScript.

Chapter 5: Filters

The fifth chapter of Web Development with Jade discusses use of other preprocessed languages within Jade by taking advantage of Jade filters and the underlying transformers library. The chapter provides a lengthy list of supported template engines along with lists of supported stylesheet languages, minifiers, and a miscellaneous category of supported preprocessor languages. The author then demonstrates embedding a subset of these (Markdown, CoffeeScript, and Stylus) into Java via code examples.

Chapter 6: Mixins

Web Development with Jade's sixth chapter covers Jade mixins and describes mixins as "small, encapsulated pieces of code that are reusable throughout the template" that "allow you to reduce redundancy" and to "make code easier to understand by providing good names." The chapter introduces mixin syntax, demonstrates passing of values and blocks of code to a mixin via arguments, and warns again regarding use of interpolation with mixins.

Chapter 7: Template Inheritance

Chapter 7 of Web Development with Jade covers insertion of "interchangeable blocks into templates" to "prevent you from needing to repeat [a base page layout] in every single file." The chapter describes and illustrates using the block keyword to designate Jade blocks. The chapter includes concise descriptions and short, clear example of how to extend, replace, append and prepend template blocks.

The seventh chapter also describes and provides examples of using Jade's support for includes, which it describes as the "simplest way" to "insert content from another file," but which is "the least dynamic because you cannot change/generate the name of the file you want to include." Static assets, filters, and including external Jade files are demonstrated and discussed as types of includes.

Chapter 8: Organizing Jade Projects

The eighth chapter of Web Development with Jade covers applying "conventions and best practices" when developing with Jade. After pointing out that most HTML conventions and best practices apply to Jade as well, the author discusses "more Jade-specific" practices.

The use of JSON to separate business logic from presentation is covered and the author recommends using JSON Schema. The section of this chapter on inlining explains the advantages of not inlining source code, but inlining compiled code. This section references Yahoo! Developer Network's Best Practices for Speeding Up Your Web Site and the assetgraph optimization framework (the latter of which is also recommended for minification).

Other practices discussed in Chapter 8 include use of mixins to remove redundant style specifications, "dividing templates into separated mixins and blocks," selecting between client-side rendering and server-side rendering, and build systems (Grunt, roots, and make).

Other Observations
  • Web Development with Jade is, at times, an opinionated book. Examples of this include the author calling angle brackets used in HTML/XML "lame and ugly" and stating that "PHP's already awful design" combined with ability to easily mix presentation and business logic "makes for some pretty horrific code." I don't mind this kind of opinionated writing (even if I don't always fully agree with it), but some readers might be put off by it.
  • The code examples in the PDF version of Web Development with Jade feature color coded syntax, making the code easier to read.
  • There are a few basic graphics in Web Development with Jade. Although all of these are pretty basic in terms of aesthetics (they look like simple diagrams drawn in PowerPoint), they do a great job of communicating the message they are intended to communicate.
  • Although I had never seen Jade before reviewing this book, I quickly became comfortable with Jade's syntax and prime uses after the quick read of the relatively short Web Development with Jade. Although Jade is not particularly complex and seems easy to pick up, there does appear to me to be a dearth of introductory Jade resources. LearnJade.com has some good introductory Jade material. The Jade Language Reference provides some nice code examples minimal explanations, but the Jade Tutorial is still lacking quite a bit of content. Web Development with Jade combines tutorial information, basic language reference information, and additional usage explanations in a single easy-to-read and convenient location.
  • The examples are simple and only a rudimentary knowledge of HTML, CSS, and JavaScript is needed to understand the discussion and examples.
Conclusion

Web Development with Jade is an excellent introduction to Jade. Web Development with Jade concisely and clearly outlines the basics of Jade and provides some thoughts on how Jade might be applied in web development. Jade seems to be a templating language that is easy to learn and Web Development with Jade appears to me to be the most efficient available approach for quickly learning this templating language.

Thứ Hai, 21 tháng 4, 2014

Coverity Scan 2013 Open Source Report

The Heartbleed Bug has received significant attention lately and has reignited discussions regarding open source security issues and open source quality issues. The article Heartbleed: Open source's worst hour goes so far as to open with the sentiment that Heartbleed is "open source software's biggest failure to date." In the midst of this discussion, the Coverity ScanTM 2013 Open Source Report has been released and provides another interesting source of input for the discussion.

Coverity Scan'sTM main page states that it uses static analysis to "find and fix defects in your C/C++ or Java open source project for free." Coverity, which was recently acquired by Synopsys, originally teamed up with the Department of Homeland Security to develop the Coverity ScanTM as part of the "Open Source Code Hardening Project." Last year's edition, the Coverity Scan: 2012 Open Source Report, found that "Code quality for open source software continues to mirror that of proprietary software–and both continue to surpass the accepted industry standard for good software quality." The just-released 2013 Coverity ScanTM Open Source Report reports a change this year, "Open source code quality surpasses proprietary code quality in C/C++ projects."

Although the Coverity ScanTM Open Source Report has mainly focused on the "state of open source software quality" in terms of C/C++ projects and Linux in the past, the 2013 report also adds Java-based open source projects Apache Cassandra, Apache CloudStack, Apache Hadoop, and Apache HBase. The report acknowledges that "we are still in the early days of working with Java projects" and looks at some possible explanations for the Java code that was analyzed having higher defect rates than the C/C++ code that was analyzed. These reasons include Java source code being new to the analysis (and thus not benefiting from being able to address previous results) and the use of FindBugs ("Many of the FindBugs checkers generate large quantities of results, in particular in the areas of dodgy code, performance and bad practices").

One of the other "key differences" analyzed in the 2013 Coverity Scan ReportTM is a lower percentage of "resource leaks" being fixed in analyzed Java code than in analyzed C/C++ code. The report's authors postulate that this might be explained by Java developers relying more on "some of the built-in protections in the language, such as the garbage collection." The authors point out potential fallacies of those types of reliance.

The 2013 Coverity Scan ReportTM includes an interesting assessment, "Quality concerns are no longer a barrier to open source adoption in the enterprise. In fact, the quality of the open source code for Coverity Scan participants can be higher than the proprietary code included in an enterprise product." Although not all open source is created equal and although product A is not necessarily superior to product B simply because the former is open source and the latter is proprietary, it is interesting to see more empirically driven studies demonstrating advantages of open source rather than relying on opinion, wishful thinking, and anecdotal evidence.

Thứ Năm, 17 tháng 4, 2014

Handy New Map Default Methods in JDK 8

The Map interface provides some handy new methods in JDK 8. Because the Map methods I cover in this post are implemented as default methods, all existing implementations of the Map interface enjoy the default behaviors defined in the default methods without any new code. The JDK 8 introduced Map methods covered in this post are getOrDefault(Object, V), putIfAbsent(K, V), remove(Object, Object), remove(Object, Object), replace(K, V), and replace(K, V, V).

Example Map for Demonstrations

I will be using the Map declared and initialized as shown in the following code throughout the examples in this blog post. The statesAndCapitals field is a class-level static field. I intentionally have only included a small subset of the fifty states in the United States for reading clarity and to allow easier demonstration of some of the new JDK 8 Map default methods.


private final static Map statesAndCapitals;

static
{
statesAndCapitals = new HashMap<>();
statesAndCapitals.put("Alaska", "Anchorage");
statesAndCapitals.put("California", "Sacramento");
statesAndCapitals.put("Colorado", "Denver");
statesAndCapitals.put("Florida", "Tallahassee");
statesAndCapitals.put("Nevada", "Las Vegas");
statesAndCapitals.put("New Mexico", "Sante Fe");
statesAndCapitals.put("Utah", "Salt Lake City");
statesAndCapitals.put("Wyoming", "Cheyenne");
}
Map.getOrDefault(Object, V)

Map's new method getOrDefault(Object, V) allows the caller to specify in a single statement to get the value of the map that corresponds to the provided key or else return a provided "default value" if no match is found for the provided key.

The next code listing compares how checking for a value matching a provided key in a map or else using a default if no match is found was implemented before JDK 8 and how it can now be implemented with JDK 8.


/*
* Demonstrate Map.getOrDefault and compare to pre-JDK 8 approach. The JDK 8
* addition of Map.getOrDefault requires fewer lines of code than the
* traditional approach and allows the returned value to be assigned to a
* "final" variable.
*/

// pre-JDK 8 approach
String capitalGeorgia = statesAndCapitals.get("Georgia");
if (capitalGeorgia == null)
{
capitalGeorgia = "Unknown";
}

// JDK 8 approach
final String capitalWisconsin = statesAndCapitals.getOrDefault("Wisconsin", "Unknown");

The Apache Commons class DefaultedMap provides functionality similar to the new Map.getOrDefault(Object, V) method. The Groovy GDK includes a similar method for Groovy, Map.get(Object, Object), but that one's behavior is a bit different because it not only returns the provided default if the "key" is not found, but also adds the key with the default value to the underlying map.

Map.putIfAbsent(K, V)

Map's new method putIfAbsent(K, V) has Javadoc advertising its default implementation equivalent:


The default implementation is equivalent to, for this map:

V v = map.get(key);
if (v == null)
v = map.put(key, value);

return v;

This is illustrated with another code sample that compares the pre-JDK 8 approach to the JDK 8 approach.


/*
* Demonstrate Map.putIfAbsent and compare to pre-JDK 8 approach. The JDK 8
* addition of Map.putIfAbsent requires fewer lines of code than the
* traditional approach and allows the returned value to be assigned to a
* "final" variable.
*/

// pre-JDK 8 approach
String capitalMississippi = statesAndCapitals.get("Mississippi");
if (capitalMississippi == null)
{
capitalMississippi = statesAndCapitals.put("Mississippi", "Jackson");
}

// JDK 8 approach
final String capitalNewYork = statesAndCapitals.putIfAbsent("New York", "Albany");

Alternate solutions in the Java space before the addition of this putIfAbsent method are discussed in the StackOverflow thread Java map.get(key) - automatically do put(key) and return if key doesn't exist?. It's worth noting that before JDK 8, the ConcurrentMap interface (extends Map) already provided a putIfAbsent(K, V) method.

Map.remove(Object, Object)

Map's new remove(Object, Object) method goes beyond the long-available Map.remove(Object) method to remove a map entry only if both the provided key and provided value match an entry in the map (the previously available version only looked for a "key" match to remove).

The Javadoc comment for this method explains the how the default method's implementation works in terms of equivalent pre-JDK 8 Java code:

The default implementation is equivalent to, for this map:

if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.remove(key);
return true;
} else
return false;

A concrete comparison of the new approach to the pre-JDK 8 approach is shown in the next code listing.


/*
* Demonstrate Map.remove(Object, Object) and compare to pre-JDK 8 approach.
* The JDK 8 addition of Map.remove(Object, Object) requires fewer lines of
* code than the traditional approach and allows the returned value to be
* assigned to a "final" variable.
*/

// pre-JDK 8 approach
boolean removed = false;
if ( statesAndCapitals.containsKey("New Mexico")
&& Objects.equals(statesAndCapitals.get("New Mexico"), "Sante Fe"))
{
statesAndCapitals.remove("New Mexico", "Sante Fe");
removed = true;
}

// JDK 8 approach
final boolean removedJdk8 = statesAndCapitals.remove("California", "Sacramento");
Map.replace(K, V)

The first of the two new Map "replace" methods sets the specified value to be mapped to the specified key only if the specified key already exists with some mapped value. The Javadoc comment explains the Java equivalent of this default method implementation:

The default implementation is equivalent to, for this map:

if (map.containsKey(key)) {
return map.put(key, value);
} else
return null;

The comparison of this new approach to the pre-JDK 8 approach is shown next.


/*
* Demonstrate Map.replace(K, V) and compare to pre-JDK 8 approach. The JDK 8
* addition of replace(K, V) requires fewer lines of code than the traditional
* approach and allows the returned value to be assigned to a "final"
* variable.
*/

// pre-JDK 8 approach
String replacedCapitalCity;
if (statesAndCapitals.containsKey("Alaska"))
{
replacedCapitalCity = statesAndCapitals.put("Alaska", "Juneau");
}

// JDK 8 approach
final String replacedJdk8City = statesAndCapitals.replace("Alaska", "Juneau");
Map.replace(K, V, V)

The second newly added Map "replace" method is more narrow in its interpretation of which existing values are replaced. While the method just covered replaces any value in a value available for the specified key in the mapping, this "replace" method that accepts an additional (third) argument will only replace the value of a mapped entry that has both a matching key and a matching value. The Javadoc comment shows the default method's implementation:


The default implementation is equivalent to, for this map:

if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.put(key, newValue);
return true;
} else
return false;

My comparison of this approach to the pre-JDK 8 approach is shown in the next code listing.


/*
* Demonstrate Map.replace(K, V, V) and compare to pre-JDK 8 approach. The
* JDK 8 addition of replace(K, V, V) requires fewer lines of code than the
* traditional approach and allows the returned value to be assigned to a
* "final" variable.
*/

// pre-JDK 8 approach
boolean replaced = false;
if ( statesAndCapitals.containsKey("Nevada")
&& Objects.equals(statesAndCapitals.get("Nevada"), "Las Vegas"))
{
statesAndCapitals.put("Nevada", "Carson City");
replaced = true;
}

// JDK 8 approach
final boolean replacedJdk8 = statesAndCapitals.replace("Nevada", "Las Vegas", "Carson City");
Observations and Conclusion

There are several observations to make from this post.

  • The Javadoc methods for these new JDK 8 Map methods are very useful, especially in terms of describing how the new methods behave in terms of pre-JDK 8 code. I discussed these methods' Javadoc in a more general discussion on JDK 8 Javadoc-based API documentation.
  • As the equivalent Java code in these methods' Javadoc comments indicates, these new methods do not generally check for null before accessing map keys and values. Therefore, one can expect the same issues with nulls using these methods as one would find when using "equivalent" code as shown in the Javadoc comments. In fact, the Javadoc comments generally warn about the potential for NullPointerException and issues related to some Map implementations allowing null and some not for keys and values.
  • The new Map methods discussed in this post are "default methods," meaning that implementations of Map "inherit" these implementations automatically.
  • The new Map methods discussed in this post allow for cleaner and more concise code. In most of my examples, they allowed the client code to be converted from multiple state-impacting statements to a single statement that can set a local variable once and for all.

The new Map methods covered in this post are not ground-breaking or earth-shattering, but they are conveniences that many Java developers previously implemented more verbose code for, wrote their own similar methods for, or used a third-party library for. JDK 8 brings these standardized methods to the Java masses without need for custom implementation or third-party frameworks. Because default methods are the implementation mechanism, even Map implementations that have been around for quite a while suddenly and automatically have access to these new methods without any code changes to the implementations.

Thứ Ba, 15 tháng 4, 2014

Programmatic Access to Sizes of Java Primitive Types

One of the first things many developers new to Java learn about is Java's basic primitive data types, their fixed (platform independent) sizes (measured in bits or bytes in terms of two's complement), and their ranges (all numeric types in Java are signed). There are many good online resources that list these characteristics and some of these resources are the Java Tutorial lesson on Primitive Data Types, The Eight Data Types of Java, Java's Primitive Data Types, and Java Basic Data Types.

Java allows one to programmatically access these characteristics of the basic Java primitive data types. Most of the primitive data types' maximum values and minimum values have been available for some time in Java via the corresponding reference types' MAX_VALUE and MIN_VALUE fields. J2SE 5 introduced a SIZE field for most of the types that provides each type's size in bits (two's complement). JDK 8 has now provided most of these classes with a new field called BYTES that presents the type's size in bytes (two's complement).

DataTypeSizes.java

package dustin.examples.jdk8;

import static java.lang.System.out;
import java.lang.reflect.Field;

/**
* Demonstrate JDK 8's easy programmatic access to size of basic Java datatypes.
*
* @author Dustin
*/
public class DataTypeSizes
{
/**
* Print values of certain fields (assumed to be constant) for provided class.
* The fields that are printed are SIZE, BYTES, MIN_VALUE, and MAX_VALUE.
*
* @param clazz Class which may have static fields SIZE, BYTES, MIN_VALUE,
* and/or MAX_VALUE whose values will be written to standard output.
*/
private static void printDataTypeDetails(final Class clazz)
{
out.println("\nDatatype (Class): " + clazz.getCanonicalName() + ":");
final Field[] fields = clazz.getDeclaredFields();
for (final Field field : fields)
{
final String fieldName = field.getName();
try
{
switch (fieldName)
{
case "SIZE" : // generally introduced with 1.5 (twos complement)
out.println("\tSize (in bits): " + field.get(null));
break;
case "BYTES" : // generally introduced with 1.8 (twos complement)
out.println("\tSize (in bytes): " + field.get(null));
break;
case "MIN_VALUE" :
out.println("\tMinimum Value: " + field.get(null));
break;
case "MAX_VALUE" :
out.println("\tMaximum Value: " + field.get(null));
break;
default :
break;
}
}
catch (IllegalAccessException illegalAccess)
{
out.println("ERROR: Unable to reflect on field " + fieldName);
}
}
}

/**
* Demonstrate JDK 8's ability to easily programmatically access the size of
* basic Java data types.
*
* @param arguments Command-line arguments: none expected.
*/
public static void main(final String[] arguments)
{
printDataTypeDetails(Byte.class);
printDataTypeDetails(Short.class);
printDataTypeDetails(Integer.class);
printDataTypeDetails(Long.class);
printDataTypeDetails(Float.class);
printDataTypeDetails(Double.class);
printDataTypeDetails(Character.class);
printDataTypeDetails(Boolean.class);
}
}

When executed, the code above writes the following results to standard output.

The Output


Datatype (Class): java.lang.Byte:
Minimum Value: -128
Maximum Value: 127
Size (in bits): 8
Size (in bytes): 1

Datatype (Class): java.lang.Short:
Minimum Value: -32768
Maximum Value: 32767
Size (in bits): 16
Size (in bytes): 2

Datatype (Class): java.lang.Integer:
Minimum Value: -2147483648
Maximum Value: 2147483647
Size (in bits): 32
Size (in bytes): 4

Datatype (Class): java.lang.Long:
Minimum Value: -9223372036854775808
Maximum Value: 9223372036854775807
Size (in bits): 64
Size (in bytes): 8

Datatype (Class): java.lang.Float:
Maximum Value: 3.4028235E38
Minimum Value: 1.4E-45
Size (in bits): 32
Size (in bytes): 4

Datatype (Class): java.lang.Double:
Maximum Value: 1.7976931348623157E308
Minimum Value: 4.9E-324
Size (in bits): 64
Size (in bytes): 8

Datatype (Class): java.lang.Character:
Minimum Value:

UPDATE: Note that, as Attila-Mihaly Balazs has pointed out in the comment below, the MIN_VALUE values showed for java.lang.Float and java.lang.Double above are not negative numbers even though these constant values are negative for Byte, Short, Int, and Long. For the floating-point types of Float and Double, the MIN_VALUE constant represents the minimum absolute value that can stored in those types.

Although the characteristics of the Java primitive data types are readily available online, it's nice to be able to programmatically access those details easily when so desired. I like to think about the types' sizes in terms of bytes and JDK 8 now provides the ability to see those sizes directly measured in bytes.