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

Subscribe to our newsletter to start Rocking right now!

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

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

and many more ....

Featured FREE Whitepapers

What's New Here?


Master Detail CRUD operations with Regions ADF 11g

This is an example that demonstrates how to create a Master Detail relationship between tables by using Regions. The main purpose of regions is the notion of reusability. With regions and bounded task flows we can reuse our pages into many other pages keeping the same functionality and having a more cleaner approach Download the Sample Application. For this example we are going to use only one Model project and keep things simple. We are going to create our Business Components through JDeveloper and it’s wizards. We are using Master Detail for Departments and Employees.So, we are going to create two Bounded Task Flows that use fragments. One for the Departments One for the employees.In each bounded task flow we drag and drop a view and place the appropriate names of departments and employees.Then in the unbounded flow we create a jspx that will have two Regions defined. One for the Department BTF One for the Employees BTF For Departments we are going to drag and drop the Departments iterator as a form with navigation buttons and submit button. Additionally, we add the createInsert and Delete Operation buttons next to submitWe do the same with employees. The only difference here is that we drop an editable table and not a form. Additionally we drag it from the hierarchy and not the alone one in our Data Control. This means that we drag the detailed employees.Next, we are going to create an index page in our unbounded task flow that will contain our Bounded Task Flows as regions. In order to that, after we created the index page, we simply drag and drop each Bounded Task Flow as a RegionWe do the same for the Employees Bounded Task Flow. Up to now, we have our hierarchy done and well placed. Since we share the same application module instance, we are good to go!! All that is left now is to place commit and rollback buttons in our Departments fragment and we are done! For the rollback button we have to make a specific adjustment: The emps region needs to be refreshed and indicate that the rollback is performed. For this reason we are going to set the refresh property as follows:So, what we do here is, to set a refresh condition on our detail region. What we say here is, refresh emps fragment when the dept fragments is refreshed. NOTE: this is a simple application demonstrating the ease of use of Regions. It is not intended to cover all aspects of regions. Download the Sample Application. Reference: Master Detail CRUD operations with Regions ADF 11g from our JCG partner Dimitrios Stassinopoulos at the Born To DeBug blog....

JavaOne 2012: Observations and Impressions

I am starting this particular blog post as I sit the the San Francisco International Airport waiting to board an airplane to head home after another satisfying but tiring JavaOne (2012) experience. It is difficult to write another blog post after having frantically written ~30 blog posts on the conference since the keynotes on last Sunday, but I want to record some of my observations and impressions of the conference while they’re still relatively fresh. More than in previous years, I did embed some general observations (usually complaints) within posts on individual sessions.This post is broken up into ‘the good,’ ‘the bad,’ and ‘the ugly’ of JavaOne 2012. I want to emphasize that the conference overall was outstanding and I am appreciative of the opportunity to have attended. I hope the overall tone of my post reflects my overall highly positive feelings about this conference, but also presents a realistic portrait of the not-so-great aspects of the conference. The GoodOverall Technical Content There is a wide variety of things conference attendees look forward to in a conference. Many of us look forward to many of the same things in a conference. For me, the single most important attribute of a technical conference is its content. In that category, JavaOne 2012 was a success. There was actually too much good content to take it all in, but that’s a welcome dilemma.High Attention to Low-Level Details I think Adam Bien made an important observation: even though it’s nice to have community involvement in the conference, JavaOne presents a special opportunity to hear from the folks (mostly Oracle employees) working ‘in the trenches’ on the latest Java APIs, specifications, and SDKs. Bien put it this way, ‘I mainly attended sessions delivered by Oracle engineers. 90% of this sessions were great with unique, deep technical content probably only deliverable by someone implementing the low level stuff. This is my personal motivation for attending JavaOne.’ I’ve been to database-oriented conferences where many of the Oracle employees’ presentations are heavy on marketing and slideware and low on technical detail. That’s not the case at JavaOne where Oracle employees present the low-level details that Java developers want to hear.Breadth and Scope of Technical Content No matter in which dimension it is measured, JavaOne 2012 featured breadth and depth of content. Subjects in Java SE, Java EE, Java ME/embedded, web, JVM (alternate languages), and even some non-Java topics were available in nearly every session block. The keynotes (especially the Strategy Keynote and Technical Keynote) and select presentations that I attended provided roadmaps and vision for what lies ahead. I enjoyed the breadth of ‘temporal usefulness’ available in the presentations. I learned about things I like won’t use anytime soon but are interesting and mind-expanding (Ceylon, JavaFX Embedded, Play Framework, Akka, Tiggzi), things that I’ll definitely use in the intermediate future (Project Lambda, JSR 310 Date/Time API), things I’ll use in the near future (Scala), and things I’ll use almost as soon as I get home (JDK 7’s jcmd, NetBeans Project Easel, Checker Framework). I was even able to learn several new tips and/or tricks for things for which I already had significant familiarity (Groovy, JavaFX, NetBeans’s custom declarative language for refactoring/hints).Attention to Community I stated above that I agree with Adam Bien’s assertion that one of the most valuable aspects of JavaOne is the access to people working directly on the future of Java. That being stated, I do appreciate Oracle making a real effort to reach out to the community. I posted during several presentations in which the speakers solicited feedback and ideas from the community and the audience. This was a nearly universal theme of any of the presentations related to anything open source. The JavaOne Community Keynote is the most obvious manifestation of JavaOne’s commitment to community, but that theme was reiterated in numerous presentations.The Host City San Francisco is a great city to visit and offers lots to do for downtime and for people traveling with JavaOne participants who are not themselves attending JavaOne. Although I look forward to any opportunity I get to attend JavaOne, I think I look forward to the visit to San Francisco as much as the conference. It’s definitely an interesting city to visit with great dining and other activities. The weather was pleasant and clear most of the time, though fog rolled in occasionally to remind us it is San Francisco and it was unusually hot in the early portion of the conference.Oracle makes the presence of Oracle OpenWorld and JavaOne well-known throughout the city. Taxicabs feature signs for the respective conferences on their advertisements, there are signs all over the place, and some sections of the downtown near the conference venues (Moscone for Oracle OpenWorld and three Union Square hotels for JavaOne) for activities.Extracurricular Activities JavaOne provides numerous extracurricular activities beyond the technical content of the conference and beyond what the city provides. I didn’t participate in many of these this year due to other commitments and activities, but the offerings are fairly impressive. The Oracle Appreciation Night, which featured Pearl Jam and Kings of Leon this year, is especially impressive. Although there are numerous disadvantages to JavaOne being the ‘little brother’ held simultaneously with Oracle OpenWorld, some of these activities are available because of the bigger and better attended big brother conference being held simultaneously. The Return of James Gosling There was no denying that the ‘surprise’ return of James Gosling to JavaOne (Community Keynote) left a big and very positive impression. The nostalgic factor (reminder of JavaOne’s most glorious days) seemed to be as big as Gosling’s presentation itself. I monitored a lot of the Twitter traffic during the week on ‘javaone’ and no single Tweet or set of Tweets came anywhere close to being tweeted and re-treeted as often as mention of Gosling’s return to JavaOne.Increased Exposure to Tools Master craftsmen in any industry are more successful with the correct tools. At JavaOne 2012, I became familiar with tools that I either had not been aware of previously or had not fully appreciated previously. These were either the subject of the presentations I saw or were used ‘incidentally’ during projects and hallways discussions. These projects included JaCoCo Java Code Coverage Library (first read about in a Tweet), Checker Framework, the Oracle JDK 7 jcmd command-line tool, and NetBeans 7.3 Project Easel. I was also reminded that JDeveloper provides one of the better free UML tools, an important reminder now that NetBeans no longer supports UML (UML last supported in NetBeans 6.7). Online JavaOne 2012 Coverage Modern technology continues to make JavaOne more accessible to developer worldwide each year. Oracle made a lot of content available online early in the conference and individual members of the community also contributed significantly to the JavaOne coverage. Even some of the individual contributions were in part due to Oracle; I, for example, attended JavaOne 2012 on a blogger pass and was able to write posts like this one thanks to that complimentary pass. Between attending sessions, visiting some San Francisco sites, and writing my own blog posts, I’ve only been able to read a fraction of the other posts written about JavaOne 2012. I hope to catch up on those in coming weeks. I did try to watch Tweeted messages about the conference as it went along and was impressed with the quick coverage of important aspects of the conference. Oracle has made ‘featured keynotes and highlights’ available online (video). There have been several Oracle-originated blogs of interest including Oracle Outlines Roadmap for Java SE and JavaFX at JavaOne 2012, Virtual Collateral Rack (PDFs of sessions), Thursday Community Keynote: ‘By the Community, For the Community’, JavaOne 2012 Sunday Strategy Keynote, and The JavaOne 2012 Sunday Technical Keynote. Individual JavaOne 2012 summaries include Jim Gough‘s Highlights From Java One 2012, Mark Stephens‘s 5 key things I learnt at Javaone2012, Yakov Fain‘s My Three Days at JavaOne 2012, and Trisha Gee‘s JavaOne: The Summary.A Dose of Reality The blogosphere tends to distort the reality of software development for a variety of reasons (dominated by ‘new’ and ‘interesting’ developments, for one). Attending conferences can be a good way to talk to others to get a better perspective on the reality of general software development. For example, at JavaOne 2012, there were several reminders that there is still significant software development that occurs on the desktop (it’s not all web/mobile) and that the demise of UML has been overstated. The Bad These ‘bad’ things are mostly accepted parts of the JavaOne experience. They are certainly outweighed by the good both in terms of number of ‘bad’ or ‘good’ things and in terms of importance of the things. In other words, there were more good things about JavaOne and the good things were more important to me than the bad things.The Hotels Venue The spreading of JavaOne over three Union Square hotels (Hilton, Parc 55, and Nikko) and the Masonic Auditorium would probably not be as big of a negative if JavaOne attendees were not aware of the presentations-friendly Moscone Center in the same city just blocks away. I am getting used to this venue and can navigate it better now than previously. I actually often enjoy the opportunity of going outside to move between buildings. However, I also found myself changing a couple selected presentations in the last couple of days because my original choice was in a particularly poor conference room area.Poor Wifi The Wifi at JavaOne simply cannot scale to the number of people wanting to use it via laptops, iPads, iPod Touch devices, Android tablets, and other personal devices. The Wifi was pretty good in the mornings before things got going and was outstanding on Thursday afternoon when a lot of people had already left. The Food Like the venues, the food is not completely awful; it’s just not very good. It is sufficient for what is needed (providing nutrients and energy), but its lack of flavor stands in stark contrast to the excellent breakfasts and dinners I enjoyed again this year while in San Francisco.Getting To and Leaving San Francisco My flights into and out of San Francisco were both delayed due to fog in San Francisco and/or due to metering of traffic in the airport. In addition to this, we were told that the U.S. Navy‘s use on SFO for some of their Fleet Week exercises was the reason we sat on the runway for an extra twenty minutes. This is an example of where the good (being in San Francisco for the conference) outweighed the bad. The UglyInconsiderate and Intentionally Rude Misbehavior Perhaps the ugliest part of JavaOne 2012 had little to do with the conference itself or its organizers, but was instead caused by a small portion of its attendees. It seemed that I repeatedly got behind the person trying to text and walk at the same time. These individuals slowed down traffic in the already congested halls as they walked more slowly and wandered in unpredictable directions and caused people to try to walk around them, causing additional issues. People tend not to drive and text as well as they might think and walking and texting is no different. The walking while texting may be less dangerous than driving while texting, but it’s not without its dangers. There was one guy I was behind who was stopping intermittently while trying to eat and walk down the stairs because he was losing his lunch or snack. Continuing to try to do both made it so that neither was done well.Other misbehavior that I observed were observed by others as well. These included unnecessary presentation hijacking, mobile phones ringing in sessions and some people even taking the call without leaving, people cutting in lines, and excessive entering and exiting of presentations at mid-point (most noticeably a problem when someone who sat in the first few rows made a show of his or her exit). The majority of attendees were well-behaved, but the small fraction of inconsiderate and even intentionally rude attendees was probably the ugliest part of JavaOne 2012. In defense of JavaOne, this ‘ugliness’ seems to be more reflective of human behavior than of the conference. Additional / Miscellaneous ObservationsTrendy Topics Some of the topics that seemed particular popular at this year’s JavaOne included REST, HTML5, Project Nashorn, JDK8/Lambda, NetBeans, and Embedded/Raspberry Pi.Convergence A major theme of JavaOne 2012 was ‘convergence.’ This theme was explicitly identified in the keynotes and several presentations such as ‘Looking into the JVM Crystal Ball‘ (convergence of Oracle’s JRockit and HotSpot JVMs), ‘Mastering Java Deployment‘ (convergence of Java SE and JavaFX), ‘JavaFX on Smart Embedded Devices‘ (convergence of JavaFX and JavaFX Embedded, representing convergence of editions of Java [EE, SE, ME]), ‘NetBeans.Next – The Roadmap Ahead‘ (sharing of features between NetBeans and JDeveloper), and ‘Diagnosing Your Application on the JVM‘ (convergence of VM tools between JRockit and HotSpot and converge of command-line tools into single new jcmd tool). One of the manifestations of this convergence of versions of Java is the renaming of versions. It was interesting to hear multiple speakers refer to current JavaFX as JavaFX 2.2 and the ‘next’ major version of JavaFX as JavaFX 8 (version that was to be called JavaFX 3). This version naming change is documented in the post JavaFX 2.2 is here, and JavaFX 8.0 is on its way! Similarly, Java ME is seeing a version naming change as well: Java ME 3.2 is the current version and Java ME 8 is the ‘next’ major version.JDK 7 Update 10: The Next ‘Big’ Minor Release? I heard multiple Oracle presenters mention features that they are already using in JDK 7 Update 10. Given that most of us who are using JDK 7 are using JDK 7 Update 6 (and JDK 7 Update 7 is the current regular download), it sounds to me like JDK 7 Update 10 may be the next ‘minor’ release of JDK 7 with significant new tools for things such as application diagnosis and application deployment. The naming of JDK minor releases with odd numbers for Critical Patch Updates (CPUs) and even numbers for ‘limited update releases’ was announced previously. JDK 7u10 Build b10 is available in Developer Preview.‘Java’ Becoming Bigger Than Ever One thing that is clearer to me than ever before after attending JavaOne 2012 is that ‘Java’ has become big for any one person to get his or her hands around the whole thing. Even some of the most knowledgeable experts I know in the Java community were heard to say that they would need to ask someone else to answer a specific question out of their area of expertise. It’s becoming increasingly difficult for any one person to thoroughly understand all aspects of Java (JVM, EE, SE, ME, etc.). When you throw in alternate languages and new frameworks and tools, one person simply cannot learn or understand all of it. It’s great that we have so many choices, but it can be frustrating to see entire areas of ‘Java’ that would be interesting to delve into, but simply require too much time and effort to give it those areas the desired degree of attention. Overall Overall, I think JavaOne 2012 was a success by most peoples’ measures. It certainly was by mine. I’m not the only one who was sorry to see it end. JavaOne 2013 will be held September 22–26, 2013, in San Francisco. Don’t forget to share! Reference: JavaOne 2012: Observations and Impressions from our JCG partner Dustin Marx at the Inspired by Actual Events blog....

JavaOne 2012: JavaFX Graphics Tips and Tricks

I returned to the Hilton (Imperial Ballroom B) to see Richard Bair‘s (Oracle Java Client Architect) ‘JavaFX Graphics Tips and Tricks.’ Bair is associated with FX Experience and obviously knows JavaFX. Bair said a theme of his talk is on performance. He cautioned that as with most things performance related, avoid performance pre-optimization. He had a big yellow caution screen stating ‘WRITE CLEAN CODE, THEN PROFILE!’ He said his talk is based on JavaFX 2.2 and some of the tips and tricks may not be applicable with JavaFX 8.Bair covered the ‘GUIMark 2 Vector’ benchmark for several browers on three different operating systems (versions not specified): Windows, Linux, and Mac OS X. Bair compared JavaFX to these browsers’ native support. He also pointed out that sometimes SceneGraph is faster and sometimes Canvas is faster. Many of the points Bair brought up are more important on smaller devices than on desktops. JavaFX was much quicker than the browsers in GUIMark 2 Bitmap and JavaFX Canvas was the quickest of all. The GUIMark 2 Text test did not provide useful data for Windows due to limited rate, but JavaFX did well on Linux and Mac OS X. Bair intends to release benchmarking approaches for public consumption and he showed a chart indicating significant performance improvement from JavaFX 2.2 to JavaFX 8. Bair’s Performance Rule #1 is ‘Do Less Work.’ Bair stated, ‘Smaller systems require a much more intense round of performance tuning.’ He added that ‘every line counts’ and ‘extra method calls add up.’ Although in traditional desktop Java we’ve been taught not to worry about number of methods calls, this can be an issue on smaller devices (‘excessive inlining is expensive’ and ‘excessive method invocations are expensive’). Bair showed how to use a local final variable to reduce the number of method invocations. He acknowledged that it is ‘absolutely micro performance pre-optimization’ on the desktop, but is a useful tactic for smaller devices. Bair said that ‘fill rate’ is a limitation with ‘nearly 100% certainty.’ Geometry rate is unlikely to be a significant limit in JavaFX unless you have ‘zillions of vertices.’ CSS overhead is a possible limitation as is layout computation. JavaFX does a lot of caching and the latter may not always be an issue. There is a ‘good chance’ that system I/O will limit you, especially on smaller devices. Bair showed an example of ‘abusing the fill rate’ by drawing the furthest back background first and then drawing over the majority of that with another fill. He had some points for avoiding this unnecessary filling such as ‘only draw what has changed.’ Bair pointed out that the developer identifies ‘dirty regions’ in Swing, but that JavaFX SceneGraph ‘does this automatically!’ He did caution that JavaFX Canvas requires the developer to identify the ‘dirty regions.’ Another approach for improving fill rate is to ‘limit use of (some) effects.’ ‘Effects are almost free on your desktop systems,’ but may need to watch them more closely on smaller devices. Bair discussed a bullet stating, ‘Limit use of non-rectangular non-axis aligned clips’ as another tactic for improving fill rate. Directly clipping aligned images is quick, but the process of anti-aliasing, rendering as a background image, and rotating non-aligned pixel boundaries ‘costs you a little more’ (but you won’t notice on most desktop applications). Bair stated that reducing overdraw is an effective way of improving fill rate. Related to reduction of overdraw, he discussed using ‘image skinning.’ Bair also mentioned here that JavaFX 8 includes automatic region texture cache. Other ideas for reducing overdraw include simplifying the style (Metro, Android), consolidating background fills, and reducing the number of overlapping nodes. Bair stated that Microsoft intentionally came up with an easy-to-draw style in Metro. The Android style is similarly quicker and easier to draw. ‘Occlusion Culling‘ allows avoidance of drawing (culling) things that won’t be visible.’ Doing this allows us to ‘reduce overdraw and increase rendering performance.’ The JavaFX engine can respond to JavaFX CSS opaque insets to know when to not redraw these areas. There are CSS costs to be aware of such as parsing a stylesheet. Bair showed a ‘CSS Horror Show’ slide with .parent:hover .child {...} and explanation of why this is so terrifying: all the children must be revisited each time the parent is hovered over. Similarly, .parent .child {...} can be bad if there is a large number of children since ‘when we encounter a node with the .child style class, we must walk up the entire scene graph until we find it.’ It is better to limit the search to immediate parent. Bair stated that the setStyle CSS property is very convenient, but can be costly. The parsing and other support can add to performance problems. CSS provides power, flexibility, and convenience, but that does come at a performance cost. One of Bair’s tips is to ‘avoid structural changes to SceneGraph.’ All CSS from the changed point on down must be recomputed. Besides this reapplication of CSS, ‘structural integrity checks’ are required when the SceneGraph is changed. JavaFX has optimized toFront/toBack, so use these rather than removing and adding back. Another Bair tip is to ‘use FXCollections.’ His first bullet on this stated, ‘Shoot for minimal notification overhead.’ A sub-bullet recommended using setAll instead of clear and addAll. Another sub-bullet added, ‘Avoid multiple add calls.’ Use of FXColections.sort() is best because it ‘sends ‘permutation’ change events.’ This means that JavaFX engine knows what has changed and so only recomputes what is necessary for that specific type of change. These ‘permutations’ are ‘handled by separate fast paths.’ Bair stated that ‘ListView is blistering fast’ because it ‘reuses nodes’ and maintains minimum changes. Bair concluded that slide with ‘Reuse ListView for all your virtualization needs!’ Bair’s ‘Manual Layout’ tip included the idea of custom extensions of Region. He cautioned that you almost always need to implement computePrefWidth and computePrefHeight when extending Region. Bair had a slide listing the questions that ‘JavaFX asks’ when handling layout. These are questions like ‘How wide/tall would you like to be?’ and ‘Can you be resized?’ JavaFX asks these questions at least once and sometimes many more times that number of times when trying to render a layout. A customized layout can reduce the number of times attempted and the number of questions asked. ‘JavaFX asks a lot of questions’ and they are ‘all asked for each node during layout.’ Bair had a ‘Major Tip!’ related to ‘Content Bias.’ If height depends on width, you’re HORIZONTAL biased. If width depends on height, you’re VERTICAL biased. Bair stated that ‘(contentBias = null) is by far the fastest’ (all computed preferences for height and width are cached). Content Bias is typically null or horizontal. There is a bug in that ‘contentBias != null isn’t actually well supported in the built-in layouts.’ Everything covered so far has been under Bair’s Rule #1 (do less work). Rule #2 is now ‘Know Your Device.’ Bair showed a slide comparing the powerful NVidia GForce GTX 690 to the less powerful NVidia GForce 310 and to the even lowlier PowerVR SGX543MP3. Bair’s point, of course, is that ‘JavaFX gives you a single development platform and a single set of APIs, but which APIs you can and can’t use is going to depend on the inherent performance characteristics of the device.’ Bair had some rules of thumb for JavaFX on devices. Use desktop application for handling 20 thousand to 100 thousand nodes. Five hundred to one thousand nodes is the better range for embedded. For really small embedded devices, stick to range of 100 to 200 nodes for the JavaFX application. Bair provided another tip related to cache. He talked about caching a chart because it will then only be drawn to the image once and can then quickly be drawn to the screen ‘a bazillion times.’ Bair cautioned, though, that this ‘backfires if the node is changing a lot.’ Bair said that he’ll often turn cache to true, do an animation, and then set cache to false again. CacheHint can be set to SPEED when rotating and scaling for better performance. If you want it redrawn when it rotates for greater accuracy, then use cache hint other than SPEED. JavaFX 8 has a Pulse Logger (-Djavafx.pulseLogger=true system property) that ‘prints out a lot of crap’ (in a good way) about the JavaFX engine’s execution. There is a lot of provided information on a per-pulse basis including pulse number (auto-incremented integer), pulse duration, and time since last pulse. The information also includes thread details and events details. This data allows a developer to see what it taking most of the time. Bair ended the session with the same bright yellow caution slide: Write Clean Code, Then Profile! The slide also points out, ‘Don’t overdo it or you will have an unmaintainable mess. Reference: JavaOne 2012: JavaFX Graphics Tips and Tricks from our JCG partner Dustin Marx at the Inspired by Actual Events blog....

Spring MVC Customized User Login Logout Implementation Example

This post describes how to implement a customized user access to an Spring MVC web application (login logout). As a prerequisite, readers are advised to read this post which introduces several Spring Security concepts. The code example is available from Github in the Spring-MVC-Login-Logout directory. It is derived from the Spring MVC with annotations example. Customized Authentication Provider In order to implementation our own way of accepting user login requests, we need to implement an authentication provider. The following let’s users in if their id is identical to their passwords: public class MyAuthenticationProvider implements AuthenticationProvider {private static final List<GrantedAuthority> AUTHORITIES = new ArrayList<GrantedAuthority>();static { AUTHORITIES.add(new SimpleGrantedAuthority('ROLE_USER')); AUTHORITIES.add(new SimpleGrantedAuthority('ROLE_ANONYMOUS')); }@Override public Authentication authenticate(Authentication auth) throws AuthenticationException {if (auth.getName().equals(auth.getCredentials())) { return new UsernamePasswordAuthenticationToken(auth.getName(), auth.getCredentials(), AUTHORITIES); }throw new BadCredentialsException('Bad Credentials');}@Override public boolean supports(Class<?> authentication) { if ( authentication == null ) return false;return Authentication.class.isAssignableFrom(authentication); }}Security.xml We need to create a security.xml file: <beans:beans xmlns='' xmlns:beans='' xmlns:xsi='' xsi:schemaLocation=''><http> <intercept-url pattern='/*' access='ROLE_ANONYMOUS'/> <form-login default-target-url='/' always-use-default-target='true' /> <anonymous /> <logout /> </http><authentication-manager alias='authenticationManager'> <authentication-provider ref='myAuthenticationProvider' /> </authentication-manager><beans:bean id='myAuthenticationProvider' class='com.jverstry.LoginLogout.Authentication.MyAuthenticationProvider' /> </beans:beans>The above makes sure all users have the anonymous role to access any page. Once logged in, they are redirected to the main page. If they don’t log in, they are automatically considered as anonymous users. A logout function is also declared. Rather than re-implementing the wheel, we use items delivered by Spring itself. Main Page We implement a main page displaying the name of the currently logged in user, together with login and logout links: <%@ taglib prefix='c' uri='' %> <!doctype html> <html lang='en'> <head> <meta charset='utf-8'> <title>Welcome To MVC Customized Login Logout!!!</title> </head> <body> <h1>Spring MVC Customized Login Logout !!!</h1> Who is currently logged in? <c:out value='${CurrPrincipal}' /> !<br /> <a href='<c:url value='/spring_security_login'/>'>Login</a>  <a href='<c:url value='/j_spring_security_logout'/>'>Logout</a> </body> </html>Controller We need to provide the currently logged in user name to the view: @Controller public class MyController {@RequestMapping(value = '/') public String home(Model model) {model.addAttribute('CurrPrincipal', SecurityContextHolder.getContext() .getAuthentication().getName());return 'index';}}Running The Example Once compile, one can start the example by browsing: http://localhost:9292/spring-mvc-login-logout/. It will display the following:Log in using the same id and password:The application returns to the main and displays:More Spring related posts here. Happy coding and don’t forget to share! Reference: Spring MVC Customized User Login Logout Implementation Example from our JCG partner Jerome Versrynge at the Technical Notes blog....

Install Cloudera Manager 3.7.5 Free Edition

I recently installed Cloudera Manager Free Edition on my test cluster. I ran into a few problems during install so hopefully this will help you with your troubles.Cloudera Manager Free Edition will build and configure your single or multi-node CDH cluster and help you manage future changes to it. This software is free to use for up to 50 nodes with no term limit. Cloudera Documentation (PDF): To download and run the Cloudera Manager installer: 1. Download cloudera-manager-installer.bin from the Cloudera Downloads page wget 2. After downloading cloudera-manager-installer.bin, change it to have executable permission. $ chmod u+x cloudera-manager-installer.bin 3. Run cloudera-manager-installer.bin. $ sudo ./cloudera-manager-installer.bin 4. Read the Cloudera Manager Readme and then click Next. 5. Read the Cloudera Manager License and then click Next. Click Yes to confirm you accept the license. 6. Read the Oracle Binary Code License Agreement and then click Next. Click Yes to confirm you accept the Oracle Binary Code License Agreement. The Cloudera Manager installer begins installing the Oracle JDK (if necessary), CDH3, and Cloudera Manager repo files and then installs the packages. The installer also installs the embedded PostgreSQL database and the Cloudera Manager Server. Note If an error message “Failed to start server” appears while running cloudera-managerinstaller.bin, exit the installation program. If the Cloudera Manager Server log file /var/log/cloudera-scm-server/cloudera-scm-server.log contains the following message, then it's likely you have SELinux enabled: Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver at$ Source) at Method) at Source) at java.lang.ClassLoader.loadClass(Unknown Source) ... You can permanently disable SELinux by setting the following property in the /etc/selinux/config file on the Cloudera Manager Server host: SELINUX=disabled After editing the /etc/selinux/config file, reboot your system. 7. Click Close. 8. Click Finish to quit the installer program. Note If the installation is interrupted for some reason, you may need to clean up before you can re-run it. See Uninstalling Cloudera Manager Free Edition. Step 2: Start the Cloudera Manager Admin Console The Cloudera Manager Admin console enables you to use Cloudera Manager to configure, manage, and monitor Hadoop on your cluster. In this release, the Cloudera Manager Admin console supports the following browsers: • Internet Explorer 8 and 9 • Google Chrome • Safari 5Automated Installation of CDH by Cloudera Manager • Firefox 3.6 and later To start the Cloudera Manager Admin console: 1. In a web browser, type the following URL: http(s)://serverhost:port where: “serverhost” is the fully-qualified domain name or IP address of the host machine where the Cloudera Manager Server is installed. “port” is the port configured for the Cloudera Manager Server. The default port is 7180. For example, if you are on the host where the Cloudera Manager Server is installed, enter the following URL: http://localhost:7180/ If you are on another host, use a URL such as the following: The login screen for Cloudera Manager appears. 2. Log into Cloudera Manager. The default credentials are: Username: admin (you can add other admin user accounts and remove the default admin account later using Cloudera Manager after you run the wizard in the next section) Password: admin (you can change the default password later) Note You must have “ localhost” in your /etc/hosts file Test port 7180 by: telnet localhost 7180 Reference: Install Cloudera Manager 3.7.5 Free Edition CentOS 6.2 from our JCG partner Evan Conkle at the Evan Conkle’s blog blog....

Self-Service is the Future of Enterprise Software

Despite human desire to be pampered and served, there is a huge affinity to self service throughout the economy. Some samples: 1) Would you prefer to print your own boarding pass or have an agent do it for you? 2) Do you like taking your computer in for technical support or do you prefer to fix at home? 3) Do you want to call a restaurant for reservations or book it on OpenTable yourself? Given the right tools, humans prefer self service. Especially when its easy. Even more so if they get value out of doing it (ie OpenTable will learn what you like and make recommendations). If it starts to get hard, people might prefer some help. If it gets hard, people refuse self-service and at that point, forcing them into a self-service model will push them to seek alternatives. The future of enterprise software is self-service. Clients do not prefer to talk to sales people, but they have to, as a means to an end. Clients don’t like to hire consultants, but they have to when things get hard. Clients don’t want to take training classes, but they have to if the products are not intuitive. Despite the claims heard every day on Silicon Valley Radio (my term for the chatter), the future of enterprise software is not holistically SaaS/Cloud. SaaS and Cloud do not necessarily deliver self-service, but they can. Irrespective of delivery model (On-Premise, Saas, Cloud), I believe clients will migrate to software with the following attributes: 1) Available for download on a public website. 2) Intuitive use: no manuals, no training…unless desired. 3) No sales people, consultants, or meetings…unless desired. 4) Quick value, based on how the software is used. 5) The software understands what the user needs, so every usage is more valuable. Interestingly, I talk to very few companies that are focused on this. I am aware of only one that I think has done this quite well…and accordingly, they have been very successful. This is not easy, but it is the future of enterprise software. Don’t forget to share! Reference: Self-Service is the Future of Enterprise Software from our JCG partner Rob Thomas at the Rob’s Blog blog....

Spring Collection Merging

Spring collection merging is a feature that I first came across as an answer to a StackOverflow question It is a way of creating a base collection (list, set, map or properties) and modifying this base collection in other beans, best explained using an example –             Consider a Person class with a field holding a list of addresses: public class Person { private List<Address> addresses; .. } Assume that all Person instances have a common set of addresses, which can be specified using an abstract person bean this way: <bean name='basePerson' class='Person' abstract='true'> <property name='addresses'> <list> <bean class='Address' p:street='Street1' p:state='State1' p:zip='001'></bean> <bean class='Address' p:street='Street2' p:state='State2' p:zip='002'></bean> <bean class='Address' p:street='Street3' p:state='State3' p:zip='003'></bean> </list> </property> </bean> Now, Person bean instances with addresses in addition to the addresses from the basePerson can be specified using Collection Merging feature this way – note the ‘merge=true’ attribute of list: <bean name='person1' class='Person' parent='basePerson'> <property name='addresses'> <list merge='true'> <bean class='Address' p:street='Street4' p:state='State4' p:zip='004'></bean> </list> </property> </bean> Collection merging also works with <set/>, <map/> and <props/> With Spring 3.1 and higher, a simpler option though could be simply to use @Configuraion and @Bean options, as then the merging can be directly handled with Java code, for eg, an equivalent @Configuration for the above xml bean configuration: @Configuration public class CollectionConfig{ private List<Address> baseAddresses(){ return Lists.newArrayList(new Address('Street1', 'State1', '001'), new Address('Street2', 'State2', '002'), new Address('Street3', 'State3', '003')); } @Bean public Person person1(){ Person person1 = new Person(); person1.setAddresses(baseAddresses()); person1.getAddresses().add(new Address('Street4', 'State4', '004')); return person1; } } Reference: Spring Collection Merging from our JCG partner Biju Kunjummen at the all and sundry blog....

JavaOne 2012: NetBeans.Next – The Roadmap Ahead

I walked the few steps necessary from Continental Ballroom 4 and one NetBeans topic (Project Easel) to Continental Ballroom 5 to see another NetBeans-oriented presentation: ‘NetBeans.Next – The Roadmap Ahead.’Ashwin Rao started the Birds of a Feather (BoF) presentation and introduced John Ceccarelli and Tinuola Awopetu. Several audience members attended yesterday’s NetBeans Community Day. Rao showed the typical Oracle disclaimer slide about outlining ‘general product direction,’ but in this case (roadmap) it did seem particularly relevant. Rao talked about the ‘Motivation for Roadmap.’ This motivation includes ‘providing best end-to-end development experience for Java platform’ and supporting various Java releases as well as ‘HTML5 and popular languages and frameworks that complement and co-exist with the Java platform.’ He added that two main forces drive the NetBeans Roadmap: ‘Industry and Technology Trends’ and the ‘Java Platform Roadmap.’ Rao introduced the topic of ways to determine industry and technology trends including market analysis and community engagement. Awopetu then talked about how the community can use bug reports and RFEs (requests for enhancements) to relay to the NetBeans team the level of priority to apply to bugs and enhancements. She added that NetCAT (NetBeans Community Acceptance Testing program) is a main driver of what they work on. NetCAT users have contributed as many as 7,000 bugs/enhancements. Awopetu also stated that user satisfaction surveys and monitoring forum posts over the past 18 months have helped give them an idea of what the community wants in NetBeans. I was pleased to hear Ceccarelli state that they will be tackling NetBeans‘s known memory issues in the same way that they have tackled the scanning issues in NetBeans 7.2. It was pointed out that there is a command-line switch that can be used with NetBeans Rich Client Platform in production. One of the main motivations I had in attending this session was a peek at the road ahead. This chart came toward the end and was titled ‘The Road Ahead.’ Rao talked about NetBeans 7.3 (advanced HTML5 tooling, Oracle Public Cloud, and Java ME 3.2 and Embedded). He also cited Java EE 7 support (Avatar) and NetBeans JDK 8 support (Lambdas, JavaFX 8, and Java ME 8 and Embedded), and NetBeans JDK 9 support (Jigsaw). One audience member expressed interest in NetBeans supporting specific cloud vendors and warning when code is not compliant with a particular cloud provider. The lack of standardization in cloud is reminiscent of the lack of standards implementation in web development in the past and even to some degree today. Therefore, it’s not surprising that this would be a desirable feature to have. Another audience member wondered about a tool for code collaboration. I was interested in this question because I would love to see a NetBeans equivalent of the Code Collaborator plugin for Eclipse. It was explained that Kenai was a sponsored project that became, but support does not include code collaboration. It was stated that it is relatively easy to write GUI for code collaboration, but the repository is what is difficult. NetBeans will support Oracle Cloud ALM tools and there is some consideration of Github support. There is no plan to add WYSIWYG support for HTML/CSS/JavaScript to NetBeans and the audience seemed to be fine (and even welcome) that. It was explained that it is easier to do this with GWT, Oracle ADF, or other known deployments. It is difficult enough to make the editor work with JavaScript. Discussion of ‘Top Feature Requests’ with no delivery plans focused on three features not anticipated for NetBeans at this time:UML Visual Web Android/IOSThere was a large percentage of those in attendance who expressed interest (even if forced by employers and clients) in UML support. Based on this support, it was stated that ‘reports of UML death are overrated.’ It was also expressed that they would like to move JDeveloper’s UML into NetBeans. The team has moved much NetBeans functionality into JDeveloper, so this would be other direction. JDeveloper UML has been heavily used, but the many complaints about it led the NetBeans team to think it wasn’t wanted in NetBeans. For times I need to create UML, I too would like to see UML support available again in NetBeans. UPDATE – Apparently IntelliJ IDEA users also use UML frequently. Although NetBeans will not provide native support for Android or iOS, it was pointed out that there is a community Android plugin for NetBeans. Also, the NetBeans team may add PhoneGap support (PhoneGap allows for HTML/CSS/JavaScript to be used to write applications to 7 native mobile device formats) for Project Easel at some point in the future. Ceccarelli stated that his ‘job now is not to make NetBeans successful, but to make Java successful.’ He added that the ‘Java IDE wars are over.’ Each of the IDEs has pieces of other IDEs in it now. One of the compelling things for NetBeans in the short-term future will be the availability of HTML5 support in NetBeans with Project Easel. Reference: JavaOne 2012: NetBeans.Next – The Roadmap Ahead from our JCG partner Dustin Marx at the Inspired by Actual Events blog....

Android: Leaf fall-like animation using property animators

In the previous tutorial we explained how property animations work in general. Now we’ll go even further and explain how to create a property animation that would create leaf-falling-like effect for an ImageView in which we’ll, apparently put images of leaves. For that purpose we need few images that represent leaves. We found the ones we use in the example somewhere on the net, hopefully not infringing any designer’s work:If you don’t have anything better, get this images and use them. When you imagine a falling leaf represented in digital context you can notice three things:the leaf is falling down the leaf is rotating around its axes at some angle the leaf is making curve movementThese three properties would make the effect of a leaf falling down flown by the wind, taken off the tree. One thing that at this point we won’t implement is the curvic transformation since we plan to create separate tutorial about it, as extension to this one. So we would need to create translation and rotation, putting some more logics here and there. In Android sense, as we mentioned earlier the leaves would be ImageView objects. They would be created randomly and added to the root layout right before the animation starts. So we’ll need some timer that would knock-off the animation of a single leaf. Let’s say that we want new leaf every 5 seconds. So we’ll need timer that would send empty message, handled by a Handler object. When the message is handled (received), we get random leaf from a set of leaves (Drawables), create ImageView object and put the drawable as its contents, and add the imageview to the root layout of the activity. Then we call a method which in our case is named ‘startAnimation’ that would accept one ImageView object as parameter which will be animated. We do this in this way so that we leave space in the ‘startAnimation’ method where the ViewAnimator would be create, initialized and started, and also its listener. Let’s go again step by step. Let’s create the Handler object first: private Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); int viewId = new Random().nextInt(LEAVES.length); Drawable d = getResources().getDrawable(LEAVES[viewId]); LayoutInflater inflate = LayoutInflater.from(FallAnimationActivity.this); ImageView leafImageView = (ImageView) inflate.inflate(R.layout.ani_image_view, null); leafImageView.setImageDrawable(d); mRootLayout.addView(leafImageView); LayoutParams animationLayout = (LayoutParams) leafImageView.getLayoutParams(); animationLayout.setMargins(0, (int)(-150*mScale), 0, 0); animationLayout.width = (int) (60*mScale); animationLayout.height = (int) (60*mScale); startAnimation(imageView); } }; The leafImageView object is inflated from XML so that we don’t have to create it programmatically, mScale is global field holding the density of the screen (used on few other places in the code, that’s why globally declared). After we add the leafImageView to the root layout we’ll programmatically set its top margin to 150dp in minus only to position it above the visible area of the screen. We create TimerTask like this: private class AnimTimerTask extends TimerTask { @Override public void run() { mHandler.sendEmptyMessage(0x001); } } and the TimerTask is executed like this, in our case in the onCreate method of the Activity: new Timer().schedule(new AnimTimerTask(), 0, 5000); This means, create new imageview every 5 seconds, add it to the root layout and start animation on it. Now back to the logic of the animation. As we previously mentioned we need a to translate to the bottom and side (x/y) and minor rotate animation. Both pivots (x and y) are the center of the axis, so the center of the leaf imageview. The delay before the animation starts is again calculated randomly as value between 0 and 6000 (milliseconds). The animator would be ofFloat from 0 to 1. For now, we set the animation to last for 10 seconds (10000 ms). That might be little fast so you can increase this value as you wish. What happens in the AnimatorUpdateListener is the following: The final ‘x’ position of the leaf imageview would be calculated as random value from 0 (left of the screen) and display’s width (right of the screen). Any point between this would be the ‘x’ final position. The final ‘y’ position of the leaf imageview would be display’s height/bottom, plus 150dp just to make the view not stop in the visible area. I like to make it fall to some point of display’s height + 10dp which would look just as if the leaf has fallen on the ground. This time, we make the leaf dissapear in the void of the screen. So now we have an imageview that goes from top to bottom where the x final position is random. But we miss 2 more things (rotation + curve animation) out of which we decided to implement only one more, the rotation. Let’s imagine the wind is not that strong so we need tremble-like effect for the leaf. An angle of 50 to 100 would be enough for this to take effect. One general rule to implement this would be this practice: Min + (int)(Math.random() * ((Max - Min) + 1)) In our case that’d be: 50 + (int)(Math.random() * 101) onAnimationUpdate is called till every last frame is done. Rotation and Translation are set here. Lastly we start the animator. Here is the whole method: public void startAnimation(final ImageView leafImageView) {leafImageView.setPivotX(leafImageView.getWidth()/2); leafImageView.setPivotY(leafImageView.getHeight()/2);long delay = new Random().nextInt(6000);final ValueAnimator animator = ValueAnimator.ofFloat(0, 1); animator.setDuration(10000); animator.setInterpolator(new AccelerateInterpolator()); animator.setStartDelay(delay);animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { int movex = new Random().nextInt(mDisplaySize.right); int angle = 50 + (int)(Math.random() * 101); @Override public void onAnimationUpdate(ValueAnimator animation) { float value = ((Float) (animation.getAnimatedValue())).floatValue(); leafImageView.setRotation(angle*value); leafImageView.setTranslationX((movex-40)*value); leafImageView.setTranslationY((mDisplaySize.bottom + (150*mScale))*value); } });animator.start(); } When we run this application we’re supposed to see something like this:We use this animation for our latest project which is in its latest polishing process. Also, download the sources and see if we’ve missed something or made a mistake explaining the code. Reference: Android: Leaf fall-like animation using property animators from our JCG partner Aleksandar Balalovski at the 2Dwarfs blog....

Tips for identifying and debugging problems

It seems that some/many developers haven’t developed (pun intended) a good set of techniques to identify and resolve problems. And problems always occur, even in simple programs. Recently I’ve been answering a lot of questions on StackOverflow and those questions confirmed my suspicions. Some of the advice here may sound like advice for newbies, but pactice shows they are needed. I’m a Java developer, but the tips below may be considered language-agnostic. Note that the steps are often regarding Exceptions, but in case there is no exception – just an undesired behaviour, those steps are skipped.Exception stacktraces – these are so often ignored and even considered irrelevant. Stacktraces are the place to start looking for the problem. Not only the exception message, but the line of code at which the exception occurred (in your code, in the library code). The code in question – after seeing what line of code causes the exception, immediately go to that line and see if the problem won’t become obvious. Try understanding the behaviour of the code (even if it is your code!). In case there is no exception, but an undesired behaviour, identify the code that is relevant Google – if it doesn’t become obvious, or the exception/problem occurred somewhere in a framework you are using, rather than in your code, then google the exception message or the problem description. Google it for 15 minutes, trimming various parts of the exception message – most importantly your package and class names. Most of the common exceptions occurring in popular frameworks are explained many times (because people skipped this step) Read the documentation – this is not always applicable, but in cases when the problem/exception regards a concrete component of the framework used, read the documentation about it. As the saying goes – 5 hours debugging save 20 minutes reading documentation Debugger – if there isn’t an obvious solution from the previous steps, use the debugger of your IDE. Put breakpoints at relevant places and trace the flow of the program. This will help you understand how exactly the program functions (again, even if it is your code). You will be able to monitor variables and fields, and see if their values are not the ones you expect Decompiler / framework source code – I’m always having a decompiler plugin installed on my IDE. It extends the process of looking at your own code to looking at all the code that’s involved. Alternatively, you can download/check-out the sources of the framework you are using (if it’s open-source) and add them to your IDE. Debugging with either the decompiled sources or the real sources can provide even more beneficial information about the problem, if you look at the appropriate places Finally, if you haven’t solved the problem – ask a question. In the forums of the framework/tool, in general forums (JavaRanch, Sun forums, etc), or in dedicated Q & A sites like StackOverflow. State the question clearly, show what have you already done in order to find/fix it, and give the appropriate information (setup, version of the framework, the code in question, the whole stacktrace, etc). At the same time try not to make the question too long and try to emphasize the main points – people that aren’t paid to answer will be reading it after all It sometimes happens that you have discovered a bug. This is a rare case with popular and mature frameworks/tools (yes!), but if you are sure it is a bug, go to the issue tracker and file a detailed bug report. They will either instruct you how to use a workaround, or will fix it eventuallyI’ve used words like “relevant” or “appropriate”. The degree of benefit from each step will depend on your experience, and each time you will get better at each of the steps. Don’t forget to share! Reference: Tips for Identifying and Debugging Problems from our JCG partner Bozhidar Bozhanov at the Bozho’s tech blog blog....
Java Code Geeks and all content copyright © 2010-2015, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

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

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