Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

and many more ....

Featured FREE Whitepapers

What's New Here?


Pure Java JavaFX 2.0 Menus

In recent posts on JavaFX, I have focused on using JavaFX 2.0’s new Java APIs without use of the JavaFX 1.x’s JavaFXScript and without use of JavaFX 2.0’s new FXML. All of these examples have been compiled with the standard Java compiler and executed with the standard Java launcher. In this post, I continue the theme of using pure Java APIs supported by JavaFX 2.0 while demonstrating development of JavaFX 2.0 menus. I list the entire code listing for this example later in this post, but I first show snippets of the code to make it easier to focus on each piece. A good starting point for using JavaFX 2.0 menus is to instantiate an instance of MenuBar. This is straightforward as shown next. Instantiating a javafx.scene.control.MenuBarfinal MenuBar menuBar = new MenuBar(); A MenuBar can contain Menu instances as its children and each Menu instance can have instances of MenuItem as its children. The next code listing demonstrates instantiation of a Menu, adding of MenuItem instances (or an instance of SeparatorMenuItem) to that Menu instance, and then adding the Menu instance to the instance of MenuBar.Adding Newly Instantiated Menu and MenuItem Instances to MenuBar// Prepare left-most 'File' drop-down menu final Menu fileMenu = new Menu('File'); fileMenu.getItems().add(new MenuItem('New')); fileMenu.getItems().add(new MenuItem('Open')); fileMenu.getItems().add(new MenuItem('Save')); fileMenu.getItems().add(new MenuItem('Save As')); fileMenu.getItems().add(new SeparatorMenuItem()); fileMenu.getItems().add(new MenuItem('Exit')); menuBar.getMenus().add(fileMenu); The example above is too simplified for realistic uses. There are no event handlers or actions associated with clicking on any of the menu items and there are no ways to select the menu items via keystroke rather than via mouse clicking. The next code listing demonstrates instantiation of MenuItem instances that include more than just a text string. In this code listing, there is an example of using MenuItemBuilder to build a much more complex MenuItem that includes association to a key combination and includes an association to an action handler.More Sophisticated MenuItem Instantiation with Keystroke and Event Associations// Prepare 'Help' drop-down menu final Menu helpMenu = new Menu('Help'); final MenuItem searchMenuItem = new MenuItem('Search'); searchMenuItem.setDisable(true); helpMenu.getItems().add(searchMenuItem); final MenuItem onlineManualMenuItem = new MenuItem('Online Manual'); onlineManualMenuItem.setVisible(false); helpMenu.getItems().add(onlineManualMenuItem); helpMenu.getItems().add(new SeparatorMenuItem()); final MenuItem aboutMenuItem = MenuItemBuilder.create() .text('About') .onAction( new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { out.println('You clicked on About!'); } }) .accelerator( new KeyCodeCombination( KeyCode.A, KeyCombination.CONTROL_DOWN)) .build(); helpMenu.getItems().add(aboutMenuItem); menuBar.getMenus().add(helpMenu); Besides demonstrating MenuItemBuilder, associating a key combination (CTRL-A in this case) with a menu item, and associating an action with a menu item, this code example also demonstrates making a menu item disabled (grayed out) with setDisable(boolean) or making it not appear at all with setVisible(boolean). Although I could have specified disabling the menu item or making the menu item invisible with a MenuItemBuilder, I intentionally used ‘set’ methods on the MenuItems in this example to contrast that approach with using the MenuItemBuilder. For completeness, here is the entire code listing of my (The Complete Listing)package dustin.examples;import static java.lang.System.out;import javafx.application.Application; import; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.scene.Group; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.KeyCode; import javafx.scene.input.KeyCodeCombination; import javafx.scene.input.KeyCombination; import javafx.scene.paint.Color; import javafx.stage.Stage;/** * Example of creating menus in JavaFX. * * @author Dustin */ public class JavaFxMenus extends Application { /** * Build menu bar with included menus for this demonstration. * * @param menuWidthProperty Width to be bound to menu bar width. * @return Menu Bar with menus included. */ private MenuBar buildMenuBarWithMenus(final ReadOnlyDoubleProperty menuWidthProperty) { final MenuBar menuBar = new MenuBar();// Prepare left-most 'File' drop-down menu final Menu fileMenu = new Menu('File'); fileMenu.getItems().add(new MenuItem('New')); fileMenu.getItems().add(new MenuItem('Open')); fileMenu.getItems().add(new MenuItem('Save')); fileMenu.getItems().add(new MenuItem('Save As')); fileMenu.getItems().add(new SeparatorMenuItem()); fileMenu.getItems().add(new MenuItem('Exit')); menuBar.getMenus().add(fileMenu);// Prepare 'Examples' drop-down menu final Menu examplesMenu = new Menu('JavaFX 2.0 Examples'); examplesMenu.getItems().add(new MenuItem('Text Example')); examplesMenu.getItems().add(new MenuItem('Objects Example')); examplesMenu.getItems().add(new MenuItem('Animation Example')); menuBar.getMenus().add(examplesMenu);// Prepare 'Help' drop-down menu final Menu helpMenu = new Menu('Help'); final MenuItem searchMenuItem = new MenuItem('Search'); searchMenuItem.setDisable(true); helpMenu.getItems().add(searchMenuItem); final MenuItem onlineManualMenuItem = new MenuItem('Online Manual'); onlineManualMenuItem.setVisible(false); helpMenu.getItems().add(onlineManualMenuItem); helpMenu.getItems().add(new SeparatorMenuItem()); final MenuItem aboutMenuItem = MenuItemBuilder.create() .text('About') .onAction( new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent e) { out.println('You clicked on About!'); } }) .accelerator( new KeyCodeCombination( KeyCode.A, KeyCombination.CONTROL_DOWN)) .build(); helpMenu.getItems().add(aboutMenuItem); menuBar.getMenus().add(helpMenu);// bind width of menu bar to width of associated stage menuBar.prefWidthProperty().bind(menuWidthProperty);return menuBar; }/** * Start of JavaFX application demonstrating menu support. * * @param stage Primary stage. */ @Override public void start(final Stage stage) { stage.setTitle('Creating Menus with JavaFX 2.0'); final Group rootGroup = new Group(); final Scene scene = new Scene(rootGroup, 800, 400, Color.WHEAT); final MenuBar menuBar = buildMenuBarWithMenus(stage.widthProperty()); rootGroup.getChildren().add(menuBar); stage.setScene(scene);; }/** * Main executable function for running examples. * * @param arguments Command-line arguments: none expected. */ public static void main(final String[] arguments) { Application.launch(arguments); } } The next series of screen snapshots attempt to demonstrate what this application looks like when executed using the java launcher. The images show the initial appearance of the application, the drop-down menu presented when ‘File’ menu is clicked on, the drop-down menu presented when the ‘Help’ menu is clicked on, and finally an image that shows the message written to standard output when the ‘About’ menu item is clicked on under the ‘Help’ menu. The code in the example featured in this post has numerous syntax features that should look familiar to Swing developers. In fact, many of the JavaFX classes used above have the same names as AWT classes and so care must be used to import the correct class when using the IDE’s automatic import suggestions. The example above also provides an example of JavaFX binding. In particular, the width of the menu bar is bound to the width of the stage’s width. This is useful because it looks better to have the menu bar span the entire top of the visual rather than being just wide enough to hold the menu labels. Building menus is fairly straightforward in JavaFX 2.0 and can be implemented using basic Java tools and the JavaFX 2.0 JAR. Happy coding and don’t forget to share! Reference: (Pure Java) JavaFX 2.0 Menus from our JCG partner Dustin Marx at the Inspired by Actual Events blog....

Android books giveaway for celebrating Packt’s 1000 title

Fellow geeks, We are pleased to announce that we have once again teamed up with Packt Publishing and we are organizing another giveaway for you! The occasion is the celebration of 1000 IT titles by Packt! So, 4 lucky winners will have the chance to win a copy of Packt’s best-selling books on Android (ebook format). Read along to find more details about the contest. Packt Publishing is about to publish its 1000th title. Packt books are renowned among developers for being uniquely practical and focused, covering highly specific tools and technologies.     For this occasion, Packt is giving everyone a surprise gift! However, the surprise won’t be revealed until September 28, 2012, which is when the 1000th title is expected to be unveiled. To receive this gift, simply register for an account on the Packt website and return between September 28 and 30.     Another thing to notice is that Packt supports many of the Open Source projects covered by its books through a project royalty donation, which has contributed over £300,000 to Open Source projects up to now. As part of the celebration Packt is allocating $30,000 to share between projects and authors, soon to be disclosed on their website. And of course Packt was kind enough to provide some cool Android books only for the readers of Java Code Geeks. Here are the books!     AndEngine for Android Game Development Cookbook: RAWOverview of the uber-cool AndEngine game engine for Android Game Development. Includes step by step detailed instructions and information on a number of AndEngine functions, including illustrations and diagrams for added support and resultsThis book is currently available as a RAW (Read As we Write) book. Android 3.0 Application Development CookbookQuickly develop applications that take advantage of the very latest mobile technologies, including web apps, sensors, and touch screens. Excellent for developing a full Android application. Appcelerator Titanium Smartphone App Development CookbookLeverage your JavaScript skills to write mobile applications using Titanium Studio tools with the native advantage! Android User Interface Development: Beginner’s GuideLeverage the Android platform’s flexibility and power to design impactful user-interfaces. How to Enter? Just send an email here using as subject “Packt Android Giveaway”. An empty email will do, it’s that simple! Optionally in your email, you may mention which book would you prefer the most! We are waiting for your emails! (Note: By entering the contest you will be automatically included in the forthcoming Java Code Geeks Newsletter.)     Again, don’t forget to sign-up for a free account in Packt before the 30th of September, 2012. Visit their website: A pleasant surprise gift is in order for each one of you! We would love it if you shared this! Spread the world people! ;-)...

Trying to understand CAP

The CAP theorem, stated by Brewer and proved by Gilbert and Lynch specifies a property of distributed systems. It states that such a system cannot guarantee at the same time Consistency, Availability and Partition tolerance. It is also often said as a catchy phrase: Consistency, Availability, Partition Tolerance – pick any two used mostly when talking about NoSQL databases and suggesting that a distributed system can be characterized as either CA, AP or CP (see e.g. here). For some time I’ve been trying to understand the different combinations and what do they mean in practice; having some time at various airports I caught up on reading, and here’s what I came up with. What’s C, A and P? First let’s define how I understand the three guarantees, basing on some of the articles I’ve read. Consistency is the easiest one. It roughly means that the clients get the same view of data. By saying that a system is consistent we often mean strong consistency, but it also can come in different flavors, e.g. casual. Availability is a property saying that every request to a non-failing node will return a (meaningful) response. The response may not contain all data (so the harvest will not be 100%, see the appropriate section in [3]), but it should be useful for the client. Partition tolerance means that the system will continue working even if any number of messages sent between nodes is lost. This can be e.g. a network failure between two datacenters, where nodes in each datacenter form a partition. Also note that a failure of any number of nodes forms a partition (it is not possible to distinguish between a network failure and a node failing and stopping to respond to messages). The hardest part for me is understanding the difference between Availability and Partition tolerance. Also, the various articles don’t specify what they mean by saying that a system is “working” after being e.g. partitioned – does it mean that every request gets a response with useful data, or are responses “Sorry, I can’t give you data right now” acceptable also? P+C? Let’s assume that a system is partition tolerant and that it has more than one node. If a partition is formed, splitting the system in two, the system should continue working. Hence both partitions allow clients to write. But then, how to guarantee consistency? If one client writes to partition 1, and another to partition 2? Hence: P => ~C. A+~P? Suppose now that a system is available and that we have more than one node. As the system is available, it should respond to requests even if some nodes die. As noted above, some nodes dying are equivalent to a partition. So if the system is still working, we have partition tolerance. Hence: A => P. A+C? Summarizing the two implications above (A => P and P => ~C), we get: A => ~C, so that an available system cannot be consistent (if it has more than one node). In practice however, there are of course AC systems, e.g. single-node RDBMS. Or even master-slave/master-master replicated RDBMS, provided there’s a central router knowing which nodes live and directing client appropriately. Such a router is then a single point of failure (SPoF). Relax? I suspect that in reality, when e.g. NoSQL/NewSQL systems are characterized with the CAP properties, they assume some relaxed form of C/A/P. Unfortunately, all of the definitions flying around seem to be pretty vague and are more of hand-waving than proper, precise statements. I think it would be much easier to explore the ever-growing ecosystem of new datastores if they could be more easily characterized; maybe the CAP vocabulary is just not enough? Please correct me if I’m wrong somewhere, and I probably am! :) And don’t forget to share! Reference: Trying to understand CAP from our JCG partner Adam Warski at the Blog of Adam Warski blog....

Motivation, Creativity and Innovation

I am a strong believer in that every individual on this earth can be creative and that hard focused work beats natural talent in every way. Personally I get really inspired by observing skillful people come up with amazing and creative ideas. Others may feel rivalry and/or envy. I am not sure why certain people react one way or another but dare I speculate that it insecurity have something to do about it? I feel confident to say that truly creative people does not feel intimidated or sentimental about their ideas being trumped by better ideas. In fact they encourage it. Because they know competition will inspire and push themselves further. There is nothing to fear if you are humble enough to accept and build on other peoples ideas to find ways to continuously elevate your intellect. Isaac Newton indicated that innovation is the continuous process of creating value from existing ideas, knowledge and inventions. So it is reasonable to think that most companies want to have motivated employers that are original, think differently and are highly creative. Right. And CEOs should not forget that this is just as important for them as well. So how do you engage people to be high performing, innovative and creative? I think Dan Pink is spot on.Autonomy: The desire to be self directed. Mastery: The urge to get better at stuff. Purpose: People are happiest when working for something larger than ourselves.Economical rewards are great. But they stop working as motivator for intellectual work when reaching a certain level – it is a lot better to empower people with freedom to express their creativity. I have observed that management sometimes carry out this form of hypocrisy, pushing employees in this direction without giving them the freedom to actually start doing it. As an example, do you recognize the following leadership style? According to Command-and-Conquer, managers-slash-leaders figure out where the business is going to go, and then issue the appropriate orders to their lieutenants to move the business in that direction. Their lieutenants in turn divide up the tasks into smaller chunks and command their reports to implement them. This continues down the org-chart until eventually someone at the bottom actually does some work. In this model, a programmer is a cog in the machine: a typist who carries out one part of management’s orders. Some businesses actually run this way. You can always tell when you are dealing with such a business, because the person you are talking to is doing something infuriating and senseless, and they know it, and they might even care, but there’s nothing they can do about it. Joel Spolsky: The Development Abstraction Layer This is an excellent example of how to efficiently kill motivation and creativity; encouraging a workforce with breaths smelling like urine and an awful way of growing skillful developers. Visionary people who have learned self-motivation and able to visualize patterns and connect the dots in a conceptual age and converging world will not accept this kind management and will find ways to escape it one way or another. Leadership is a crucial part in business and military success in the same way as creating a culture of innovation. If innovation does not happen in the organization, your leaders are probably killing it one way or another. For example, only trusting your users to tell you how to run your business. If I had asked people what they wanted, they would have said faster horses. Henry Ford Users know what problem they have, which is important and you should listen to your users. But listening to users *exclusively* will never make you entrepreneurial. Steve Jobs told customers what they wanted instead of asking for feedback. And before i forget – Henry Ford built cars… What will happen if peoples ideas are rejected over and over again, maybe because their leaders does not trust them? They will quickly stop sharing them because clearly their ideas are worthless to the company. But lets assume that you have a lot of creative people with mind blowing, innovative and relevant ideas. It takes almost as much creativity to understand a good idea as to have it in the first place. Alan Kay Having wonderful ideas is not enough. If you have to spend just as much time to convince people of the idea as on the idea themselves there will be no innovation left at the end of the day. Leaders must realize that innovation is fragile and must actively try to find and encourage it. Stakeholders must also accept risk and communicate that failure is expected and not punish failures. At the same time – execution is critical. Ideas are not useful if they are irrelevant to business or if you cannot make reality out of them. It is important to build excellent teams that are able take an idea and work with it. If you give a good idea to a mediocre group, they’ll screw it up. If you give a mediocre idea to a good group, they’ll fix it. Or they’ll throw it away and come up with something else. Ed Catmull, Pixar: Keep Your Crises Small This is why people should be allowed to work on the things that motivates them. Motivation is of course not a guarantee for success. But with a good ideas, passion and dreams your chances for success increase drastically since individuals will be way more productive and caring than on average. Ignore this and you may find your co-workers spending most of their time at the coffee machine or surfing the web instead of doing incredible work. Some say “ignorance is bliss” and I guess they are right. But I do not want to take the easy way out… My brain is simply allergic to ignorance. Fish rot from the head as do organisations. Remember that. Reference: Motivation, Creativity and Innovation from our JCG partner Kristoffer Sjogren at the deephacks blog....

Useful Ant build tags

Questions: How to do following tasks in ant file?Make zip file. Run command. Copy files to remote machine. Run commands on Remote Linux machine. Open an input box and respond to input value. Make an ant call.Answers: 1. Make zip file: Following is the xml for making zip file in ant: <zip destfile='${destination.folder}/'> <fileset dir= '${Source.folder}' /> </zip> In here “destfile” is the name and location of the created zip file. Inside fileset tag the dir attricute is used to specify source folder form where all files will be zipped. 2. Run commands: Here I will show you how to start tomcat in ant file to demonstrate how to run commands in ant. Following is the xml for this: <exec dir='${tomcat.home}/bin' executable='cmd' os='Windows XP'> <arg line='/c startup.bat'/> </exec> Here “${tomcat.home}” is the path of the tomcat folder. The command is given in “<arg>” tag in “line” attribute. Note: To run following commands you will need JSCH jar. 3. Copy files to remote machine: If remote machine is in your LAN and you can access it directly as \\remote_machine\path then you can use simple copy command as follows: <copy file='${source.folder.file} ' todir='\\remote\path'> </copy> To copy files on remote machine that supports SCP use following tag: <scp file='${source.folder.file} ' todir='${remote.user}@${}:${}' password='${remote.password}' trust='true'> </scp> In above both commands “file” is the source file which you want to copy with its path. And “todir” is the remote machine folder path where you want to copy the file. 4. Run commands on remote machine: You can use following tag to execute commands on remote Linux machine. <sshexec host='${}' username='${remote.username}' password='${remote.password}' command='${}' trust='true' /> For example to start tomcat use following tag: <sshexec host='${}' username='${remote.user}' password='${remote.password}' command='sh ${tomcat.home}/' trust='true' />5. Open an input box and respond to input value: To open an input dialog use following tag: <input message='Enter id: ' addproperty=''> </input> Here “” in “addproperty” is the variable name which holds input value. Now to check if user has denied to enter value in input: <condition property='do.abort'> <equals arg1='n' arg2='${}'/> </condition> <fail if='do.abort'>Build aborted by user.</fail> And if user enters value and press OK then after you can refer to entered value as “${}”. 6. Make an ant call: <antcall target='targetName'> </antcall> Here “target” is the name of the target that will be executed. Note: In above examples all values starting with “${”and ending with “}’’ are variables and you may have to put appropriate values in them to successfully run them. Reference: Useful Ant build tags from our JCG partner Harsh Raval at the harryjoy blog....

Checked and unchecked exceptions in Java

Java has two types of exceptions – checked and unchecked. In short – checked are meant for cases when the developer can reasonably recover from the exception, while unchecked exceptions are programming errors that can’t be dealt with. This article explains when to use which. But it is not that simple – checked exceptions are making the code “uglier”. They force the developer to write try/catch blocks or to rethrow the exception. But rethrowing hides another problem – some exceptions should not cross module boundaries. The most common thing to do when you are forced to catch a checked exception, which you have no idea what to do with, is to simply wrap it in a RuntimeException and rethrow it. Actually, it might not be the most common – especially novice programmers tend to swallow exceptions, with empty catch blocks. Log & rethrow leads to doubled stacktraces sometimes, if there is some general layer for exception handling. Anyway, there are multiple bad practices here that lead to code that’s hard to debug and maintain. Some say checked exceptions should be eliminated completely, given the verbosity, tediousness and error-proneness they introduce. C# does not have checked exceptions at all. Of course eliminating them should take into account backward compatibility. I, however, believe the decision to have these two types of exceptions has its plus(es). It forces the developer to think that an exception is likely to happen in this situation, so he must take measures. The API declares that it will throw exceptions and the developer sees this compile-time. It enforces compile-time safety. You should not wait until the code goes to production to discover that something might fail. Javadoc? Well, a good option to say that, but I bet no one will read the javadoc until the exception actually happens. So, how to have the “best of both worlds” ? I had a bizarre idea (explained in details here) for APIs to define two interfaces (linked through inheritance, so that only one interface is actually supported), and providing a way, through a factory, to get either an implementation whose methods throw checked exceptions, or one that wraps the checked exceptions into unchecked ones. It may be viable, it may be stupid, I can’t tell. For now it just looks strange. But the above is a workaround at best. Then another idea came – introduce @RethrowExceptions annotation on methods. It will tell the compiler that in this method you don’t want to handle checked exceptions, but you also don’t want to declare them to be thrown. (The name of the annotation can be improved). In the simplest implementation that comes to my mind this can simply tell the compiler to surround the whole method body with try {..} catch (Exception ex) { throw new RuntimeException(ex);}. The benefits:you are still warned by the compiler that the method you are using can throw an exception and you must think of handling it you don’t make your code ugly by needless try/catches. And you don’t force your callers to think what to do with the exception the possibility of swallowing the exception is decreased.So in short – such an annotation would mark a method as one that is unable to handle the exception and does not want to propagate this decision to its callers. This idea sounds less bizarre. I guess it can be implemented even now, using a compiler plug-in. Or perhaps it is already implemented in something like project lombok? Don’t forget to share! Reference: Checked and Unchecked Exceptions in Java from our JCG partner Bozhidar Bozhanov at the Bozho’s tech blog blog....

Fault-tolerance primitives in Scala: links and traps

Over the last decade Actor Model is actively marketed as a simple, effective and save concept for building concurrency. Being popularized by Erlang in early nineties, and used as a primary concurrency construct in Scala, Actors offer share-nothing event-driven model, where creating and maintaining a single actor is cheap (so that you can keep running millions of them), and remote actors working at distributed nodes look and feel as the local ones. However, being used unwisely, actors may bring even more pain and boilerplate, than thread-based concurrency or STM. Lack of the in-depth documentation on actor-based modeling leads to misconceptions and myths that can be broken working through best-practices and design guidelines of building fault-tolerant systems in Erlang. Fault-tolerance primitives Defensive programing forces you to put a huge effort to protect the system against all kinds of unexpected behavior you may think of, checking inputs and current state whenever possible, and defining ways to escalate the problem on a higher level. Being a defensive programmer you should always be proactive and look for a new potential problems to handle, because even the smallest one causing a failure in insignificant component may lead to a huge system crash. Fault-tolerant systems as apposed don’t tend to predict all possible failure reasons (to prevent a single component from crash), but rather isolate the component from the rest of the system and restart it, keeping the system work consistently. If restart of the component doesn’t help, the problem may be propagated to the higher level, in order to [possibly] restart the parties that exchange messages with the component. As Joe Armstrong says on his book “Programming Erlang”, when one actor dies in the room full of actors, others should probably notice that and start fixing the problem (cleaning out the bodies). In Erlang and Scala this behavior is achieved by linking actors. In the most basic form, when two actors are linked, and one of them dies, it sends an exit signal to another actor to terminate it too. Actors linking is bidirectional operation, so, when you link actor A to B, B is on the background linked to A, and death of any of them cause sending an exit signal to another. In Erlang it’s possible to create unidirectional linking with monitors (when monitored process dies, ‘DOWN’ message is sent to the handler). There’s no analogue to the monitors in Scala standard library, however implementing it on demand would be easy. Linked actor can create an exit trap, so that exit signal will be processed as a normal message, not causing actor termination. Exit signal normally contains the reference to the failed actor (that can be used to restart it), and failure reason. In “Programming Erlang” several link/trap exit scenarios are represented with a simple example: -module(edemo1). -export([start2]). start(Bool, M) -> A = spawn(fun() -> a() end), B = spawn(fun() -> b(A, Bool) end), C = spawn(fun() -> c(B, M) end), sleep(1000), status(b, B), status(c, C). In the code above three processes are created, synchronized with sleep, in order to give them time to process the passed messages (ugly in general, but works for a simple example), and afterwards, their state is checked. Actors are defined as follows: a() -> process_flag(trap_exit, true), wait(a). b(A, Bool) -> process_flag(trap_exit, Bool), link(A), wait(b). c(B, M) -> link(B), case M of {die, Reason} -> exit(Reason); {divide, N} -> 1N, wait(c); normal -> true end. Process A always traps exits, process B is linked to A and traps exits depending on the function input, process C linked to B receives messages and either makes computation or fails. wait(Prog) -> receive Any -> io:format('Process ~p received ~p~n' ,[Prog, Any]), wait(Prog) end. Method wait recursively receives messages printing out the message content. Being translated into Scala, using standard Actors library, the example looks as follows: object LinkedActors { case class Die(reason:AnyRef) case class Divide(number: Int) def status(name: String, actor: Actor) = println('Actor %s is %s' format(name, actor.getState)) def printMessage(actorName: String):PartialFunction[Any, Unit] = {case msg => println('Actor %s received %s' format(actorName, msg))} def start(isTrapExit: Boolean, message: Any) = { val A = actor{ self.trapExit = true loop(react(printMessage('a'))) } val B = actor{ self.trapExit = isTrapExit self link A loop(react(printMessage('b'))) } val C = actor{ self link B loop{ react{ case Die(reason) => exit(reason) case Divide(number) => 1number } } } C! message Thread.sleep(1000) status('b', B) status('c', C) } } Essentially, code is the same with the difference that messages accepted by actor C are classified with case classes and receive behavior of actors B and C is represented with partial functions. Let’s pass some inputs to the start method in order to see, how will the chained actors behave, when some of them die: scala> start(false, Die('abc')) Actor a received Exit(scala.actors.Actor$$anon$1@dc8f6d,abc) Actor b is Terminated Actor c is Terminated Actor C receives message Die and exists with the reason “abc”. Actor B linked to C doesn’t trap exits, therefore it terminates too. As long as A connected to B traps exits, when actor B terminates it sends A a message with the reason why it has failed (case class with the following signature): ** An `Exit` message (an instance of this class) is sent to an actor * with `trapExit` set to `true` whenever one of its linked actors * terminates. * * @param from the actor that terminated * @param reason the reason that caused the actor to terminate * case class Exit(from: AbstractActor, reason: AnyRef) In the same time, when exit is expected (not caused with computational exception), linked actors are untouched: scala> start(false, Die('normal)) Actor b is Suspended Actor c is Terminated In the snippet below, unhandled division by zero exception causes C and B to die: scala> start(false, Divide(0)) Actor a received Exit(scala.actors.Actor$$anon$1@113eb9c,UncaughtException (scala.actors.Actor$$anon$1@1a1446d,Some(Divide(0)),Some(scala.act ors.ActorProxy@14f83d1),java.lang.ArithmeticException: by zero)) Actor b is Terminated Actor c is Terminated If we force B to trap exit, the actor stays alive in all the scenarios described above: scala> start(true, Die('abc')) Actor b received Exit(scala.actors.Actor$$anon$1@13e49a8,abc) Actor b is Suspended Actor c is Terminated Compared to the first snippet, now B receives exit message from C. Unhandled errors are also not propagated to A: scala> start(true, Divide(0)) Actor b received Exit(scala.actors.Actor$$anon$1@119f779,UncaughtException (scala.actors.Actor$$anon$1@119f779,Some(Divide(0)),Some(scala.act ors.ActorProxy@14f83d1),java.lang.ArithmeticException: by zero)) Actor b is Suspended Actor c is TerminatedBasic Supervisor Exit message contains the reference to the failed actor that can be used to restart it. It’s possible to implement a very simple actor supervisor, by analogy with supervisor behavior in Erlang. case class ChildSpecification(worker: Worker, restartBehavior: Child RestartBehavior.Value = permanent) case class OneForOne(maxRestarts: Long = 3, maxTime: Long = 3000) extends RestartStrategy case class OneForAll(maxRestarts: Long = 3, maxTime: Long = 3000) extends RestartStrategy class Supervisor(supervisorId: String, strategy: RestartStrategy, childSpecs: List[ChildSpecification]) extends Worker { ... override def act = { self.trapExit = true linkWorkers loop { react{ case Exit(worker: Worker, reason) => println('Worker [%s] has failed due to [%s]' format(, reason)) if(worker.restartsInPeriod(strategy.maxTime) >= strategy .maxRestarts) exit('Maximum restart intensity for %s is reached!' format( strategy match { case str:OneForOne => restartWorker(worker) case str:OneForAll => childSpecs.foreach{spec => restartWorker(spec.worker)} } case Terminate(reason) => println('Supervisor terminated with reason [%s]' format(reason)) exit(reason) } } } ... } Supervisor itself is a normal Scala Actor that traps messages from the other actors linked to it (workers, in terms of supervision terminology), and restarts either only one failed actor or all supervised actors. When restart frequency reaches the limit specified by the restart strategy, supervisor terminates, so that supervisor at the higher hierarchy position may try to handle the problem. In the simplest scenario, supervisor restarts the actor terminated due to uncaught exception: 'Actor terminated due to uncaught exception is restarted by the supervisor' in { val worker = new SimpleWorker('simple_worker') Supervisor('basic_supervisor', OneForOne(), List(ChildSpecification(worker))).start worker !? (1000, Divide(0)) (worker !? (1000, Divide(1))).asInstanceOf[Option[Int]] must be equalTo Some(1) } Output of the specification is: Starting worker simple_worker Worker [simple_worker] has failed due to [UncaughtException(com.vasilrem.linked. SupervisorSpec$SimpleWorker@fd54ec,Some(Divide(0)),Some(scal a.actors.Channel@16167ab),java.lang.ArithmeticException: by zero)] Restarting worker [simple_worker]... [info] + Actor terminated due to uncaught exception is restarted by the supervisor In a more complex scenario, when supervisors are linked in a tree, high-level supervisor restarts low-level supervisor, when it dies, that causes restart of the workers linked to it: 'High-level supervisor restarts low-level supervisor and the wrokers linked to it' in{ val worker = new SimpleWorker('simple_worker') val lowLevel = Supervisor('lowlevel_supervisor', OneForOne(), List(ChildSpecification(worker))) val highLevel = Supervisor('lowlevel_supervisor', OneForOne(), List(ChildSpecification(lowLevel))).start worker.getState must not be equalTo(State.Terminated) lowLevel ! Terminate('Kill lowlevel') Thread.sleep(1000) worker.getState must not be equalTo(State.Terminated) } Test output is following: Starting worker lowlevel_supervisor Starting worker simple_worker Supervisor terminated with reason [Kill lowlevel] Worker [lowlevel_supervisor] has failed due to [Kill lowlevel] Restarting worker [lowlevel_supervisor]... Starting worker simple_worker [info] + High-level supervisor restart low-level supervisor You can find more specifications and code of the supervisor here. Happy coding and don’t forget to share! Reference: Fault-tolerance primitives in Scala: links and traps from our JCG partner Vasil Remeniuk at the Vasil Remeniuk blog blog....

Android: Copy-paste with Intent and support for HTML

Android provides support for copy and paste feature using ClipBoardManager. The provides a brief description along with an image which helps to understand the Copy-paste framework. “To copy data, an application puts a ClipData object on the ClipboardManager global clipboard. The ClipData contains one or more ClipData.Item objects and one ClipDescription object. To paste data, an application gets the ClipData, gets its MIME type from the ClipDescription, and gets the data either from the ClipData.Item or from the content provider referred to by ClipData.Item.”This tutorial covers the latest feature introduced in JellyBean, supporting the styled text. We will cover the methods listed below.HTML supported methodsClipData.newHtmlText() with clipboard Intent.putExtra() with Intent.EXTRA_HTML_TEXT Intent.setClipData() with newHtmlText() methodProject Information : Meta-data about the project. Platform Version : Android API Level 16. IDE : Eclipse Helios Service Release 2 Emulator : Android 4.1(API 16) Prerequisite : Preliminary knowledge of Android application framework and Intent.Example source code To start with, create project by Eclipse > File> New Project>Android Application Project. The following dialog box will appear. Fill the required field, i.e Application Name, Project Name and Package. Now press the next button.Once the dialog box appears, select the BlankActivity and click the next button.Fill the Activity Name and Layout file name in the dialog box shown below and hit the finish button.This process setups the basic project files. Now we are going to add view components in the layout activity_jbclipboard.xml file. You can modify the layout file using either Graphical Layout editor or xml editor. In this layout, we will add four buttons, namely copy, paste, send html Intent, and send clipdata intent and attach onClick methods with CopyHtml, pasteHtml, sendHtmlIntent and sendClipdataIntent buttons, respectively. These methods will be defined in JBClipboard class. We will also include two radio buttons i.e Paste HTML and Paste Text. These radio buttons help to select the required type of text to be extracted from the clipboard. We also have three EditViews to show the text. The first Editview contains the Styled text, the second one shows either HTML or text string. The third one shows the Coerce HTML string. The layout file is shown below. <LinearLayout xmlns:android='' xmlns:tools='' android:layout_width='match_parent' android:layout_height='match_parent' android:orientation='vertical'><EditText android:id='@+id/etCopy' android:layout_width='fill_parent' android:layout_height='wrap_content' android:padding='@dimen/padding_medium' android:gravity='top' android:scrollHorizontally='false' android:inputType='textMultiLine' /> <RadioGroup android:id='@+id/rbgTextHTML' android:orientation='horizontal' android:layout_width='fill_parent' android:layout_height='wrap_content' > <RadioButton android:id='@+id/rbHtml' android:layout_weight='.5' android:layout_width='0dp' android:layout_height='wrap_content' android:checked='true' android:text='@string/rbHtml'/> <RadioButton android:id='@+id/rbText' android:layout_weight='.5' android:layout_width='0dp' android:layout_height='wrap_content' android:text='@string/rbText'/> </RadioGroup> <LinearLayout android:layout_width='match_parent' android:layout_height='wrap_content' android:orientation='horizontal'> <Button android:layout_width='0dp' android:layout_height='wrap_content' android:layout_weight='.5' android:onClick='copyHtml' android:text='@string/btCopy'/> <Button android:layout_width='0dp' android:layout_height='wrap_content' android:layout_weight='.5' android:onClick='pasteHtml' android:text='@string/btPaste'/> </LinearLayout> <LinearLayout android:layout_width='fill_parent' android:layout_height='wrap_content' android:orientation='horizontal'> <Button android:layout_width='0dp' android:layout_weight='.5' android:layout_height='wrap_content' android:onClick='sendHtmlIntent' android:text='@string/btSendHtmlIntent'/> <Button android:layout_width='0dp' android:layout_weight='.5' android:layout_height='wrap_content' android:onClick='sendClipdataIntent' android:text='@string/btSendClipdataIntent'/> </LinearLayout> <TextView android:layout_width='fill_parent' android:layout_height='wrap_content' android:text='@string/tvCopiedText'/> <EditText android:id='@+id/etPaste' android:layout_width='fill_parent' android:layout_height='wrap_content' android:inputType='textMultiLine' android:gravity='top' android:scrollHorizontally='false' /> <TextView android:layout_width='fill_parent' android:layout_height='wrap_content' android:text='@string/tvcoerceText'/> <EditText android:id='@+id/etPasteCoerceText' android:layout_width='fill_parent' android:layout_height='wrap_content' android:gravity='top' android:scrollHorizontally='false' android:inputType='textMultiLine'/> </LinearLayout> Now we need to add two more layout files for two different activities. Let’s define the first Layout file by Eclipse > File > Android XML file. Eventually we get the following dialog box. Make sure that the Layout resource type is selected. Name the layout file as activity_htmlintent and then click finish.Add two TextViews for showing text tags and two EditTexts view for showing the HTML and text strings. This layout file will be attached with which gets invoked once “text/html” type intent is broadcasted. The content of the activity_htmlintent.xml is given below: <LinearLayout xmlns:android='' android:layout_width='match_parent' android:layout_height='match_parent' android:orientation='vertical' > <TextView android:layout_width='match_parent' android:layout_height='wrap_content' android:text='@string/tvIntentHtml' /> <EditText android:id='@+id/etHtml' android:layout_width='match_parent' android:layout_height='wrap_content' android:inputType='textMultiLine' android:padding='@dimen/padding_medium' android:scrollHorizontally='false' /> <TextView android:layout_width='match_parent' android:layout_height='wrap_content' android:text='@string/tvIntentText' /> <EditText android:id='@+id/etText' android:layout_width='match_parent' android:layout_height='wrap_content' android:inputType='textMultiLine' android:padding='@dimen/padding_medium' android:scrollHorizontally='false' /> </LinearLayout> Now we will define another layout file called activity_clipdataintent.xml. Follow the similar steps given above to generate the layout xml file. This file is similar to the above file and contains two EditView and two TextViewThe. The content of the file is given below. This layout file will be attached to the ClipdataIntentActivity class which gets invoked when an intent with Clipdata object is passed. <LinearLayout xmlns:android='' android:layout_width='match_parent' android:layout_height='match_parent' android:orientation='vertical' ><TextView android:layout_width='match_parent' android:layout_height='wrap_content' android:text='@string/tvIntentClipdataHtml' /><EditText android:id='@+id/etClipBoardHtml' android:layout_width='match_parent' android:layout_height='wrap_content' android:inputType='textMultiLine' android:padding='@dimen/padding_medium' android:scrollHorizontally='false' /><TextView android:layout_width='match_parent' android:layout_height='wrap_content' android:text='@string/tvIntentClipdataText' /><EditText android:id='@+id/etClipBoardText' android:layout_width='match_parent' android:layout_height='wrap_content' android:inputType='textMultiLine' android:padding='@dimen/padding_medium' android:scrollHorizontally='false' /> </LinearLayout> You may have notice there are string resources have been used in the layout file. Define this string constants in string.xml as shown below. <resources><string name='app_name'>JellyBeanClipboard</string> <string name='menu_settings'>Settings</string> <string name='title_activity_jbclipboard'>JBClipboard</string> <string name='title_activity_htmlintent'>Html Intent Activity</string> <string name='title_activity_clipdataintent'>ClipData Intent Activity</string> <!-- CDATA tag is required otherwise you can't have the html text properly parsed in Textview --> <string name='tvHtml'><![CDATA[<b>Link:</b> <a href=''>Code4Reference</a>]]></string> <!-- Text string for button --> <string name='btCopy'>Copy</string> <string name='btPaste'>Paste</string> <string name='btSendHtmlIntent'>send HTML Intent</string> <string name='btSendClipdataIntent'>send ClipData Intent</string> <!-- Text string for RadioButton --> <string name='rbHtml'>Paste Html</string> <string name='rbText'>Paste Text</string> <!-- Text string for Text View --> <string name='tvCopiedText'><b><i>Copied text</i></b></string> <string name='tvcoerceText'><b><i>Copied coerce Text</i></b></string> <string name='tvIntentText'><b><i>Intent Text</i></b></string> <string name='tvIntentHtml'><b><i>Intent Html</i></b></string> <string name='tvIntentClipdataText'><b><i>Intent Clipdata Text</i></b></string> <string name='tvIntentClipdataHtml'><b><i>Intent Clipdata Html</i></b></string> </resources> Once we are done with the layout files, it’s time to define the activity classes. Let’s define the main activity called JBClipboard. This activity has various methods which use the HTML supported APIs. The embedded comments will help to understand the code. package com.code4reference.rakesh.jellybeanclipboard;import; import android.content.ClipData; import android.content.ClipDescription; import android.content.ClipboardManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.Html; import android.text.Spannable; import android.view.View; import android.widget.EditText; import android.widget.RadioButton; import android.widget.Toast;import com.example.jellybeanclipboard.R;public class JBClipboard extends Activity {EditText etCopy; EditText etPaste; EditText etPasteCoerceText; RadioButton rbText; RadioButton rbHtml; ClipboardManager mClipboard;ClipboardManager.OnPrimaryClipChangedListener mPrimaryChangeListener = new ClipboardManager.OnPrimaryClipChangedListener() { /** * This method is a callback. It get called when the primary clip * on the clipboard changes. */ public void onPrimaryClipChanged() { //Toast message will appear whenever the clipboad //primary data changes. Utility.showToastMessage(getApplicationContext(), 'Primary clipdata changed', Toast.LENGTH_SHORT); } };@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_jbclipboard); etCopy = (EditText) findViewById(; etPaste = (EditText) findViewById(; etPasteCoerceText = (EditText) findViewById(; etCopy.setText(Html.fromHtml(getString(R.string.tvHtml))); rbText = (RadioButton) findViewById(; rbHtml = (RadioButton) findViewById(; mClipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); mClipboard.addPrimaryClipChangedListener(mPrimaryChangeListener); }/** * This method gets called when 'Copy' button get pressed. * @param view */ public void copyHtml(View view) { String htmlText = getHtmltxt(etCopy); String plainText = getOnlyText(etCopy); mClipboard.setPrimaryClip(ClipData.newHtmlText('HTML Text', plainText, htmlText));} /** * This method gets called when 'Paste' button get pressed. * @param view */ public void pasteHtml(View view) { // Check if there is primary clip exsiting. // If it does then echeck the mime type to make sure // it has HTML content. if (mClipboard.hasPrimaryClip() && mClipboard.getPrimaryClipDescription().hasMimeType( ClipDescription.MIMETYPE_TEXT_HTML)) { // Get the very first item from the clip. ClipData.Item item = mClipboard.getPrimaryClip().getItemAt(0);// If 'Paste HTML' radio button is selected then paste // HTML in the Textview. if (rbHtml.isChecked()) { etPaste.setText(item.getHtmlText()); } else { // Paste the only text version. etPaste.setText(item.getText()); } // Paste the CoerceText . etPasteCoerceText.setText(item.coerceToText(this)); } } /** * This method gets called when 'send Html Intent' button get pressed. * @param view */ public void sendHtmlIntent(View view) { // This kind of intent can be handle by this application // Or other application which handle text/html type Intent Intent intent = new Intent(Intent.ACTION_SEND);String htmlText = getHtmltxt(etCopy); String text = getOnlyText(etCopy); intent.putExtra(Intent.EXTRA_HTML_TEXT, htmlText); intent.putExtra(Intent.EXTRA_TEXT, text); intent.setType('text/html'); startActivity(Intent.createChooser(intent, null)); }/** * This method gets called when 'send Clipdata Intent' button get pressed. * * @param view */ public void sendClipdataIntent(View view) { String htmlText = getHtmltxt(etCopy); String plainText = getOnlyText(etCopy); Intent intent = new Intent(this, ClipdataIntentActivity.class); //create a clipdata object with HTML text. //and associate with the intent. intent.setClipData(ClipData.newHtmlText( 'HTML text in Intent's clipdata', plainText, htmlText)); //Start the activity which can handle clipData object. startActivity(intent); } @Override protected void onDestroy() { super.onDestroy(); //Remove the ClipChanged Listener to save the resources. mClipboard.removePrimaryClipChangedListener(mPrimaryChangeListener); } /** * This method gets the EditText object and returns the HTML text. It * can be called only with EditTexts having spannable object with * the HTML text. * * @param editText * @return */ private String getHtmltxt(EditText editText) { //get the spannable object from EditText Spannable spannable = (Spannable) editText.getText(); //return the HTML text from spannable object. return Html.toHtml(spannable); }/** * This method takes the EditText object which has spannable object with HTML * text and returns the simple text without HTML tags. * * @param editText * @return */ private String getOnlyText(EditText editText) { return editText.getText().toString(); } }Now we are going to define HTMLIntentActivitywhich handles intent with HTML text. The intended intent will be triggered by the main activity (JBClibboard) package com.code4reference.rakesh.jellybeanclipboard;import com.example.jellybeanclipboard.R;import; import android.content.Intent; import android.os.Bundle; import android.widget.EditText;public class HtmlIntentActivity extends Activity {private EditText etHtml; private EditText etText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_htmlintent); etHtml = (EditText) findViewById(; etText = (EditText) findViewById(;//Get the intent that started this activity Intent intent = getIntent(); //Make sure intent and its type is not null. if (intent != null && intent.getType() != null && intent.getType().equals('text/html')) { //This contition will full-fill when this application receive the //intent who's type is 'test/html'. In this application sendHtmlIntent //method sends this type of Intent. Bundle bundle = intent.getExtras(); if(bundle != null){ etHtml.setText(bundle.getCharSequence(Intent.EXTRA_HTML_TEXT)); etText.setText(bundle.getCharSequence(Intent.EXTRA_TEXT)); } } } } Now we will define another activity called ClipdataIntentActivity which handles the Intent having clilpdata object. The content of the ClipdataIntentActivity class is given below. package com.code4reference.rakesh.jellybeanclipboard;import; import android.content.ClipboardManager; import android.content.Intent; import android.os.Bundle; import android.widget.EditText; import android.widget.Toast; import android.content.ClipData; import android.content.ClipDescription;import com.example.jellybeanclipboard.R;public class ClipdataIntentActivity extends Activity { private EditText etHtml; private EditText etText; ClipboardManager mClipboard;@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_clipdataintent); etHtml = (EditText) findViewById(; etText = (EditText) findViewById(;//Get the intent that started this activity Intent intent = getIntent(); if (intent != null) { ClipData clipdata = intent.getClipData(); //Make sure clipdata object is not null and it has HTML MIME type. if (clipdata != null && clipdata.getDescription().hasMimeType( ClipDescription.MIMETYPE_TEXT_HTML)) {ClipData.Item item = clipdata.getItemAt(0); etHtml.setText(item.getHtmlText()); etText.setText(item.getText()); } else { Utility.showToastMessage(this, 'Intent clipdata doesn't have HTML', Toast.LENGTH_SHORT); }} }}Create another class called Utility. It contains method to display the toast message. As you may have noticed that this function is static, so there is no need to create an object to invoke this method. It’s always a good idea to put the utility methods in a separate file and access this file in different places. In this way your code will be organized. package com.code4reference.rakesh.jellybeanclipboard;import android.content.Context; import android.widget.Toast;public class Utility {public static void showToastMessage(Context context, String message, int duration){ Toast.makeText(context, message, duration).show(); } } And finally define the Anroid Manifest file which basically provides Application information to the Android system. Here, you should notice that the HtmlIntentActivity Activity has an intent filter and specifies the Intent type as “text/html”. It basically means that the activity can handle intent whose type is text/html. Remaining part of the file is simple and easy to understand. <manifest xmlns:android='' package='com.example.jellybeanclipboard' android:versionCode='1' android:versionName='1.0' ><uses-sdk android:minSdkVersion='16' android:targetSdkVersion='16' /><application android:icon='@drawable/ic_launcher' android:label='@string/app_name' android:theme='@style/AppTheme' > <activity android:name='com.code4reference.rakesh.jellybeanclipboard.JBClipboard' android:label='@string/title_activity_jbclipboard' > <intent-filter> <action android:name='android.intent.action.MAIN' /> <category android:name='android.intent.category.LAUNCHER' /> </intent-filter> </activity> <activity android:name='com.code4reference.rakesh.jellybeanclipboard.ClipdataIntentActivity' android:label='@string/title_activity_clipdataintent' > </activity> <activity android:name='com.code4reference.rakesh.jellybeanclipboard.HtmlIntentActivity' android:label='@string/title_activity_htmlintent' > <intent-filter> <action android:name='android.intent.action.SEND' /> <category android:name='android.intent.category.DEFAULT' /> <!-- This activity will get launched when proper Intent type will match. In this case Intent type is 'text/html' --> <data android:mimeType='text/html' /> </intent-filter> </activity> </application></manifest> Once you are done with the coding, just execute it. You can launch this application on your android device or emulator. Make sure that the Android version is 16(Jelly Bean) or higher, only then this application will work. Screen-shots of the applications are shown below.You can get the source code here at github. Happy coding and don’t forget to share! Reference: Copy-paste with Intent and support for HTML on Android. from our JCG partner Rakesh Cusat at the Code4Reference blog....

The crystal ball illusion

I have noticed that people sometimes avoid doing thorough testing. This may sound as bogus to some, but hear me out… I do understand why this happen. Tests can create a feeling of being trapped, a burden that gets heavier to carry with every new test introduced. Building a stable, non-intrusive and quality ensuring suite of tests is a difficult task… but *why* does these problems surface? Most people can agree that testing, performed in one way or another, for any type of product, is a great way for revealing quality and potentially later increase it. But the testing process can get problematic when you specify a static suite of tests and then continuously re-execute it through the lifecycle of the product, i.e. regression testing. Stop and think for a second… what value does interfaces and abstractions provide to clients? They provide a way to enjoy a *particularly* valuable service without having to worry about the complex internal details of *how* it is provided to us. Interfaces are not unique to software development, they are everywhere in our everyday community. Consider leaving your Toyota in for repair. Employer Mike is excellent fixing Toyota cars using custom-made tools. But do you, as a client, really care *how* and by *whom* the car was repaired, if you can observe that malfunctioning parts have been replaced and the car works better than before? Mike will do his job better without being bothered by people who cannot keep up with his bleeding-edge techniques. Mike may quit or learn even better methods, throwing some of his old custom-made tools away. It is better to assure that the company service, as a whole, can deliver high quality for a wide array of diverse problems and clients. This is a simplification, but you get the point. I have observed that testing efforts (far too often) tries to verify unspecified implementation details, without really thinking of the consequences. Having too many poorly specified tests can easily snowball into a chaotic maintenance nightmare, making future product development difficult and unproductive. When these symptoms come creeping developers stop making continuous improvements, to avoid problematic refactoring and infectious conflicts with QA, hurting product quality more than helping it. Internal domain experts can help you understand fundamental business strategies and what *really* matters for the company to be successful. Think long and hard when specifying significant interfaces that are visible for *both* internal and external business processes. Distill abstractions that capture high-level goals and concepts, not complex implementation details. Focus your design and testing efforts on these interfaces and you will earn stability. Remember that business is fiercely competitive and vibrant, changing rapidly to outrun competitors. Allow flexibility for business to grow and evolve when defining interfaces and tests in your architecture. Enable interfaces to be combined into unique service compositions to support unforeseen business capabilities, maximizing value with minimal efforts. The future will forever remain untold so do not make too many assumptions on what tomorrow brings. There is no such thing as a crystal ball. Reference: The crystal ball illusion from our JCG partner Kristoffer Sjogren at the deephacks blog....

Guava Files: Java File Management

Both Groovy and Java SE 7 provide improvements for file management in Java as I discussed in posts here, here, here, and here. However, when a particular Java application is not able to yet use Java SE 7 or Groovy for its file management, an improved file management experience can still be obtained by using Guava‘s Files class. File handling has always seemed a little more difficult in Java than in many other programming languages. Java SE 7 certainly improves Java’s file handling capabilities dramatically with NIO.2, but not every project can make use of Java SE 7. For those projects not able to use Java SE 7, Guava’s Files class is a nice intermediate solution for easier file handling. It is important to note here that Java SE 7 introduces a Files class of its own, so any use of Guava’s Files class in Java SE 7 must be fully scoped if the Java version of Files is used in the same code. My examples have been written and built in Java SE 7, but I avoid using Java SE 7’s Files class and so don’t need to fully scope Guava’s same-named class.File Creation Guava’s Files class includes a couple overloaded write methods for easily writing content to a file. The next code sample demonstrates using Files.write(byte[],File).Demonstrating Files.write(byte[],File)/** * Demonstrate writing bytes to a specified file. * * @param fileName Name of file to be written to. * @param contents Contents to be written to file. */ public void demoFileWrite(final String fileName, final String contents) { checkNotNull(fileName, 'Provided file name for writing must NOT be null.'); checkNotNull(contents, 'Unable to write null contents.'); final File newFile = new File(fileName); try { Files.write(contents.getBytes(), newFile); } catch (IOException fileIoEx) { err.println( 'ERROR trying to write to file '' + fileName + '' - ' + fileIoEx.toString()); } } There are a couple observations that can be from this first code sample that will apply to all other code samples in this post. First, I make use of the statically imported Guava Preconditions class to provide an easy check ensuring that the provided parameters are not null. The second common feature of this code is that it explicitly catches and ‘handles’ the checked exception IOException. All other Files methods demonstrated in this post similarly throw this same checked exception.File Copying The next example demonstrates how easy it is to copy files using Guava’s Files.copy(File,File) method (one of several overloaded methods with name ‘copy’).Demonstrating Files.copy(File,File)/** * Demonstrate simple file copying in Guava. This demonstrates one of the * numerous overloaded copy methods provided by Guava's Files class. The * version demonstrated here copies one provided File instance to another * provided File instance. * * @param sourceFileName Name of file that is to be copied. * @param targetFileName Name of file that is result of file copying. */ public void demoSimpleFileCopy( final String sourceFileName, final String targetFileName) { checkNotNull(sourceFileName, 'Copy source file name must NOT be null.'); checkNotNull(targetFileName, 'Copy target file name must NOT be null.'); final File sourceFile = new File(sourceFileName); final File targetFile = new File(targetFileName); try { Files.copy(sourceFile, targetFile); } catch (IOException fileIoEx) { err.println( 'ERROR trying to copy file '' + sourceFileName + '' to file '' + targetFileName + '' - ' + fileIoEx.toString()); } }File Moving Moving files with Guava is as easy as copying. The Files.move(File,File) method is demonstrated in the next code snippet.Demonstrating Files.move(File,File)/** * Demonstrate moving a file with Guava's Files.move(File,File). * * @param sourceFileName Path/name of File to be moved. * @param targetFileName Path/name of Destination of file. */ public void demoMove(final String sourceFileName, final String targetFileName) { checkNotNull(sourceFileName, 'Move source file name must NOT be null.'); checkNotNull(targetFileName, 'Move destination name must NOT be null.'); final File sourceFile = new File(sourceFileName); final File targetFile = new File(targetFileName); try { Files.move(sourceFile, targetFile); } catch (IOException fileIoEx) { err.println( 'ERROR trying to move file '' + sourceFileName + '' to '' + targetFileName + '' - ' + fileIoEx.toString()); } }Comparing Files Determining if two files are the same is straightforward with the Gauva Files.equal(File,File) methodDemonstrating Files.equal(File,File)/** * Demonstrate using Guava's Files.equal(File,File) to compare contents of * two files. * * @param fileName1 Name of first file to be compared. * @param fileName2 Name of second file to be compared. */ public void demoEqual(final String fileName1, final String fileName2) { checkNotNull(fileName1, 'First file name for comparison must NOT be null.'); checkNotNull(fileName2, 'Second file name for comparison must NOT be null.'); final File file1 = new File(fileName1); final File file2 = new File(fileName2); try { out.println( 'File '' + fileName1 + '' ' + (Files.equal(file1, file2) ? 'IS' : 'is NOT') + ' the same as file '' + fileName2 + ''.'); } catch (IOException fileIoEx) { err.println( 'ERROR trying to compare two files '' + fileName1 + '' and '' + fileName2 + '' - ' + fileIoEx.toString()); } }Touching Files Touching a file to create a new empty file or to update the timestamp on an existing file can be easily accomplished with Guava’s Files.touch(File) as shown in the next code sample.Demonstrating Files.touch(File)/** * Demonstrate Guava's Files.touch(File) method. * * @param fileNameToBeTouched Name of file to be 'touch'-ed. */ public void demoTouch(final String fileNameToBeTouched) { checkNotNull(fileNameToBeTouched, 'Unable to 'touch' a null filename.'); final File fileToTouch = new File(fileNameToBeTouched); try { Files.touch(fileToTouch); } catch (IOException fileIoEx) { err.println( 'ERROR trying to touch file '' + fileNameToBeTouched + '' - ' + fileIoEx.toString()); } }Retrieving File Contents With a simplicity reminiscent of Groovy’s GDK extension File.getText(), Guava’s Files.toString(File,Charset) makes it easy to retrieve text contents of a file.Demonstrating Files.toString(File,Charset)/** * Demonstrate retrieving text contents of a specified file with Guava's * Files.toString(File) method. * * @param nameOfFileToGetTextFrom Name of file from which text is to be * retrieved. */ public void demoToString(final String nameOfFileToGetTextFrom) { checkNotNull(nameOfFileToGetTextFrom, 'Unable to retrieve text from null.'); final File sourceFile = new File(nameOfFileToGetTextFrom); try { final String fileContents = Files.toString(sourceFile, Charset.defaultCharset()); out.println( 'Contents of File '' + nameOfFileToGetTextFrom + '' are: ' + fileContents); } catch (IOException fileIoEx) { err.println( 'ERROR trying to get text contents of file '' + nameOfFileToGetTextFrom + '' - ' + fileIoEx.toString()); } }Temporary Directory Creation Guava makes it easy to generate a temporary directory with Files.createTempDir().Demonstrating Files.createTempDir()/** * Demonstrate Guava's Files.createTempDir() method for creating a temporary * directory. */ public void demoTemporaryDirectoryCreation() { final File newTempDir = Files.createTempDir(); try { out.println( 'New temporary directory is '' + newTempDir.getCanonicalPath() + ''.'); } catch (IOException ioEx) { err.println('ERROR: Unable to create temporary directory - ' + ioEx.toString()); } } I don’t provide a code sample here, but it’s worth noting that Guava provides a convenience method for creating a new directory will all necessary new parent directories with its Files.createParentDirs(File) method.Retrieving Contents of File as Lines There are times when it is most convenient to get the contents of a file as a series of lines so that each line can be processed. This is commonly done in Groovy with overloaded versions of readLines() and eachLine(). Guava provides similar functionality to Groovy’s File.readLines() with its Files.readLines(File, Charset) method. This is demonstrated in the following code sample.Demonstrating Files.readLines(File,Charset)/** * Demonstrate extracting lines from file. * * @param fileName Name of file from which lines are desired. */ public void demoRetrievingLinesFromFile(final String fileName) { final File file = new File(fileName); try { final List<String> lines = Files.readLines(file, Charset.defaultCharset()); for (final String line : lines) { out.println('>> ' + line); } } catch (IOException ioEx) { err.println( 'ERROR trying to retrieve lines from file '' + fileName + '' - ' + ioEx.toString()); } } The other overloaded version of readLines is interesting because it allows a LineProcessor callback to be specified to terminate returning of lines earlier than the end of the file.Reading File’s First Line I have run into numerous situations in which it has been useful to read only the first line of file. This first line might tell my code what type of script is being run, provide XML prolog information, or other interesting overview data of a file’s contents. Guava makes it easy to retrieve just the first line with the Files.readFirstLine(File,Charset) method. This is demonstrated in the next code listing.Demonstrating Files.readFirstLine(File,Charset)/** * Demonstrate extracting first line of file. * * @param fileName File from which first line is to be extracted. */ public void demoRetrievingFirstLineFromFile(final String fileName) { final File file = new File(fileName); try { final String line = Files.readFirstLine(file, Charset.defaultCharset()); out.println('First line of '' + fileName + '' is '' + line + ''.'); } catch (IOException fileIoEx) { err.println( 'ERROR trying to retrieve first line of file '' + fileName + '' - ' + fileIoEx.toString()); } }There’s Much More Although I have discussed and demonstrated several useful Files methods in this post, the class has many more to offer. Some of these include the ability to append to an existing file with Files.append(CharSequence,File,Charset), getting a file’s checksum with Files.getChecksum(File,Checksum), getting a file’s digest with Files.getDigest(File,MessageDigest), accessing a BufferedReader with Files.newReader(File,Charset), accessing a BufferedWriter with Files.newWriter(File,Charset), and accessing a MappedByteBuffer mapped to an underlying file via overloaded methods.Conclusion File handling in Java is much easier and more convenient with Guava’s Files class. Guava brings file-handling convenience to Java applications that cannot make use of Groovy’s or Java SE 7’s file handling conveniences. Happy coding and don’t forget to share! Reference: File Management in Java with Guava’s Files Class from our JCG partner Dustin Marx at the Inspired by Actual Events blog....
Java Code Geeks and all content copyright © 2010-2015, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

Get ready to Rock!
To download the books, please verify your email address by following the instructions found on the email we just sent you.