Featured FREE Whitepapers

What's New Here?

software-development-2-logo

Best Practices Ever for Software Development

Write programs for people, not computers.a program should not require its readers to hold more than a handful of facts in memory at once names should be consistent, distinctive and meaningful code style and formatting should be consistent all aspects of software development should be broken down into tasks roughly an hour longAutomate repetitive tasks.rely on the computer to repeat tasks save recent commands in a file for re-use use a build tool to automate scientific workflowsUse the computer to record history.software tools should be used to track computational work automaticallyMake incremental changes.work in small steps with frequent feedback and course correctionUse version control.use a version control system everything that has been created manually should be put in version controlDon’t repeat yourself (or others).every piece of data must have a single authoritative representation in the system code should be modularized rather than copied and pasted re-use code instead of rewriting itPlan for mistakes.add assertions to programs to check their operation use an off-the-shelf unit testing library use all available oracles when testing programs turn bugs into test cases use a symbolic debuggerOptimize software only after it works correctly.use a profiler to identify bottlenecks write code in the highest-level language possibleDocument design and purpose, not mechanics.document interfaces and reasons, not implementations refactor code instead of explaining how it works embed the documentation for a piece of software in that softwareCollaborate.use pre-merge code reviews use pair programming when bringing someone new up to speed and when tackling particularly tricky problemsThe only extra I would have included would be: 11. Maintain and update older code.   Reference: Best Practices Ever for Software Development from our JCG partner Andriy Andrunevchyn at the Java User Group of Lviv blog. ...
git-logo

Git – let’s make errors (and learn how to revert them)

It’s not a secret that git is not a very easy tool to use. I am able to use it more or less; but I always feel a little scared and confused about what’s happening. I feel that I want more informations. I have followed some tutorial and read distractedly some book but, with too much information I always end up with just the feeling that I could do what I want to do. But I do not know how to do it. I want to fix this situation so I have started to investigate more and I am trying to stick some key concept in my head, hoping to never forget them. Let me start giving the credits for my source: http://osteele.com/posts/2008/05/my-git-workflow and http://longair.net/blog/2009/04/16/git-fetch-and-merge/. I have found those articles interesting and helpful, the first in particular, but they are saying already   too many things for the simplified model that I need. Let’s assume that you are already a git user. You have a local repo, a remote one used to pull and push you work. And you also are aware of the existence of branches and you are using them. But still, with this basic knowledge you have the feeling of not being sure about your actions. I guess that one of the key of this confusion is the role of the staging area. Please, note that in my discussion I am giving my understanding of it, and that I could be wrong. But nevertheless I can build my knowledge on this concept and be able to give my self a rationale behind it that helps me to gain confidence with the tool. I like to think at the staging area, (that place where your modifications get tracked when you perform a git add operation, as a way to do ‘lighter commit‘. What I mean with lighter commit is that, since you are not forced to give a comment upon this action, you have less constraints. And since you are not even saving your action yet, you are clearly encouraged to perform add much more often than  commit. Let’s give a scenario for our add use case: the process of adding some new functionality to your codebase; it probably involves the creation of new files and ideas just pop in your mind in an unordered fashion. To give an example, let’s pretend that you are creating 2 files with a reference to each other. Maybe a source code file and it’s configuration file. You create the first, and start working on it. When you have finished to work on it you could think to commit it, but since your logical unit of work is not complete until you’ll also create the configuration file you have the opportunity to perform the mentioned ‘lighter commit, i.e. a simple add. After you have finished the work with the configuration file, you have to add it to the index and now you can commit it. Or if you prefer you can do a git commit -a , to obtain the same result. Since we have given a use case for the staging area, it should become easier to figure it’s role in the git workflow. It’s the logical place that stays between the current untracked directory and the committed (and safe) repository. We are calling it a ‘place’ so we can assume that we are interested in interacting with it. The already well known way to put things in it is the command: git add and it has 2 companion commands that you will use very often: git diff As the name suggests, it lists differences. But which ones? In its form without parameters, it lists differences between your current folder and the staging area. touch test.txt echo 'text' >> test.txt git add test.txt echo 'added1' >> test.txt git diff returns this output: gittest$ git diffdiff --git a/test.txt b/test.txt index 8e27be7..2db9057 100644 --- a/test.txt +++ b/test.txt @@ -1 +1,2 @@ text +added1 Ok we are now able to see differences between our working folder and the tracking context. We can obviously track the new modification, with an add command but we want also the opportunity to throw away our modification. This is obtained with git checkout . Git checkout, without parameters (others than ‘dot’, representing the current folder) will throw away the modification to your files and revert the status to the one tracked in the staging area with the previous add commands. gittest$ git status# On branch master # Changes to be committed: # (use 'git reset HEAD <file>...' to unstage) # # new file: test.txt # # Changes not staged for commit: # (use 'git add <file>...' to update what will be committed) # (use 'git checkout -- <file>...' to discard changes in working directory) # # modified: test.txt #gittest$ git checkout .gittest$ git status # On branch master # Changes to be committed: # (use 'git reset HEAD <file>...' to unstage) # # new file: test.txt # We have given a meaning to the staging area. And we can also think about it as the very first ‘environment’ we are facing with, since every command without specific parameters works on staging. Let’s move on. We are now able to add or discard changings to the staging area. We also know how to persistently store the changings, via git commit. What we do not yet know how to do is to discard completely our staging area. With a parallel with what we just did before, discarding staging is performed with: git checkout HEAD . That technically means that we are reverting to a specific commit point, the last one(HEAD). Before testing this we have to perform a couple of interactions since inconsistent git behaviour doesn’t allow us to execute the test right away. The reason is because our file was a ‘new’ file and not a ‘modified’ one. This breaks the symmetry but let me come back on this concept later. @pantinor gittest$ git status # On branch master # Changes to be committed: # (use 'git reset HEAD <file>...' to unstage) # # new file: test.txt # pantinor@pantinor gittest$ git commit -m 'added new file' [master f331e52] added new file 1 file changed, 1 insertion(+) create mode 100644 test.txt pantinor@pantinor gittest$ git status # On branch master nothing to commit (working directory clean) pantinor@pantinor gittest$ echo 'added' >> test.txt pantinor@pantinor gittest$ git status # On branch master # Changes not staged for commit: # (use 'git add <file>...' to update what will be committed) # (use 'git checkout -- <file>...' to discard changes in working directory) # # modified: test.txt # no changes added to commit (use 'git add' and/or 'git commit -a') pantinor@pantinor gittest$ git add test.txt pantinor@pantinor gittest$ git status # On branch master # Changes to be committed: # (use 'git reset HEAD <file>...' to unstage) # # modified: test.txt # pantinor@pantinor gittest$ git checkout HEAD . pantinor@pantinor gittest$ git status # On branch master nothing to commit (working directory clean) We have just learnt how to revert to a clean situation. We are now much less scared of the staging area. But we are still bad git users. We always forget to branch before starting to modify a working folder as suggested here: http://nvie.com/posts/a-successful-git-branching-model/ In my case it often goes like this: I have a stable situation, than I start to tweak something. But the tweaking is not linear and after some minutes I have lots of modified files. Yes, I could stage them all and commit them, but I do not trust myself and I do not want to pollute the master branch. It would have been much better if I was on a dev branch from the beginning of my modifications. What I could do now? We can create on the fly a branch and switch to it. pantinor@pantinor gittest$ echo something >> test.txt pantinor@pantinor gittest$ git status # On branch master # Changes not staged for commit: # (use 'git add <file>...' to update what will be committed) # (use 'git checkout -- <file>...' to discard changes in working directory) # # modified: test.txt # no changes added to commit (use 'git add' and/or 'git commit -a') pantinor@pantinor gittest$ git checkout -b dev M test.txt Switched to a new branch 'dev' On this new branch we will still accessing the shared staging area as you can see from my output: pantinor@pantinor gittest$ git status # On branch dev # Changes not staged for commit: # (use 'git add <file>...' to update what will be committed) # (use 'git checkout -- <file>...' to discard changes in working directory) # # modified: test.txt # no changes added to commit (use 'git add' and/or 'git commit -a') What we want to do now, is to add the working situation to the staging and to commit it, so to be able to flush the shared staging area. pantinor@pantinor gittest$ git add . pantinor@pantinor gittest$ git commit -m unstable [dev 5d597b2] unstable 1 file changed, 1 insertion(+) pantinor@pantinor gittest$ git status # On branch dev nothing to commit (working directory clean)pantinor@pantinor gittest$ cat test.txt text something and then, when we will go back to our master, we can find it free of all our experimental modification, not mature for the master branch: pantinor@pantinor gittest$ git checkout master Switched to branch 'master' pantinor@pantinor gittest$ git status # On branch master nothing to commit (working directory clean) pantinor@pantinor gittest$ echo test.txt test.txt Great. Keeping our commands relatively simple and free of parameters and flag we are able to do all the errors that we are inevitable going to do anyway. Let’s now introduce another pattern to cope with our other typical errors. The situation is similar to the one just described, but a little worse. Again, we haven’t branched before starting to play with the code, but this time we have also committed a couple of times before realizing that what we have committed is not as good as we thought. What we want to do this time, is to keep our unstable situation, but we want to move it away(hard reset) from the current branch. Let’s do a couple of commits: pantinor@pantinor gittest$ git status # On branch master nothing to commit (working directory clean) pantinor@pantinor gittest$ cat test.txt text pantinor@pantinor gittest$ echo 'modification1' >> test.txt pantinor@pantinor gittest$ git commit -a -m'first commit' [master 9ad2aa8] first commit 1 file changed, 1 insertion(+) pantinor@pantinor gittest$ echo 'modification2' >> test.txt pantinor@pantinor gittest$ git commit -a -m'second commit' [master 7005a92] second commit 1 file changed, 1 insertion(+) pantinor@pantinor gittest$ cat test.txt text modification1 modification2 pantinor@pantinor gittest$ git log commit 7005a92a3ceee37255dc7143239d55c7c3467551 Author: Paolo Antinori <pantinor redhat.com='redhat.com'> Date: Sun Dec 16 21:05:48 2012 +0000second commitcommit 9ad2aa8fae1cbd844f34da2701e80d2c6e39320e Author: Paolo Antinori <pantinor redhat.com='redhat.com'> Date: Sun Dec 16 21:05:23 2012 +0000first commitcommit f331e52f41a862d727869b52e2e42787aa4cb57f Author: Paolo Antinori <pantinor redhat.com='redhat.com'> Date: Sun Dec 16 20:20:15 2012 +0000added new file At this point we want to move the last 2 commit to a different branch: git branch unstable We created a new branch, but we haven’t switched to it. The just created new branch has obviously everything that was present at the time of its creation, i.e. the 2 commits that we want to remove. So we can revert our current branch to a previous commit, discarding completely the recent ones that will remain available on the unstable branch. To see what’s the commit that we want to revert to: git log we need to read the hashcode associated with the commit, to be able to perform our rollback(hard reset): pantinor@pantinor gittest$ git reset --hard f331e52f41a862d727869b52e2e42787aa4cb57f HEAD is now at f331e52 added new file If you now execute a git status or a git log, you will see no trace of the unstable commit, that are instead accessible in the unstable branch. On current: pantinor@pantinor gittest$ cat test.txt text pantinor@pantinor gittest$ git log commit f331e52f41a862d727869b52e2e42787aa4cb57f Author: Paolo Antinori <pantinor redhat.com='redhat.com'> Date: Sun Dec 16 20:20:15 2012 +0000added new file On branch: pantinor@pantinor gittest$ git checkout unstable Switched to branch 'unstable' pantinor@pantinor gittest$ cat test.txt text modification1 modification2 pantinor@pantinor gittest$ git log commit 7005a92a3ceee37255dc7143239d55c7c3467551 Author: Paolo Antinori <pantinor redhat.com='redhat.com'> Date: Sun Dec 16 21:05:48 2012 +0000second commitcommit 9ad2aa8fae1cbd844f34da2701e80d2c6e39320e Author: Paolo Antinori <pantinor redhat.com='redhat.com'> Date: Sun Dec 16 21:05:23 2012 +0000first commitcommit f331e52f41a862d727869b52e2e42787aa4cb57f Author: Paolo Antinori <pantinor redhat.com='redhat.com'> Date: Sun Dec 16 20:20:15 2012 +0000added new file   Reference: Git – let’s make errors (and learn how to revert them) from our JCG partner Paolo Antinori at the Someday Never Comes blog. ...
java-logo

My Custom Thread Pool Executor in Java

ThreadPoolExecutor is a feature added by java concurrent api to maintain and reuse threads efficiently , so that our programs don’t have to worry about creating and destroying threads and focus on the core functionality. I have created a custom thread pool executor to get better understanding of how thread pool executor would work . Functionality :It maintains a fixed thread pool ,and creates threads and start the threads even if no task is submitted whereas ThreadPoolExecutor creates threads on demand , i.e. whenever a runnable is submitted to pool and the number of threads are less than core pool size . In ThreadPoolExecutor, we provide a waiting queue ,where new runnable task waits when all threads are busy running existing task. Once the queue is filled , new threads will be created up to maximum pool size. In MyThreadPool , i am storing the runnable in a linked list , so every task will wait in the list and it is unbounded , so no usage of maxPoolSize in this . In ThreadPoolExecutor , we use Future Objects to get the result from task , future.get() method will block if the result is not available , or we use CompletionService . In MyThreadPoolExecutor , i have created a simple interface called ResultListener , user has to provide a implementation of this as to how he wants the output to be processed . After every task is completed , the ResultListener will get callback with the output of task or error method will be called in case of any exception. When shutdown method is called , MyThreadPoolExecutor will stop accepting new tasks and complete the remaining tasks . I have provided very basic functionality as compared to ThreadPoolExecutor , i have used simple thread mechanism like wait() , notify() , notifyAll(), and join(). Performance wise it is similar to ThreadPoolExecutor , some times better in some cases. Do let me know if you find any interesting results or ways to improve it .package com.util;import java.util.concurrent.Callable;/** * Run submitted task of {@link MyThreadPool} After running the task , It calls * on {@link ResultListener}object with {@link Output}which contains returned * result of {@link Callable}task. Waits if the pool is empty. * * @author abhishek * * @param*/import java.util.concurrent.Callable; /** * Run submitted task of {@link MyThreadPool} After running the task , It calls * on {@link ResultListener}object with {@link Output}which contains returned * result of {@link Callable}task. Waits if the pool is empty. * * @author abhishek * * @param <V> */ public class MyThread<V> extends Thread { /** * MyThreadPool object, from which the task to be run */ private MyThreadPool<V> pool; private boolean active = true; public boolean isActive() { return active; } public void setPool(MyThreadPool<V> p) { pool = p; } /** * Checks if there are any unfinished tasks left. if there are , then runs * the task and call back with output on resultListner Waits if there are no * tasks available to run If shutDown is called on MyThreadPool, all waiting * threads will exit and all running threads will exit after finishing the * task */ public void run() { ResultListener<V> result = pool.getResultListener(); Callable<V> task; while (true) { task = pool.removeFromQueue(); if (task != null) { try { V output = task.call(); result.finish(output); } catch (Exception e) { result.error(e); } } else { if (!isActive()) break; else { synchronized (pool.getWaitLock()) { try { pool.getWaitLock().wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } } } void shutdown() { active = false; } } package com.util; import java.util.LinkedList; import java.util.concurrent.Callable; /** * This class is used to execute submitted {@link Callable} tasks. this class * creates and manages fixed number of threads User will provide a * {@link ResultListener}object in order to get the Result of submitted task * * @author abhishek * * */ public class MyThreadPool<V> { private Object waitLock = new Object(); public Object getWaitLock() { return waitLock; } /** * list of threads for completing submitted tasks */ private final LinkedList<MyThread<V>> threads; /** * submitted task will be kept in this list untill they run by one of * threads in pool */ private final LinkedList<Callable<V>> tasks; /** * shutDown flag to shut Down service */ private volatile boolean shutDown; /** * ResultListener to get back the result of submitted tasks */ private ResultListener<V> resultListener; /** * initializes the threadPool by starting the threads threads will wait till * tasks are not submitted * * @param size * Number of threads to be created and maintained in pool * @param myResultListener * ResultListener to get back result */ public MyThreadPool(int size, ResultListener<V> myResultListener) { tasks = new LinkedList<Callable<V>>(); threads = new LinkedList<MyThread<V>>(); shutDown = false; resultListener = myResultListener; for (int i = 0; i < size; i++) { MyThread<V> myThread = new MyThread<V>(); myThread.setPool(this); threads.add(myThread); myThread.start(); } } public ResultListener<V> getResultListener() { return resultListener; } public void setResultListener(ResultListener<V> resultListener) { this.resultListener = resultListener; } public boolean isShutDown() { return shutDown; } public int getThreadPoolSize() { return threads.size(); } public synchronized Callable<V> removeFromQueue() { return tasks.poll(); } public synchronized void addToTasks(Callable<V> callable) { tasks.add(callable); } /** * submits the task to threadPool. will not accept any new task if shutDown * is called Adds the task to the list and notify any waiting threads * * @param callable */ public void submit(Callable<V> callable) { if (!shutDown) { addToTasks(callable); synchronized (this.waitLock) { waitLock.notify(); } } else { System.out.println('task is rejected.. Pool shutDown executed'); } } /** * Initiates a shutdown in which previously submitted tasks are executed, * but no new tasks will be accepted. Waits if there are unfinished tasks * remaining * */ public void stop() { for (MyThread<V> mythread : threads) { mythread.shutdown(); } synchronized (this.waitLock) { waitLock.notifyAll(); } for (MyThread<V> mythread : threads) { try { mythread.join(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } package com.util;/** * This interface imposes finish method * which is used to get the {@link Output} object * of finished task * @author abhishek * * @param*/public interface ResultListener{public void finish(T obj); public void error(Exception ex);} you can implement this class as you want to get back and process the result returned by tasks. package com.util;public class DefaultResultListener implements ResultListener{@Override public void finish(Object obj) {}@Override public void error(Exception ex) { ex.printStackTrace(); }} For example this class will add the number returned by tasks . package com.util;import java.util.concurrent.atomic.AtomicInteger;/** * ResultListener class to keep track of total matched count * @author abhishek * * @param*/ public class MatchedCountResultListenerimplements ResultListener{/** * matchedCount to keep track of the number of matches returned by submitted * task */ AtomicInteger matchedCount = new AtomicInteger();/** * this method is called by ThreadPool to give back the result of callable * task. if the task completed successfully then increment the matchedCount by * result count */ @Override public void finish(V obj) { //System.out.println('count is '+obj); matchedCount.addAndGet((Integer)obj); }/** * print exception thrown in running the task */ @Override public void error(Exception ex) { ex.printStackTrace(); }/** * returns the final matched count of all the finished tasks * * @return */ public int getFinalCount() { return matchedCount.get(); } } This is a test class which runs simple for loop using CompletionService and MyThreadPoolExecutor package test;import java.util.concurrent.Callable; import java.util.concurrent.CompletionService; import java.util.concurrent.ExecutorCompletionService; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future;import com.util.DefaultResultListener; import com.util.MyThreadPool;public class TestClass {public static void main(String[] args) throws InterruptedException { CompletionServicethreadService; ExecutorService service = Executors.newFixedThreadPool(2); threadService = new ExecutorCompletionService(service);long b = System.currentTimeMillis(); for(int i =0;i<50000;i++){ threadService.submit(new MyRunable (i)); }service.shutdown(); System.out.println('time taken by Completion Service ' + (System.currentTimeMillis()-b));DefaultResultListener result = new DefaultResultListener(); MyThreadPoolnewPool = new MyThreadPool(2,result); long a = System.currentTimeMillis();int cc =0; for(int i =0;i<50000;i++) { cc = cc+i; } System.out.println('time taken without any pool ' + (System.currentTimeMillis()-a)); a= System.currentTimeMillis();for(int i =0;i<5000;i++){ newPool.submit(new MyRunable (i)); }newPool.stop(); System.out.println('time taken by myThreadPool ' + (System.currentTimeMillis()-a)); }}class MyRunable implements Callable{ int index = -1; public MyRunable(int index) { this.index = index; } @Override public Integer call() throws Exception { return index; }}   Reference: My Custom Thread Pool Executor in Java from our JCG partner Abhishek Somani at the Java , J2EE , Server blog. ...
career-logo

Mobile Development Job Trends – 2013-02

Today is the final winter job trends post, mobile development job trends. Initially, this was a look at how mobile phone development was moving, but now tablets have become a major force as well. Obviously, these trends are not . The terms included in this list were iPhone (including iOS and iPad), Android, WP7 or “Windows Phone“, BlackBerry, WebOS, Apache Cordova and PhoneGap. Symbian was removed as it barely registers on the basic demand charts and is showing essentially no growth. First, let’s look at the basic job trends from Indeed:        Oddly, there has been a fairly significant decline in mobile development demand over the past year for all of these technologies. This is consistent with the programming language trends, but I expected mobile to be different. It seems that development demand had slowed during 2012. All things Apple seems to have a significant lead, but it is the one area where there is some noise in the data. Android currently trails, but has a large lead on the others. Blackberry continues a steady downward trend that started two years ago. Windows phone is showing some signs of life, but it can’t seem to break away from the trailing pack. WebOS is in a bit of a decline but recent news of its continued life mean it could still be a player in some circles. PhoneGap and Cordova are not showing much increase in demand, but being cross platform development tools means that they will likely never reach the same heights as Android or iOS. Now we can look at the short-term trends from SimplyHired:I changed the SimplyHired trend query to look at each term individually because ORing terms together had a weird effect on the trends. As you can see, iPhone is still leading a bit with iOS slowly moving towards matching it. iPad demand trails the others, but it is unlikely that iPad appears where iOS or iPhone don’t. Android is increasing steadily, but it does not look like it will hold off iOS. Obviously, given the noise with iPhone and iPad jobs, the real trend is with iOS but not the overall demand. Blackberry does not show the same steep decline as the Indeed trend, but it is still in decline just slower. All of the others, Windows Phone, WP7, WebOS, Cordova and PhoneGap, trail far beneath the others. You can see a glimmer of hope from the PhoneGap trend as it is increasing in the past 6 months, but demand is still small. Lastly, we have the relative growth trends from Indeed:Um … Android is growing very rapidly. This renders the chart useless, so let’s look at the trends without Android:We can see the trends more clearly now. WebOS had a great spike in 2011, but growth has declined significantly. Interesting, PhoneGap had a great peak in the middle of 2012, but it does not look like it is maintaining its pace. This will be a trend to watch this year, as well as how Cordova affects it. Windows phone shows a very nice growth trend, though the growth slowed a bit at the end of 2012. As huge as demand for iOS development is, the growth is still very strong. Typically, when demand is very high, the growth tapers off, but iOS is bucking that trend. Blackberry growth really started to decline in 2012, but that was before the most recent releases which could affect demand. Cordova does not seem to be having an affect yet, but it is something to watch long term. As mobile development continues to grow, the options are becoming more numerous as well. iPhone development and Android development will continue to be strong, but cross platform development is gaining adoption with things like PhoneGap development. Apache Cordova is something to watch, given that it is an Apache project and cross platform. Another trend to watch is how the new Firefox OS and Ubuntu Touch affect the other technologies. Related ArticlesTraditional Programming Language Job Trends – February 2013 (regulargeek.com) NoSQL Job Trends – February 2013 (regulargeek.com) Firefox OS won’t magically succeed just because it’s open source – see webOS (guardian.co.uk) LG To Write Next Chapter For HP WebOS (informationweek.com)  Reference: Mobile Development Job Trends – 2013-02 from our JCG partner Rob Diana at the Regular Geek blog. ...
jcg-logo

Devoxx UK free ticket giveaway – Roundup

Fellow geeks, Our giveaway of a £350 Devoxx UK 2013 London community conference ticket has ended. You may find the original post for the competition here. The Prize Winner The lucky winner who will receive a ticket for the Devoxx UK 2013 London community conference going to take place on the 26th and 27th of March 2013 is (name is as appeared on their email): Christopher Batey Overview of the conference The Devoxx non-profit community conferences have been very successfully run in Belgium and France. We enjoyed them so much that the London Java Community (LJC) decided to bring a version over to London (http://www.devoxx.co.uk)! So we’re bringing the who’s who of the Java/JVM and Software Development including folks such as Milton Smith – head of Java security and Charlie Nutter – the inventor of JRuby, as well as showcasing talent from the local development community. Tracks Include:Languages on the JVM Java SE Java EE Mobile Architecture, Cloud and Security Web and Big Data Methodology The FutureWe’d love to see you and members from your dev teams there as attendees (it’s a non-profit conference by developers for developers). It’s only £350 for the two days, so get in quick at (http://www.devoxx.co.uk) More details at: http://www.devoxx.co.uk Register now at: http://reguk.devoxx.com Twitter: @DevoxxUK   Congratulations to the winner! Thank you all for participating. Happy coding!   The Java Code Geeks team ...
java-logo

Difference between Comparator and Comparable in Java

One of the common interview question is ‘What are differences between Comparator and Comparable’. or ‘How will you sort collection of employee objects by its id or name’.For that we can use two interfaces.i.e. Comparator and Comparable.Before we actually see differences,let me give you brief introduction of both. Comparable interface: Class whose objects to be sorted must implement this interface.In this,we have to implement compareTo(Object) method. For example:       public class Country implements Comparable{ @Override public int compareTo(Object arg0) { Country country=(Country) arg0; return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ; }} If any class implements comparable inteface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort().Object will be sort on the basis of compareTo method in that class. Objects which implement Comparable in java can be used as keys in a SortedMap like TreeMap or SortedSet like TreeSet without implementing any other interface. Comparator interface: Class whose objects to be sorted do not need to implement this interface.Some third class can implement this interface to sort.e.g.CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by id. For example: public class CountrySortByIdComparator implements Comparator<Country>{@Override public int compare(Country country1, Country country2) {return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ; }} Using Comparator interface,we can write different sorting based on different attributes of objects to be sorted.You can use anonymous comparator to compare at particular line of code. For example: Country indiaCountry=new Country(1, 'India'); Country chinaCountry=new Country(4, 'China'); Country nepalCountry=new Country(3, 'Nepal'); Country bhutanCountry=new Country(2, 'Bhutan');List<Country> listOfCountries = new ArrayList<Country>(); listOfCountries.add(indiaCountry); listOfCountries.add(chinaCountry); listOfCountries.add(nepalCountry); listOfCountries.add(bhutanCountry);//Sort by countryNameCollections.sort(listOfCountries,new Comparator<Country>() {@Override public int compare(Country o1, Country o2) {return o1.getCountryName().compareTo(o2.getCountryName()); } }); Comparator vs ComparableParameter Comparable ComparatorSorting logic Sorting logic must be in same class whose objects are being sorted. Hence this is called natural ordering of objects Sorting logic is in separate class. Hence we can write different sorting based on different attributes of objects to be sorted. E.g. Sorting using id,name etc.Implementation Class whose objects to be sorted must implement this interface.e.g Country class needs to implement comparable to collection of country object by id Class whose objects to be sorted do not need to implement this interface.Some other class can implement this interface. E.g.-CountrySortByIdComparator class can implement Comparator interface to sort collection of country object by idSorting method int compareTo(Object o1) This method compares this object with o1 object and returns a integer.Its value has following meaning 1. positive – this object is greater than o1 2. zero – this object equals to o1 3. negative – this object is less than o1 int compare(Object o1,Object o2) This method compares o1 and o2 objects. and returns a integer.Its value has following meaning. 1. positive – o1 is greater than o2 2. zero – o1 equals to o2 3. negative – o1 is less than o1Calling method Collections.sort(List) Here objects will be sorted on the basis of CompareTo method Collections.sort(List, Comparator) Here objects will be sorted on the basis of Compare method in ComparatorPackage Java.lang.Comparable   Java.util.ComparatorJava code: For Comparable: We will create class country having attribute id and name.This class will implement Comparable interface and implement CompareTo method to sort collection of country object by id. 1. Country.java package org.arpit.javapostsforlearning; //If this.cuntryId < country.countryId:then compare method will return -1 //If this.countryId > country.countryId:then compare method will return 1 //If this.countryId==country.countryId:then compare method will return 0 public class Country implements Comparable{ int countryId; String countryName;public Country(int countryId, String countryName) { super(); this.countryId = countryId; this.countryName = countryName; }@Override public int compareTo(Object arg0) { Country country=(Country) arg0; return (this.countryId < country.countryId ) ? -1: (this.countryId > country.countryId ) ? 1:0 ; }public int getCountryId() { return countryId; }public void setCountryId(int countryId) { this.countryId = countryId; }public String getCountryName() { return countryName; }public void setCountryName(String countryName) { this.countryName = countryName; }} 2.ComparatorMain.java package org.arpit.javapostsforlearning;import java.util.ArrayList; import java.util.Collections; import java.util.List;public class ComparatorMain {/** * @author Arpit Mandliya */ public static void main(String[] args) { Country indiaCountry=new Country(1, 'India'); Country chinaCountry=new Country(4, 'China'); Country nepalCountry=new Country(3, 'Nepal'); Country bhutanCountry=new Country(2, 'Bhutan');List<Country> listOfCountries = new ArrayList<Country>(); listOfCountries.add(indiaCountry); listOfCountries.add(chinaCountry); listOfCountries.add(nepalCountry); listOfCountries.add(bhutanCountry);System.out.println('Before Sort : '); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country) listOfCountries.get(i); System.out.println('Country Id: '+country.getCountryId()+'||'+'Country name: '+country.getCountryName()); } Collections.sort(listOfCountries);System.out.println('After Sort : '); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country) listOfCountries.get(i); System.out.println('Country Id: '+country.getCountryId()+'|| '+'Country name: '+country.getCountryName()); } }} Output: Before Sort : Country Id: 1||Country name: India Country Id: 4||Country name: China Country Id: 3||Country name: Nepal Country Id: 2||Country name: Bhutan After Sort : Country Id: 1|| Country name: India Country Id: 2|| Country name: Bhutan Country Id: 3|| Country name: Nepal Country Id: 4|| Country name: China For Comparator: We will create class country having attribute id and name and will create another class CountrySortByIdComparator which will implement Comparator interface and implement compare method to sort collection of country object by id and we will also see how to use anonymous comparator. 1.Country.java package org.arpit.javapostsforlearning;public class Country{ int countryId; String countryName;public Country(int countryId, String countryName) { super(); this.countryId = countryId; this.countryName = countryName; }public int getCountryId() { return countryId; }public void setCountryId(int countryId) { this.countryId = countryId; }public String getCountryName() { return countryName; }public void setCountryName(String countryName) { this.countryName = countryName; }} 2.CountrySortbyIdComparator.java package org.arpit.javapostsforlearning;import java.util.Comparator; //If country1.getCountryId()<country2.getCountryId():then compare method will return -1 //If country1.getCountryId()>country2.getCountryId():then compare method will return 1 //If country1.getCountryId()==country2.getCountryId():then compare method will return 0 public class CountrySortByIdComparator implements Comparator<Country>{@Override public int compare(Country country1, Country country2) {return (country1.getCountryId() < country2.getCountryId() ) ? -1: (country1.getCountryId() > country2.getCountryId() ) ? 1:0 ; }} 3.ComparatorMain.java package org.arpit.javapostsforlearning;import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List;public class ComparatorMain {/** * @author Arpit Mandliya */ public static void main(String[] args) { Country indiaCountry=new Country(1, 'India'); Country chinaCountry=new Country(4, 'China'); Country nepalCountry=new Country(3, 'Nepal'); Country bhutanCountry=new Country(2, 'Bhutan');List<Country> listOfCountries = new ArrayList<Country>(); listOfCountries.add(indiaCountry); listOfCountries.add(chinaCountry); listOfCountries.add(nepalCountry); listOfCountries.add(bhutanCountry);System.out.println('Before Sort by id : '); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country) listOfCountries.get(i); System.out.println('Country Id: '+country.getCountryId()+'||'+'Country name: '+country.getCountryName()); } Collections.sort(listOfCountries,new CountrySortByIdComparator());System.out.println('After Sort by id: '); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country) listOfCountries.get(i); System.out.println('Country Id: '+country.getCountryId()+'|| '+'Country name: '+country.getCountryName()); }//Sort by countryName Collections.sort(listOfCountries,new Comparator<Country>() {@Override public int compare(Country o1, Country o2) { return o1.getCountryName().compareTo(o2.getCountryName()); } });System.out.println('After Sort by name: '); for (int i = 0; i < listOfCountries.size(); i++) { Country country=(Country) listOfCountries.get(i); System.out.println('Country Id: '+country.getCountryId()+'|| '+'Country name: '+country.getCountryName()); } }} Output: Before Sort by id : Country Id: 1||Country name: India Country Id: 4||Country name: China Country Id: 3||Country name: Nepal Country Id: 2||Country name: Bhutan After Sort by id: Country Id: 1|| Country name: India Country Id: 2|| Country name: Bhutan Country Id: 3|| Country name: Nepal Country Id: 4|| Country name: China After Sort by name: Country Id: 2|| Country name: Bhutan Country Id: 4|| Country name: China Country Id: 1|| Country name: India Country Id: 3|| Country name: Nepal   Reference: Difference between Comparator and Comparable in Java from our JCG partner Arpit Mandliya at the Java frameworks and design patterns for beginners blog. ...
java-logo

Observer design pattern in Java

As the name suggests it is used for observing some objects.Observer watch for any change in state or property of subject.Suppose you are interested in particular object and want to get notified when its state changes then you observe that object and when any state or property change happens to that object,it get notified to you. As described by GoF: ‘Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically’ You can think of observer design pattern in two waysSubject-Observer relationship:Object which is being observed is refereed as Subject and classes which observe subject are called Observer Publisher-Subscriber relationship:A publisher is one who publish data and notifies it to the list of subscribers who have subscribed for the same to that publisher. A simple example is Newspaper. Whenever a new edition is published by the publisher,it will be circulated among subscribers whom have subscribed to publisher.The observers will not monitor every time whether there is any change in state of subject or not, since they will be notified for every state change of subject, until they stop observing subject. So it follows hollywood principle-‘Don’t call us,we will call you’. Some real life examples: You might have surfed ‘Flipkart.com-Online megastore’.So when you search for any product and it is unavailable then there is option called ‘Notify me when product is available’.If you subscribe to that option then when state of product changes i.e. it is available,you will get notification mail ‘Product is available now you can buy it’.In this case,Product is subject and You are an observer. Lets say,your permanent address is changed then you need to notify passport authority and pan card authority.So here passport authority and pan card authority are observers and You are a subject. On facebook also,If you subscribe someone then whenever new updates happen then you will be notified. When to use it:When one object changes its state,then all other dependents object must automatically change their state to maintain consistency When subject doesn’t know about number of observers it has. When an object should be able to notify other objects without knowing who objects are.UML diagram for observer design pattern:Components: SubjectKnows its observers Has any number of observer Provides an interface to attach and detaching observer object at run timeObserverProvides an update interface to receive signal from subjectConcreteSubjectStores state of interest to ConcreteObserver objects. Send notification to it’s observerConcreteObserverMaintains reference to a ConcreteSubject object Maintains observer state consistent with subjects. Implements update operationJava in-built API for observer pattern: The java API provides one class and one inteface for implementing observer pattern. 1. java.util.Observable-class 2. java.util.Observer-interface java.util.Observable: For being observed,class must extend this class. The subclass becomes observable and override methods of java.util.Observable and other objects can ‘observe’ changes in state of this object. Methods: addObserver(Observer o) :add Observer to the list of observers for this subject. deleteObserver(Observer o) :delete Observers from the list of observers . notifyObservers() : notify all the observers if object has changed. hasChanged() :return true if object has changed. setChanged() :This method marks object has changed clearChanged() :this method will indicate that subject has no changes or all the observers has been notified. java.util.Observer: The class that performs the ‘observing’ must implement the java.util.Observer interface. There is a single method: public void update(Observable obj, Object arg) :This method is called whenever the observed object is changed. An application calls an Observable object’s notifyObservers method for notifying to all the observers of change. Example: You might have surfed ‘Flipkart.com-Online megastore’.So when you search for any product and it is unavailable then there is option called ‘Notify me when product is available’.If you subscribe to that option then when state of product changes i.e. it is available,you will get notification mail ‘Product is available now you can buy it’.Java code: Below interface is our subject interface.It consists of method for adding or removing observers and also in condition of state change,notify all observer. 1.Subject.java: package org.arpit.javapostsforlearning;public interface Subject { public void registerObserver(Observer observer); public void removeObserver(Observer observer); public void notifyObservers(); } Below class is our ConcreteSubject class.It implements subject interface thus provide implementation of all above three methods. 2.Product.java: package org.arpit.javapostsforlearning;import java.util.ArrayList;public class Product implements Subject{private ArrayList<Observer> observers = new ArrayList<Observer>(); private String productName; private String productType; String availability;public Product(String productName, String productType,String availability) { super(); this.productName = productName; this.productType = productType; this.availability=availability; }public ArrayList<Observer> getObservers() { return observers; } public void setObservers(ArrayList<Observer> observers) { this.observers = observers; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductType() { return productType; } public void setProductType(String productType) { this.productType = productType; }public String getAvailability() { return availability; }public void setAvailability(String availability) { this.availability = availability; notifyObservers(); }public void notifyObservers() { System.out.println('Notifying to all the subscribers when product became available'); for (Observer ob : observers) { ob.update(this.availability ); }}public void registerObserver(Observer observer) { observers.add(observer);}public void removeObserver(Observer observer) { observers.remove(observer);}} Below interface is our observer interface.It consists of single method called ‘update’ 3.Observer.java: package org.arpit.javapostsforlearning; public interface Observer { public void update(String availability); } Below class is our ConcreteObserver class.It implements observer interface and provide implementation for update and other ConcreteObserver specific methods. 4.Person.java: package org.arpit.javapostsforlearning; public class Person implements Observer{String personName;public Person(String personName) { this.personName = personName; }public String getPersonName() { return personName; }public void setPersonName(String personName) { this.personName = personName; }public void update(String availabiliy) {System.out.println('Hello '+personName+', Product is now '+availabiliy+' on flipkart'); } } 5.ObserverPatternMain.java: package org.arpit.javapostsforlearning; public class ObserverPatternMain {/** * @Author arpit mandliya */ public static void main(String[] args) { Person arpitPerson=new Person('Arpit'); Person johnPerson=new Person('John');Product samsungMobile=new Product('Samsung', 'Mobile', 'Not available');//When you opt for option 'Notify me when product is available'.Below registerObserver method //get executed samsungMobile.registerObserver(arpitPerson); samsungMobile.registerObserver(johnPerson);//Now product is available samsungMobile.setAvailability('Available');} } Run it: Notifying to all the subscribers when product became available Hello Arpit, Product is now Available on flipkart Hello John, Product is now Available on flipkart Now in above program,when availability of samsung mobile changes,it get notified subscribers who has subscribed for it. Using java inbuilt APIs: 1.Product.java: package org.arpit.javapostsforlearning; import java.util.ArrayList; import java.util.Observable; import java.util.Observer;public class Product extends Observable{private ArrayList<Observer> observers = new ArrayList<Observer>(); private String productName; private String productType; String availability;public Product(String productName, String productType,String availability) { super(); this.productName = productName; this.productType = productType; this.availability=availability; }public ArrayList<Observer> getObservers() { return observers; } public void setObservers(ArrayList<Observer> observers) { this.observers = observers; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductType() { return productType; } public void setProductType(String productType) { this.productType = productType; }public String getAvailability() { return availability; }public void setAvailability(String availability) { if(!(this.availability.equalsIgnoreCase(availability))) { this.availability = availability; setChanged(); notifyObservers(this,availability); } }public void notifyObservers(Observable observable,String availability) { System.out.println('Notifying to all the subscribers when product became available'); for (Observer ob : observers) { ob.update(observable,this.availability); }}public void registerObserver(Observer observer) { observers.add(observer);}public void removeObserver(Observer observer) { observers.remove(observer);} } 2.Person.java package org.arpit.javapostsforlearning; import java.util.Observable; import java.util.Observer;public class Person implements Observer{String personName;public Person(String personName) { this.personName = personName; }public String getPersonName() { return personName; }public void setPersonName(String personName) { this.personName = personName; }public void update(Observable arg0, Object arg1) { System.out.println('Hello '+personName+', Product is now '+arg1+' on flipkart');}} 3.ObserverPatternMain.java: package org.arpit.javapostsforlearning; public class ObserverPatternMain {/** * @Author arpit mandliya */ public static void main(String[] args) { Person arpitPerson=new Person('Arpit'); Person johnPerson=new Person('John');Product samsungMobile=new Product('Samsung', 'Mobile', 'Not available');//When you opt for option 'Notify me when product is available'.Below registerObserver method //get executed samsungMobile.registerObserver(arpitPerson); samsungMobile.registerObserver(johnPerson);//Now product is available samsungMobile.setAvailability('Available');} } Run it: Notifying to all the subscribers when product became available Hello Arpit, Product is now Available on flipkart Hello John, Product is now Available on flipkart Some important points about observer pattern:Loose coupling between Subject and Observer:Only thing subject know about its observers is that observer implements Observer interface.You can register or delete any observer without affecting subject. Support for broadcast communication:Notification about subject state change does not need to specify its receiver.This notification is broadcasted to all interested object that subscribed to it. The one of the problem with this pattern is that debugging become very hard,if you have large number of subscribers because flow of control is implicit between subject and observers. Spurious updates:If criteria for state change is not well defined then sometimes it lead to spurious updates.Source code: Source: Download without java API Source + lib: Download with java API   Reference: Observer design pattern in Java from our JCG partner Arpit Mandliya at the Java frameworks and design patterns for beginners blog. ...
jboss-resteasy-logo

Java: Rest-assured (or Rest-Very-Easy)

Recently I had to write some Java code to consume REST services over HTTP. I’ve decided to use the Client libraries of RestEasy, the framework I use most of the time to expose REST services in Java, since it also implements the official JAX-RS specification. I am very satisfied with the annotation driven approach that the specification defines and it makes exposing REST services a very pleasant task. But unluckily I cannot say that I like the client API the same way. If you are lucky enough to be able to build a proxy client based on the interface implemented by the service, well, that’s not bad:       import org.jboss.resteasy.client.ProxyFactory; ... // this initialization only needs to be done once per VM RegisterBuiltin.register(ResteasyProviderFactory.getInstance());SimpleClient client = ProxyFactory.create(MyRestServiceInterface.class, 'http://localhost:8081'); client.myBusinessMethod('hello world'); Having a Proxy client similar to a JAX-WS one is good, I do agree. But most of the time, when we are consuming REST web service we do not have a Java interface to import. All those Twitter, Google or whatever public rest services available out there are just HTTP endpoints. The way to go with RestEasy in these cases is to rely on the RestEasy Manual ClientRequest API: ClientRequest request = new ClientRequest('http://localhost:8080/some/path'); request.header('custom-header', 'value');// We're posting XML and a JAXB object request.body('application/xml', someJaxb);// we're expecting a String back ClientResponse<String> response = request.post(String.class);if (response.getStatus() == 200) // OK! { String str = response.getEntity(); } That is in my opinion a very verbose way to fetch what is most of the time, just a bunch of strings from the web. And it gets even worse if you need to include Authentication informations: // Configure HttpClient to authenticate preemptively // by prepopulating the authentication data cache.// 1. Create AuthCache instance AuthCache authCache = new BasicAuthCache();// 2. Generate BASIC scheme object and add it to the local auth cache BasicScheme basicAuth = new BasicScheme(); authCache.put('com.bluemonkeydiamond.sippycups', basicAuth);// 3. Add AuthCache to the execution context BasicHttpContext localContext = new BasicHttpContext(); localContext.setAttribute(ClientContext.AUTH_CACHE, authCache);// 4. Create client executor and proxy httpClient = new DefaultHttpClient(); ApacheHttpClient4Executor executor = new ApacheHttpClient4Executor(httpClient, localContext); client = ProxyFactory.create(BookStoreService.class, url, executor); I have found that Rest-assured provide a much nicer API to write client invocations. Officially the aim of the project is to create a testing and validating framework; and most of the tutorials out there are covering those aspects, like the recent Heiko Rupp’s one: http://pilhuhn.blogspot.nl/2013/01/testing-rest-apis-with-rest-assured.html. I suggest yout, instead, to use it as a development tool to experiment and write REST invocation very rapidly. What is important to know about rest-assured:it implements a Domain Specific Language thanks to fluid API it is a single Maven dependency it almost completely expose a shared style for both xml and json response objects it relies on Apache Commons ClientSo, I’ll show you a bunch of real world use cases and I will leave you with some good link if you want to know more. As most of the DSL on Java, it works better if you import statically the most important objects: import static com.jayway.restassured.RestAssured.*; import static com.jayway.restassured.matcher.RestAssuredMatchers.*; Base usage: get('http://api.twitter.com/1/users/show.xml').asString(); That returns: <errors> <error code="34">Sorry, that page does not exist</error> </errors> Uh oh, some error. Yeah, we need to pass some parameter: with() .parameter('screen_name', 'resteasy') .get('http://api.twitter.com/1/users/show.xml').asString(); That returns: <user> <id>27016395</id> <name>Resteasy</name> <screen_name>resteasy</screen_name> <location></location> <profile_image_url>http://a0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png</profile_image_url> <profile_image_url_https>https://si0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png</profile_image_url_https> <url></url> <description>jboss.org/resteasy JBoss/Red Hat REST project</description> <protected>false</protected> <followers_count>244</followers_count> <profile_background_color>C0DEED</profile_background_color> <profile_text_color>333333</profile_text_color> <profile_link_color>0084B4</profile_link_color> <profile_sidebar_fill_color>DDEEF6</profile_sidebar_fill_color> <profile_sidebar_border_color>C0DEED</profile_sidebar_border_color> <friends_count>1</friends_count> <created_at>Fri Mar 27 14:39:52 +0000 2009</created_at> <favourites_count>0</favourites_count> <utc_offset></utc_offset> <time_zone></time_zone> <profile_background_image_url>http://a0.twimg.com/images/themes/theme1/bg.png</profile_background_image_url> <profile_background_image_url_https>https://si0.twimg.com/images/themes/theme1/bg.png</profile_background_image_url_https> <profile_background_tile>false</profile_background_tile> <profile_use_background_image>true</profile_use_background_image> <geo_enabled>false</geo_enabled> <verified>false</verified> <statuses_count>8</statuses_count> <lang>en</lang> <contributors_enabled>false</contributors_enabled> <is_translator>false</is_translator> <listed_count>21</listed_count> <default_profile>true</default_profile> <default_profile_image>true</default_profile_image> ... </user> Much better! Now, let’s say that we want only a token of this big String XML: with() .parameter('screen_name', 'resteasy') .get('http://api.twitter.com/1/users/show.xml') .path('user.profile_image_url') And here’s our output: http://a0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png What if it was a JSON response? with() .parameter('screen_name', 'resteasy') .get('http://api.twitter.com/1/users/show.json') And here’s our output:{"id":27016395,"id_str":"27016395","name":"Resteasy","screen_name":"resteasy","location":"","url":null,"description":"jboss.org\/resteasy\n\nJBoss\/Red Hat REST project","protected":false,"followers_count":244,"friends_count":1,"listed_count":21,"created_at":"Fri Mar 27 14:39:52 +0000 2009","favourites_count":0,"utc_offset":null,"time_zone":null,"geo_enabled":false,"verified":false,"statuses_count":8,"lang":"en","status":{"created_at":"Tue Mar 23 14:48:51 +0000 2010","id":10928528312,"id_str":"10928528312","text":"Doing free webinar tomorrow on REST, JAX-RS, RESTEasy, and REST-*. Only 40 min, so its brief. http:\/\/tinyurl.com\/yz6xwek","source":"web","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"geo":null,"coordinates":null,"place":null,"contributors":null,"retweet_count":0,"favorited":false,"retweeted":false},"contributors_enabled":false,"is_translator":false,"profile_background_color":"C0DEED","profile_background_image_url":"http:\/\/a0.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_image_url_https":"https:\/\/si0.twimg.com\/images\/themes\/theme1\/bg.png","profile_background_tile":false,"profile_image_url":"http:\/\/a0.twimg.com\/sticky\/default_profile_images\/default_profile_0_normal.png","profile_image_url_https":"https:\/\/si0.twimg.com\/sticky\/default_profile_images\/default_profile_0_normal.png","profile_link_color":"0084B4","profile_sidebar_border_color":"C0DEED","profile_sidebar_fill_color":"DDEEF6","profile_text_color":"333333","profile_use_background_image":true,"default_profile":true,"default_profile_image":true,"following":null,"follow_request_sent":null,"notifications":null} And the same interface undestands JSON object navigation. Note that the navigation expression does not include ‘user’ since it was not there in the full json response: with() .parameter('screen_name', 'resteasy') .get('http://api.twitter.com/1/users/show.json') .path('profile_image_url') And here’s our output: http://a0.twimg.com/sticky/default_profile_images/default_profile_0_normal.png Now an example of Path Parameters: with() .parameter('key', 'HomoSapiens') .get('http://eol.org/api/search/{key}').asString() Information about the http request: get('http://api.twitter.com/1/users/show.xml').statusCode(); get('http://api.twitter.com/1/users/show.xml').statusLine(); An example of Basic Authentication: with() .auth().basic('paolo', 'xxxx') .get('http://localhost:8080/b/secured/hello') .statusLine() An example of Multipart Form Upload with() .multiPart('file', 'test.txt', fileContent.getBytes()) .post('/upload') Maven dependency: <dependency> <groupid>com.jayway.restassured</groupid> <artifactid>rest-assured</artifactid> <version>1.4</version> <scope>test</scope> </dependency>And a Groovy snippet that can be pasted and executed directly in groovyConsole thanks to Grapes fetches the dependencies and add them automatically to the classpath, that shows you JAXB support: @Grapes([ @Grab('com.jayway.restassured:rest-assured:1.7.2') ]) import static com.jayway.restassured.RestAssured.* import static com.jayway.restassured.matcher.RestAssuredMatchers.* import javax.xml.bind.annotation.*@XmlRootElement(name = 'user') @XmlAccessorType( XmlAccessType.FIELD ) class TwitterUser { String id; String name; String description; String location;@Override String toString() { return 'Id: $id, Name: $name, Description: $description, Location: $location' }}println with().parameter('screen_name', 'resteasy').get('http://api.twitter.com/1/users/show.xml').as(TwitterUser.class)// This is just a brief list of the features of the library, just you an idea of how easy it is to work with it. For a further examples I suggest you to read the official pages here: https://code.google.com/p/rest-assured/wiki/Usage. Or another good tutorial here with a sample application to play with: http://www.hascode.com/2011/10/testing-restful-web-services-made-easy-using-the-rest-assured-framework   Reference: Java: Rest-assured (or Rest-Very-Easy) from our JCG partner Paolo Antinori at the Someday Never Comes blog. ...
java-logo

Java – Handmade Classloader Isolation

In a recent project we had a typical libraries conflict problem. One component that we could control wanted a specific version of an Apache Commons library, while another component was expecting a different one. Due to external constraints we could not specify any class loading isolation at the Container level. It wasn’t an option for us. What we decided to do instead has been to use the two different classes definition at the same time. To obtain this we had to let one class be loaded by the current thread class loader and to load manually the second one; in this way the two classes still have the same fully qualified name. The only restriction to this approach is the we had to interact with the manually loaded class only via reflection, since the current context, that is using a different class loader,   has a different definition of a class and we would be able to cast or assign a instance of the class loaded with a classloader to a variable defined in the context of the other. Our implementation is in effect a Classloader itself: DirectoryBasedParentLastURLClassLoader extends ClassLoader The characteristic of this Classloader is that we are passing it a file system folder path: public DirectoryBasedParentLastURLClassLoader(String jarDir) Our implementation scans the filesystem path to produce URLs and uses this information to pass them to a wrapped instance of a URLClassLoader that we are encapsulating with our CustomClassloader: public DirectoryBasedParentLastURLClassLoader(String jarDir) { super(Thread.currentThread().getContextClassLoader());// search for JAR files in the given directory FileFilter jarFilter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith('.jar'); } };// create URL for each JAR file found File[] jarFiles = new File(jarDir).listFiles(jarFilter); URL[] urls;if (null != jarFiles) { urls = new URL[jarFiles.length];for (int i = 0; i < jarFiles.length; i++) { try { urls[i] = jarFiles[i].toURI().toURL(); } catch (MalformedURLException e) { throw new RuntimeException( 'Could not get URL for JAR file: ' + jarFiles[i], e); } }} else { // no JAR files found urls = new URL[0]; }childClassLoader = new ChildURLClassLoader(urls, this.getParent()); } With this setup we can override the behaviour of the main classloading functionality, giving priority to the loading from our folder and falling back to the parent classloader only if we could find the requested class: @Override protected synchronized Class loadClass(String name, boolean resolve) throws ClassNotFoundException { try { // first try to find a class inside the child classloader return childClassLoader.findClass(name); } catch (ClassNotFoundException e) { // didn't find it, try the parent return super.loadClass(name, resolve); } } With our CustomClassloader in place we can use it in this way: //instantiate our custom classloader DirectoryBasedParentLastURLClassLoader classLoader = new DirectoryBasedParentLastURLClassLoader( ClassLoaderTest.JARS_DIR ); //manually load a specific class Class classManuallyLoaded = classLoader .loadClass('paolo.test.custom_classloader.support.MyBean'); //request a class via reflection Object myBeanInstanceFromReflection = classManuallyLoaded.newInstance(); //keep using the class via reflection Method methodToString = classManuallyLoaded.getMethod('toString'); assertEquals('v1', methodToString.invoke(myBeanInstanceFromReflection)); This idea for this post and part of its code come from this interesting discussion on Stackoverflow. A fully working Maven project is available on GitHub with a bunch of unit tests to verify the right behaviour.   Reference: Java – Handmade Classloader Isolation from our JCG partner Paolo Antinori at the Someday Never Comes blog. ...
play-framework-logo

Using twitter4j with Play! Framework and Secure Social is this easy

Dur­ing yesterday’s per­sonal Hackathon, I started a project which I might intro­duce here some­time. But the coolest rev­e­la­tion was (again) how easy it was to get up and running.Cre­ate a new Play Project Add Secure Social and con­fig­ure it for Twit­ter, and use the InMem­o­ryUserSer­vice from the exam­ples. (all this is described here http://securesocial.ws/guide/getting-started.html and only takes a minute) Add the depen­decy to twitter4j to your Build.scala like this:     'org.twitter4j'% 'twitter4j-core'% '3.0.3'Secure your con­troller action method to force the (Login) Authen­ti­ca­tion with Twit­ter. Remem­ber — because you are using the InMem­o­ryUserSer­vice none of the Authen­ti­ca­tion data is stored — you will have to recon­nect each time. @SecureSocial.SecuredAction I then added these stan­dard meth­ods to get the Authen­ti­cated Twit­ter User, Token, Secret and the twitter4J Con­nec­tion: (The tokenSe­cret, token and cur­rent User are com­ing from the Secure Social Oauth1 Con­nec­tion, and are used to authen­ti­cate the Twit­ter Con­nec­tion.             public static Twitter getTwitterInstance() { // The factory instance is re-useable and thread safe. TwitterFactory factory = new TwitterFactory(); Twitter twitter = new TwitterFactory().getInstance();twitter.setOAuthConsumer(Play.application().configuration() .getString('securesocial.twitter.consumerKey'), Play.application().configuration().getString('securesocial.twitter.consumerSecret')); twitter4j.auth.AccessToken accessToken = new twitter4j.auth.AccessToken(token(), tokenSecret()); twitter.setOAuthAccessToken(accessToken); return twitter; } public static String tokenSecret() { String retval = ''; scala.collection.Iterator iterator = Application.getCurrentUser().oAuth1Info().iterator(); while (iterator.hasNext()) { OAuth1Info oAuth1Info = iterator.next(); retval = oAuth1Info.secret(); } return retval; } public static String token() { String retval = ''; scala.collection.Iterator iterator = Application.getCurrentUser().oAuth1Info().iterator(); while (iterator.hasNext()) { OAuth1Info oAuth1Info = iterator.next(); retval = oAuth1Info.token(); } return retval; } public static Identity getCurrentUser() { return (Identity) ctx().args.get(SecureSocial.USER_KEY); }Then I added some code in my Con­troller to list (for exam­ple) my Fol­low­ers long cursor = -1; IDs ids; System.out.println('Listing following ids.'); do { ids = twitter.getFriendsIDs(cursor); for (long id : ids.getIDs()) { twitter4j.User twitterUser = twitter.showUser(id); twitterUsers.put(twitterUser.getScreenName(), new TwitterUser(id,twitterUser)); System.out.println(id); } } while ((cursor = ids.getNextCursor()) != 0);Yes, that is it…   Reference: Using twitter4j with Play! Framework and Secure Social is this easy from our JCG partner Brian Porter at the Poornerd blog. ...
Java Code Geeks and all content copyright © 2010-2014, 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