Featured FREE Whitepapers

What's New Here?

software-development-2-logo

How To Remove Friction From Your Version Control Experience

Last week, I spend several days fixing a bug that only surfaced in a distributed environment.I felt pressure to fix it quickly, because our continuous integration build was red, and we treat that as a “stop the line” event. Then I came across a post from Tomasz Nurkiewicz who claims that breaking the build is not a crime. Tomasz argues that a better way to organize software development is to make sure that breaking changes don’t affect your team mates. I agree. Broken Builds Create Friction Breaking changes from your co-workers are a form of friction, since they take away time and focus from your job. Tomasz’ setup has less friction than ours. But I feel we   can do better still. In a perfect Frictionless Development Environment (FDE), all friction is removed. So what would that look like with regard to version control? With current version control systems, there is lots of friction. I complained about Perforce before because of that. Git is much better, but even then there are steps that have to be performed that take away focus from the real goal you’re trying to achieve: solving the customer’s problem using software. For instance, you still have to create a new topic branch to work on. And you have to merge it with the main development line. In a perfect world, we wouldn’t have to do that. Frictionless Version Control So how would a Frictionless Development Environment do version control for us? Knowing when to create a branch is easy. All work happens on a topic branch, so every time you start to work on something, the FDE could create a new branch. The problem is knowing when to merge. But even this is not as hard as it seems. You’re done with your current work item (user story or whatever you want to call it) when it’s coded, all the tests pass, and the code is clean. So how would the FDE know when you’re done thinking of new tests for the story? Well, if you practice Behavior-Driven Development (BDD), you start out with defining the behavior of the story in automated tests. So the story is functionally complete when there is a BDD test for it, and all scenarios in that test pass. Now we’re left with figuring out when the code is clean. Most teams have a process for deciding this too. For instance, code is clean when static code analysis tools like PMD, CheckStyle, and FindBugs give no warnings. Some people will argue that we need a minimum amount of code coverage from our tests as well. Or that the code needs to be reviewed by a co-worker. Or that Fortify must not find security vulnerabilities. That’s fine. The basic point is that we can formally define a pipeline of processes that we want to run automatically. At each stage of the pipeline can we reject the work. Only when all stages complete successfully, are we done. And then the FDE can simply merge the branch with the main line, and delete it. Zero friction from version control. What do you think? Would you like to lubricate your version control experience? Do you think an automated branching strategy as outlined above would work?   Reference: How To Remove Friction From Your Version Control Experience from our JCG partner Remon Sinnema at the Secure Software Development blog. ...
career-logo

Traditional Programming Language Job Trends – 2013-02

The winter edition of the job trends are back! Today, we are looking at traditional programming languages, which currently include Java, C++, C#, Objective C, Perl and Visual Basic. After this months job trends are posted, I will be reviewing all of the posts and the languages included. I believe some change is needed, so hopefully we will see some change in the summer edition. As always, please review some of the other job trends posts to see if your favorite language is already in one of these posts.             First, we look at the job trends from Indeed.com:Most of the job trends have continued to decline for about a year. Oddly, the one language that looks to have grown during the past year was Visual Basic. VB is showing more demand now than it has in over seven years. Objective-C has a fairly flat trend for the past year, while the others show declining trends. Java shows a significant drop in the past six months, returning to job levels from 2008. Perl has dipped below Visual Basic for the first time in over six years. C# and C++ show almost identical trends and demand. Now, let’s look at SimplyHired’s short term trends:SimplyHired’s trends differ greatly from Indeed’s. Overall, these trends are fairly flat, with a slight rebound towards the end of last year. Objective-C does not show much growth during 2012, except at the very beginning of the year. Java leads the rebound at the end of the year, showing more growth than the other languages, but still less demand than in February 2012. C++ and C# continue their twin trends, showing almost identical demand. Perl barely stays ahead of Visual Basic, and both showing slight growth in the end. If we ignore the hiccups prior to February, all of the trends seem to be flat for the year. Finally, here is a review of the relative scaling from Indeed, which provides an interesting perspective on relative job growth:Surprisingly, Objective-C growth slowed significantly during the past six months. However, slowing from over 700% to about 550% is not a terrible decline. C# growth is also slowing significantly, dropping below 100% for the first time in over 4 years. Interestingly, Perl and Java are showing similar declining growth trends, with current growth dropping to the same level as 2006. Visual Basic seems to have held steady at slightly positive growth, while C++ continues to decline. What does all this mean? There has been a definite slowdown in demand in the past year. Given the growth of mobile, this is very surprising due to the leading mobile development languages being Java and Objective-C. What we could be seeing is the true rise of web development, which allow companies to use a much greater breadth of languages than before. Java and Perl are not required knowledge when writing for the web, and the continued decline of languages like C++ and C# point to the same possible conclusion. Being a true polyglot, meaning developing in multiple languages during the same project, may soon become a requirement. We will likely see more evidence of this when we look at the web and scripting languages in the next job trends installment. Related articlesDoes The World Still Need Visual Basic? (pluralsight.com) Job Trends Via Twitter Activity (i-programmer.info) Reflecting On Programming Language Trends (dorai.me)  Reference: Traditional Programming Language Job Trends – 2013-02 from our JCG partner Rob Diana at the Regular Geek blog. ...
java-logo

Analysing a Java Core Dump

In this post, I will show you how you can debug a Java core file to see what caused your JVM to crash. I will be using a core file I generated in my previous post: Generating a Java Core Dump. There are different ways you can diagnose a JVM crash, listed below: The hs_err_pid log file When a fatal error occurs in the JVM, it produces an error log file called hs_err_pidXXXX.log, normally in the working directory of the process or in the temporary directory for the operating system. The top of this file contains the cause of the crash and the ‘problematic frame’. For example, mine shows: $ head hs_err_pid21178.log # # A fatal error has been detected by the Java Runtime Environment: # # SIGSEGV (0xb) at pc=0x0000002b1d00075c, pid=21178, tid=1076017504 # # JRE version: 6.0_21-b06 # Java VM: Java HotSpot(TM) 64-Bit Server VM (17.0-b16 mixed mode linux-amd64 ) # Problematic frame: # C [libnativelib.so+0x75c] bar+0x10 # There is also a stack trace: Stack: [0x000000004012b000,0x000000004022c000], sp=0x000000004022aac0, free space=3fe0000000000000018k Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code) C [libnativelib.so+0x75c] bar+0x10 C [libnativelib.so+0x772] foo+0xe C [libnativelib.so+0x78e] Java_CoreDumper_core+0x1a j CoreDumper.core()V+0 j CoreDumper.main([Ljava/lang/String;)V+7 v ~StubRoutines::call_stub V [libjvm.so+0x3e756d] The stack trace shows that my java method, CoreDumper.core(), called into JNI and died when the bar function was called in native code. Debugging a Java Core Dump In some cases, the JVM may not produce a hs_err_pid file, for example, if the native code abruptly aborts by calling the abort function. In such cases, we need to analyse the core file produced. On my machine, the operating system writes out core files to /var/tmp/cores. You can use the following command to see where your system is configured to write out core files to: $ cat /proc/sys/kernel/core_pattern /var/tmp/cores/%e.%p.%u.core $ ls /var/tmp/cores java.21178.146385.core There are a few, different ways to look at core dumps: 1. Using gdb GNU Debugger (gdb) can examine a core file and work out what the program was doing when it crashed. $ gdb $JAVA_HOME/bin/java /var/tmp/cores/java.14015.146385.core (gdb) where #0 0x0000002a959bd26d in raise () from /lib64/tls/libc.so.6 #1 0x0000002a959bea6e in abort () from /lib64/tls/libc.so.6 #2 0x0000002b1cecf799 in bar () from libnativelib.so #3 0x0000002b1cecf7a7 in foo () from libnativelib.so #4 0x0000002b1cecf7c3 in Java_CoreDumper_core () from libnativelib.so #5 0x0000002a971aac88 in ?? () #6 0x0000000040113800 in ?? () #7 0x0000002a9719fa42 in ?? () #8 0x000000004022ab10 in ?? () #9 0x0000002a9a4d5488 in ?? () #10 0x000000004022ab70 in ?? () #11 0x0000002a9a4d59c8 in ?? () #12 0x0000000000000000 in ?? () The where command prints the stack frames and shows that the bar function called abort() which caused the crash. 2. Using jstack jstack prints stack traces of Java threads for a given core file. $ jstack -J-d64 $JAVA_HOME/bin/java /var/tmp/cores/java.14015.146385.core Debugger attached successfully. Server compiler detected. JVM version is 17.0-b16 Deadlock Detection:No deadlocks found.Thread 16788: (state = BLOCKED)Thread 16787: (state = BLOCKED) - java.lang.Object.wait(long) @bci=0 (Interpreted frame) - java.lang.ref.ReferenceQueue.remove(long) @bci=44, line=118 (Interpreted frame) - java.lang.ref.ReferenceQueue.remove() @bci=2, line=134 (Interpreted frame) - java.lang.ref.Finalizer$FinalizerThread.run() @bci=3, line=159 (Interpreted frame)Thread 16786: (state = BLOCKED) - java.lang.Object.wait(long) @bci=0 (Interpreted frame) - java.lang.Object.wait() @bci=2, line=485 (Interpreted frame) - java.lang.ref.Reference$ReferenceHandler.run() @bci=46, line=116 (Interpreted frame)Thread 16780: (state = IN_NATIVE) - CoreDumper.core() @bci=0 (Interpreted frame) - CoreDumper.main(java.lang.String[]) @bci=7, line=12 (Interpreted frame) 3. Using jmap jmap examines a core file and prints out shared object memory maps or heap memory details. $ jmap -J-d64 $JAVA_HOME/bin/java /var/tmp/cores/java.14015.146385.core Debugger attached successfully. Server compiler detected. JVM version is 17.0-b16 0x0000000040000000 49K /usr/sunjdk/1.6.0_21/bin/java 0x0000002a9566c000 124K /lib64/tls/libpthread.so.0 0x0000002a95782000 47K /usr/sunjdk/1.6.0_21/jre/lib/amd64/jli/libjli.so 0x0000002a9588c000 16K /lib64/libdl.so.2 0x0000002a9598f000 1593K /lib64/tls/libc.so.6 0x0000002a95556000 110K /lib64/ld-linux-x86-64.so.2 0x0000002a95bca000 11443K /usr/sunjdk/1.6.0_21/jre/lib/amd64/server/libjvm.so 0x0000002a96699000 625K /lib64/tls/libm.so.6 0x0000002a9681f000 56K /lib64/tls/librt.so.1 0x0000002a96939000 65K /usr/sunjdk/1.6.0_21/jre/lib/amd64/libverify.so 0x0000002a96a48000 228K /usr/sunjdk/1.6.0_21/jre/lib/amd64/libjava.so 0x0000002a96b9e000 109K /lib64/libnsl.so.1 0x0000002a96cb6000 54K /usr/sunjdk/1.6.0_21/jre/lib/amd64/native_threads/libhpi.so 0x0000002a96de8000 57K /lib64/libnss_files.so.2 0x0000002a96ef4000 551K /lib64/libnss_db.so.2 0x0000002a97086000 89K /usr/sunjdk/1.6.0_21/jre/lib/amd64/libzip.so 0x0000002b1cecf000 6K /home/sharfah/tmp/jni/libnativelib.so Useful Links: Crash course on JVM crash analysis Generating a Java Core Dump   Reference: Analysing a Java Core Dump from our JCG partner Fahd Shariff at the fahd.blog blog. ...
couchbase-logo

Introduction to Collated Views with Couchbase 2.0

Most of the applications have to deal with ‘master/detail’ type of data:breweries and beer department and employees invoices and items …This is necessary for example to create application view like the following:        With Couchbase, and many of the document oriented databases you have different ways to deal with this, you can:Create a single document for each master and embed all the children in it Create a master and child documents and link them using an attribute.In the first case when all the information are stored in a single document it is quite easy to use the entire set of data and for example create a screen that shows all the information, but what about the second case? In this post I am explaining how it is possible to use Couchbase views to deal with that an make it easy to create master/detail views. As an ex-Oracle employee, I am using the infamous SCOTT schema with the DEPT and EMP tables, as the first example. Then at the end I will extend this to the beer sample data provided with Couchbase. The Data Couchbase is a schema-less database, and you can store “anything you want” into it, but for this you need to use JSON documents and create 2 types of document : “department” and “employee”. The way we usually do that is using a technical attribute to type the document. So the employee and department document will look as follow : Department { 'type': 'dept', 'id': 10, 'name': 'Accounting', 'city': 'New York' } Employee { 'type': 'emp', 'id': 7782, 'name': 'Blake', 'job': 'Clark', 'manager': 7839, 'salary': 2450, 'dept_id': 'dept__10' } This shows just the document, in Couchbase you have to associate a document to a key. For this example I am using a simple pattern : type__id , for these documents the keys will look like the following:dept__10 emp__20You can use any pattern to create a key, for example for the employee you could chose to put an email. Note the “dept_id” attribute in the employee document. This is the key of the department; you can see that as the “foreign key”. But remember, the relationship between the department and employee documents are managed entirely by the application, Couchbase Server does not enforce it. I have created a Zip file that contains all the data, you can download it from here; and import the data into Couchbase using the cbdocloader utility. To import the data run the following command from a terminal window: ./cbdocloader -n 127.0.0.1:8091 -u Administrator -p password -b default ~/Downloads/emp-dept.zip You can learn more about the cbdocloader tool in the documentation. The View Queries inside Couchbase are based on views; and views build indexes, so we have to create a view, a ‘collated view’ to be exact. The idea behing a collated view is to produce an index where the keys are ordered so that a parent id appears first followed by its children. So we are generating an index that will look like: DEPT_10, Accounting DEPT_10, Blake DEPT_10, Miller DEPT_20, Research DEPT_20, Adams DEPT_20, Ford … This is in fact quite easy to do with Couchbase views. The only trick here is to control the order and be sure the master is always the first one, just before its children. So to control this we can create an compound key that contains the department id, a ‘sorting’ element and the name (beer or brewery). So the map function of the view looks like the following: function (doc, meta) { if (doc.type == "emp" || doc.type == "dept") { switch(doc.type) { case "dept" : emit( [meta.id, 0, doc.name], 0 ); break; case "emp" : emit( [doc.dept_id, 1, doc.name ], doc.salary + ((doc.comm)?doc.comm:0) ); break; } } } The key is composed of:the department id extracted from the department document itself or from the employee document depending of the type of document an arbitrary number that is used to control the ordering. I put 0 for the department, 1 for the employee the name of the department or the employee, this also allows to sort the result by nameIn addition to the key, this view is used to emit some information about the salary of the employees. The salary is simply the sum of the salary plus the commission when exists. The result of the view looks like:With this view you can now use the result of the view to build report for your application. It is also possible to use parameters in your query to see only a part of the data, for example by departement, using for example startkey=[‘dept__20′,0]&endkey=[‘dept__20′,2] to view only the data -Department and Employees- of the deparment 20-Research. The Beer Sample Application You can create an equivalent view for the beer sample application where you print all the breweries and beers in the same report. The view is called ‘all_with_beers’ in the design document ‘brewery’. The view looks like: function(doc, meta) { switch(doc.type) { case "brewery": emit([meta.id, 0, doc.name]); break; case "beer": if (doc.name && doc.brewery_id) { emit([doc.brewery_id, 1, doc.name], null); } } } Once you have publish it in production you can use it in the Beer Sample application, for this example I have modified the Java sample application. Create a servlet to handle user request and on the /all URI. The ‘BreweryAndBeerServlet’ that calls the view using the following code : View view = client.getView("brewery", "all_with_beers"); Query query = new Query(); query.setIncludeDocs(true).setLimit(100); ViewResponse result = client.query(view, query);ArrayList<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>(); for(ViewRow row : result) { HashMap<String, String> parsedDoc = gson.fromJson( (String)row.getDocument(), HashMap.class);HashMap<String, String> item = new HashMap<String, String>(); item.put("id", row.getId()); item.put("name", parsedDoc.get("name")); item.put("type", parsedDoc.get("type"));items.add(item); } request.setAttribute("items", items);request.getRequestDispatcher("/WEB-INF/breweries/all.jsp") .forward(request, response); The result of the query is set into the HttpRequest and the all.jsp page is executed. The JSP uses JSTL to print the information using the following code: <table id="brewery-table" class="table table-striped"> <thead> <tr> <th>Name</th> <th></th> <th></th> </tr> </thead> <tbody> <c:forEach items="${items}" var="item"> <c:if test="${ item.type == 'brewery' }"> <tr> <td colspan="2"><strong><a href="/breweries/show/${item.id}">${item.name}</a></strong></td> <td><a class="btn btn-small btn-danger" href="/breweries/delete/${item.id}">Delete</a> </td> </tr> </c:if> <c:if test="${ item.type == 'beer' }"> <tr> <td></td> <td><a href="/beers/show/${item.id}">${item.name}</a></td> <td> <a class="btn btn-small btn-danger" href="/beers/delete/${item.id}">Delete</a> <a class="btn btn-small btn-warning" href="/beers/edit/${item.id}">Edit</a> </td> </tr> </c:if> </c:forEach> </tbody> </table> The JSP gets the items from the HTTP Request and loops on each items, then based on the type of the item the information is printed. The final result looks like :This extension to the Beer Sample application is available here : https://github.com/tgrall/beersample-java/tree/BreweriesAndBeers   Reference: Introduction to Collated Views with Couchbase 2.0 from our JCG partner Tugdual Grall at the Tug’s Blog blog. ...
jsf-logo

JSF – Eager CDI beans

Everybody knows eager managed beans in JSF 2. @ManagedBean has an eager attribute. If eager=’true’ and the scope is application, then this bean must be created when the application starts and not during the first reference to the bean. This is a nice feature when you want to load application scoped data (e.g. some select items for menus) during application startup in order to increase the performance at runtime.             @ManagedBean(eager=true) @ApplicationScoped public class GlobalBean { ... } @ManagedBean annotation will be deprecated with JSF 2.2. It is highly recommended to use CDI (context dependency injection) beans in JEE environment. But what is the equivalent to the eager managed beans in CDI? Well, CDI is flexible, you can write portable CDI extensions. I asked Thomas Andraschko how to do this. Thomas is a CDI expert, co-owner of PrimeFaces Extensions and the committer in OpenWebBeans (OWB) project. His tip was to implement such extension as follows: @Qualifier @Retention(RetentionPolicy.RUNTIME) @Target({TYPE}) public @interface Eager { } package mydomain.mypackage;import java.util.ArrayList; import java.util.List; import javax.enterprise.context.ApplicationScoped; import javax.enterprise.event.Observes; import javax.enterprise.inject.spi.AfterDeploymentValidation; import javax.enterprise.inject.spi.Bean; import javax.enterprise.inject.spi.BeanManager; import javax.enterprise.inject.spi.Extension; import javax.enterprise.inject.spi.ProcessBean;public class EagerExtension implements Extension { private List<Bean<?>> eagerBeansList = new ArrayList<Bean<?>>();public <T> void collect(@Observes ProcessBean<T> event) { if (event.getAnnotated().isAnnotationPresent(Eager.class) && event.getAnnotated().isAnnotationPresent(ApplicationScoped.class)) { eagerBeansList.add(event.getBean()); } }public void load(@Observes AfterDeploymentValidation event, BeanManager beanManager) { for (Bean<?> bean : eagerBeansList) { // note: toString() is important to instantiate the bean beanManager.getReference(bean, bean.getBeanClass(), beanManager.createCreationalContext(bean)).toString(); } } } The extensions should be registered in a file META-INF/services/javax.enterprise.inject.spi.Extension. The file has only one line with a fully qualified path to the EagerExtension class, e.g. mydomain.mypackage.EagerExtension. Using is simple. Assume, we have an application scoped LayoutController CDI bean which is responsible for the entire layout configration. We can annotate it with @Eager and speed up the layout creation. @ApplicationScoped @Eager @Named public class LayoutController implements Serializable { private LayoutOptions layoutOptions;@PostConstruct protected void initialize() { layoutOptions = new LayoutOptions();LayoutOptions panes = new LayoutOptions(); panes.addOption('slidable', false); panes.addOption('spacing', 6); layoutOptions.setPanesOptions(panes);... }public LayoutOptions getLayoutOptions() { return layoutOptions; } } Have fun with CDI!   Reference: JSF – Eager CDI beans from our JCG partner Oleg Varaksin at the Thoughts on software development blog. ...
java-logo

JavaFX: Space Invaders in less than 175 LOC

With the current version of the API I’m at less than 175 LOC for Space Invaders. I’ve got lot’s of “Functional Interfaces” in my APIs that can be converted to Lambda Expressions with JavaFX 8( e.g. SpriteProvider and CollisionHandler). That will make the code nicer and shorter. I could probably also reduce the linecount by bundling the recources (e.g. TileSets) and creating more factories and Builders (SpriteBuilder). But I’m getting closer to what I want…           package de.eppleton.fx2d.samples.spaceinvaders;import de.eppleton.fx2d.collision.*; import de.eppleton.fx2d.*; import de.eppleton.fx2d.action.*; import de.eppleton.fx2d.tileengine.*; import java.util.Collection; import java.util.logging.*; import javafx.beans.property.DoubleProperty; import javafx.beans.property.SimpleDoubleProperty; import javafx.scene.canvas.*; import javafx.scene.input.*; import javafx.scene.media.*; import javafx.scene.paint.Color; import javafx.scene.text.Font; import javax.xml.bind.JAXBException; import org.openide.util.Lookup; import org.openide.util.lookup.Lookups;public class SpaceInvaders extends Game {Points TEN = new Points(10); Points TWENTY = new Points(30); Points THIRTY = new Points(40); DoubleProperty invaderXVelocity = new SimpleDoubleProperty(0.3); AudioClip shootSound = new AudioClip(SpaceInvaders.class.getResource('/assets/sound/shoot.wav').toString()); AudioClip invaderKilledSound = new AudioClip(SpaceInvaders.class.getResource('/assets/sound/invaderkilled.wav').toString()); MediaPlayer mediaPlayer = new MediaPlayer(new Media(SpaceInvaders.class.getResource('/assets/sound/invader_loop1.mp3').toString())); int score = 0; String message; int[][] enemies = new int[][]{ {30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30}, {20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20}, {20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20}, {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10}, {10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10} };@Override protected void initGame() { final GameCanvas canvas = getCanvas(); try { TileSet invaders = TileMapReader.readSet('/assets/graphics/invaders1.tsx'); TileSet playerTiles = TileMapReader.readSet('/assets/graphics/player.tsx'); final TileSetAnimation animation30 = new TileSetAnimation(invaders, new int[]{0, 1}, 2); final TileSetAnimation animation10 = new TileSetAnimation(invaders, new int[]{4, 5}, 2); final TileSetAnimation animation20 = new TileSetAnimation(invaders, new int[]{2, 3}, 2); final TileSetAnimation playerAnimation = new TileSetAnimation(playerTiles, new int[]{0}, 100_000); for (int i = 0; i < enemies.length; i++) { int[] is = enemies[i]; for (int j = 0; j < is.length; j++) { Points points = is[j] == 30 ? THIRTY : is[j] == 20 ? TWENTY : TEN; Sprite sprite = new Sprite(canvas, '' + ((j * 11) + i), 50 + (40 * j), 140 + (40 * i), 30, 20, Lookups.fixed(points)); sprite.setAnimation(is[j] == 30 ? animation30 : is[j] == 20 ? animation20 : animation10); sprite.setVelocityXProperty(invaderXVelocity); } } Sprite player = new Sprite(canvas, playerAnimation, 'Player', 350, 620, 40, 30, Lookup.EMPTY); player.setAnimation(playerAnimation); player.addAction(KeyCode.LEFT, ActionFactory.createMoveAction(playerAnimation, 'left', -4, 0, 0, 0)); player.addAction(KeyCode.RIGHT, ActionFactory.createMoveAction(playerAnimation, 'right', 4, 0, 0, 0)); player.addAction(KeyCode.UP, new ShootAction(playerAnimation, 'fire', new BulletProvider(), new HitHandler(), shootSound)); } catch (JAXBException ex) { Logger.getLogger(SpaceInvaders.class.getName()).log(Level.SEVERE, null, ex); } canvas.addLayer(new Background()); canvas.addBehaviour(new MoveInvadersBehavior()); mediaPlayer.setCycleCount(MediaPlayer.INDEFINITE); mediaPlayer.play(); canvas.addLayer(new SpriteLayer()); canvas.start(); }@Override protected double getViewPortWidth() { return 700; }@Override protected double getViewPortHeight() { return 700; }public static void main(String[] args) { launch(args); }private class Points {int points;public Points(int points) { this.points = points; }public int getPoints() { return points; } }static class BulletProvider implements SpriteProvider {@Override public Sprite getSprite(GameCanvas parent, double x, double y) { return new Sprite(parent, 'bullet', x, y + 10, 10, 20, Lookup.EMPTY); } }class HitHandler implements CollisionHandler {@Override public void handleCollision(Collision collision) { Points points = collision.getSpriteTwo().getLookup().lookup(Points.class); if (points != null) { score += points.getPoints(); invaderKilledSound.play(); collision.getSpriteOne().remove(); collision.getSpriteTwo().remove(); } } }class MoveInvadersBehavior extends Behavior {@Override public boolean perform(GameCanvas canvas, long nanos) { Collection<Sprite> sprites = canvas.getSprites(); boolean stop = false; boolean win = true; for (Sprite sprite1 : sprites) { if (sprite1.getLookup().lookup(Points.class) != null) { win = false; if (sprite1.getX() > 650 || sprite1.getX() < 50) { invaderXVelocity.set(-invaderXVelocity.doubleValue() * (stop ? 0 : 1.3)); if (sprite1.getY() >= 600) { message = 'Game Over!'; stop = true; mediaPlayer.stop(); } for (Sprite sprite2 : sprites) { if (sprite2.getLookup().lookup(Points.class) != null) { sprite2.setY(sprite2.getY() + (stop ? 0 : 20)); } } break; } } } if (win) { message = 'You win!'; canvas.stop(); mediaPlayer.stop(); } return true; } }class Background extends Layer {@Override public void draw(GraphicsContext graphicsContext, double x, double y, double width, double height) { graphicsContext.setFill(Color.BLACK); graphicsContext.fillRect(0, 0, width, height); graphicsContext.setFill(Color.WHITE); graphicsContext.setFont(Font.font('OCR A Std', 20)); graphicsContext.fillText('SCORE<1> HI-SCORE SCORE<2>', 30, 30); graphicsContext.fillText('' + score + ' 9990 ', 30, 60); graphicsContext.fillText(message, 300, 400); graphicsContext.fillText('' + 3 + ' CREDIT ' + 1, 30, 680); graphicsContext.setFill(Color.GREEN); graphicsContext.fillRect(30, 650, 640, 4); } } } Here’s a video of the game:  Reference: JavaFX: Space Invaders in less than 175 LOC from our JCG partner Toni Epple at the Eppleton blog. ...
java-logo

Styling JavaFX Pie Chart with CSS

JavaFX provides certain colors by default when rendering charts. There are situations, however, when one wants to customize these colors. In this blog post I look at changing the colors of a JavaFX pie chart using an example I intend to include in my presentation this afternoon at RMOUG Training Days 2013. Some Java-based charting APIs provided Java methods to set colors. JavaFX, born in the days of HTML5 prevalence, instead uses Cascading Style Sheets (CSS) to allow developers to adjust colors, symbols, placement, alignment and other stylistic issues used in their charts. I demonstrate using CSS to change colors here. In this post, I will look at two code samples demonstrating simple JavaFX applications that render pie charts based on data from Oracle’s sample ‘hr’ schema. The first   example does not specify colors and so uses JavaFX’s default colors for pie slices and for the legend background. That example is shown next. EmployeesPerDepartmentPieChart (Default JavaFX Styling) package rmoug.td2013.dustin.examples;import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.chart.PieChart; import javafx.scene.layout.StackPane; import javafx.stage.Stage;/** * Simple JavaFX application that generates a JavaFX-based Pie Chart representing * the number of employees per department. * * @author Dustin */ public class EmployeesPerDepartmentPieChart extends Application { final DbAccess databaseAccess = DbAccess.newInstance();@Override public void start(final Stage stage) throws Exception { final PieChart pieChart = new PieChart( ChartMaker.createPieChartDataForNumberEmployeesPerDepartment( this.databaseAccess.getNumberOfEmployeesPerDepartmentName())); pieChart.setTitle('Number of Employees per Department'); stage.setTitle('Employees Per Department'); final StackPane root = new StackPane(); root.getChildren().add(pieChart); final Scene scene = new Scene(root, 800 ,500); stage.setScene(scene); stage.show(); }public static void main(final String[] arguments) { launch(arguments); } } When the above simple application is executed, the output shown in the next screen snapshot appears.I am now going to adapt the above example to use a custom ‘theme’ of blue-inspired pie slices with a brown background on the legend. Only one line is needed in the Java code to include the CSS file that has the stylistic specifics for the chart. In this case, I added several more lines to catch and print out any exception that might occur while trying to load the CSS file. With this approach, any problems loading the CSS file will lead simply to output to standard error stating the problem and the application will run with its normal default colors. EmployeesPerDepartmentPieChartWithCssStyling (Customized CSS Styling) package rmoug.td2013.dustin.examples;import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.chart.PieChart; import javafx.scene.layout.StackPane; import javafx.stage.Stage;/** * Simple JavaFX application that generates a JavaFX-based Pie Chart representing * the number of employees per department and using style based on that provided * in CSS stylesheet chart.css. * * @author Dustin */ public class EmployeesPerDepartmentPieChartWithCssStyling extends Application { final DbAccess databaseAccess = DbAccess.newInstance();@Override public void start(final Stage stage) throws Exception { final PieChart pieChart = new PieChart( ChartMaker.createPieChartDataForNumberEmployeesPerDepartment( this.databaseAccess.getNumberOfEmployeesPerDepartmentName())); pieChart.setTitle('Number of Employees per Department'); stage.setTitle('Employees Per Department'); final StackPane root = new StackPane(); root.getChildren().add(pieChart); final Scene scene = new Scene(root, 800 ,500); try { scene.getStylesheets().add('chart.css'); } catch (Exception ex) { System.err.println('Cannot acquire stylesheet: ' + ex.toString()); } stage.setScene(scene); stage.show(); }public static void main(final String[] arguments) { launch(arguments); } } The chart.css file is shown next: chart.css /* Find more details on JavaFX supported named colors athttp://docs.oracle.com/javafx/2/api/javafx/scene/doc-files/cssref.html#typecolor*//* Colors of JavaFX pie chart slices. */ .data0.chart-pie { -fx-pie-color: turquoise; } .data1.chart-pie { -fx-pie-color: aquamarine; } .data2.chart-pie { -fx-pie-color: cornflowerblue; } .data3.chart-pie { -fx-pie-color: blue; } .data4.chart-pie { -fx-pie-color: cadetblue; } .data5.chart-pie { -fx-pie-color: navy; } .data6.chart-pie { -fx-pie-color: deepskyblue; } .data7.chart-pie { -fx-pie-color: cyan; } .data8.chart-pie { -fx-pie-color: steelblue; } .data9.chart-pie { -fx-pie-color: teal; } .data10.chart-pie { -fx-pie-color: royalblue; } .data11.chart-pie { -fx-pie-color: dodgerblue; }/* Pie Chart legend background color and stroke. */ .chart-legend { -fx-background-color: sienna; } Running this CSS-styled example leads to output as shown in the next screen snapshot. The slices are different shades of blue and the legend’s background is ‘sienna.’ Note that while I used JavaFX ‘named colors,’ I could have also used ‘#0000ff’ for blue, for example.I did not show the code here for my convenience classes ChartMaker and DbAccess. The latter simply retrieves the data for the charts from the Oracle database schema via JDBC and the former converts that data into the Observable collections appropriate for the PieChart(ObservableList) constructor. It is important to note here that, as Andres Almiray has pointed out, it is not normally appropriate to execute long-running processes from the main JavaFX UI thread (AKA JavaFX Application Thread) as I’ve done in this and other other blog post examples. I can get away with it in these posts because the examples are simple, the database retrieval is quick, and there is not much more to the chart rendering application than that rendering so it is difficult to observe any ‘hanging.’ In a future blog post, I intend to look at the better way of handling the database access (or any long-running action) using the JavaFX javafx.concurrent package (which is well already well described in Concurrency in JavaFX). JavaFX allows developers to control much more than simply chart colors with CSS. Two very useful resources detailing what can be done to style JavaFX charts with CSS are the Using JavaFX Charts section Styling Charts with CSS and the JavaFX CSS Reference Guide. CSS is becoming increasingly popular as an approach to styling web and mobile applications. By supporting CSS styling in JavaFX, the same styles can easily be applied to JavaFX apps as the HTML-based applications they might coexist with.   Reference: Styling JavaFX Pie Chart with CSS from our JCG partner Dustin Marx at the Inspired by Actual Events blog. ...
devops-logo

Releasing more often drives better Dev and better Ops

One of the most important decisions that we made as a company was to release less software, more often. After we went live, we tried to deliver updates quarterly, because until then we had followed a staged delivery lifecycle to build the system, with analysis and architecture upfront, and design and development and testing done in 3-month phases. But this approach didn’t work once the system was running. Priorities kept changing as we got more feedback from more customers, too many things needed to fixed or tuned right away, and we had to deal with urgent operational issues. We kept interrupting development to deploy interim releases and patches and then re-plan and re-plan again, wasting everyone’s time and making it harder to keep track of what we needed to do. Developers and ops were busy getting customers on and fire fighting which meant we couldn’t get changes out when we needed to. So we decided to   shorten the release cycle down from 3 months to 1 month, and then shorten it down again to 3 weeks and then 2 weeks, making the releases smaller and more focused and easier to manage. Smaller, more frequent releases changes how Development is done Delivering less but more often, whether you are doing it to reduce time-to-market and get fast feedback in a startup, or to contain risk and manage change in an enterprise, forces you to reconsider how you develop software. It changes how you plan and estimate and how you think about risks and how you manage risks. It changes how you do design, and how much design you need to do. It changes how you test. It changes what tools people need, and how much they need to rely on tools. It changes your priorities. It changes the way that people work together and how they work with the customer, creating more opportunities and more reasons to talk to each other and learn from each other. It changes the way that people think and act – because they have to think and act differently in order to keep up and still do a good job. Smaller, more frequent releases changes how Development and Ops work together Changing how often you release and deploy will also change how operations works and how developers and operations work together. There’s not enough time for heavyweight release management and change control with lots of meetings and paperwork. You need an approach that is easier and cheaper. But changing things more often also means more chances to make mistakes. So you need an approach that will reduce risk and catch problems early. Development teams that release software once a year or so won’t spend a lot of time thinking about release and deployment and operations stuff in general because they don’t have to. But if they’re deploying every couple of weeks, if they’re constantly having to push software out, then it makes sense for them to take the time to understand what production actually looks like and make deployment – and roll-back – easier on them and easier on ops. You don’t have to automate everything to start – and you probably shouldn’t until you understand the problems well enough. We started with check lists and scripting and manual configuration and manual system tests. We put everything under source control (not just code), and then started standardizing and automating deployment and configuration and roll-back steps, replacing manual work and check lists with automated audited commands and health checks. We’ve moved away from manual server setup and patching to managing infrastructure with Puppet. We’re still aligning test and production so that we can test more deployment steps more often with fewer production-specific changes. We still don’t have a one-button deploy and maybe never will, but release and deployment today is simpler and more standardized and safer and much less expensive. Deployment is just the start Improving deployment is just the start of a dialogue that can extend to the rest of operations. Because they’re working together more often, developers and ops will learn more about each other and start to understand each other’s languages and priorities and problems. To get this started, we encouraged people to read Visible Ops and sent ops and testers and some of the developers and even managers on ITIL Foundation training so that we all understood the differences between incident management and problem resolution, and how to do RCA, and the importance of proper change management – it was probably overkill but it made us all think about operations and take it seriously. We get developers and testers and operations staff together to plan and review releases, and to support production and in RCA whenever we have a serious problem, and we work together to figure out why things went wrong and what we can do to prevent them from happening again. Developers and ops pair up to investigate and solve operational problems and to improve how we design and roll out new architecture, and how we secure our systems and how we set up and manage development and test environments It sounds easy. It wasn’t. It took a while, and there were disagreements and problems and back sliding, like any time you fundamentally change the way that people work. But if you do this right, people will start to create connections and build relationships and eventually trust and transparency across groups – which is what Devops is really about. You don’t have to change your organization structure or overhaul the culture – in most cases, you won’t have this kind of mandate anyways. You don’t have to buy into Continuous Deployment or even Continuous Delivery, or infrastructure as code, or use Chef or Puppet or any other Devops tools – although tools do help. Once you start moving faster, from deploying once a year every few months to once a month and as your organization’s pace accelerates, people will change the way that they work because they have to. Today the way that we work, and the way that we think about development and operations, is much different and definitely healthier. We can respond to business changes and to problems faster, and at the same time our reliability record has improved dramatically. We didn’t set out to “be Agile” – it wasn’t until we were on our way to shorter release cycles that we looked more closely at Scrum and XP and later Kanban to see how these methods could help us develop software. And we weren’t trying to “do Devops” either – we were already down the path to better dev and ops collaboration before people started talking about these ideas at Velocity and wherever else. All we did was agree as a company to change how often we pushed software into production. And that has made all the difference.   Reference: Releasing more often drives better Dev and better Ops from our JCG partner Jim Bird at the Building Real Software blog. ...
software-development-2-logo

Java is dead (again)

Here is a couple of responses to this annual question I thought worth sharing: The Day Java lost the Battle There is a common myth amongst technologists that better technology will always be the most successful or that you must keep improving or die. A counter example I use is the QWERTY keyboard. No one who uses it, does so because it is a) natural or easy to learn b) faster to use c) newer or cooler than the alternatives. Yet many developers who couldn’t imagine using anything other than a qwerty keyboard insist that Java must be dead for these reasons. I have looked at predictions that Java is dead from the year 1996 and found these predictions follow Java’s popularity and when there was a drop interest due to the long age of Java 1.4 and Java 6, there was also a drop in predictions that Java is dead. (When IMHO that would have been a good time to question such things) I have come to the conclusion that passionate calls that Java is dead is a good sign that Java is alive and well and annoying developers who would prefer people used a “better” language. In a discussion on the same topic I added: Tiobe Index This table suggest Java has the highest interest of any language. (Possibly in part due to a security issue) Secondly, the other languages which are it’s main competition are both older and lower level. While there are many who would like to believe that higher level languages are winning, there isn’t any evidence this is the case. For example, the security hole was in using Java with medium security level (not the default) as an applet. While Java applet are not that popular, running ruby, php or python in a browser is far less popular. On a final note: Just because Java is popular, doesn’t make it the best, but conversely it’s failings are not  a good indication of the beginning of the end.  If you look at talent show winners, the most popular celebrities or election winners, you have to wonder what makes these people so special really.  It is not surprising you might think the same thing about Java, but just like popular people, what make a language popular is not purely a technical or rational argument.   Reference: Java is dead (again) from our JCG partner Peter Lawrey at the Vanilla Java blog. ...
java-logo

Testing Expected Exceptions with JUnit Rules

This post shows how to test for expected exceptions using JUnit. Let’s start with the following class that we wish to test:                   public class Person { private final String name; private final int age;/** * Creates a person with the specified name and age. * * @param name the name * @param age the age * @throws IllegalArgumentException if the age is not greater than zero */ public Person(String name, int age) { this.name = name; this.age = age; if (age <= 0) { throw new IllegalArgumentException('Invalid age:' + age); } } } In the example above, the Person constructor throws an IllegalArgumentException if the age of the person is not greater than zero. There are different ways to test this behaviour: Approach 1: Use the ExpectedException Rule This is my favourite approach. The ExpectedException rule allows you to specify, within your test, what exception you are expecting and even what the exception message is. This is shown below: import static org.hamcrest.Matchers.*; import static org.junit.Assert.*;import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException;public class PersonTest {@Rule public ExpectedException exception = ExpectedException.none();@Test public void testExpectedException() { exception.expect(IllegalArgumentException.class); exception.expectMessage(containsString('Invalid age')); new Person('Joe', -1); } } Approach 2: Specify the exception in the @Test annotation As shown in the code snippet below, you can specify the expected exception in the @Test annotation. The test will pass only if an exception of the specified class is thrown by the test method. Unfortunately, you can’t test the exception message with this approach. @Test(expected = IllegalArgumentException.class) public void testExpectedException2() { new Person('Joe', -1); } Approach 3: Use a try-catch block This is the ‘traditional’ approach which was used with old versions of JUnit, before the introduction of annotations and rules. Surround your code in a try-catch clause and test if the exception is thrown. Don’t forget to make the test fail if the exception is not thrown! @Test public void testExpectedException3() { try { new Person('Joe', -1); fail('Should have thrown an IllegalArgumentException because age is invalid!'); } catch (IllegalArgumentException e) { assertThat(e.getMessage(), containsString('Invalid age')); } }   Reference: Testing Expected Exceptions with JUnit Rules from our JCG partner Fahd Shariff at the fahd.blog 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 two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close