What's New Here?

json-logo

Android JSON Parsing with Gson Revisited

A while ago we hosted an article about using Gson for JSON parsing with Android. The tutorial was a simple showcase of how to leverage Gson with Android. Recently, Bill Mote from the AYDABTU Development site contacted me and informed me that he had used our sample code in one of his Android applications, namely Broadcast SMS. More specifically, he refined and improved the initial version in order to create a more robust parser. Let’s here what he has to say about his experience. I was in the midst of writing my first Android application and I wanted to make my app “phone home” to accomplish a few things: 1. I wanted it to display a Message Of The Day (MOTD) to inform my customers of relevant information or to simply say thank you for their support occasionally, 2. I wanted it to present a list of features available in newer releases than is currently installed by any given user and provide them a vehicle for upgrading and 3. I wanted to set a low-water mark to disable older versions of the application. A JSON web service seemed like the natural solution for this, but as I mentioned above, “I was writing my FIRST Android app.” ;) I stumbled upon your Android JSON parsing with GSON article. What a wonderful and timely find! I know the article was simply intended to get the user started. Almost all articles are written this way. I want to give something back so I’ve taken your original article and expounded on it by hardening the HTTP request and the actual parsing of the JSON. I’ve also made the entire thing run in an AsyncTask (background thread) to get it off the UI thread as any kind of network hiccup or a large JSON string could cause the UI to become unresponsive and generate an error. The full-on Try/Catch code can be found here: JSON Parsing Full Try-Catch. Improvements: * Runs as an AsyncTask to get it off the UI thread * Handles socket/network timeouts * Handles 404 errors * Handles JSON syntax errors Of note:Anything that can throw an exception has been surrounded by a try/catch block and the application has been built to handle a null return. I implemented an onStop() method to cancel the AsyncTask if the application should terminate as creating more than 1 AsyncTask will cause a force close. Notice that we check for ‘this.isCancelled()’ before we finish the doInBackground() method — You can force this by starting the application and hitting the back button quickly. You could grab the appropriate failure (aka catch()) and make the application retry on some period but that’s outside the scope of this example.So, after making this run in a background thread and creating all those layers of try/catch complexity it occurred to me that I don’t care why it failed. I just need to account for it. I talked this over with a friend of mine that has much more development experience and he agreed with my basic idea: wrap the basic functions with a try/catch block and account for it, but remove all the layers. That includes removing the HTTP status response because in this case we don’t care if it failed. We’re either going to see the list of names or we’re not. The simplified try-catch version of this code works in exactly the same way, but it’s less smart about why it had a problem. It can be found here: JSON Parsing Simplified Try-Catch. My app, Broadcast SMS, has benefited from numerous on-line examples and tutorials. JavaCodeGeeks article helped me implement a JSON string parser that is working perfectly. Many thanks to them and all those that publish their works for the masses. I hope you find my enhancements useful. Very nice, the enhancements helped create a more robust and less error-prone application. Thank you Bill. If you also have any improvements or additions you would like to contribute, please let shoot us an e-mail. Cheers! Related Articles :“Android Full Application Tutorial” series Android Location Based Services Application – GPS location Android Reverse Geocoding with Yahoo API – PlaceFinder Boost your Android XML parsing with XML Pull Android Text-To-Speech Application Install Android OS on your PC with VirtualBox...
google-app-engine-logo

Google App Engine: Host application in your own domain

When you create a new application in Google App Engine, you’ll get a domain name “yourapp.appspot.com”. But, who’ll want to host their app with such a suffix (unless you like it!)? To improve your app branding, the best thing to do is to host your app in “www.yourapp.com“. So, how to do this in App Engine? There are two ways.You can buy a new domain name with Google partnered sites. If you have already bought a domain, you can map that domain to “yourapp.appspot.com”.I’m going to explain the second method in this post. Steps to host GAE app in your own domain 1. Buy Hosting Space and Signup for Google AppsThe first step, obviously, is you should buy a domain + hosting. You will be adding CNAME entry in the DNS mapping to make things work and some hosting providers wont let you to add CNAME if you just bought only the domain name from them. So, it is good to buy the domain name as well as the hosting space so that you have full control over it. Then you need to signup for Google apps with your domain name. You can get a free Google Apps version which is pretty much sufficient for a small company/individual. You’ll be asked to verify the ownership of your domain. Just follow the steps given there. You’ll be also creating a admin account to manage Google Apps.2. Add your application to Google Apps accountNext, login to https://appengine.google.com and go to the Dashboard of your app and choose “Application Settings -> Domain Setup -> Add Domain“. In the “Add Domain” screen, enter your domain name. You’ll be asked to login to Google Apps with the admin account which you would have created during the second step. Once you login, your application will be added to your Google Apps account.3. Add ‘www.yourapp.com’ sub-domain mapping to yourapp.appspot.comNow login to www.google.com/a/yourapp.com with your admin account (if you are not logged in already). There you can see you app engine application listed in the Google Apps dashboard. Click on your appspot application. In the next screen, enter www in the text box to add a URL in the form of www.yourapp.com. As Google app engine does not support naked domains, you have to map the sub-domain, in our case www, to the appspot application. Once you add the URL you’ll be given steps to add the CNAME record in your domain. After adding the CNAME record (explained in next steps), you should come back to this page and click complete.4. Using CPanel, add a CNAME entry to ghs.google.comNow login to your domain admin panel. Since most of the hosting providers support CPanel, i’m giving the steps for CPanel. Login to yourapp.com/cpanel and go to “Advanced DNS Zone editor” where you can see the DNS mappings. Click the “Edit” link against the www.yourapp.com and type “ghs.google.com” against the CNAME field. Leave other fields as it is. Save the changes. Thats it. It will take some time for the DNS propagation to happen. After that you can start accessing your appspot application with the URL www.yourapp.com!Reference: Hosting Google App Engine application in your own domain from Veera Sundar one of our JCG partners. Related Articles :Java Best Practices App Engine Java Development with Netbeans Google App Engine Java Capabilities and Namespaces API Java beginners Guide...
java-logo

How to Avoid ConcurrentModificationException when using an Iterator

Java Collection classes are fail-fast which means that if the Collection will be changed while some thread is traversing over it using iterator, the iterator.next() will throw a ConcurrentModificationException. This situation can come in case of multithreaded as well as single threaded environment. Lets explore this scenario with the following example: import java.util.*; public class IteratorExample { public static void main(String args[]){ List<String> myList = new ArrayList<String>(); myList.add("1"); myList.add("2"); myList.add("3"); myList.add("4"); myList.add("5"); Iterator<String> it = myList.iterator(); while(it.hasNext()){ String value = it.next(); System.out.println("List Value:"+value); if(value.equals("3")) myList.remove(value); } Map<String,String> myMap = new HashMap<String,String>(); myMap.put("1", "1"); myMap.put("2", "2"); myMap.put("3", "3"); Iterator<String> it1 = myMap.keySet().iterator(); while(it1.hasNext()){ String key = it1.next(); System.out.println("Map Value:"+myMap.get(key)); if(key.equals("2")){ myMap.put("1","4"); //myMap.put("4", "4"); } } } }Output is: List Value:1 List Value:2 List Value:3 Exception in thread "main" java.util.ConcurrentModificationException at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372) at java.util.AbstractList$Itr.next(AbstractList.java:343) at com.journaldev.java.IteratorExample.main(IteratorExample.java:27)From the output stack trace, its clear that the exception is coming when we call iterator next() function. If you are wondering how Iterator checks for the modification, its implementation is present in AbstractList class where an int variable modCount is defined that provides the number of times list size has been changed. This value is used in every next() call to check for any modifications in a function checkForComodification(). Now comment the list part and run the program again. Output will be: Map Value:3 Map Value:2 Map Value:4Since we are updating the existing key value in the myMap, its size has not been changed and we are not getting ConcurrentModificationException. Note that the output may differ in your system because HashMap keyset is not ordered like list. If you will uncomment the statement where I am adding a new key-value in the HashMap, it will cause ConcurrentModificationException. To Avoid ConcurrentModificationException in multi-threaded environment: 1. You can convert the list to an array and then iterate on the array. This approach works well for small or medium size list but if the list is large then it will affect the performance a lot. 2. You can lock the list while iterating by putting it in a synchronized block. This approach is not recommended because it will cease the benefits of multithreading. 3. If you are using JDK1.5 or higher then you can use ConcurrentHashMap and CopyOnWriteArrayList classes. It is the recommended approach. To Avoid ConcurrentModificationException in single-threaded environment: You can use the iterator remove() function to remove the object from underlying collection object. But in this case you can remove the same object and not any other object from the list. Let us run an example using Concurrent Collection classes: package com.journaldev.java; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; public class ThreadSafeIteratorExample { public static void main(String[] args) { List<String> myList = new CopyOnWriteArrayList<String>(); myList.add("1"); myList.add("2"); myList.add("3"); myList.add("4"); myList.add("5"); Iterator<String> it = myList.iterator(); while(it.hasNext()){ String value = it.next(); System.out.println("List Value:"+value); if(value.equals("3")){ myList.remove("4"); myList.add("6"); myList.add("7"); } } System.out.println("List Size:"+myList.size()); Map<String,String> myMap = new ConcurrentHashMap<String,String>(); myMap.put("1", "1"); myMap.put("2", "2"); myMap.put("3", "3"); Iterator<String> it1 = myMap.keySet().iterator(); while(it1.hasNext()){ String key = it1.next(); System.out.println("Map Value:"+myMap.get(key)); if(key.equals("1")){ myMap.remove("3"); myMap.put("4", "4"); myMap.put("5", "5"); } } System.out.println("Map Size:"+myMap.size()); } }Output is: List Value:1 List Value:2 List Value:3 List Value:4 List Value:5 List Size:6 Map Value:1 Map Value:null Map Value:4 Map Value:2 Map Size:4From the above example its clear that: 1. Concurrent Collection classes can be modified avoiding ConcurrentModificationException. 2. In case of CopyOnWriteArrayList, iterator doesn’t accomodate the changes in the list and works on the original list. 3. In case of ConcurrentHashMap, the behavior is not always the same. For condition: if(key.equals("1")){ myMap.remove("3");Output is: Map Value:1 Map Value:null Map Value:4 Map Value:2 Map Size:4It is taking the new object added with key “4? but not the next added object with key “5?. Now if I change the condition to if(key.equals("3")){ myMap.remove("2");Output is: Map Value:1 Map Value:3 Map Value:null Map Size:4In this case its not considering the new added objects. So if you are using ConcurrentHashMap then avoid adding new objects as it can be processed depending on the keyset. Note that the same program can print different values in your system because HashMap keyset is not in any order. Extra Toppings: for(int i = 0; i<myList.size(); i++){ System.out.println(myList.get(i)); if(myList.get(i).equals("3")){ myList.remove(i); i--; myList.add("6"); } }If you are working on single-threaded environment and want your code to take care of the extra added objects in the list then you can do so using following code and avoiding iterator. Note that I am decreasing the counter because I am removing the same object, if you have to remove the next or further far object then you don’t need to decrease the counter. Try it yourself. Reference : How to Avoid ConcurrentModificationException when using an Iterator from our JCG partner at JournalDev.Related Articles:Java Best Practices – Vector vs ArrayList vs HashSet Java Best Practices – Queue battle and the Linked ConcurrentHashMap Java Fork/Join for Parallel Programming ConcurrentLinkedHashMap v 1.0.1 releasedRelated Snippets :Blocking Queue example to execute commands Semaphores example limiting URL connections  Synchronous Queue example to execute commands CountDownLatch example of a more general wait/notify mechanism ...
google-app-engine-logo

App Engine Java Development with Netbeans

If you just started with App engine development, you might be having a feeling that Eclipse is the preferred IDE. And, Google also has offered its official plug-in to Eclipse IDE alone. But what about the people who are not using Eclipse? Of course, you can always do a command line development but who does that these days!? For Netbeans users, the plug-in nbappengine brings the Java app engine development to the Netbeans platform. Here’s how you can start developing your app engine apps on Netbeans. Installing nbappengine plugin on NetbeansFirst thing first: Install the latest Netbeans (6.9 at the time of typing these characters) and open the IDE. Go to Tools -> Plugins -> Settings and click “Add” button to add the nbappengine update center URL. Now give a name and the URL of the update center according to your version of Netbeans.Netbeans 6.9: http://kenai.com/downloads/nbappengine/NetBeans69/updates.xml Netbeans 6.8: http://kenai.com/projects/nbappengine/downloads/download/Latest_NetBeans68/updates.xml Netbeans 6.7: http://kenai.com/projects/nbappengine/downloads/download/1.0_NetBeans671/updates.xmlAfter adding it, now come back to the “Available Plugins” tab and do a search for “Google”. Select all the plug-ins that are related to the App Engine and click install button.Configuring App Engine SDK with Netbeans Now you’ve installed the nbappengine plugin on your Netbeans IDE.  The coming steps will tell you how you can configure the plugin with the App Engine SDK.Download the App Engine SDK for Java and extract the zip contents to your favorite location. In the Netbeans IDE, go to Services window (Ctrl + 5 is the shortcut key) and right click on the Servers menu and select “Add Server“. Now select the “Google App Engine” from the list of servers and in the next screen choose the folder where you extracted your SDK files. Configure the server properties if you wish to change it and then click “Finish”.Creating and deploying your first App Engine app on Netbeans Now its the time to create a brand-new app engine application.In Netbeans, select “File -> New Project -> Java Web -> Web application” and follow the wizard to create the project. In the “Server and Settings” page choose “Google App Engine” as your server so that you’ll get the app-engine related files (such as appengine-web.xml) pre-created for you. When you run/debug this application, Netbeans will start the app engine server (Jetty) and will deploy your application there. To deploy the application to the App Engine server, just right click on the project and choose “Deploy to Google App Engine”. it’ll prompt you for the Google account credentials. After you provided that info, your app will be uploaded to the cloud.Reference : App Engine Java development on Netbeans from our JCG partner Veera Sundar. Related Articles:Java Code Geeks Andygene Web Archetype Google App Engine Java Capabilities and Namespaces API Spring MVC Development – Quick Tutorial Getting Started with SmartGWT for awesome GWT interfaces GWT 2 Spring 3 JPA 2 Hibernate 3.5 Tutorial...
oracle-hudson-logo

Refactoring Hudson God Class

Jakub Holy, one of our JCG partners, has recently shared his experience at attempting to refactor Hudson, the main class behind the famous Continuous Integration (CI) server, now renamed to Jenkins. Let’s see what he has to say about this refactoring experience. We’ve tried to refactor Hudson.java but without success; only later have I been able to refactor it successfully, thanks to the experience from the first attempt and more time. In any case it was a great learning opportunity.   Lessons Learned The two most important things we’ve learned are:Never underestimate legacy code. It’s for more complex and intertwined than you expect and it has more nasty surprises up in its sleeves than you can imagine. Never underestimate legacy code.And another important one: when you’re tired and depressed, have some fun reading the “best comments ever” at StackOverflow :-) . Seeing somebody else’ suffering makes one’s own seem to be smaller. I’ve also started to think that the refactoring process must be more rigorous to protect you from wandering too far your original goal and from getting lost in the eternal cycle of fixing something <-> discovering new problems. People tend to do depth-first refactoring changes that can easily lead them astray, far from where they actually need to go; it is important to stop periodically and look at where we are, where we are trying to get and whether we aren’t getting lost and shouldn’t just prune the current “branch” of refactorings and return to some earlier point and try perhaps a completely different solution. I guess that one of the key benefits of the Mikado method is that it provides you with this global overview – which gets easily lost when it is only in your head – and with points to roll-back to.   Evils of Legacy Code Use a dependency injection framework, for God’s sake! Singletons and their manual retrieval really complicate testing and affect the flexibility of the code. Don’t use public fields. They make it really hard to replace a class with an interface. Reflection and multithreading make it pretty difficult if not impossible to find out the dependencies of a particular piece of code and thus the impacts of its change. I’d hard time finding out all the places where Hudson.getInstance is invoked while its constructor is still running.   Our Way to Failure and Success There is a lot of refactoring that could be done with Hudson.java, for it is a typical God Class which additionally spreads its tentacles through the whole code base via its evil singleton instance being used by just about anyone for many different purposes. Gojko describes some of the problems worth removing.   The FailureWe’ve tried to start small and “normalize” the singleton initialization, which isn’t done in a factory method, but in the constructor itself. I haven’t chosen the goal very well as it doesn’t bring much value. The idea was to make it possible to have potentially also other implementations of Hudson – e.g. a MockHudson – but with respect to the state of the code it wasn’t really feasible and even if it was, a simple Hudson.setInstance would perhaps suffice. Anyway we’ve tried to create a factory method and move the initialization of the singleton instance there but at the end we got lost in concurrency issues: there were either multiple instances of Hudson or the application deadlocked itself. We tried to move pieces of code around, but the dependencies wouldn’t have let us do that. The Success While reflecting on our failure I’ve come to the realization that the problem was that Hudson.getInstance() is called (many times) already during the execution of the Hudson’s constructor by the objects used there and threads started from there. It is of course a hideous practice to access a half-baked instance before it is fully initialized. The solution is then simple: to be able to initialize the singleton field outside of the constructor, we must remove all calls to getInstance from its context.The steps can be seen very well from the corresponding GitHub commits. Summary: 1. I used the “introduce factory” refactoring on the constructor 2. I modified ProxyConfiguration not to use getInstance but to expect that the root directory will be set before its first use 3. I moved the code that didn’t need to be run from the constructor out, to the new factory method – this resulted in some, hopefully insignificant, reordering of the code 4. Finally, I also moved the instance initialization to the factory method I can’t be 100% sure that the resulting code has the same semantic as far as it matters, for I had to do few changes outside of the safe automated refactorings and there are no useful tests except for trying to run the application (and, as is common with legacy applications, it wasn’t feasible to create them beforehand). The refactored code doesn’t provide much added value yet but it is a good start for further refactorings (which I won’t have the time to try :-( ), it got rid of the offending use of an instance while it is being created and the constructor code is simpler and better. The exercise took me about four pomodoros, i.e. little less than two hours. If I had the time, I’d continue with extracting an interface from Hudson, moving its unrelated responsibilities to classes of their own (perhaps keeping the methods in Hudson for backwards compatibility and delegating to those objects) and I might even use some AOP magic to get a cleaner code while preserving binary compatibility (as Hudson/Jenkins actually already does). Try it for Yourself! Setup Get the code Get the code as .zip or via git: git@github.com:iterate/coding-dojo.git # 50MB => takes a while cd coding-dojo git checkout -b mybranch INITIALCompile the Code as described in the dojo’s README. Run Jenkins/Hudson cd coding-dojo/2011-04-26-refactoring_hudson/ cd maven-plugin; mvn install; cd .. # a necessary dependency cd hudson/war; mvn hudson-dev:runand browse to http://localhost:8080/ (Jetty should pick changes to class files automatically). Further Refactorings If you’re the adventurous type, you can try to improve the code more by splitting out the individual responsibilities of the god class. I’d proceed like this:Extract an interface from Hudson and use it wherever possible Move related methods and fields into (nested) classes of their own, the original Hudson’s methods just delegate to them (the move method refactoring should be useful); for example:           – Management of extensions and descriptors            – Authentication & authorization            – Cluster management            – Application-level functionality (control methods such as restart, updates of configurations, management of socket listeners)            -UI controller (factoring this out would require re-configuration of Stapler)Convert the nested classes into top-level ones Provide a way to get instances of the classes without Hudson, e.g. as singletons Use the individual classes instead of Hudson wherever possible so that other classes depend only on the functionality they actually need instead of on the whole of Hudson  Learning about Jenkins/Hudson If you want to understand mode about what Hudson does and how it works, you may check:Hudson’s Architecture and optionally proceed withHudson’s Remote Access API Extension points Exposing data to the remote APIBuilding Hudson Introduction into the UI framework Stapler (its key feature is that it cleverly maps URLs to object hierarchies [and view files and action methods]), perhaps check also Stapler’s reference  Sidenote: Hudson vs. Jenkins Once upon time there was a continuous integration server called Hudson but after its patron Sun died, it ended up in the hands of a man called Oracle. He wasn’t very good at communication and nobody really knew what he is up to so when he started to behave little weird – or at least so the friends of Hudson perceived it – those worried about Hudson’s future (including most people originally working in the project) made its clone and named it Jenkins, which is another popular name for butlers. So now we have Hudson backed by Oracle and the maven guys from Sonatype and Jenkins, supported by a vivid community. This exercise is based on the source code of the Jenkins, but to keep the confusion level low I refer to it often as Hudson for that is how the package and main class are called.   Conclusion Refactoring legacy code always turns out to be more complicated and time-consuming than you expect. It’s important to follow some method – e.g. the Mikado method – that helps you to keep a global overview of where you want to go and where you are and to regularly consider what and why you’re doing so that you don’t get lost in a series of fix a problem – new problems discovered steps. It’s important to realize when to give up and try a different approach. It’s also very hard or impossible to write tests for the changes so you must be very careful (using safe, automated refactorings as much as possible and proceeding in small steps) but fear shouldn’t stop you from trying to save the code from decay. Reference: What I’ve Learned from (Nearly) Failing to Refactor Hudson from our JCG partner at The Holy Java blog. Related Articles:Java Code Geeks Andygene Web Archetype Why Automated Tests Boost Your Development Speed Code quality matters to the customers. A lot. Using FindBugs to produce substantially less buggy code Agile software development recommendations for users and new adopters...
jcg-logo

Best Of The Week – 2011 – W18

Hello guys, Time for the “Best Of The Week” links for the week that just passed. Here are some links that drew JavaCodeGeeks attention: * All I Want for Java 8 is… : A Java 8 feature wishlist including Full Runtime Generics Support, JMX 2.0 Features, Improved Date/Time Support and others. * Application Performance Monitoring in production – Step by Step Guide – Measuring a distributed system: In this article, the author explains step by step how to measure performance on a distributed system. Data collection and correlation, usage and utilization measurement and impact measurement are some issues discussed. * Amazon EC2 Outage Explained and Lessons Learned: A short and to the point analysis of the recent Amazon EC2 outage accompanied by lessons that Amazon and us should learn. * Quartz 2.0 Supports Fluent Configuration API and Monitoring of Job Scheduling: New additions in the well established, open source job scheduling framework: Fluent Config API and easier job monitoring. * How Garbage Collection works in Java: A nice and concise article on garbage collection in Java. Heap generations, types of collector, JVM parameters for GC are all explained.. * Android Fundamentals: Scheduling Recurring Tasks: Nice tutorial on how to use BroadcastReceivers and the AlarmManager service in order to schedule and execute recurring tasks. Also check out our Android related posts and our Android Full Application Tutorial. That’s all for this week. Stay tuned for more, here at JavaCodeGeeks. Related Articles:Best Of The Week – 2011 – W17 Best Of The Week – 2011 – W16 Best Of The Week – 2011 – W15 Best Of The Week – 2011 – W14 Best Of The Week – 2011 – W13 Best Of The Week – 2011 – W12 Best Of The Week – 2011 – W11 Best Of The Week – 2011 – W10 Best Of The Week – 2011 – W09 Best Of The Week – 2011 – W08...
play-framework-logo

RabbitMQ Module for Play! Framework

RabbitMQ offers a highly available, scalable and portable messaging system with predictable and consistent throughput and latency. RabbitMQ is the leading implementation of AMQP, the open standard for business messaging, and, through adapters, supports XMPP, SMTP, STOMP and HTTP for lightweight web messaging. This new module allows you to consume and produce messages on a RabbitMQ instance from your Play! Framework application. Installation play install rabbitmqConfiguration module.rabbitmq=${play.path}/modules/rabbitmq-0.0.1 rabbitmq.host=localhost rabbitmq.port=5672 rabbitmq.userName=guest rabbitmq.password=guest rabbitmq.vhost=/ rabbitmq.exchangeType=direct rabbitmq.durable=true rabbitmq.autoAck=false rabbitmq.basicQos=trueDefine Message that will be used by the Queue (just a simple POJO) public class SampleMessage implements Serializable {/** The field1. */ private String field1;/** The field2. */ private String field2;/** * Instantiates a new sample message. */ public SampleMessage() {}/** * Instantiates a new sample message. * * @param field1 the field1 * @param field2 the field2 */ public SampleMessage(String field1, String field2) { super(); this.field1 = field1; this.field2 = field2; }/** * Gets the field1. * * @return the field1 */ public String getField1() { return field1; }/** * Sets the field1. * * @param field1 the new field1 */ public void setField1(String field1) { this.field1 = field1; }/** * Gets the field2. * * @return the field2 */ public String getField2() { return field2; }/** * Sets the field2. * * @param field2 the new field2 */ public void setField2(String field2) { this.field2 = field2; }/** * To String * * @see java.lang.Object#toString() */ @Override public String toString() { return "SampleMessage [field1=" + field1 + ", field2=" + field2 + "]"; } }Publish a Message public static void publish(String q) { RabbitMQPublisher.publish("myQueue", new SampleMessage(q, q)); render(q); }Creating a Message Consumer @OnApplicationStart(async=true) public class RabbitMQSampleConsumer extends RabbitMQConsumer {/** * Consume Message * * @see play.modules.rabbitmq.consumer.RabbitMQConsumer#consume(T) */ @Override protected void consume(SampleMessage message) { System.out.println("******************************"); System.out.println("* Message Consumed: " + message); System.out.println("******************************"); }/** * Name of the Queue that this consumer will be listening to. * * @return the string * @see play.modules.rabbitmq.consumer.RabbitMQConsumer#queue() */ @Override protected String queue() { return "myQueue"; }/** * Return message type. * * @return the message type * @see play.modules.rabbitmq.consumer.RabbitMQConsumer#getMessageType() */ protected Class getMessageType() { return SampleMessage.class; } }* Please note this is a Play! job so you can start it manualy or you can use the other annotations provided by Play! like @On or @Every. More information available at Asynchronous Jobs documentation. Firehose – Another way to publish messages in batch @OnApplicationStart(async = true) public class RabbitMQSampleFirehose extends RabbitMQFirehose {/** The count. */ public int count = 0;/** * Get data to be loaded. * * @param n the n * @return the data * @throws Exception the exception * @see play.modules.rabbitmq.producer.RabbitMQFirehose#getData(int) */ @Override protected List getData(int n) throws Exception { if ( count >= 10 ) { return null; } List results = new ArrayList(); for (int i = 0; i < n; i++) { results.add(new SampleMessage("field1", "field2")); count++; } return results; }/** * Batch Size - How many records we will select at the time?. * * @return the int * @see play.modules.rabbitmq.producer.RabbitMQFirehose#batchSize() */ @Override protected int batchSize() { return 2; }/** * Queue Name. * * @return the string * @see play.modules.rabbitmq.producer.RabbitMQFirehose#queueName() */ @Override protected String queueName() { return "myQueue"; }}* Please note this is a Play! job so you can start it manualy or you can use the other annotations provided by Play! like @On or @Every. More information available at Asynchronous Jobs documentation. Of course the code is available on Github. Now Go Play! Reference : RabbitMQ Module for Play! Framework from our JCG partner Felipe Oliveira at Geeks Are Totally In. Related Articles:Java Code Geeks Andygene Web Archetype Things Every Programmer Should Know Spring MVC Development – Quick Tutorial Getting Started with SmartGWT for awesome GWT interfaces GWT 2 Spring 3 JPA 2 Hibernate 3.5 Tutorial...
google-app-engine-logo

Google App Engine Java Capabilities and Namespaces API

Capabilities API With the Capabilities API, your application can detect outages and scheduled downtime for specific API capabilities. You can use this API to reduce downtime in your application by detecting when a capability is unavailable and then bypassing it. How do we handle this, what’s the tradeoff? 1. Elegantly: create an aspect that cross cuts all data store writes, and checks for capability. Fail with friendly error message. 2. Not so elegantly: add capability checking into the repository code before every write. Fail with friendly error message. 3. Quickly: write filter that wraps the entire transaction and checks for data store writes. How can we test this on a local environment? 1. No API hooks. Currently, I have not been able to find or use GAE Java proxies to test the capability call. 2. The solution would be to create different builds one with a Mocked Capability Service that is able to return the CapabilityStatus.DISABLED flags and test. Due to time reasons, I went for the quick approach. I will try to revisit this later and incorporate AspectJ or Google Juice to leverage aspects for this obvious cross-cutting concern. Map<Capability, Boolean> apis = new HashMap<Capability, Boolean>();public void init(FilterConfig filterConfig) throws ServletException { apis.put(Capability.DATASTORE, true); apis.put(Capability.MEMCACHE, false); }public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {HttpServletResponse httpResponse = (HttpServletResponse)res; HttpServletRequest httpRequest = (HttpServletRequest)req;CapabilitiesService service = CapabilitiesServiceFactory.getCapabilitiesService();for(Map.Entry api : apis.entrySet()) {if(api.getValue()) { CapabilityStatus status = service.getStatus(api.getKey()).getStatus();if (status != CapabilityStatus.ENABLED) { log.warn("API " + api.getKey().getPackageName() + ":" + api.getKey().getName() + " has been disabled!"); httpResponse.sendRedirect(NEPAL_RES_HOST + "/html/read-only.html"); return; } } } chain.doFilter(req, res); }Namespaces API Before we can talk about this API, let’s introduce the concept of Multitenancy. One of the most compelling uses of Namespaces API is multitenancy. Multitenancy is the name given to a software architecture in which one instance of an application, running on a remote server, serves many client organizations (also known as tenants). Multitenancy simplifies administration and provisioning of tenants. You can provide a more streamlined, customized user experience, and also aggregate different silos of data under a single database schema. As a result, your applications become more scalable as well as more cost-effective as you scale Data becomes easier to segregate and analyze across tenants because all tenants share the same database schema. Multitenancy is different than multi-instance:In multi-instance different software instances are set up for different client organizations. In multi-instance the application is typically not aware of the difference of customers, whereas in multitenancy the application is reposible for segregating and partitioning the data.The Namespaces API in Google App Engine makes it easy to create silos of your Google App Engine data. This API is implemented via a new package called the Namespace Manager. When you set a namespace in the namespace manager, these APIs get the current namespace and use it globally. Any App Engine request can access any namespace, leaving the application to enforce an access control policy across namespaces. In this approach, it is the application which is responsible for setting the working namespace. Namespace-aware APIs: 1. Datastore 2. Memcache 3. Task Queue Using the Namespaces API, you can easily partition data across tenants simply by specifying a unique namespace string for each tenant. You simply set the namespace for each tenant globally using the Namespace Manager. The namespace-enabled APIs always use the current namespace by default. In the datastore, the Namespace Manager will apply the namespace to every Key and Query object. There is no Java API to explicitly set the namespace of a Key or Query, all happens through the Namespace Manager. Reference : Google App Engine Java Capabilities and Namespaces API from our JCG partner at ReflectiveThought. Related Articles:Java Code Geeks Andygene Web Archetype Things Every Programmer Should Know Spring MVC Development – Quick Tutorial Getting Started with SmartGWT for awesome GWT interfaces GWT 2 Spring 3 JPA 2 Hibernate 3.5 Tutorial...
java-logo

Java Generics Quick Tutorial

Generics is a Java feature that was introduced with Java SE 5.0 and, few years after its release, I swear that every Java programmer out there not only heard about it, but used it. There are plenty of both free and commercial resources about Java generics and the best sources I used are:The Java Tutorial Java Generics and Collections, by Maurice Naftalin and Philip Wadler Effective Java (second edition), by Joshua Bloch.Despite the wealth of information out there, sometimes it seems to me that many developers still don’t understand the meaning and the implications of Java generics. That’s why I’m trying to summarize the basic information developers need about generics in the simplest possible way. The Motivation for Generics The simplest way to think about Java generics is thinking about a sort of a syntactic sugar that might spare you some casting operation: List<Apple> box = ...; Apple apple = box.get(0);The previous code is self-speaking: box is a reference to a List of objects of type Apple. The get method returns an Apple instance an no casting is required. Without generics, this code would have been: List box = ...; Apple apple = (Apple) box.get(0);Needless to say, the main advantage of generics is having the compiler keep track of types parameters, perform the type checks and the casting operations: the compiler guarantees that the casts will never fail. Instead of relying on the programmer to keep track of object types and performing casts, which could lead to failures at runtime difficult to debug and solve, the compiler can now help the programmer enforce a greater number of type checks and detect more failures at compile time. The Generics Facility The generics facility introduced the concept of type variable. A type variable, according to the Java Language Specification, is an unqualified identifier introduced by:Generic class declarations Generic interface declarations Generic method declarations Generic constructor declarations.Generic Classes and Interfaces A class or an interface is generic if it has one or more type variable. Type variable are delimited by angle brackets and follow the class (or the interface) name: public interface List<T> extends Collection<T> { ... }Roughly speaking, type variables act as parameters and provide the information the compiler needs to make its checks. Many classes in the Java library, such as the entire Collections Framework, were modified to be generic. The List interface we’ve used in the first code snippet, for example, is now a generic class. In that snippet, box was a reference to a List<Apple> object, an instance of a class implementing the List interface with one type variable: Apple. The type variable is the parameter that the compiler uses when automatically casting the result of the get method to an Apple reference. In fact, the new generic signature or the get method of the interface List is: T get(int index);The method get returns indeed an object of type T, where T is the type variable specified in the List<T> declaration. Generic Methods and Constructors Pretty much the same way, methods and constructors can be generic if they declare one or more type variables. public static <t> T getFirst(List<T> list)This method will accept a reference to a List<T> and will return an object of type T. Examples You can take advantage of generics in both your own classes or the generic Java library classes. Type Safety When Writing… In the following code snippet, for example, we create an instance List<String> of populate it with some data: List<String> str = new ArrayList<String>(); str.add("Hello "); str.add("World.");If we tried to put some other kind of object into the List<String>, the compiler would raise an error: str.add(1); // won't compile… and When Reading If we pass the List<String> reference around, we’re always guaranteed to retrieve a String object from it: String myString = str.get(0);Iterating Many classes in the library, such as Iterator<T>, have been enhanced and made generic. The iterator() method of the interface List<T> now returns an Iterator<T> that can be readily used without casting the objects it returns via its T next() method. for (Iterator<String> iter = str.iterator(); iter.hasNext();) { String s = iter.next(); System.out.print(s); }Using foreach The for each syntax takes advantage of generics, too. The previous code snippet could be written as: for (String s: str) { System.out.print(s); }that is even easier to read and maintain. Autoboxing and Autounboxing The autoboxing/autounboxing features of the Java language are automatically used when dealing with generics, as shown in this code snippet: List<Integer> ints = new ArrayList<Integer>(); ints.add(0); ints.add(1);int sum = 0; for (int i : ints) { sum += i; }Be aware, however, that boxing and unboxing come with a performance penalty so the usual caveats and warnings apply. Subtypes In Java, as in other object-oriented typed languages, hierarchies of types can be built:In Java, a subtype of a type T is either a type that extends T or a type that implements T (if T is an interface) directly or indirectly. Since “being subtype of” is a transitive relation, if a type A is a subtype of B and B is a subtype of C, then A will be a subtype of C too. In the figure above:FujiApple is a subtype of Apple Apple is a subtype of Fruit FujiApple is a subtype of Fruit.Every Java type will also be subtype of Object. Every subtype A of a type B may be assigned to a reference of type B: Apple a = ...; Fruit f = a;Subtyping of Generic Types If a reference of an Apple instance can be assigned to a reference of a Fruit, as seen above, then what’s the relation between, let’s say, a List<Apple> and a List<Fruit>? Which one is a subtype of which? More generally, if a type A is a subtype of a type B, how does C<A> and C<B> relate themselves? Surprisingly, the answer is: in no way. In more formal words, the subtyping relation between generic types is invariant. This means that the following code snippet is invalid: List<Apple> apples = ...; List<Fruit> fruits = apples;and so does the following: List<Apple> apples; List<Fruit> fruits = ...; apples = fruits;But why? Is an apple is a fruit, a box of apples (a list) is also a box of fruits. In some sense, it is, but types (classes) encapsulate state and operations. What would happen if a box of apples was a box of fruits? List<Apple> apples = ...; List<Fruit> fruits = apples; fruits.add(new Strawberry());If it was, we could add other different subtypes of Fruit into the list and this must be forbidden. The other way round is more intuitive: a box of fruits is not a box of apples, since it may be a box (List) of other kinds (subtypes) of fruits (Fruit), such as Strawberry. Is It Really a Problem? It should not be. The strongest reason for a Java developer to be surprised is the inconsistency between the behavior of arrays and generic types. While the subtyping relations of the latter is invariant, the subtyping relation of the former is covariant: if a type A is a subtype of type B, then A[] is a subtype of B[]: Apple[] apples = ...; Fruit[] fruits = apples;But wait! If we repeat the argument exposed in the previous section, we might end up adding strawberries to an array of apples: Apple[] apples = new Apple[1]; Fruit[] fruits = apples; fruits[0] = new Strawberry();The code indeed compiles, but the error will be raised at runtime as an ArrayStoreException. Because of this behavior of arrays, during a store operation, the Java runtime needs to check that the types are compatible. The check, obviously, also adds a performance penalty that you should be aware of. Once more, generics are safer to use and “correct” this type safety weakness of Java arrays. In the case you’re now wondering why the subtyping relation for arrays is covariant, I’ll give you the answer that Java Generics and Collections give: if it was invariant, there would be no way of passing a reference to an array of objects of an unknown type (without copying every time to an Object[]) to a method such as: void sort(Object[] o);With the advent of generics, this characteristics of arrays is no longer necessary (as we’ll see in the next part of this post) and should indeed by avoided. Wildcards As we’ve seen in the previous part of this post, the subtyping relation of generic types is invariant. Sometimes, though, we’d like to use generic types in the same way we can use ordinary types:Narrowing a reference (covariance) Widening a reference (contravariance)Covariance Let’s suppose, for example, that we’ve got a set of boxes, each one of a different kind of fruit. We’d like to be able to write methods that could accept a any of them. More formally, given a subtype A of a type B, we’d like to find a way to use a reference (or a method parameter) of type C<B> that could accept instances of C<A>. To accomplish this task we can use a wildcard with extends, such as in the following example: List<Apple> apples = new ArrayList<Apple>(); List<? extends Fruit> fruits = apples;? extends reintroduces covariant subtyping for generics types: Apple is a subtype of Fruit and List<Apple> is a subtype of List<? extends Fruit>. Contravariance Let’s now introduce another wildcard: ? super. Given a supertype B of a type A, then C<B> is a subtype of C<? super A>: List<Fruit> fruits = new ArrayList<Fruit>(); List<? super Apple> = fruits;How Can Wildcards Be Used? Enough theory for now: how can we take advantage of these new constructs? ? extends Let’s go back to the example we used in Part II when introducing Java array covariance: Apple[] apples = new Apple[1]; Fruit[] fruits = apples; fruits[0] = new Strawberry();As we saw, this code compiles but results in a runtime exception when trying to add a Strawberry to an Apple array through a reference to a Fruit array. Now we can use wildcards to translate this code to its generic counterpart: since Apple is a subtype of Fruit, we will use the ? extends wildcard to be able to assign a reference of a List<Apple> to a reference of a List<? extends Fruit> : List<Apple> apples = new ArrayList<Apple>(); List<? extends Fruit> fruits = apples; fruits.add(new Strawberry());This time, the code won’t compile! The Java compiler now prevents us to add a strawberry to a list of fruits. We will detect the error at compile time and we won’t even need any runtime check (such as in the case of array stores) to ensure that we’re adding to the list a compatible type. The code won’t compile even if we try to add a Fruit instance into the list: fruits.add(new Fruit());No way. It comes out that, indeed, you can’t put anything into a structure whose type uses the ? extends wildcard. The reason is pretty simple, if we think about it: the ? extends T wildcard tells the compiler that we’re dealing with a subtype of the type T, but we cannot know which one. Since there’s no way to tell, and we need to guarantee type safety, you won’t be allowed to put anything inside such a structure. On the other hand, since we know that whichever type it might be, it will be a subtype of T, we can get data out of the structure with the guarantee that it will be a T instance: Fruit get = fruits.get(0);? super What’s the behavior of a type that’s using the ? super wildcard? Let’s start with this: List<Fruit> fruits = new ArrayList<Fruit>(); List<? super Apple> = fruits;We know that fruits is a reference to a List of something that is a supertype of Apple. Again, we cannot know which supertype it is, but we know that Apple and any of its subtypes will be assignment compatible with it. Indeed, since such an unknown type will be both an Apple and a GreenApple supertype, we can write: fruits.add(new Apple()); fruits.add(new GreenApple());If we try to add whichever Apple supertype, the compiler will complain: fruits.add(new Fruit()); fruits.add(new Object());Since we cannot know which supertype it is, we aren’t allowed to add instances of any. What about getting data out of such a type? It turns out that you the only thing you can get out of it will be Object instances: since we cannot know which supertype it is, the compiler can only guarantee that it will be a reference to an Object, since Object is the supertype of any Java type. The Get and Put Principle or the PECS Rule Summarizing the behavior of the ? extends and the ? super wildcards, we draw the following conclusion:Use the ? extends wildcard if you need to retrieve object from a data structure Use the ? super wildcard if you need to put objects in a data structure If you need to do both things, don’t use any wildcard.This is what Maurice Naftalin calls The Get and Put Principle in his Java Generics and Collections and what Joshua Bloch calls The PECS Rule in his Effective Java. Bloch’s mnemonic, PECS, comes from “Producer Extends, Consumer Super” and is probably easier to remember and use. Wildcards in Method Signatures As seen in Part II of this series, in Java (as in many other typed languages), the Substitution principle stands: a subtype can be assigned to a reference of any of its supertypes. This applies during the assignment of whichever reference, that is, even when passing parameters to a function or storing its result. One of the advantages of this principle, then, is that when defining class hierarchies, “general purpose” methods can be written to handle entire sub-hierarchies, regardless of the class of the specific object instances time being handled. In the Fruit class hierarchy we’ve used so far, a function that accepts a Fruit as a parameter will accept any of its subtypes (such as Apple or Strawberry). As seen in the previous post, wildcards restore covariant and contravariant subtyping for generic types: using wildcards, then, let the developer write functions that can take advantage of the benefits presented so far. If, for example, a developer wanted to define a method eat that accepted a List of whichever fruit, it could use the following signature: void eat(List<? extends Fruit> fruits);Since a List of whichever subtype of the class Fruit is a subtype of List<? extends Fruit>, the previous method will accept any such list as a parameter. Note that, as explained in the previous section, the Get and Put Principle (or the PECS Rule) will allow you to retrieve objects from such list and assign them to a Fruit reference. On the other hand, if you wanted to put instances on the list passed as a parameter, you should use the ? super wildcard: void store(List<? super Fruit> container);This way, a List of whichever supertype of Fruit could be passed in to the store function and you could safely put whichever Fruit subtype into it. Bounded Type Variables The flexibility of generics is greater than this, though. Type variables can be bounded, pretty much in the same way wildcards can be (as we’ve seen in Part II). However, type variables cannot be bounded with super, but only with extends. Look at the following signature: public static <T extends I<T>> void name(Collection<T> t);It takes a collections of objects whose type is bounded: it must satisfy the T extends I<T> condition. Using bounded type variables may not seem more powerful than wildcards at first, but we’ll detail the differences in a moment. Let’s suppose some, but not all, fruits in your hierarchy can be juicy as in: public interface Juicy<T> { Juice<T> squeeze(); }Juicy fruits will implement this interface and publish the squeeze method. Now, you write a library method that takes a bunch of fruits and squeezes them all. The first signature you could write might be: <T> List<Juice<T>> squeeze(List<Juicy<T>> fruits);Using bounded type variables, you would write the following (which, indeed, has got the same erasure of the previous method): <T extends Juicy<T>> List<Juice<T>> squeeze(List<T> fruits);So far, so good. But limited. We could use the very same arguments used in the same posts and discover that the squeeze method is not going to work, for example, with a list of red oranges when: class Orange extends Fruit implements Juicy<Orange>; class RedOrange extends Orange;Since we’ve already learned about the PECS principle, we’re going to change the method with: <T extends Juicy<? super T>> List<Juice<? super T>> squeezeSuperExtends(List<? extends T> fruits);This method accepts a list of objects whose type extends Juicy<? super T>, that is, in other words, that there must exist a type S such that T extends Juicy<S> and S super T. Recursive Bounds Maybe you feel like relaxing the T extends Juicy<? super T> bound. This kind of bound is called recursive bound because the bound that the type T must satisfy depends on T. You can use recursive bounds when needed and also mix-and-match them with other kinds of bounds. Thus you can, for example, write generic methods with such bounds: <A extends B<A,C>, C extends D<T>>Please remember that these examples are only given to illustrate what generics can do. Bounds you’re going to use always depend on the constraints you’re putting into your type hierarchy. Using Multiple Type Variables Let’s suppose you want to relax the recursive bound we put on the last version of the squeeze method. Let’s then suppose that a type T might extend Juicy<S> although T itself does not extends S. The method signature could be: <T extends Juicy<S>, S> List<Juice<S>> squeezeSuperExtendsWithFruit(List<? extends T> fruits);This signature has pretty much equivalent to the previous one (since we’re only using T in the method arguments) but has got one slight advantage: since we’ve declared the generic type S, the method can return List<Juice<S> instead of List<? super T>, which can be useful in some situations, since the compiler will help you identify which type S is according to the method arguments you’ve passed. Since you’re returning a list, chances are you want your caller to be able to get something from it and, as you’ve learned in the previous part, you can only get Object instances from a list such as List<? super T>. You can obviously add more bounds to S, if you need them, such as: <T extends Juicy<S>, S extends Fruit> List<Juice<S>> squeezeSuperExtendsWithFruit(List<? extends T> fruits);Multiple Bounds What if you want to apply multiple bounds on the same type variable? It turns out that you can only write a bound per generic type variable. The following bounds are thus illegal: <T extends A, T extends B> // illegalThe compiler will fail with a message such as: T is already defined in… Multiple bounds must be expressed with a different syntax, which turns out to be a pretty familiar notation: <T extends A & B>The previous bounds means that T extends both A and B. Please take into account that, according to the Java Language Secification, Chapter 4.4, states that a bound is either:A type variable. A class. An interface type followed by further interface types.This means that multiple bounds can only be expressed using interface types. There’s no way of using type variables in a multiple bound and the compiler will fail with a message such as: A type variable may not be followed by other bounds. This is not always clear in the documentation I’ve read. References :Series of articles about Java Generics from our JCG partner Gray at The Grey BlogHappy Coding! Do not forget to share! Byron Related Articles:Java Best Practices Series 10 Tips for Proper Application Logging Things Every Programmer Should Know 9 Tips on Surviving the Wild West Development Process Laws of Software Design Java Fork/Join for Parallel Programming...
jcg-logo

Best Of The Week – 2011 – W17

Hello guys, Time for the “Best Of The Week” links for the week that just passed. Here are some links that drew JavaCodeGeeks attention: * The Usability of Passwords: An excellent article that discusses password usability and security. It describes the most commonly used ways to attack a password and what countermeasures we can use to avoid this. * Why aren’t we all doing Model Driven Development yet?: In this article, the author attempts to figure out why Model Driven Development (MDD) is not yet more widely used. He talks about the dangers of MDD, discusses tool support and provides some reasons on why use MDD. Also, check our relevant articles on Domain Driven Design (DDD), Using the State pattern in a Domain Driven Design and Domain Driven Design with Spring and AspectJ. * 6 Ways Not to Scale that Will Make You Hip, Popular and Loved By VCs: An entertaining, yet highly informative, presentation of ways use to NOT scale your application. Well, forget about resource monitoring, performance testing, traffic monitoring, load testing, tuning analysis, do not embrace parallel programming, ignore caching, do not eliminate single points of failure etc. * White Box Testing Best Practices for Performance Regression and Scalability Analysis: A very interesting article discussing white box testing with emphasis on performance and scalability. Also, check out our Java Best Practices series. * The Top Java Memory Problems – Part 1: A must-read article discussing the most common memory related problems in Java applications. Thread local variables, mutable static fields and collections, circular references, to name a few. See also, Erlang vs Java memory architecture and Java Memory Model – Quick overview and things to notice. * Your coding conventions are hurting you: A very interesting article that explains how coding conventions can hurt programmers. Even the most established conventions (e.g. the -er suffix, the -able suffix etc.) can stifle object oriented thinking and facilitate hidden functional programming notions. The author uses .NET as reference, but the principles definitely apply to Java as well. * Android Fundamentals: Downloading Data With Services: A detailed guide on how to leverage services in order to perform long running tasks, such as downloading data. Also check out our Android related posts and our Android Full Application Tutorial. That’s all for this week. Stay tuned for more, here at JavaCodeGeeks. Related Articles:Best Of The Week – 2011 – W16 Best Of The Week – 2011 – W15 Best Of The Week – 2011 – W14 Best Of The Week – 2011 – W13 Best Of The Week – 2011 – W12 Best Of The Week – 2011 – W11 Best Of The Week – 2011 – W10 Best Of The Week – 2011 – W09 Best Of The Week – 2011 – W08 Best Of The Week – 2011 – W07...
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
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.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books