Featured FREE Whitepapers

What's New Here?

jboss-hibernate-logo

Hibernate: save vs persist and saveOrUpdate

What is difference between save and saveOrUpdate or Difference between save and persist are common interview question in any Hibernate interview, much like Difference between get and load method in Hibernate. Hibernate Session class provides couple of ways to save object into database by methods like save , saveOrUpdate and persist . You can use either save() , saveOrUpdate() or persist() based upon your requirement for persisting object into Database. Along with Spring framework Interview questions, Hibernate questions are also quite popular on J2EE interviews because of its status as leading ORM. It’s good to prepare some questions from Hibernate before appearing in any J2EE interviews. One of them is Difference between save , saveOrUpdate and persist, which we will see in this Hibernate article. Difference between save and saveOrUpdate in Hibernate Main difference between save and saveOrUpdate method is that save() generates a new identifier and INSERT record into database while saveOrUpdate can either INSERT or UPDATE based upon existence of record. Clearly saveOrUpdate is more flexible in terms of use but it involves an extra processing to find out whether record already exists in table or not. In summary save() method saves records into database by INSERT SQL query, Generates a new identifier and return the Serializable identifier back. On the other hand saveOrUpdate() method either INSERT or UPDATE based upon existence of object in database. If persistence object already exists in database then UPDATE SQL will execute and if there is no corresponding object in database than INSERT will run. Difference between save and persist method in Hibernate In last section we saw What are difference between save and saveOrUpdate and now we will see Difference on save vs persist method.First difference between save and persist is there return type. Similar to save method persist also INSERT records into database but return type of persist is void while return type of save is Serializable object. Another difference between persist and save is that both methods make a transient instance persistent. However, persist() method doesn’t guarantee that the identifier value will be assigned to the persistent instance immediately, the assignment might happen at flush time. One more thing which differentiate persist and save method in Hibernate is that is there behaviour on outside of transaction boundaries. persist() method guarantees that it will not execute an INSERT statement if it is called outside of transaction boundaries. save() method does not guarantee the same, it returns an identifier, and if an INSERT has to be executed to get the identifier (e.g. ‘identity’ generator), this INSERT happens immediately, no matter if you are inside or outside of a transaction. Fourth difference between save and persist method in Hibernate is related to previous difference on save vs persist. Because of its above behaviour of persist method outside transaction boundary, its useful in long-running conversations with an extended Session context. On the other hand save method is not good in a long-running conversation with an extended Session context.These were some differences between save, saveOrUpdate and persist method of Hibernate. All three method are related to saving Object into database but there behaviour are quite different. Knowledge of save , persist and saveOrUpdate not only helps to decide better use of Hibernate API but also help you to do well in Hibernate interviews. Don’t forget to share! Reference: Difference between save vs persist and saveOrUpdate in Hibernate from our JCG partner Javin Paul at the Javarevisited blog....
software-development-2-logo

Software Development tips and tricks

These are just some tips and tricks I learnt over my career that I’d like to share. This list does not contains silver bullets and it doesn’t pretend to be complete or be an absolute truth. It’s just a list that I hope may be helpful for someone. 1 ) Push the coding to the last This point can be also be read as think before coding. I found myself, lots of times, especially in the beginning of my career, in rush of writing classes, methods, interfaces as soon as I was receiving a spec for a new functionality. This impulse turned out 90% of the times into a PAINFUL situation. The spec was unclear and so unclear was my code; The spec was too ‘code oriented’ and so blindly coding this was producing wrong design/ implementation that needed to be trashed out and completely re-designed; Many other are the disadvantages of writing code straight away after receiving a spec. So, lesson learnt and this is what I’m doing now after receiving a spec/story to develop:I stay away from the keyboard! I print the spec (sorry amazonian jaguars ) and I take my time to read them carefully. Do not think that everything you will read there is exempt of mistakes or cannot be done in better and simpler ways. At the end of the day, people who wrote the specs, know little or nothing about the software, what they know is how to make more money with new functionality. If something is not clear to you, it will not clarify magically by itself if you start to code. Ask questions to other colleagues, to the business, clarify as much as possible and only when you feel confident, when you see the real pitcure of what they really want, then and only then you can switch the monitor on and click on the eclipse icon…2 ) Simple = perfect Make the 2 famous principles, KISS and YAGNI, part of your blood, skin and bones. Strive for simplicity, forget about the trends, focus on the most basic thing that will give you what is needed. Don’t think straight about XML configuration, spring/seam framework, drools, aspects, multithreading solutions, ejbs, or whatever complex/cool technology you know or you heard out there, nobody really cares about the technologies you use. What everyone cares is that your code does what is supposed to do, it is READABLE and it is MAINTAINABLE. Pure java is enough to cover 90% or more of everything you need. Always code as if the person who ends up maintaining your code is a violent psychopath who knows where you live. Make him happy, write simple, clear straightforward code. I remember I read somewhere that, if you read your code after 1 or 2 years and you immediately understand everything is doing and you cannot simplify it more, than your code is PERFECT.3 ) Paper and pen I never found a tool more useful than paper and pen to design software. Before writing software I usually spend a bit of time trying to put the idea of the design down on paper. I then , if in doubt, go through it with a colleague. Because it is on paper I can fast go to the point with my pair and he can quick tell me if I’m missing something. Knowing that you are missing something in a piece of paper, it’s far way better then knowing that you are missing something in the code! So don’t waste time using UML tools, unless what you are doing is big-fantastic-amazing-new architectural prototype. 4 ) Don’t leave for tomorrow what you can do today If you are fixing a bug or adding new functionality and you notice in the existing code, DUPLICATION or BAD NAMES or a POSSIBLE BUG then FIX IT IMMEDIATELY. Don’t wait for the next sprint and don’t add a technical story in the technical backlog. Technical stories laid in the backlog for long time, when/if it will be the time to work on it, it will be more complicated to re-understand the context of the problem and fix it. The exception it’s when the fix/refactoring is too complex and required long time, then it’s appropriate to create a story in the technical backlog! 5 ) You have time! Really, you have time! Don’t rush. There is no competition and you are not at the programming Olympics. Your job is to deliver good quality code. That’s it. This is your job! If you feel that a task takes longer that what you initially estimated, just make the team aware in the next stand up and that’s it. If a client/manager is screaming above your shoulders because he wants something faster than you can deliver, it’s not your problem!!! When they say ‘I want this functionality to be ready asap’ translated in Truthlish it means ‘I want this functionality to be PERFECT with NO BUGS asap’. They will be happier to wait more and have less bugs than having a fast release full of issues. So take your time and be intransigent on the quality level of your software and forget about external pressures! 6 ) Implement leaves first So, you just received a brand new story to develop and you want to implement it right. For example the story is about calculating item prices. One price for each item. Each price is obtained with a different calculation. Choose one item price logic and as first thing write a unit test against this logic. Don’t be stressed about implementing the whole design or writing interfaces, abstract classes etc. Focus on one small leaf per time! When the first leaf is finished, start with a second test for the second small logic you want to implement. The design will come out almost by itself. The tests will tell you which direction is best to take.7 ) Do Pair programming! I fully applied this technique only recently (less than 1 year ago) and I have to say, it’s powerful! It is twice productive than working alone, the quality of the code is superior, the development speed is increased. A strength of this technique is the fact that is funny. being funny and so more stimulating means that you are more focused and you pay more attention to details. You can learn a lot doing pair programming, so push for it as much as you can! 8 ) Rarely use checked Exceptions Every time I use an API that force me to put around its method call the try and catch block, it makes me nervous, like a violent psychopath, but often I don’t know where they leave. Especially if there is nothing I can do about the exception. What the hell I’ m supposed to do with this error? If you want to use checked Exception used them ONLY if the client can reasonably recover from it at run time! Remember that checked exceptions will spread all over your design in case you need to extend the behavior! 9 ) Say NO to Hacks Programming is like sex. One mistake and you have to support it for the rest of your life. (Michael Sinz). And Hacks ARE mistakes! Simply don’t implement hacks. I did it in the past, for whatever reasons ( no time,pressure, desire to release a feature as soon as possible, managers screaming, Orcs, Leprechauns, whatever), and now after years we need to maintain them. Hacks are difficult to understand,they break the normal logic flow of your code and they are hard to die! You implement an hack today and tomorrow (1 year after maybe ) someone else will need to fix a bug on this hack and ..well good luck with that! Spend more time on the spec if the hack is a business request, and explain why this will cost a lot to maintain. Propose other solutions, discuss it with your team, a better solution is on the way! 10 ) Forget about comments, just write proper names! Write proper names when writing packages, classes, methods and variables. Write names that make sense, ask a review before committing your code, but don’t explain verbally what you have done, try first letting your reviewer read the code, and see how good you were in writing self explanatory code! Comments need to be maintained, otherwise they are misleading. How often did you fix a bug in the code and you changed the class documentation?me, rarely!Use javadoc only if it is really necessary!and if you do,then remember to update them every time you change the code and enforce the same behavior in your team! 11 ) Reinvent the wheels Read books, blogs, tutorial, etc as much as possible, but always with a critical and open mind! The same apply when listening to your team or leader. Don’t be fooled by authorities, think always with your own mind. If you decide to go for some approach it must be because you believe in it. Because you see good reasons to do so. If you feel that something could be done better or you see problems in the approach you are using , discuss it with your team and try to clarify your doubts. If after talking to the team you still feel that things should be done differently, then push for better approaches and fight for your ideas! Sometimes, to progress, you need to reinvent the wheels or at this time we were all developing in FORTRAN. Don’t forget to share! Reference: Some development tips and tricks from our JCG partner Marco Castigliego at the Remove duplication and fix bad names blog....
software-development-2-logo

Programming Like Kent Beck

Three of us, namely Stig, Krzysztof, and Jakub, have had the pleasure of spending a week with Kent Beck during Iterate Code Camp 2012, working together on a project and learning programming best practices. We would like to share the valuable lessons that we have learnt and that made us better programmers (or so we would like to think at least). Values Underlying the Programming Style Most of the things that we have learnt stem from three basic values: communication, simplicity, and flexibility (in the order of importance). We will introduce them briefly here, you can find a more detailed description in Kent’s book Implementation Patterns, along with few fundamental practices such as the application of symmetry.Communication Programs are read much more often than written and therefore should communicate clearly their intent. Code is primarily means of communication. (For a typical enterprise system, a lot of code will be modified by many programmers over 5 – 15 years and they’ll all need to understand it.)Simplicity Eliminate excess complexity. Apply simplicity at all levels. Simplicity helps communication by making programs easier to understand. Communication helps simplicity by making it easier to see what is excess complexity.Flexibility “Making workable decisions today and maintaining the flexibility to change your mind in the future is a key to good software development.” — Implementation Patterns, Kent Beck Programs should be flexible in the ways they change, they should make common changes easy or at least easier. Complexity can often arise from excess flexibility, but if that flexibility is not needed then it is waste. The best kind of flexibility comes from simplicity coupled with extensive tests. Trying to create flexibility through design phases or the likes usually ends up with this kind of “complex flexibility”. Most of the time you do not have enough information to make a proper design decision about where your program will need to change, so the lean mantra of postponing your decisions til the last responsible moment is a valid and useful approach. That is when you have the best grounds for any decision.Summary Write code that communicates well what and why is done so that your co-workers and future maintainers can take it over without too much cost. (Yet you have to assume some level of skill and knowledge in you audience.) You cannot foresee the future so keep your code simple and sufficiently flexible so that it can evolve.Key Learnings 1. You Ain’t Gonna Need It! What is today’s demo? What test to start with? Before we arrived, we settled on a topic that we thought would be fun and challenging. We settled on trying our hands at prototyping a highly scalable, distributed database. We expected upon arrival to spend few hours discussing approaches to how we should actually implement this. After all, there are lot of things to consider: replication strategies, consistent hashing, cluster membership auto-discovery, and conflict resolution, to name a few. If you have just 5 days, you need to plan how to implement it in the simplest possible way. What to do. What to skip. Right? Wrong. Instead of any planning, Kent just asked us what would be the demo we would like to show at the end of the day. And his next question was what test to write. It turned out to be a very smart approach because we actually implemented only a very small subset of the possible functionality, deciding daily what to do next based on our experiences with the problem so far. Any discussion from the beginning longer than 10 minutes would be 90% wasted time. This doesn’t mean that planning is bad (though the resulting plans are usually useless), it only means that we usually do much more of it than we actually need. Getting real feedback and basing our decisions on that, on real data, is much more practical and valuable than any speculations. Therefore prefer on-going planning based on feedback and experience to extensive up-front planning. Ask yourself: What am I going to present at the next demo/meeting/day? What test to write to reflect that and thus guide my development effort?2. Write High-Level Tests to Guide the Development The goal of our second day was replication, demonstrated by writing to one instance, killing it, and reading the (replicated) data from the second instance. We started by writing a corresponding test, which follows these steps closely, nearly literally: List<Graft> grafts = Graft.getTwoGrafts(); Graft first = grafts.get(0); Graft second = grafts.get(1);first.createNode().put("key", "value") first.kill();assertNotNull(second.getNodeByProperty("key", "value")); (The API of course evolved later into something more general.) Now the interesting thing is that this is not a unit test. It is basically an integration test, or to use a less technical term, a story test exercising a rather high-level feature. A feature of interest to the customer. While a unit tests tells me “this class is working as intended,” a story test tells me “this feature works as intended”. I used to think about TDD at the unit/class level but this is TDD at a much higher level. It has some interesting properties:It helps measure real progress of the project because it exercises something that is actually meaningful to the customer (if you permit me to use this “customer” in a little blurry fashion) It helps keep you focused on delivering business functionality (by being on its level) It’s likely to stay mostly unchanged and live much longer than unit tests or actually most of the code base because it is on such a conceptual levelNow, according to the testing pyramid, there are of course fewer story tests than there are unit tests, and story tests do not test all possible cases. Does it mean that you need to do all these story tests and then do them again only in smaller unit tests? No, that is not the point. Getting back to the principle of flexibility and the way things change, create additional unit tests only when you need them. For example when you encounter some case where the first story test did not actually “capture the whole” properly, or when you discover a really important corner case, or when you want to focus on implementing a part of the overall solution. Speculating about failure points can be just as wasteful as speculating about design.3. Best Practices for [Unit] Testing Write Tests From the End We normally start a test with an idea of what we want to verify, but we may be not completely sure how to arrive there. Therefore it is good practice to express what we do know, the desired end-result, first. We do this in the form of an assertion and only then shift our focus to figuring how to get there. That’s how we started the test of replication in Graft, shown above. This is an application of the key principle of focus.Write Implementation in Tests, Refactor Later You know the functionality you want and so you start writing the test for it. Instead of thinking about how it should be organized (what classes to create, where to put them, whether to use a factory class or a factory method), why not initially write the code directly in the test method? You can always factor out the code later. This way you can focus on what’s really important – describing the desired functionality with a test – instead of being distracted by secondary considerations. Additionally, by postponing the decision about the internal organization of the implementation, you will have more knowledge when actually deciding it and you will likely end up with a better solution. Key principles: Focus, avoiding premature decision-making.Bottom-up Design Avoids:assuming too much, too early locking yourself into a specific design and premature design restricting yourself (you will usually end up with the design you first intended)Start by implementing small parts of functionality. Then combine them to form more complex behavior. Don’t get distracted by dependencies, write simple stubs for them that you will replace later with real implementations. Using this technique you are not bound to design decisions taken at the beginning as in the ‘top-down’ approach. It requires a little bit of intuition and some experience, but combined with TDD it helps to make better design and implementation. We found this technique quite useful as we didn’t know the final solution at the beginning. When developing Graft, we haven’t designed the whole application up-front. We picked a use case on the first day, implemented it, and continued by choosing and implementing other use cases each day.Act & Assert at the Same Level of Abstraction Our Graft DB has a telnet-like interface for receiving commands from users. Consider the following two (simplified) variations of the addComment test: // Test 1 Graft db = ...; this.subject = new CommandProcessor(db); subject.process("addComment eventId my_comment");assertThat(subject.process("getComments eventId")).isEqualTo("my_comment"); // Test 2 (same setUp) subject.process("addComment eventId my_comment");assertThat(db.getComments("eventId")).containsOnly("my_comment"); The first test, while testing the addComment command, uses another command – getComments – to check the resulting state. It uses only a single API entry point – subject – during the whole test. The second test accesses directly the underlying database instance and its API to get the same data, i.e. aside of subject it uses also the underlying db. Thus the first test is not truly “unit” test as it depends on the correctness of another method of the tested class. The second test is much more focused and potentially simpler to write as it accesses directly the target data structure and thus performs the checks right at the source. We would argue that tests like the first one, which perform all operations at the same level, namely the level of the public API of the object under test, are better. “Better” here means easier to understand and, more importantly, much more stable and maintainable because they are not coupled to the internal implementation of the functionality being tested. The price of increased complexity of these unit-integration tests (due to relying on multiple methods in each test) is absolutely worth the gain. Tests similar to the second one are none the less more common, either accessing directly the underlying layers (an object, property, database, …) or using mocks to gain the possibility of direct verification of side-effects. These techniques often lead to coupled and hard to maintain tests and should be limited to the “private unit tests,” as described and argued in Never Mix Public and Private Unit Tests!4. Focus!Put tasks that pop up on a Later list instead of doing them at once Focus on fixing the test first – however ugly and simple (and refactor later) Focus on the current needs – no premature abstractionOne thing that really caught our attention is Kent’s focus on what he is doing at any moment. Being focused means concentrating on finishing that one thing you’re currently doing without getting distracted by other concerns, however important or simple to fix. (Side note: Never say never.) When having a failing test, focus on making it pass quickly, no matter how ugly the (temporary) solution is or that it “cuts corners.” If you notice along the way something else that needs to be done – giving a method a better name, removing a dead code, fixing an unrelated bug – don’t do it, put it on a task list and do it later. Otherwise you risk losing your attention and the current context. Do one thing at a time. When making a test pass, focus just on that, and leave concerns such as good code til the subsequent refactoring (which should follow shortly). (This reminds me of the Mikado method for large-scale refactorings, whose main purpose is also to keep focus and not getting lost in many sidetracks.) A related practice is to focus on the current needs when implementing a feature, without speculatively designing for tomorrow’s needs (possibly literally tomorrow). Focus on what is needed right now, to finish the current task, and make the solution simple so that it will be easy to refactor and extend for both known and unforseen future needs. As Kent argues in Implementation Patterns (and others elsewhere), we’re very bad at speculative design, i.e. the future needs are usually quite different from what we expected and therefore it’s better to create solutions that are simple and with that also flexible. You of course need to pay some attention to the future needs but far less than we tend to do. Admit to yourself that you cannot predict the future. Even if you know what else is going to be required, how can you know that no new requirements that would change or delay that (up til infinity) will appear?Some other stuff we learned Parallel Design Parallel design means that when changing a design, you keep the old design as long as possible while gradually adding the new one and then you gradually switching to the new design. This applies both at large and also (surprisingly) small scale. Though it’s costly – you have to figure out how to have them both run and it requires more effort to have them both – it often pays off because it’s safer and it enables resumable refactoring, discussed below. An example of a high-level parallel design is the replacement of a RDBMS with a NoSQL database. You’d start by implementing the code for writing into the new DB, then you would use it and write both to the old and the new one, then you would start also reading from the new one (perhaps comparing the results to the old code to verify their correctness) while still using the old DB’s data. Next you would start actually using the NoSQL DB’s data, while still writing to/reading from the old DB (so that you could easily switch back). Only when the new DB proves itself would you gradually remove the old DB. An example of a micro-level parallel design is the replacement of method parameters (message etc.) with the object they come from (an Edge), as we did for notifyComment: - public void notifyComment(String message, String eventName, String user) { - notifications.add(user + ": commented on " + eventName + " " + message); --- + public void notifyComment(Edge target) { + notifications.add(target.getTo().getId() + ": commented on " + target.getFrom().getId() + " " + target.get("comment")); The steps were:Adding the Edge as another parameter (Refactor – Change Method Signature) Replacing one by one usages of the original parameters with properties of the target Edge (Infinitest running tests automatically after each change to verify we’re still good) Finally removing all the original parameters (Refactor – Change Method Signature)The good thing is that your code always works and you can commit or stop at any time.Resumable Refactoring If you apply the practices described below when performing a larger-scale refactoring then your code will always be buildable and you will be able to stop in the middle of the refactoring and continue (or not) at any later time. The practices are parallel design and going forward in small, safe steps i.e. steps that provably do not break anything. In essence it’s about keeping the oversight and control, at each step you know exactly what you did which broke the test and this way you can not only quickly put the application back in a working state, but also quickly hone in on what exactly caused the problem. (The Mikado method mentioned above is a great guide for refactoring systems where every change reveals a number of other changes required to make it possible. Of course the ultimate resource for refactoring legacy systems is Michael Feathers’s Working Effectively with Legacy Code).Refactor on Green, at Will The dogmatic TDD practitioners claim that you cannot change the behavior of production code unless some test forces you to do so. Thus it might be refreshing to hear that Kent doesn’t hesitate to generalize the code (e.g. by replacing fakes with a real implementation) even though there are no tests that require the generalization to pass. On the other hand it doesn’t mean that forcing a generalization by tests is a bad thing or that you should not do it. This is basically a question of the economics of software development, of balancing the cost (of writing and maintaining tests) with the benefits (defect and regression prevention). It’s a question of the risk involved and of your confidence in your coding skills. Kent has rightfully much more confidence in his coding skills (and much more experience with it) than many of us. Our confidence is quite low based on past experiences and therefore we’ll probably go on enforcing generalizations with tests. We’d close this topic by quoting Kent speaking about how much testing to do: I get paid for code that works, not for tests, so my philosophy is to test as little as possible to reach a given level of confidence (I suspect this level of confidence is high compared to industry standards, but that could just be hubris). If I don’t typically make a kind of mistake (like setting the wrong variables in a constructor), I don’t test for it. I do tend to make sense of test errors, so I’m extra careful when I have logic with complicated conditionals. When coding on a team, I modify my strategy to carefully test code that we, collectively, tend to get wrong. Different people will have different testing strategies based on this philosophy, but that seems reasonable to me given the immature state of understanding of how tests can best fit into the inner loop of coding. Ten or twenty years from now we’ll likely have a more universal theory of which tests to write, which tests not to write, and how to tell the difference. In the meantime, experimentation seems in order.Symmetry in the Code Symmetry is an abstract concept, more specific than the values of communication, simplicity, and flexibility, but still rather general. In Implementation Patterns Kent refers to symmetry as a programming principle. Code with symmetries is easier to grasp than code that is asymmetric. It’s easier to read and understand. So what, more specifically, is symmetric code? To quote Kent again: Symmetry in code is where the same idea is expressed the same way everywhere it appears in the code. Imagine a code where the some idea, like “getting the last updated document from the DB,” is implemented several times. The code is asymmetric if the method names differ, if they do things in different order, if there are some important differences between them. When you ask yourself “what does this method do” and you arrive at pretty much the same answer for all methods in spite of all the differences, then you have some violation of symmetry. An example of symmetry in code is keeping the abstraction level consistent within a code block, like a method. if the block is a mix of low level assignments and method calls, you may want to see if you can abstract away the assignments with a method. The astute reader have probably noticed that consistency is a large part of symmetry: being consistent with abstraction levels, consistent with method naming, and so on. But symmetry is more abstract in that it deals more with ideas, not rules (such as the rule that class and method names should be in camel-case).And What Do you Know, Even Some More …Manage your energy – be aware of your energy and stop before becoming tired. Don’t forget to take breaks. A rested developer is multiple times more productive than a tired one. (J.B. Rainsberger in The Economics of Software Design shares the story of working so intensively that he became exhausted and totally unproductive). Pair-programming is a skill one must consciously learn (and it may be more challenging for some personality types, which shall to be respected) Prefer IDE’s refactorings to manual changes – f.ex. none of us had ever before used the “inline” refactoring while Kent uses it all the time. Once you master the refactorings, they’ll become much more efficient than changing things manually and, more importantly, they avoid the small but non-zero probability of breaking something (remember that Murphy guy who said – what can break will break)Code You can find code for Iterate Code Camp 2012 on GitHub – bit.ly/codecamp2012Conclusion We hope that you, our dear reader, find some of these ideas interesting and have got inspired to try them in your daily practice, as we did.Related ResourcesJakub’s blog post Principles for Creating Maintainable and Evolvable Tests summarizes some complementary principles for writing tests that he learnt from Kent Rich Hickey: Simple Made Easy – a great talk that explains the crucial difference between “simple” (vs. complex) and “easy” and how our languages and tools aren’t as simple as they should be, often because they try to be easyReference: Programming Like Kent Beck from our JCG partner Jakub Holy at the The Holy Java blog....
twitter-logo

Twitter REST API from Scala and Java using signpost

If you’ve read some other articles on this blog you might know that I like creating visualizations of various datasets. I’ve just started a small project where I want to visualize some data from Twitter. For this I want to retrieve information about followers and profile information directly from twitter. I actually started looking for a set of all twitter accounts, but could only find one that was two years old. So, only option left, directly access the twitter API and get the data myself. There are a couple of open source libraries out that we can use directly from Scala (or java) but as far as I could see they use the old v1 API and not the v1.1 API. The old API has a very strict data rate limit, which is a bit lighter in the new API. And besides that I’m more interested in the raw data and parsing the returning JSON isn’t that hard with Scala (or Java for that matter).Register an application at twitter First thing to do, and easiest way to get started is registing a new application for your twitter account. Go to https://dev.twitter.com/apps/new and create a new application. Don’t worry about the urls, since we won’t be using the OAuth callback mechanism:Depending on what you want to do with the API you need to give additional permissions to this app. Default is ‘read-only’, if you want to allow your new application to post or access your direct messages you need to update the permissions. This is done from the settings page of your application:Once you’ve created the application and setup the correct permissions you can generate an access token. Doing this will avoid having to go through the complete OAuth dance. You do this by going to your new app details and at the bottom select the ‘create my access token’ option.Now you’ll have a set of tokens (see the details part of your applications):We’ll use these tokens to authenticate the requests we’ll make to twitter.Using a OAuth library The OAuth protocol is a pretty good documented protocol, but implementing it yourself is a lot of work and very error-prone. Luckily there are many OAuth libraries that can help you. I’ve tried a couple and the one that’s most easy to use (at least for me) was signpost. The examples below show how to do this from Scala, but you can follow the same approach for Java. First the dependencies. I’ve used sbt and from signpost I use the client with support for HTTP commons. In sbt add the following: .. libraryDependencies ++= Seq( 'oauth.signpost' % 'signpost-core' % '1.2', 'oauth.signpost' % 'signpost-commonshttp4' % '1.2', 'org.apache.httpcomponents' % 'httpclient' % '4.2', ... ) For maven you can use the same libraries. Next we can write a simple test to see if everything is working. In java it looks like this: import oauth.signpost.OAuthConsumer; import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer; import org.apache.commons.io.IOUtils; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; public class Tw { static String AccessToken = 'access token for your app'; static String AccessSecret = 'access secret for your app'; static String ConsumerKey = 'consumer key for your app'; static String ConsumerSecret = 'consumer secret for your app'; /** * @param args */ public static void main(String[] args) throws Exception { OAuthConsumer consumer = new CommonsHttpOAuthConsumer( ConsumerKey, ConsumerSecret); consumer.setTokenWithSecret(AccessToken, AccessSecret); HttpGet request = new HttpGet('http://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=josdirksen'); consumer.sign(request); HttpClient client = new DefaultHttpClient(); HttpResponse response = client.execute(request); int statusCode = response.getStatusLine().getStatusCode(); System.out.println(statusCode + ':' + response.getStatusLine().getReasonPhrase()); System.out.println(IOUtils.toString(response.getEntity().getContent())); } } And in Scala it looks pretty much the same: import org.apache.http.client.HttpClient import org.apache.http.impl.client.DefaultHttpClient import org.apache.http.client.methods.HttpGet import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer import org.apache.commons.io.IOUtils object TwitterPull { val AccessToken = 'access token for your app'; val AccessSecret = 'access secret for your app'; val ConsumerKey = 'consumer key for your app'; val ConsumerSecret = 'consumer secret for your app'; def main(args: Array[String]) { val consumer = new CommonsHttpOAuthConsumer(ConsumerKey,ConsumerSecret); consumer.setTokenWithSecret(AccessToken, AccessSecret); val request = new HttpGet('http://api.twitter.com/1.1/followers/ids.json?cursor=-1&screen_name=josdirksen'); consumer.sign(request); val client = new DefaultHttpClient(); val response = client.execute(request); println(response.getStatusLine().getStatusCode()); println(IOUtils.toString(response.getEntity().getContent())); } } When you run this the output will look something like this: 200 {"previous_cursor_str":"0","next_cursor":0,"ids": [48342167,21011010,824959303,97242821,16953163,218083367,20869799,5234221,13604142,80 4783128,271050984,405121284,26470609,50201837,1723451,374494377,120867838,14311946,25 3114713,39554511,7375412,42507395,112806109,92787154,218238023,110443797,76922155,198 798790,294104985,305625416,217698029,21803482,14927822,15453445,15715866,15657036,186 956616,36028164,70380613,326158542,573546312,14401332,521488579,9108612,576970378,293 236313,16398366,16220300,15234937,32000283,439444353,14300622,67204409,155850135,1419 8255,32264673,15852981,313248158,20123099,608942046,234930032,36896958,18466675,45496 942,330899833,18980755,88253383,461023805,31175627,11044952,142780445,63175189,107991 607,94830953,600993241,6195002,115391430,550080945,381418927,168603682,142388604,8258 462,218411138,30450578,77728346,2521381,182867524,494119147,29426983,572417260,943448 49,325413275,389354525,501438275,164346498,22730282,8293302,21085554,341645357,569788 53,180507788,10074002,22536424,14247654,581293627,15259428,483317230,462826270,477464 1,15366832,96850673,278486993,22273826,17716679,14566626,158473088,20461042,161242434 ,43756629,40163100,141165981,5325152,7620782,266749648,524476136,557713614,39602637,1 8843154,1623,565954426,39639621,166672305,18683074,233118689,44876099,235258223,21931 0062,10699922,12660502,218030046,91552210,19361980,206645598,35346200,58440021,470388 557,26495649,59066453,40292255,543375441,33242290,6015852,317150447,22935775,23230034 6,476045917,90913482,249088920,67658976,614873,522722520,186766721,285517705,71683175 ,131444964,166501605,477920664,38154550,18738205,8861832,15594932,18536741,7595202,46 5378842,11838952,14848133,431696576,14358671,414520167,222578501,67058139,28976735,95 601387,426582611,24874129,418762594,128157235,106030956,31352215,18733178,260196778,1 53179029,91842580,229494512,83414433,285579699,19957600,54295155,14929418,51516573,20 0076011,18758733,17776895,59397841,216802709,149834999,327507356,8200322,174345369,10 8636400,27504001,326877592,139919716,49949338,215035403,118421144,49410665,149550914, 18446431,25662335,261725134,267634174,57737391,146506056,126964949,71055234,20870640, 210196418,222806923,13290742,72247756,180410163,14784480,36684216,25611502,95614691,5 4629161,112967594,181656257,17994312,72918901,140082918,149087212,137272324,99534020, 121755576,93964779,35848342,43059008,34704029,87672717,113137792,17863333,90407665,90 591814,54297023,57924897,87551006,28300354,48990752,26188013],"previous_cursor":0, "next_cursor_str":"0"If you get a 403 check whether the tokens match. Happy coding and don’t forget to share! Reference: Access the Twitter REST API (v1.1) from Scala and Java using signpost from our JCG partner Jos Dirksen at the Smart Java blog....
java-logo

Java Hidden code

Sometime ago I came across the issue of invisible characters in Strings. These can really cause confusion because they are invisible. String a = "Hello\u200e"; String b = "Hello\u200f"; System.out.println('\'' + a + "' and '" + b + "' are length " + a.length() + " and " + b.length() + ", equals() is " + a.equals(b));prints 'Hello?' and 'Hello?' are length 6 and 6, equals() is falseInvisible identifiers Imagine my reaction to discovering you can use invisible characters in identifiers in Java :P. These characters cannot appear at the start of identifiers in Java but can be anywhere else. System.out.println("String _\u200e = \"Hello \";"); System.out.println("String _\u200f = \"World\";"); System.out.println("String _\u200e\u200f = \" !!\";"); System.out.println("System.out.println(_\u200e+_\u200f+_\u200e\u200f);");prints String _? = "Hello "; String _? = "World"; String _?? = " !!"; System.out.println(_?+_?+_??);which when run prints Hello World !!So we have three identifiers which all appear the same because they have different invisible characters in their names !! Amazingly this code compiles, runs and prints all the characters which can be in an identifier but not start them. The code contains \u202e which really messes with the display of the code. for (char c??h = 0; c??h < Character.MAX_VALUE; c??h++) if (Character.isJavaIdentifierPart(c??h) && !Character.isJavaIdentifierStart(c??h)) System.out.printf("%04x <%s>%n", (int) c??h, "" + c??h);Reference: Hidden code from our JCG partner Peter Lawrey at the Vanilla Java blog. ...
jcg-logo

JCG Flashback – 2011 – W37

Hello guys, Time for another post in the JCG Flashback series. These posts will take you back in time and list the hot articles on Java Code Geeks from one year ago. So, let’s see what was popular back then: 5. Simple Twitter: Play Framework, AJAX, CRUD on Heroku This is a cool tutorial on how to build a very basic Ajax-based Twitter clone with Play! Framework which will be deployed on Heroku. Check it out! 4. Java Concurrency Tutorial – Semaphores Java concurrency is always a topic of interest and this article discusses semaphores and how they can be used in order to develop concurrent, multi-threaded code. 3. The OpenJDK as the default Java on Linux This was an announcement back then mentioning that OpenJDK will be the default Java on Linux from now on (with Java SE 7 being the reference implementation). 2. The Java Logging Mess An interesting article discussing the logging approaches used in a Java environment and how those have come to be a bit complicated. Of course don’t miss our other hot article on this topic, 10 Tips for Proper Application Logging. 1. Scala use is less good than Java use for at least half of all Java projects Another article by David Pollak, discussing Scala and how it can be an alternative to Java in many cases and by a certain class of developers. Don’t miss it! That’s all guys. Stay tuned for more, here at Java Code Geeks. And don’t forget to share! Cheers, Ilias ...
spring-interview-questions-answers

Spring 3.1 Caching and @CacheEvict

My last blog demonstrated the application of Spring 3.1’s @Cacheable annotation that’s used to mark methods whose return values will be stored in a cache. However, @Cacheable is only one of a pair of annotations that the Guys at Spring have devised for caching, the other being @CacheEvict. Like @Cacheable, @CacheEvict has value, key and condition attributes. These work in exactly the same way as those supported by @Cacheable, so for more information on them see my previous blog: Spring 3.1 Caching and @Cacheable. CacheEvict supports two additional attributes: allEntries and beforeInvocation. If I were a gambling man I’d put money on the most popular of these being allEntries. allEntries is used to completely clear the contents of a cache defined by @CacheEvict‘s mandatory value argument. The method below demonstrates how to apply allEntries: @CacheEvict(value = "employee", allEntries = true) public void resetAllEntries() { // Intentionally blank }resetAllEntries() sets @CacheEvict’s allEntries attribute to “true” and, assuming that thefindEmployee(...) method looks like this: @Cacheable(value = "employee") public Person findEmployee(String firstName, String surname, int age) {return new Person(firstName, surname, age); }…then in the following code, resetAllEntries(), will clear the “employees” cache. This means that in the JUnit test below employee1 will not reference the same object as employee2: @Test public void testCacheResetOfAllEntries() {Person employee1 = instance.findEmployee("John", "Smith", 22); instance.resetAllEntries(); Person employee2 = instance.findEmployee("John", "Smith", 22);assertNotSame(employee1, employee2); }The second attribute is beforeInvocation. This determines whether or not a data item(s) is cleared from the cache before or after your method is invoked. The code below is pretty nonsensical; however, it does demonstrate that you can apply both @CacheEvict and @Cacheable simultaneously to a method. @CacheEvict(value = "employee", beforeInvocation = true) @Cacheable(value = "employee") public Person evictAndFindEmployee(String firstName, String surname, int age) {return new Person(firstName, surname, age); }In the code above, @CacheEvict deletes any entries in the cache with a matching key before @Cacheable searches the cache. As @Cacheable won’t find any entries it’ll call my code storing the result in the cache. The subsequent call to my method will invoke @CacheEvict which will delete any appropriate entries with the result that in the JUnit test below the variable employee1 will never reference the same object asemployee2: @Test public void testBeforeInvocation() {Person employee1 = instance.evictAndFindEmployee("John", "Smith", 22); Person employee2 = instance.evictAndFindEmployee("John", "Smith", 22);assertNotSame(employee1, employee2); }As I said above, evictAndFindEmployee(...) seems somewhat nonsensical as I’m applying both@Cacheable and @CacheEvict to the same method. But, it’s more that that, it makes the code unclear and breaks the Single Responsibility Principle; hence, I’d recommend creating separate cacheable and cache-evict methods. For example, if you have a cacheing method such as: @Cacheable(value = "employee", key = "#surname") public Person findEmployeeBySurname(String firstName, String surname, int age) {return new Person(firstName, surname, age); }then, assuming you need finer cache control than a simple ‘clear-all’, you can easily define its counterpart: @CacheEvict(value = "employee", key = "#surname") public void resetOnSurname(String surname) { // Intentionally blank}This is a simple blank marker method that uses the same SpEL expression that’s been applied to@Cacheable to evict all Person instances from the cache where the key matches the ‘surname’ argument. @Test public void testCacheResetOnSurname() {Person employee1 = instance.findEmployeeBySurname("John", "Smith", 22); instance.resetOnSurname("Smith"); Person employee2 = instance.findEmployeeBySurname("John", "Smith", 22); assertNotSame(employee1, employee2); }In the above code the first call to findEmployeeBySurname(...) creates a Person object, which Spring stores in the “employee” cache with a key defined as: “Smith”. The call to resetOnSurname(...) clears all entries from the “employee” cache with a surname of “Smith” and finally the second call tofindEmployeeBySurname(...) creates a new Person object, which Spring again stores in the “employee” cache with the key of “Smith”. Hence, the variables employee1, and employee2 do not reference the same object. Having covered Spring’s caching annotations, the next piece of the puzzle is to look into setting up a practical cache: just how do you enable Spring caching and which caching implementation should you use? More on that later… Happy coding and don’t forget to share! Reference: Spring 3.1 Caching and @CacheEvict from our JCG partner Roger Hughes at the Captain Debug’s Blog blog....
career-logo

Does It Get Boring To Be A Programmer?

Programmers are people who create computer programs. (I’ll skip the discussion whether it should be “programmer”, “developer”, “engineer”, “coder” or whatever. You know what I’m talking about). What makes programming different than most professions is that it’s way more diverse – you can do new things every day, because new technologies emerge all the time. Not only that, but programming is actually a creative job – given a couple of rules and foundations you can build whatever you like – something nobody else has built. Just like the poet starts with words, metric and rhyme rules and comes up with a poem. Or the compose starts with notes and the rules of harmony and comes up with a song. The good thing about programming is that there are always new things to start with and different rules to adhere to. So, programming is a well-paid, creative profession that gives you the opportunity to do a lot of different things. Not exactly. Programming has another feature – it has to be practical, to serve a business purpose. That’s why many programmers tend to do the same thing over and over again – website after website, ERP customization after ERP customization. Then they change jobs to do a very similar task. Partly because they are already experienced with a given technology or process and other companies want them because of that experience, partly because most companies do the same – they build websites for clients, they build or customize ERPs, or they have their own online service that has to be supported/created, but which is essentially the same as what you previously did. So, in fact, you handle HTTP requests and access the database all day long, day after day, with a couple of scheduled jobs or indexing thrown in, using the same technology for years and years? Sadly, yes. So it’s not so creative now, is it? How come people don’t get bored? They do. At that point, how can programmers make their work interesting, if what they do is writing very similar, mundane functionality all the time? They learn new technologies. If lucky, you can work on new projects and choose new technologies at work every year or so. If not so lucky, you can still write pet-projects at home, using the cutting-edge technologies, which later you can transfer to your workplace. There are new languages to be learnt, new frameworks to be explored and new storage engines to be used every day. Scala, Groovy, Go. NoSQL. Node.js. MapReduce. Hadoop. These are new paradigms that serve new purposes, and if you are a real programmer you should be fascinated and interested to at least read about them. And probably use some of them for a “proof of concept” at least. Having the ability to always explore something new is what makes the professional life of a programmer so much less boring. Even if at work you do the same thing, you can use your skills and make your own projects. And if they are good, you can open-source them so that other people use it, or they can become popular and you can eventually quit your job. And these are very realistic opportunities, which makes it even less boring. But does it get boring? Yes, it does. For two reasons. The first one is that some programmers are just lazy and not that interested in anything else other than the paycheck. These are the ones, for whom programming is not a hobby, it’s just a mere profession. It’s their choice, so I’ll leave them aside. The other type are people like me, who like what they are doing, who stay up to date, like to learn new things all the time. People like me can get bored when at some point each new technology becomes too easy. When you are proficient in everything you use and you learn a new framework in six hours and a new language in two days. New concepts like MapReduce, the CAP-theorem, API design, become easily mastered, because you already have so much experience and have seen so many things. Each new step is now easy, there is no challenge anymore, so you get bored. There are a couple of options from this point:compensate the boredom of your professional life with something really interesting in your “real” life. But when you get from the programming world of infinite options, to a pretty limited real world, not many things seem challenging. I don’t say this is not a good option – by all means it is. It’s just not interesting from a programming point of view, but feel free to “get out in the real world”, if you are less bored there. you seek to get promoted to management, that is – change the nature of your work and start using your expertise to direct the process in your company rather than program. But usually a great programmer doesn’t like not to program. You would at least like to be technically involved in the development process. remain bored, get the paycheck. You are still a professional and there’s nothing wrong with this choice. And at some point you may forget that you are bored. you start thinking of something new, something nobody else has done or thought of. A product, a framework, doesn’t matter. It occupies your creative thinking and all your current skills. Eventually you may end up with some great new technology or product. You may get bored after that, of course, but you can iterate this step. It can be done at home, at work, or if your idea requires a lot of time and dedication, you can do it as a research project in a university. I guess this is how the internet, Google, p2p, Linux, and many more great technologies are born.Thanks to the people choosing the 4th option, professional life for the majority of developers remains interesting and intriguing. If you get to the point where you are bored by everything, please choose the 4th option. I haven’t yet fully reached that point, but I’ll certainly try to utilize all my programming skills to create something new and cool, rather than sitting quiet and getting my paycheck. Don’t forget to share! Reference: Do Programmers Get Bored? from our JCG partner Bozhidar Bozhanov at the Bozho’s tech blog blog....
java-logo

Duck typing in Java ? Well, not exactly

According to Wikipedia duck typing is: style of dynamic typing in which an object’s methods and properties determine the valid semantics, rather than its inheritance from a particular class or implementation of a specific interface In simplier words When I see a bird that walks like a duck and swims like a duck and quacks like a duck, I call that bird a duck In languages with dynamic typing this feature allows creating function that are not checking type of passed object but instead rely on existence of particular methods/properties within it and throws runtime exception when those properties not found. For instance, in groovy we could have method for printing info about some entity def printEntity = {entity -> println 'id: ${entity.id}, name: ${entity.name}' } Let’s say we have following class class Entity { Long id String name }So we can invoke our function printEntity(new Entity(id: 10L, name: 'MyName1')) id: 10, name: MyName1But the same time we could pass map as argument printEntity(['id':10L, 'name':'MyName2']) id: 10, name: MyName2Using some metaprogramming magic we could write even following class Ghost { def propertyMissing(String name) { if (name == 'id') { return -1L } else if (name == 'name') { return 'StubName' } } }And we will be still able to call our function printEntity(new Ghost()) id: -1, name: StubName Welcome to the real world Fortunately this concept can be used not only for languages with dynamic typing but for ones with more strict typing model, as Java. Wikipedia has good example of duck typing implementation in Java using Proxy class. Well, you say, what is the practical usage of this except feeling oneself the wisest guru :) Let me show some real life task that was solved in Java using duck typing technique. From the beginning I had simple report generator that queries DB of products and outputs id and name of certain entity. But then customer says: ‘I’d like to also have link to the entity detail page at our site. Beautiful, SEO friendly link. Could you do it to me’. ‘Sure ‘, I said. After digging our codebase I’ve discovered cool function generateSeoUrl() that does the job. The function takes one argument of type Entity, which is interface. So my intention was to observe implementations of Entity and try to use one of them for the report generation. How surprised was I after discovering that all of them are part of some self made ORM tool and their constructors accept query DB to get the entire information about product. So if I were using Entity implementations I had to deal with one extra query per row of my report and this is unacceptable since report was comprised of huge number of rows. So I decided to try other approach and implement Entity interface, overriding methods that are used by generateSeoUrl(). I clicked my IDE shortcut and got surprised again. Entity had about 50 (!!!) methods. Well, I already knew that only getEntityId() and getName() are used by generateSeoUrl() function, but then again, having new class with 50 empty methods just to override 2 of them doing useful action seemed not good idea for me. Thus I’ve decided stop trying coding and start to think :) Extend some of the Entity implementation to prevent querying DB or copy + paste generateSeoUrl() and adopt it for my needs were the options but still it was not beautiful. Especially when I reminded duck typing. I said to myself, we have a function that takes instance of Entity but only uses two method of this interface, so to complete my task I need something that looks like Entity and able to handle getEntityId() and getName() methods. Since entityId and name were already present in data used for generating my report I could reuse them in my new class to stub data for getEntityId() and getName(). To achieve duck typing we need to create Proxy that also implements InvocationHandler interface and static method to retrieve instance of Proxy. Final code of my class looks like public class ReportEntitySupport implements InvocationHandler {public static Entity newInstance(Long entityId, String name) { return (Entity) Proxy.newProxyInstance( Product.class.getClassLoader(), Product.class.getInterfaces(), new ReportEntitySupport(entityId, name) ); }private final String name; private final Long entityId;private ReportEntitySupport(Long entityId, String name) { this.name = name; this.entityId = entityId; }@Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals('getName')) { return this.name; } else if (method.getName().equals('getEntityId')) { return this.entityId; } return null; } } So how to use it ? Inside my report generator class while iterating over ResultSet I’m using following Long entityId; String name; .... Entity entity = ReportEntitySupport.newIntance(entityId, name); String seoUrl = generateSeoUrl(entity); .... P.S. This post just illustrates that some uncommon for Java language concepts could be successfully applied for completing real life tasks improving your programming skills and making your code more beautiful. Reference: Duck typing in Java ? Well, not exactly from our JCG partner Evgeny Shepelyuk at the jk’s blog blog....
apache-wicket-logo

Apache Wicket: Remember Me functionality

It is quite common in web applications to have “Remember Me” functionality that allows user to be automatically logged in each time when he visits our website. Such feature can be implemented using Spring Security, but in my opinion using request based authentication framework with component based web framework is not the best idea. These two worlds just do not fit well together so I prefer to use my own baked solution which I will present below. Base project We start with a simple web application written using latest, still hot Apache Wicket 6. You can download complete sources from GitHub and start application using mvn clean compile jetty:run . Base application consists of two pages:Home Page: displays welcome message for logged and not-logged users or either logout or login link. Login Page: allows user to login basing on simple in-memory collection of users. Some working login/password pairs: John/john, Lisa/lisa, Tom/tom .Remember Me functionality Standard way to implement Remember Me functionality looks as follows:Ask user if he wants to be remembered and auto-logged in the future. If so, save cookies with login and password on his computer. For every new user coming to our website, check if cookies from step 2 are present and if so, auto login user. When he manually logs out, remove cookies so it is possible to clear data used to auto-login.Point 2 needs some explanation. In this example app we are going to save login and not hashed, not encrypted password in cookies. In real scenario this is unacceptable. Instead of it, you should consider storing hashed and salted password so even if someone intercepts user cookie, password still will be secret and more work will be needed to decode it. Update: Micha? Mat?oka posted two very interesting links how this could be done in real systems. Those approaches do not even use password nor password hashes. For more details please look into his comment below this post. Step 1: As a User I want to decide if I want to use “Remember Me” featureLink to commit with this step To allow user to notify application that he wants to use ‘Remember Me’ functionality we will simply add a checkbox to login page. So we need to amend LoginPage java and html file a bit (new stuff is highlighted): <form wicket:id='form' class='form-horizontal'> <fieldset> <legend>Please login</legend> </fieldset><div class='control-group'> <div wicket:id='feedback'></div> </div> <div class='control-group'> <label class='control-label' for='login'>Login</label> <div class='controls'> <input type='text' id='login' wicket:id='login' /> </div> </div> <div class='control-group'> <label class='control-label' for='password'>Password</label> <div class='controls'> <input type='password' id='password' wicket:id='password' /> </div> </div> <div class='control-group'> <div class='controls'> <label class='checkbox'> <input type='checkbox' wicket:id='rememberMe'> Remember me on this computer </label> </div> </div> <div class='form-actions'> <input type='submit' wicket:id='submit' value='Login' title='Login' class='btn btn-primary'/> </div> </form>private String login; private String password; private boolean rememberMe;public LoginPage() {Form<Void> loginForm = new Form<Void>('form'); add(loginForm);loginForm.add(new FeedbackPanel('feedback')); loginForm.add(new RequiredTextField<String>('login', new PropertyModel<String>(this, 'login'))); loginForm.add(new PasswordTextField('password', new PropertyModel<String>(this, 'password'))); loginForm.add(new CheckBox('rememberMe', new PropertyModel<Boolean>(this, 'rememberMe')));Button submit = new Button('submit') { // (...) };loginForm.add(submit); } Now we are ready for next step. Step 2: As a System I want to save login and password in cookiesLink to commit with this step First we need a CookieService that will encapsulate all logic responsible for working with cookies: saving, listing and clearing cookie when needed. Code is rather simple, we work with WebResponse and WebRequest classes to modify cookies in user’s browser. public class CookieService {public Cookie loadCookie(Request request, String cookieName) {List<Cookie> cookies = ((WebRequest) request).getCookies();if (cookies == null) { return null; }for (Cookie cookie : cookies) { if(cookie.getName().equals(cookieName)) { return cookie; } }return null; }public void saveCookie(Response response, String cookieName, String cookieValue, int expiryTimeInDays) { Cookie cookie = new Cookie(cookieName, cookieValue); cookie.setMaxAge((int) TimeUnit.DAYS.toSeconds(expiryTimeInDays)); ((WebResponse)response).addCookie(cookie); }public void removeCookieIfPresent(Request request, Response response, String cookieName) { Cookie cookie = loadCookie(request, cookieName);if(cookie != null) { ((WebResponse)response).clearCookie(cookie); } } } Then when user checks ‘Remember Me’ on LoginPage, we have to save cookies in his browser: Button submit = new Button('submit') { @Override public void onSubmit() { UserService userService = WicketApplication.get().getUserService();User user = userService.findByLoginAndPassword(login, password);if(user == null) { error('Invalid login and/or password. Please try again.'); } else { UserSession.get().setUser(user);if(rememberMe) { CookieService cookieService = WicketApplication.get().getCookieService(); cookieService.saveCookie(getResponse(), REMEMBER_ME_LOGIN_COOKIE, user.getLogin(), REMEMBER_ME_DURATION_IN_DAYS); cookieService.saveCookie(getResponse(), REMEMBER_ME_PASSWORD_COOKIE, user.getPassword(), REMEMBER_ME_DURATION_IN_DAYS); }setResponsePage(HomePage.class); } } };Step 3: As a User I want to be auto-logged when I return to web applicationLink to commit with this step To check if user entering our application is a “returning user to auto-login” we have to enrich logic responsible for creating new user session. Currently it is done in WicketApplication class which when requested, creates new WebSession instance. So every time new session is created, we have to check for cookies presence and if they are valid user/password pair, auto-login this user. So let’s start with extracting session related logic into separate class called SessionProvider. It will need UserService and CookieService to check for existing users and cookies so we pass them as a references in the constructor. public class WicketApplication extends WebApplication {private UserService userService = new UserService(); private CookieService cookieService = new CookieService(); private SessionProvider sessionProvider = new SessionProvider(userService, cookieService);@Override public Session newSession(Request request, Response response) { return sessionProvider.createNewSession(request); } } Role of SessionProvider is to create new UserSession, check if proper cookies are present and if so, set logged user. Additionally we add feedback message to inform user that he was auto logged. So let’s look into the code: public class SessionProvider {public SessionProvider(UserService userService, CookieService cookieService) { this.userService = userService; this.cookieService = cookieService; }public WebSession createNewSession(Request request) { UserSession session = new UserSession(request);Cookie loginCookie = cookieService.loadCookie(request, REMEMBER_ME_LOGIN_COOKIE); Cookie passwordCookie = cookieService.loadCookie(request, REMEMBER_ME_PASSWORD_COOKIE);if(loginCookie != null && passwordCookie != null) { User user = userService.findByLoginAndPassword(loginCookie.getValue(), passwordCookie.getValue());if(user != null) { session.setUser(user); session.info('You were automatically logged in.'); } }return session; } } To show feedback message on HomePage.java we must add FeedbackPanel there, but for the brevity I will omit this in this post. You can read commit to check how to do that. So we after three steps we should have ‘Remember Me’ working. To check it quickly please modify session timeout in web.xml file by adding: <session-config> <session-timeout>1</session-timeout> </session-config> and then start application mvn clean compile jetty:run, go to login page, login, close browser and after over a 1 minute (when session expires) open it again on http://localhost:8080. You should see something like this:So it works. But we still need one more thing: allow user to remove cookies and turn-off auto-login. Step 4: As a User I want to be able to logout and clear my cookiesLink to commit with this step In the last step we have to allow user to clear his data and disable “Remember Me” for his account. This will be achieved by clearing both cookies when user explicitly clicks Logout link. Link<Void> logoutLink = new Link<Void>('logout') { @Override public void onClick() { CookieService cookieService = WicketApplication.get().getCookieService(); cookieService.removeCookieIfPresent(getRequest(), getResponse(), SessionProvider.REMEMBER_ME_LOGIN_COOKIE); cookieService.removeCookieIfPresent(getRequest(), getResponse(), SessionProvider.REMEMBER_ME_PASSWORD_COOKIE);UserSession.get().setUser(null); UserSession.get().invalidate(); } }; logoutLink.setVisible(UserSession.get().userLoggedIn()); add(logoutLink);Summary So that’s all. In this port we have implemented simple ‘Remember Me’ functionality in web application written using Apache Wicket without using any external authentication libraries. Happy coding and don’t forget to share! Reference: Remember Me functionality in Apache Wicket from our JCG partner Tomasz Dziurko at the Code Hard Go Pro 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