Oracle Gathers Together Java 8 Launch Materials: 35 In-Depth Sessions to Date

If you missed the Java 8 Launch Live Webcast, or if you'd like to re-review the webcast, or if you'd like to view more in depth presentations about specific areas of Java 8 (including Java SE 8, Java SE Embedded 8, Java ME 8, and the Internet of Things and The Enterprise) -- then, you'll want to visit the Java 8 Launch site that Oracle has put together. The site is an excellent collection of Java 8 reference materials, including the Java 8 Launch Live Webcast. For example, 12 Java SE 8 sessions are available: Brian Goetz: Java SE 8—Language and Library Features Stephen Colebourne: A New Date and Time API—JSR-310 Paul Sandoz: JDK Hacker on Core Libraries Stuart Marks: Introduction to Lambda Expressions Alex Buckley and Michael Ernst: Enhanced Metadata—Annotations and Access to Parameter Names Staffan Friberg: Performance Improvements in JDK 8 Jim Weaver: What's New for JavaFX in Java SE 8 Simon Ritter: New Features in Java SE 8: A Developer's Guide Geertjan Wielenga: NetBeans IDE 8: Toolbox for Java SE 8 Jim Laskey - Nashorn: JavaScript on the JVM Milton Smith: Java 8 Security Highlights Marcus Hirt: Introducing Java Mission Control 5.3.0 In addition, the site features 8 Java SE Embedded 8 sessions; 10 Java ME 8 sessions; and 5 Internet of Things and The Enterprise sessions. Subscriptions and Archives: You can subscribe to this blog using the java.net Editor's Blog Feed. You can also subscribe to the Java Today RSS feed and the java.net blogs feed. To follow Java.net net on Twitter, follow @javanetbuzz. -- Kevin Farnham (@kevin_farnham)

Posted by on 14 April 2014 | 5:58 pm

Raspberry Pi and the Internet of Things (IoT) Revolution

Recently I was wandering the aisles of a Barnes and Noble bookstore (the last big chain bookstore in the United States), and I was surprised to see a selection of 6 or 7 books about the Raspberry Pi! Perhaps this shouldn't have surprised me, but it did. Just now, I went to the Barnes and Noble web site and searched for "Raspberry Pi" books, and 70 books were returned, all of them genuinely about the actual hardware Raspberry Pi. Does this surprise you? I think part of my surprise is that some of the first professional programming I did, back in the early 1980s, was developing data acquisition and instrument control software, writing software on $35000 Hewlett-Packard 9845 computers to control custom made boards and other devices over GPIO and RS-232 interfaces. I worked with stepper motors, digitizers, and a slew of other instruments and devices, assisting the U.S. Navy in testing existing and designing new transducers and sonar arrays. That experience left me with the thought that controlling devices was a very expensive endeavor -- which it was back then. But, times change, and they have certainly changed a lot in the past 30+ years with respect to computers, sensors, instruments, and boards that can control hardware like stepper motors. If you look at the basic layout of a Raspberry Pi, you've got a device that is actually much more powerful than most of the equipment I was working with in the early 1980s. For example, that $35000 HP-9845 had a 16-bit CPU running at 5.7 MHz, and it had a base RAM of 24 kBytes (with addition of another 48 kBytes possible). Today's $35 Raspberry Pi runs at 700 MHz and features 512 MBytes of RAM. So, let's do the math: today, for 1/1000 of the cost of an HP-9845, you can get a processor that runs 123 times as fast, and has 21 times as much base RAM. Or, looking at it another way, a $35 Raspberry Pi can do the same processing that would have required 123 HP-9845s in the early 1980s. And those 123 HP-9845s would have cost more than $4.3 Million! That means that the cost of a unit of processing, using the HP-9845 and the Raspberry Pi as the comparative hardware, has fallen by 99.999% over the past three decades. Considering these facts alone, doesn't this imply a revolution of some type? Clearly, the revolution has already happened with respect to computers that can control devices and access sensors. It used to take a big government contract for me to be able to play with devices, control motors, automate research and development processes, etc. Today, a 12 year old who does yard work for the neighboring families can afford equipment that's far more powerful than what I was working with back then. Some people think the Internet of Things (IoT) is just a gimmick, just a fad. No -- when the cost of something useful is reduced by 5 orders of magnitude, something big is going to come out of that. Let the real IoT revolution begin! Watching this is going to be fun. Participating in it (as I plan to do) will be even more fun! Subscriptions and Archives: You can subscribe to this blog using the java.net Editor's Blog Feed. You can also subscribe to the Java Today RSS feed and the java.net blogs feed. To follow Java.net net on Twitter, follow @javanetbuzz. -- Kevin Farnham (@kevin_farnham) AttachmentSize RaspberryPiSml.jpeg65.31 KB RaspiModelB-diagramSml.png47.28 KB

Posted by on 3 April 2014 | 2:36 pm

Measuring Software Reuse and Deleting Code

This a fun story rather than a deep technical discussion of some performance issue, measure or tool. My memory was jogged by a story (http://www.folklore.org/StoryView.py?story=Negative_2000_Lines_Of_Code.txt) in which Bill Atkinson reported producing -2000 lines of code on his weekly productivity report and by Kevlin Henney retweeting one of my one liners, features are the asset, code is a liability. Needless to say management wasn't impressed by having Bill report that he produced -2000 lines of code. Coders main purpose is to code and if they are producing code you should be able to count how many lines of code they've produced and consequently measure productivity. The key point is that in the process of eliminating code Bill was making the software better and faster. His story reminded me of a situation that I was in 1996. I sat down to have lunch with my supervisor and he hit me with the question, how would you measure reuse. I jokingly answered with 3 questions; what number do you need, who’s bonus depends upon it and how much of that do I get when I come up with that number. It was the look that I got from my supervisor that told me this was a serious question. Apparently the CIO had been sold and then sold a bill of (reuse) good the company we worked for. All projects were being developed in Smalltalk using OO techniques because one of the biggest benefits would be software reuse (read cheaper to build). Indeed, the CIO’s bonus was dependent upon us hitting a certain reuse target. Time to get serious as we had to come up with a way to measure reuse. I started trolling the literature. I read article after book after article that all talked about reuse. The made wild claims of 80%, 90%, even 99.999% reuse! I swear someone would have published a 2000% reuse number if they thought no one would call them out on it.. it was that bad. I say this because out of all the publications that mentioned how much reuse they got on a project, *every single* one of them failed to mention how they managed to come up with this number. I repeat, as incredible as it sounds, not a single article talked about how to actually measure reuse! After much searching about I finally ran into this gem (http://www.amazon.com/Object-Oriented-Software-Metrics-Mark-Lorenz/dp/01...) and after reading it and a few other bits on software metrics I came to the conclusion that the reason we want reuse is to save effort. Effort in writing the code, testing the code, debugging the code, maintaining the code. The benefits come from many directions and the costs seemed to be mainly limited to the effort needed to learn how to use the code. So to measure reuse we should measure of effort saved. Of course this required that we started measuring tons of things that no one in the organization or any organization for that matter ever measured so that we could estimate the effort required to write something from scratch. Since bonus time was coming up fairly shortly it was obvious this turkey wasn’t going to fly. At this point was when Bob Moore, the cleverest guy in our group, stepped in and together we came up with a metric that unfortunately included lines of code as part of the measure. I can’t recall the exact details of the calculation but I do recall that it yielded two numbers, some what similar to what you get from a blood pressure measurement. Of course management wanted a single number and to comply we performed the equivalent of dividing systolic by diastolic pressure to produce a management friendly single number that made absolutely no sense what so ever. My complaint was that as our group improved the frameworks that other groups were “reusing” the reuse number was going to drop. The supervisor thought that this was a ridiculous idea and so unlikely that it didn’t matter anyways. As luck would have it, a month or so laster I was asked to port a piece of our messaging system and in the process I eliminated about 60% of the code base and since that affected the LOC count portion of our “formula” and since *every* project in the company used this messaging framework everyone’s reuse number took a serious hit. By that time I believe the CIO had gotten rid of the reuse target as part of his bonus so no one cared and the project (sensibly) died shortly after that. All I can say is that we all knew it was a silly exercise going into it and in retrospect all that came out of it was this silly story about yet another ridiculous attempt to measure developer productivity.

Posted by on 2 April 2014 | 8:26 am

What is a MEAP? A Video Tutorial + 38% off all MEAPs from manning.com

"What is a MEAP?" - is a video tutorial from Manning Publications. The video can be found here: http://youtu.be/N_CRbc-h0A0 What's a MEAP? We believe you shouldn't have to wait to start learning. In MEAP, the Manning Early Access Program, you read books as they're written. We'll send you new chapters and updates, and you'll get the final eBook the instant it's ready. If you pre-order the pBook, it ships to you weeks before it's available in stores. Check out the new and recently-updated MEAPs. To save 38% on this and all other MEAPs, just enter Promotional Code youtube38 in the Promotional Code box when you check out at manning.com

Posted by on 2 April 2014 | 5:55 am

Java's regular expression, String, and things..

The manipulation of strings is a quite common activity for which the programmer undertakes responsibility fairly frequently. In Java, strings are of a distinct data type, that are implemented as literal constants. The String class facilitates the creation and manipulation of objects that are of an immutable character, by which I mean to refer to the unchangeable property with which one must strive to become familiar. The following example is meant to illustrate this point:- package regex.strings.java; public class ImmutableString {      static String trim(String immutableRef) {         String trimmed =  immutableRef.trim();         return trimmed;     }     public static void main(String[] args) {         String immutable = "  Arbitrarily replace parts of this string";         System.out.println("\"" + immutable + "\"" );         String aString = ImmutableString.trim(immutable).replaceAll("tr|rep|p|hi", "x");         System.out.println("\"" + aString + "\"");         System.out.println("\"" + immutable + "\"");     }}/* Output  "  Arbitrarily replace parts of this string"  "Arbixarily xlace xarts of txs sxing"  "  Arbitrarily replace parts of this string"*// In this very simple example, we pass a regular expression to the replaceAll() member of the String class following a call to our own Immutable.trim() operation to remove leading whitespace, and return what might reasonably be expected to be a modified copy of our immutable String object. The replaceAll() method replaces the pattern expressed in regular expression syntax with the String object "x". The expression uses the logical regular expression operator '|' to describe a sequence of groups of characters that follow in no particular order. Following these operations, you will notice that no change has been recorded against our original string, because in actuality, only a copy of the original string reference is passed to the trim() method in the first instance, which returns a reference to a new String object to account for the modified string. The process is repeated for the call to the replaceAll() method. If you were to examine the bytecodes arising from running Java's class file disassembler (javap with -c switch) with this class, you will notice that Java creates three StringBuilder objects in total, once for our original string and the other two in relation to each call to the trim() and replaceAll() methods. This is what we mean when we make reference to the immutable property of String objects, which it is to be understood, can also become a source of inefficiency and why Java discretely makes liberal use of the StringBuilder class whenever there is the need to make a modification to a String. Java's API documentation describes the StringBuilder class as capable of providing for the construction of a sequence of mutable characters and operations designed specially for use with single threaded applications. Some very talented programmers have suggested the propriety of explicitly making use of the StringBuilder class, in particular during repeated operations involving the modification of String objects in order to avoid any issues that might arise as a result of the inefficiencies associated with immutability, particularly in environments where unnecessary overhead is not normally considered acceptable. For instance, one of the interesting things you can do with String objects is to concatenate two or more strings, the one end to the other. Java provides a number of ways to do this, like for example by means of the overloaded '+' operator. Overloaded in the sense that it takes on an extra meaning when used with the String class:- package regex.strings.java; public class ConcatenateString {     String compoundOperator = "";     public ConcatenateString(String args) {         String[] splitter = args.split(" ");         compoundOperator += " \"";         for(int i = 0; i < splitter.length; i++) {             compoundOperator += splitter[i] + " ";         }         compoundOperator += "\"";     }     public static void main(String[] args)  {         String aDefinition = "Cognitive computing is the development of computer \n" +                                       "systems modelled on the human brain";         ConcatenateString overloadedPlus = new ConcatenateString(aDefinition);         String listOfMetals = "Hydrogen"  + ", " + "Lithium" + ", " +  "Sodium" ;         String statementOfFact = "A List of metals include: " +  listOfMetals;         System.out.println(statementOfFact + "\n");         System.out.println(overloadedPlus.compoundOperator);     }}/* OutputA List of metals include: Hydrogen, Lithium, Sodium "Cognitive computing is the development of computersystems modelled on the human brain "*// In the main() method we make use of the '+' operator to combine a number of individual strings into one coherent String object. Within the class constructor, notice the use of the overloaded '+=' operator which also acts like an append method when used with String objects. Both of these methods are suitable for simple operations, but become inefficient when used in loops like you have in the above constructor because Java has to create a new StringBuilder object at every iteration which, as has been pointed out before now, is really not ideal. A more efficient way would be to explicitly create a StringBuilder object and make use of the append() method within the loop, like the following example demonstrates:- package regex.strings.java; public class ConcatenateString2 {     StringBuilder buildString = new StringBuilder();     public ConcatenateString2(String args) {         String[] splitter = args.split(" ");         buildString.append(" \"");         for(int i = 0; i < splitter.length; i++) {             buildString.append(splitter[i] + " ");         }         buildString.append(" \"");     }     public static void main(String[] args)  {         String aDefinition = "Cognitive computing is the development of computer \n" +                                 "systems modelled on the human brain";         ConcatenateString2 stringBuilder = new ConcatenateString2(aDefinition);         System.out.println(stringBuilder.buildString);     }}/* Output"Cognitive computing is the development of computersystems modelled on the human brain "*// By making an explicit call to StringBuilder before you enter your loop, you produce better and more efficient code. With the release of Java SE 7, came the addition of the ability to use String objects with the switch statement which was not always the case. Being that Java SE 8 was released while I was putting this piece together, I figured I might as well use the opportunity this example provided me to test the utility of the new Date/Time API, which altogether seems to be quite an improvement over the previous version:- package regex.strings.java; import java.time.Month;import java.time.YearMonth;import java.time.format.TextStyle;import java.util.ArrayList;import java.util.List;import java.util.Locale; public class GregorianCalendar {     private List<Month> leapYear = new ArrayList<Month>();     public void setMonths() {         for(int month = 1; month < 13; month++) {             leapYear.add(Month.of(month));         }     }     public void daysOfTheMonth(int month) {         Month whichMonth = leapYear.get(month);         switch(whichMonth.getDisplayName(TextStyle.FULL, Locale.ENGLISH)) {         case "April":         case "June":         case "September":         case "November":                   System.out.println(whichMonth.getDisplayName(TextStyle.FULL,                                                      Locale.ENGLISH) + " = 30 days");                                                     break;         case "February":                   System.out.println(whichMonth.getDisplayName(TextStyle.FULL,                                                      Locale.ENGLISH) + "  = 29 days");                                                     break;         default:                    System.out.println(whichMonth.getDisplayName(TextStyle.FULL,                                                      Locale.ENGLISH) + "  = 31 days");          }     }     public static void main(String[] args) {         GregorianCalendar aCalendar = new GregorianCalendar();         aCalendar.setMonths();         for(int i = 0; i < aCalendar.leapYear.size(); i++)             aCalendar.daysOfTheMonth(i);     }} Java 8's new Date/Time API consists of about 5 packages that provide you with a comprehensive framework for representing an instance of time. In our example, we make use of the Month class which is of an enumerated type to provide a string representation to test for a certain conditionality in our switch statement by which means we are able to print the number of days in a particular month. Regular expressions A regular expression is a string processing technique for describing the patterns that may be found in string based text. This is achieved by giving special meaning to the arrangement of metacharacters when used in particular context. A metacharacter is a character that has been given a special meaning by Java's regular expression interpreter and therefore it would not be a mistake for you to predispose your mind to the notion that presupposes that regular expressions are a completely separate, though indistinct language from Java, which really does not require too much of a stretch of the imagination, even if they are conceived as strings, and are subsequently applied to exactly this same type. There are a number of predefined character classes that represent the basic building blocks of regular expressions with which you must become properly acquainted if it is your wish to attain an expert level of proficiency in this subject. For instance, a word character is represented with a backslash followed by the letter w like so '\w'. In consequence, a digit is represented by the metacharacter '\d', while '\s' is used to represent the whitespace character , '\W', a non-word character, and the non whitespace and non-digit character are represented as '\S' and '\D' respectively. In addition, to indicate any of these predefined characters in regular expression syntax, you must precede each one with an additional backslash '\' such that the expression '\\w' would be used to indicate a word character, or '\\d' to indicate a digit, and et cetera.. You should also make yourself to become familiar with a set of arrangements that consists of characters enclosed in square brackets [...], known as character classes and used to indicate a preference, so that the arrangement "[abc]" indicates a preference for a,b or c and "[a-zA-Z]" indicates a preference for any character in the range a-z or A-Z. The '-' metacharacter acts like a range forming operator when used in square brackets. These character classes can also be arranged in other ways that make more complex operations possible, for instance the arrangement "[a-e[l-p]]" is a regular expression union operator that specifies a preference for any within the range a through e or l through p, and the expression "[a-z&&[hij]]" is an intersection operator that refers to h, i or j. And then of course you also have a number of logical operators including 'AB' to indicate that B follows A , 'A|B' to indicate A or B and (A) as a reference to a capturing group, an explanation of which is better sought within the pages of your official documentation; all of this in addition to other categories of metacharacters, boundary matchers, quantifiers and a multiplicity of character classes competing to represent every conceivable character combination you can possibly imagine. For this reason, you will probably have to become used to making a constant reference to your official documentation for a full list of Java's regular expression metacharacters and the valid range of arrangements. Nevertheless, the easiest way to use regular expressions in Java is to pass a valid argument to the convenience method, matches() of the String class to make a test of whether or not the expression matches the current String:- package regex.strings.java; public class StringMatcher {     public static void main(String[] args) {         System.out.println("Flight 8957".matches("\\w+\\s?\\d+"));         System.out.println("Flight8957".matches("[Ff]li[huog]ht\\s?\\w+"));         System.out.println(" Flight-8957".matches("\\s?\\w+-?\\d+"));         System.out.println("Flight8957".matches("[a-zA-Z]+[0-9]+"));         System.out.println("Flight8957".matches("\\w+"));     }}/* Outputtruetruetruetruetrue*// In addition to some of Java's predefined character classes, the above example uses 'quantifiers' so as to regulate the varying degrees of frequency with which a match is made against a given string, according to a particular pattern. So for instance, the first expression in the above example uses the '+' quantifier to match a word character "\\w" one or more times, and then uses the '?' quantifier to match the whitespace character "\\s" once or not at all, before this time matching a digit "\\d+" one or many times in the preceding string "Flight 8957". The matches() method returns a boolean value that should indicate the truth or falsehood of any assertion. With quantifiers, it is important to bear in mind that they apply only to the metacharacter that immediately precede their definition, except when you use parenthesis to group patterns or of course when you apply them to character classes, so for instance the expression "\\w+" which indicates a preference for a word character one or more times, will match the string "Flight8957" but to make a match of the string "Flight-8957" which contains a non-word character, you will need to write "\\w+-?\\d+" which reads match a word character one or many times, followed by a hyphen once or not at all, and then match a digit one or more times. You may apply this reasoning to unravel the mystery behind the remaining regular expression statements. Parenthesis allow you to group individual characters to form a pattern, for instance the '*' metacharacter is a third quantifier that allows you to make a match of a pattern zero or more times, so that the expression "(abc)*" would match the pattern 'abc' in a given string, zero or many times, while the expression "abc*" reads - match 'ab' followed by 'c' zero or many times. This quantifier in addition to those earlier referenced constitute a category of the so-called 'greedy' quantifiers, which when used in particular combination can be of the 'possessive' or 'reluctant' variety - the categories, are a reference to the varying degrees of regularity with which each class of quantifier is known to make a match against a given string, according to the varying levels of generality that exist within a pattern. Java provides a package of APIs' (java.util.regex) that provide you with more advanced features with which you can create, compile and match regular expressions against string based text, in a standardised way. The relevant classes that should concern you initially are the Pattern and Matcher class. With this technique, you introduce a Pattern object by passing a valid regular expression argument to the static compile() method of the Pattern class, against which you must supply your search string as argument in a manner that makes possible, the recovery of a Matcher object, from which certain operations become available, by which means you may query such an object for complex information. In the following example, we apply this technique to locate patterns, first in a file and then manually on a test string:- package pattern.matching.java; import java.io.BufferedReader;import java.io.FileReader;import java.util.NoSuchElementException;import java.util.Scanner;import java.util.regex.Matcher;import java.util.regex.Pattern; public class Parser {     static void parseString(String arg1, String arg2 ){             Pattern regex = Pattern.compile(arg1);             Matcher intepreter = regex.matcher(arg2);             // find pattern match in search string             while(intepreter.find()) {                 System.out.println("found pattern: " + intepreter.group() + " at index " + intepreter.start());              }             //System.out.println("No match found");             return;     }     public static void main(String[] args) throws Exception {         FileReader reader = new FileReader("/home/geekfest/eclipse/about.html");         BufferedReader in = new BufferedReader(reader);         Scanner input = new Scanner(in);         boolean reading = false;         String searchString;         // search pattern beginning http[^\s]         String regex = "h\\w+p\\S+";         try {             while((searchString = input.nextLine()) != null) {             //match search pattern in search string             //parseString(regex, searchString);             reading = true;             }         } catch(NoSuchElementException e) {             //System.out.println("End of input");          }         input.close();         if(reading == false)             return;         String testString = "abracadabracadab";         parseString("abr?", testString);         System.out.println("-----------------------------");        parseString("abr??", testString);         System.out.println("-----------------------------");         parseString("(abr)+", testString);      }}/* Outputfound pattern: abr at index 0found pattern: abr at index 7found pattern: ab at index 14-----------------------------found pattern: ab at index 0found pattern: ab at index 7found pattern: ab at index 14-----------------------------found pattern: abr at index 0found pattern: abr at index 7*// This example is useful to demonstrate a number of simple techniques. Firstly, we implement a simple parseString() algorithm by creating a Pattern object, and then calling the matcher() method of this object to create a Matcher object which we are then able to query repeatedly within our loop for information about specific patterns in particular using the group() and start() members. In the main(), we make use of a Scanner object to scan input from a file into a String object against which we make a test of our regular expression that describes a pattern that matches the first few letters of a URL address. In this example, we have had to comment out the code that would have resulted from this match to satisfy our desire for compactness as much as possible in the use of code for illustrations. Nevertheless, we manually apply this method to a simple search string the result of which is provided for your perusal. Notice the difference in the first two statements that make use of different classes of quantifiers. The second statement uses a quantifier from the reluctant '??' category which will match the minimum number of characters necessary to satisfy the pattern, while other two statements use quantifiers from the greedy category, which will find as many matches for the pattern as possible. Furthermore, consider the effect of the parenthesis based on the output from the third statement. Formatting String Another interesting thing you are able to do with strings is to control how they are written to a particular output destination. The Formatter class provides you with this kind of capability by acting as an interpreter for "format strings" by which means you are able to control the justification, alignment and spacing of string based output. Format strings are a combination of static text and format specifiers that describe the conversions, alignment, spacing and layout justification, that is to be applied to output. Java's format specifiers can be understood within the boundaries following conventions:- %[argument_index$][flags][width][.precision]conversion The first four specifiers in square brackets are optional and may take on a different meaning depending on the value of the conversion specifier to which they are applied. The conversion format specifier is mandatory and is used to indicate a preference for a particular data type, whose value may be optionally specified by means of the argument_index$ format specifier. Some of the typical conversions you should expect to be able to make include character conversions denoted by the specifier 'c', string conversions denoted by 's', a range of numeric conversions of either the integral or floating point kind 'd' and 'f' respectively, date/time conversions 't', and a number of less frequent others. For some of these conversions, an upper case representation is as equally valid, to the extent that the result is converted to upper case according to the rules of the prevailing locale, so for instance the conversion 't', and 'T' would both refer to Date/Time conversions except that the result of one will be in lower case and the other in upper case. The argument_index$ format specifier is an integer used to indicate the position of the required argument in the argument list, which is nominally a reference to the value of the conversion format specifier, while the optional, flags format specifier consists of metacharacter that modify the output string in any one of a number of ways depending on the conversion. By contrast, the .precision format specifier is a non-negative integer that acts to restrict the number of characters to be written but whose precise functionality also depends on the conversion to which it relates, in exactly the same way as the flags format specifier. Finally, the width format specifier is a positive integer used to indicate the minimum number of characters to be written to output. The Formatter API includes two variations of the format() method that accept a format string and type arguments and can write formatted output to a PrintStream object or other destination of your choice, with the difference being that one of the two makes use of the specified locale. The format string consists of a mixture of static text and format specifiers:- package regex.strings.java; public class MatchResult {     public static void main(String[] args) {         String s = "Team";         int i = 6;         System.out.format("%2$s-B (%1$d - 0)  %2$s-A ", i, s);     }}/* OutputTeam-B (6 - 0)  Team-A*// In the above example, we can discern five distinct pieces of static text in the format string argument to our format() method made up of "-B", "-", "0" and "-A" as well as the parenthesis grouping the integers that represent team scores. Format specifiers make up the remainder of the string, including the percent '%' argument which produces a literal result. The format string can be described from left to right to read, position the second argument as specified by the argument_index$ specifier, of type string to the left of the static text "-B" to produce the literal "Team-B", and then position the first argument of type integer to produce the literal result "6", and finally, position the second argument of type string such that it produces the output "Team-A". The argument list is comprised of two arguments of the integer and string type. Here is another example that makes use of the flags and width format specifiers only:- package regex.strings.java; public class FormatString {     public static void main(String[] args) {         System.out.format("%-20s  \n%(.2f  \n%25s", "left-justify", -3.186329, "right-justify");      } }/* Outputleft-justify(3.19)             right-justify*// The format string in this example is separated into three lines of text by the interposing new line '\n' operator, with the first and third lines specifying a size value in the immediate path of the percent '%' metacharacter which, contrary to the current JDK documentation is applicable to the .precision specifier and indeed to at least one other flag in addition to the '-' flag whose purpose is to left-justify output, the default being right justified, as may be deduced from the position of the last line of output. The second line of the format string uses the '(' flag to enclose the negative value in parenthesis and the .precision specifier to indicate the number of digits after the radix point for our floating point conversion. To employ this technique to your advantage, you must attain proficiency with the functionality of the format specifiers that comprise a fundamental part of the format string in order to write more efficient and flexible code. The following class formats a list of staff in a using the Formatter interpreter:- package pattern.matching.java; class Format {     void FormatHeader() {             System.out.format("%-10s %5s %10s  \n", "Name", "DoB", "Age");             System.out.format("%-10s %5s %10s  \n", "----", "---", "---");     }     void FormatEntry(String name, String dob, int age) {         System.out.format("%-9s %-11s %4d  \n", name, dob, age);     }}public class Printer {     public static void main(String[] args) {         Format style = new Format();         style.FormatHeader();         style.FormatEntry("John", "09/06/1981", 33);         style.FormatEntry("Amy", "20/11/1985", 29);         style.FormatEntry("Karyn", "02/02/1978", 36);     }}/* OutputName         DoB        Age----         ---        ---John      09/06/1981    33Amy       20/11/1985    29Karyn     02/02/1978    36*// Essentially, each format string divides the output into three columns with values of unequal size, into some of which we apply the '-' flag to left justify output. You will find that the '-' flag and width format specifier work closely most often to control the spacing and position of output. In this example, the arguments consists mostly of string conversions and an integer conversion. The example is an obvious demonstration of how Formatter class makes it possible to write output for which we can tightly control presentation. You should consult with your official documentation for an in-depth explanation of format specifiers. Strings are not a trivial topic by any means and overall include perhaps a slightly moderate level of complexity sufficient to satisfy any curious mind. In particular, regular expressions can be challenging, but there is absolutely nothing about it that should constitute a barrier to those interested to discover it's truth.

Posted by on 31 March 2014 | 12:29 pm

Take Magnolia to the cloud, but keep one foot on solid ground

While parts of the cloud IT that are still being hyped are changing rapidly, the whole segment is not past the hype yet. The cloud report [1] that Gartner published 9 months ago still holds true today. Reports of disillusioned customers of such solutions [2][3] are a clear sign that the hype might have reached its peak for most parts of cloud offerings, though. And while many articles discuss the failure of cloud providers, not so many actually look into what the failures mean for users of cloud services. Understandably, no customer that bet their business on cloud services and is then affected by failure wants to admit to wrong judgement publicly. Take, for example, the healthcare.gov failure in Oct 2013 [4], or the outage of Casablanca INT and their Big Blue One cloud service [5] where, even though it is a small cloud, the damage was estimated in the millions - for only a few days of outage [6]. And while clouds as a whole and services they offer continue to mature, their prospective customers are increasingly becoming aware of potential risks. This process, while very natural, re-shapes the cloud offerings towards a new silver bullet solution - hybrid clouds [7]. The trend towards hybrid solutions has been adopted in IT many times, whenever monolithic solutions didn’t lead to the desired results. And not just in IT: the car making industry has been producing hybrid cars for years now, and engineering has been working with hybrid materials (they call those composites) en masse for nearly a century. Please keep on reading. I promise that the generic intro is over and I will get to the point soon. Taking the cloud (and Magnolia) to the next level We can now see this as an emerging trend in the Cloud area, too: so called Hybrid Cloud Solutions are on the rise, starting from the simplest solutions such as hybrid (private/cloud) storage [8] or hybrid hosting [9], moving to more complex solutions such as hybrid cloud deployment of your Magnolia CMS installation. Due to its architecture that’s relying on a set of semi-independent, purpose configured instances, Magnolia has always been geared towards scaling not just vertically (by using more powerful hardware to run the instance), but also towards scaling horizontally (by simply adding more instances). The horizontal scalability feature was not just designed to increase the throughput, but also as a means to provide customers with configurable instances that could be optimized towards specific goals without affecting the rest of the web hosting infrastructure, as shown in the diagram below. In the most basic deployment of Magnolia CMS, the client ends up with a single authoring instance and a single public instance. While both instances are running the same version of Magnolia CMS, the authoring instance is configured to support the task of authoring the content, while the public instance is optimized to serve the published content to the public. This separation not only makes it easy and possible to optimize the widely opposing needs of authors and the public, it also offers free additional measures that can be taken to ensure the security of your data. And while this sort of minimalistic deployment allows you to run Magnolia CMS with a single public instance so to have an instant failover, most common customer scenarios are set up with 3 instances, ensuring that the public consuming your web content will not be affected if one of the instances goes down for whatever reason. Unless, of course, you choose to host all of those public instances in the same data centre, in which case all instances would go down if the whole data centre collapses. This would be a conscious risk on your end, driven perhaps by cost cutting measures, rather than something that the software dictates. Building a hybrid cloud solution with Magnolia This basic architecture is actually key to using Magnolia CMS in combination with cloud infrastructure to build a hybrid cloud solution. But of course, this is not the end of it. While it allows you to keep your private data secure prior to publishing, as well as giving you some public instance for emergencies on-premise and having some other instances in the cloud, it doesn’t do anything to alleviate the pain of having to spin up those multiple instances, pre-populating them with the content that is already published to the others, and registering them with the authoring environment as subscribers so it knows to publish the content there. You’ll need more than architectural choice here. The new REST API delivered with Magnolia 5.2 allows you to do all that. You were always able to execute the synchronisation command to sync new instances, you were always able to add new subscribers to the author, but it used to be a manual process. Now, with the new REST API, you can simply script those operations and add them to your startup script for new cloud based instances so they can register and sync themselves when going up as well as deregister when going down. Additionally, you might want to make this process even more simple and instantaneous. Look at the following deployment schema: Here, we do everything we did with the first setup I described, to make sure any unpublished data of yours (such as performance reports, new products or services or upcoming campaigns) stays private: we use an on-premise based author instance and one emergency public instance, to cover up possible cloud failures. However, we changed our cloud hosted instance from a set of instances to a cluster of Magnolia instances. This takes advantage of the fact that clustered instances share the same data set and thus don’t need to synchronise the data or register themselves as subscribers into your Magnolia CMS installation publishing schema. As long as one node in the cluster is registered and has all the latest data, they all are going to share and serve that data to the public, allowing you to bring new instances up and down hassle free. This gives you both the “hybrid cloud” as well as the “cloud bursting” offering, thanks to the speed with which you could be spinning up new instances, to react to spikes of web traffic in real-time. There are many more advantages to this deployment that I can’t explore here at this point. Examples include integration options such as taking advantage of the publishing mechanism to expose public-sharable data from other internal-access-only infrastructure with a flexible synchronisation schedule. Another option is the use of cloud based clustered configuration to pair instances with other already-in-the-cloud offerings that your company might currently employ, to provide real-time data to web users. And, if you want to listen to me talking about Magnolia in the cloud some more, you should make sure to attend Magnolia Conference in Basel, June 24 - 26, where I’ll present alongside Daniel Menges at ETECTURE@Ogilvy [10] See you there! [1] https://www.gartner.com/doc/2573318/hype-cycle-cloud-computing- [2] http://www.infoworld.com/slideshow/107783/the-worst-cloud-outages-of-201... [3] http://pleasediscuss.com/andimann/20130107/time-to-stop-forgiving-cloud-... [4] http://fcw.com/articles/2013/10/28/cloud-failure-crashes-healthcare-gov.... [5] http://objevit.cz/praskle-potrubi-a-cloud-uz-neni-cloud-t48785 [6] http://e-svet.e15.cz/it-byznys/skody-ze-zatopene-casablanky-se-vysplhaji... [7] http://www.cmswire.com/cms/information-management/moving-to-the-cloud-on... [8] http://www.softlayer.com/info/special-free-cloud [9] http://www.rackspace.com/cloud/hybrid/ [10] http://www.magnolia-cms.com/conference/program.html

Posted by on 31 March 2014 | 1:02 am

Poll Result: the Future of the View Layer in Java EE Applications

The most recently completed Java.net poll, which was submitted by Walter Nyland, asked the community about which technologies represent the future of the view layer in Java EE apps. A total of 245 votes were cast in the Java 8 poll, and two comments were posted. The exact question and results were: What's the future of the view layer in Java EE applications? 26% (64 votes) - Java EE component libraries will continue to dominate 40% (99 votes) - HTML5, especially AngularJS, is and will be the dominant view layer 6% (14 votes) - Neither the front-end nor the back-end of Java EE will survive HTML5 5% (12 votes) - Mobile front-ends will be the only lasting view layer 8% (20 votes) - Some other technology will replace the view layer 9% (22 votes) - Java EE never had a significant place in the Java ecosystem, ever 6% (14 votes) - Other One thing this result implies is that HTML5 is gaining traction, or developers expect that it will do so over time. This confirms the fairly revolutionary nature of HTML5, and it also confirms that many developers know enough about it to consider it the future of the view layer in Java EE apps. It's not too surprising (in my opinion) that "Java EE component libraries" finished in a strong second place. When you think about existing applications, and existing libraries that teams have used and built into their Java EE applications over years of effort, in many cases it's going to be easier for companies to utilize their existing code as the starting point in new applications, compared with starting from scratch with HTML5. Together, HTML5 and Java EE component libraries captured about 2/3 of the votes. No other option achieved a double-digit percent. Some of Walter's options provided developers with an opportunity to critique Java EE's own future with the context of this poll. For example, 6% believe that "Neither the front-end nor the back-end of Java EE will survive HTML5"; 8% think the whole concept of a "view layer" will become obsolete ("Some other technology will replace the view layer"); and 9% chose "Java EE never had a significant place in the Java ecosystem, ever." 6% of the votes went to "Other" and the two thoughtful comments may have come from this group. gkbrown commented: "There should not be any view layer in Java EE. Java EE should be a service-provider tier that any type of client (HTML, native, etc.) can communicate with." Meanwhile, tbee said: Pure client side rendering has its place but also many drawbacks, where security sensitivities are probably one of the most important issues, but unpredictable performance is a good second. So I do not believe server side HTML generation will go anywhere soon, but I'm highly in doubt if it will be JSF. More of the logic will move to the front end, and JSF is not well suited for that, but not as far as Angular.js wants it. Thanks again to Walter Nyland for providing us with a great poll! New poll: Java 8 Java 8 is here, so now is a good time to get some initial impressions. Our current poll asks How significant is the Java 8 release?. Voting will be open until Friday, April 4. What Java.net poll would you like to see? If you have a poll idea, get in touch with me by commenting on this blog post, or by sending an email to editor _at_ java.net, or by using our Submit Article/Blog form. Subscriptions and Archives: You can subscribe to this blog using the java.net Editor's Blog Feed. You can also subscribe to the Java Today RSS feed and the java.net blogs feed. To follow Java.net net on Twitter, follow @javanetbuzz. -- Kevin Farnham (@kevin_farnham)

Posted by on 26 March 2014 | 6:43 am

Java 8 is out!

Hurray Java 8 is out! See for more information at http://www.oracle.com/technetwork/java/javase/overview/java8-2100321.html

Posted by on 25 March 2014 | 2:02 pm

Hello Java 8 (and how it makes GlassFish speechless...)

After all these years, Java 8 is finally available. Of course, I have used it for about a year, while writing my book Java SE 8 for the Really Impatient. But I switched JAVA_HOME and the PATH whenever I worked on the book. Now I downloaded the official release and changed JAVA_HOME and the PATH one last time. Eclipse came up fine, and my Scala-based tools for e-book production worked without a hitch, and I forgot all about it. That's the nice thing about backwards compatibility. These days, the blogosphere is awash in blogs that sing the praises of Java 8. I don't think I add any value by writing my own. It's a major release—the biggest change in the Java language since Java 1.0 and the biggest change in the Java API since Java 1.2 (Or was that Java 2? Or Java 2 version 1.2?) Here is a great list of links. Or, if you'd rather learn from a book than a list of links, you know what to do... As my wife knows, if there is one person who can wring a drop of unhappiness from even the happiest event, that's me. So, this morning, I made a small fix to my side-project, the code-check autograder. It worked locally, and I ran the script to upload the WAR. Being a conscientious (and slightly pessimistic) person, I pointed my browser to the server, and whoa: Ugh, not again! Time to check out the logs. Now if there is one thing that I really hate in life it is the Stack Trace from Hell. Why can't GlassFish be like Play or Rails, and give the file name and line number of the offending artifact? But there is something worse than the Stack Trace from Hell. That would be Nothing At All. And that's what I got. Instead of noisily squawking about what ails its innards, it had turned into the strong and silent type: [2014-03-20T15:08:41.869+0000] [glassfish 4.0] [WARNING] [NCLS-DEPLOYMENT-00041][javax.enterprise.system.tools.deployment.autodeploy][tid: _ThreadID=69 _ThreadName=AutoDeployer][timeMillis: 1395328121869] [levelValue: 900] [[Attempt to create file /opt/domains/domain1/autodeploy/.autodeploystatus/codecheck.war failed;no further information.]] For an hour I tried This And That, to no avail. The app ran on my machine and not on the server. “The requested resource is not available” Finally, instead of using autodeploy, I logged into the server and deployed manually: $ asadmin deploy codecheck.warremote failure: Error occurred during deployment: Exception while loading the app :    java.lang.IllegalStateException: ContainerBase.addChild: start:    org.apache.catalina.LifecycleException: java.lang.IllegalArgumentException:    java.lang.UnsupportedClassVersionError: Class Initializer has unsupported major or minor version    numbers, which are greater than those found in the Java Runtime Environment version 1.7.0_40.Please see server.log for more details.Command deploy failed. Oh good grief! Of course. I had compiled the WAR for Java 8. Now why could that information not be prominently displayed in the web page? Or at least in the logs? Dear reader, if you work on developing tools for developers, please put every irregularity in their face. You'd think that nobody would be stupid enough to make errors such as compiling the WAR with the wrong version of Java, but you'd be wrong. I don't know how many hundreds of hours I have wasted with fiddly configuration stuff like this. To me, it's by far the worst part of Java EE . I would pay real money for an EE app server that serves developers and mercilessly traces every failure to a file name and line number in one of the app's artifacts. Like Play does: “No route found. In /app/views/Application/index.html (around line 4)”.

Posted by on 20 March 2014 | 11:39 am

Java 8 Launch: Less than a Week Away

The official launch of Java 8 is now less than a week away. The Java 8 Launch Webcast will take place at 10:00 AM Pacific Standard Time (PST) on Tuesday, March 25. The launch event will include a welcome and overview by Mark Reinhold, a panel discussion on Java SE 8 new features and enhancements, a chat with Twitter CIO Adam Messinger, discussion by Java community leaders, a Java ME 8 overview, and a panel discussion on Java 8 and the Internet of Things (IoT). Portions of the session will include Q&A discussion via Twitter (#Java8QA). Actually, while the official launch of Java 8 is a week away, the Java SE 8 JDK, Server JRE 8, and JRE 8 can already be downloaded, for those who want to get a head start. A packaged NetBeans 8 and JDK 8 download is also available. You can find links to lots of Java 8 related content (as well as other items of interest to Java/JVM developers) in the March issue of the Java Developer Newsletter, which just came out. Meanwhile, the jaxenter team has announced that JAX Magazine goes Java 8 crazy this March. The issue will be focused almost entirely on Java 8 and the adaptations widely used platforms are making in response. A search for "Java 8" at news.google.com returns plenty more interesting content, including a JavaWorld article about a survey run by TypeSafe where 54% of developers said they plan to upgrade to Java 8 within a year of its release. If you've been too busy to follow Java 8 developments closely, attending next Tuesday's Java 8 Launch Webcast will be a great way to get you started. Subscriptions and Archives: You can subscribe to this blog using the java.net Editor's Blog Feed. You can also subscribe to the Java Today RSS feed and the java.net blogs feed. To follow Java.net net on Twitter, follow @javanetbuzz. -- Kevin Farnham (@kevin_farnham)

Posted by on 18 March 2014 | 11:15 am