Featured FREE Whitepapers

What's New Here?

jcg-logo

Java Code Geeks are giving away FREE JCG Academy Subscriptions (worth $900)!

Ready to take your skill-set to the next level? We are running a short duration contest giving away annual subscriptions for our premium content website, JCG Academy. JCG Academy is packed with high end courses covering a wide spectrum of technologies, ranging from Java and JavaScript, to Android and NoSQL platforms. Here are some of the courses that are featured there:      Java Concurrency Essentials (FREE!) Introduction to Nginx (FREE!) Java Design Patterns Spring Integration for EAI Android UI Design – Basics Building web apps with Node.js… and many more! Enter the contest now to win your very own FREE annual subscription. There will be a total of 10 winners! In addition, we will send you free tips and the latest news from the Java community to master your technical knowledge (you can unsubscribe at any time). In order to increase your chances of winning, don’t forget to refer as much of your friends as possible! You will get 3 more entries for every friend you refer, that is 3 times more chances! Make sure to use your lucky URL to spread the word! Good luck and may the force be with you! Join the Contest! ...
enterprise-java-logo

Everything Developers Need To Know About xPaaS

I’ve been reading a lot about Red Hat products lately and being interested in cloud and such since some years now, it’s pretty obvious for me to look into the cloud offerings from Red Hat in more detail. Arun did a great overview about JBoss xPaaS back in April this year and I thought it might be time to not only give you an overview but also point you to all the relevant information that interested developers need to know about. If I missed something, or your stuck somewhere, don’t forget to reach out to me and let me know!       xPaaS= aPaaS, iPaaS, bpmPaaS, dvPaaS, mPaaS + OpenShift A very tiny little overview to get you up to speed. To make it simple, JBoss xPaaS services is another name for having all the powerful capabilities of JBoss Middleware available as a cloud based services, ready for use on OpenShift. A main differentiator to others is, that it is not just a bunch of services with little to know integration. It is a complete set of pre-build and ready to use integrated services.For those interested why it is called xPaaS: Gartner uses the term xPaaS to describe the whole spectrum of specialized middleware services that can be offered as PaaS. Red Hat has the complete implementation. More basic information:JBoss xPaaS Services at OpenShift (openshift.com/xpaas) Official Landing Page (red.ht/xpaas) Red Hat Summit JBoss Middleware Keynote (youtube.com) Mark Little about xPaaS (community.jboss.org) Gartner’s Magic Quadrant for On-Premise Application Platforms (Press Release, Gartner Report)Time to dig deeper into the individual pieces. The idea here is to just breakup the streamlined names a bit and break them down to the individual products and upstream projects used in it. Note: Some features on OpenShift are in Alpha release state. Designed and provided for developers to experiment with and explore. And for the i and bpm-PaaS offerings which can be deployed in the free OpenShift Online gears, it is recommend to use medium or large gears for optimum performance. aPaaS = JBoss Application Hosting + OpenShiftThe app-container services of OpenShift for Java EE 6 with Red Hat JBoss EAP/JBoss AS and Java EE 7 with WildFly is there for more than 2 years already. This is the foundation of everything in the xPaaS familiy. To keep it DRY, I put everything which is OpenShift related in this section. More basic information:JBoss Application Hosting on OpenShift OpenShift Getting Started GuideOpenShift Quickstarts and Cartridges:OpenShift WildFly 8 Quickstart OpenShift EAP 6.1/6.2 CartridgeBlogs to follow:Arun Gupta’s Blog Thomas Qvarnström JBoss Tech BlogVarious Developer Links:WildFly Website Java EE Samples on GitHub OpenShift Accelerator Program OpenShift GitHub Community Cartridges for OpenShift EAP Product DocumentationiPaaS = JBoss Fuse && JBoss Data Virtualization + OpenShiftThe integration services consist of two separate offerings at the moment. One is The JBoss Fuse enterprise service bus and the other is JBoss Data Virtualization. More basic information:Integration Services on OpenShift JBoss Fuse on OpenShift JBoss Data Virtualization on OpenShiftOpenShift Quickstarts and Cartridges:Fuse Getting Started Guide Fuse Quickstart Data Virtualization Getting Started Guide Data Virtualization QuickstartBlogs to follow:The Open Universe Christina James Strachan’s BlogVarious Developer Links:Samples and Demos by Kenny Peeples on Github Demo of Fuse 6.1 with Apache Camel and hawtio on OpenShift JBoss Fuse on GitHub JBoss Data Virtualization on GitHub Data Virtualization Product Documentation Fuse Product DocumentationbpmPaaS = JBoss BPM Suite + OpenShiftBusiness Process Management (BPM) and Business Rules Management (BRM) are the most important parts of this. More basic information:JBoss BPM Suite Product Overview (jboss.org/products/bpmsuite/overview/) Frequently Asked QuestionsOpenShift Quickstarts and Cartridges:BPM Suite on OpenShift Getting Started Guide BPM Suite QuickstartBlogs to follow:Eric D. SchabellVarious Developer Links:How to Use Rules and Events to Drive JBoss BRMS Cool Store for xPaaS Developer Materials on jboss.org Feedback and Support Official Product DocumentationmPaaS = AeroGear UnifiedPush Server + OpenShiftThe AeroGear UnifiedPush Server allows for sending native push messages to different mobile operation systems. This initial community version of the server supports Apple’s Push Notification Service (APNs), Google Cloud Messaging (GCM) and Mozilla’s SimplePush. More basic information:AeroGear Push 0.X on OpenShiftOpenShift Quickstarts and Cartridges:AeroGear Quickstart on OpenShiftBlogs to follow:chat & code by Corinne Matthias Wessendorf’s Weblog Bruno Oliviera’s BlogVarious Developer Links:AeroGear Project Website Mobile Push Simplified With The AeroGear Push Server On OpenShift AeroGear Documentation AeroDoc push notification application, step by step How to use the UnifiedPush ServerThat’s it for a first overview. Let me know if you’re missing something. I am committed to close the gap and make working and developing with xPaaS a fun and productive experience.Reference: Everything Developers Need To Know About xPaaS from our JCG partner Markus Eisele at the Enterprise Software Development with Java blog....
spring-logo

Secure REST services using Spring Security

Overview Recently, I was working on a project which uses a REST services layer to communicate with the client application (GWT application). So I have spent a lot of to time to figure out how to secure the REST services with Spring Security. This article describe the solution I found, and I have implemented. I hope that this solution will be helpful to someone and will save a much valuable time.         The solution In a normal web application, whenever a secured resource is accessed Spring Security check the security context for the current user and will decide either to forward him to login page (if the user is not authenticated), or to forward him to the resource not authorised page (if he doesn’t have the required permissions). In our scenario this is different, because we don’t have pages to forward to, we need to adapt and override Spring Security to communicate using HTTP protocols status only, below I liste the things to do to make Spring Security works best :The authentication is going to be managed by the normal form login, the only difference is that the response will be on JSON along with an HTTP status which can either code 200 (if the autentication passed) or code 401 (if the authentication failed) ; Override the AuthenticationFailureHandler to return the code 401 UNAUTHORIZED ; Override the AuthenticationSuccessHandler to return the code 20 OK, the body of the HTTP response contain the JSON data of the current authenticated user ; Override the AuthenticationEntryPoint to always return the code 401 UNAUTHORIZED. This will override the default behavior of Spring Security which is forwarding the user to the login page if he don’t meet the security requirements, because on REST we don’t have any login page ; Override the LogoutSuccessHandler to return the code 20 OK ;Like a normal web application secured by Spring Security, before accessing a protected service, it is mandatory to first authenticate by submitting the password and username to the Login URL. Note: The following solution requires Spring Security in version minimum 3.2. Overriding the AuthenticationEntryPoint Class extends org.springframework.security.web.AuthenticationEntryPoint, and implements only one method, which sends response error (with 401 status code) in cause of unauthorized attempt. @Component public class HttpAuthenticationEntryPoint implements AuthenticationEntryPoint { @Override public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, authException.getMessage()); } } Overriding the AuthenticationSuccessHandler The AuthenticationSuccessHandler is responsible of what to do after a successful authentication, by default it will redirect to an URL, but in our case we want it to send an HTTP response with data. @Component public class AuthSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler { private static final Logger LOGGER = LoggerFactory.getLogger(AuthSuccessHandler.class);private final ObjectMapper mapper;@Autowired AuthSuccessHandler(MappingJackson2HttpMessageConverter messageConverter) { this.mapper = messageConverter.getObjectMapper(); }@Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { response.setStatus(HttpServletResponse.SC_OK);NuvolaUserDetails userDetails = (NuvolaUserDetails) authentication.getPrincipal(); User user = userDetails.getUser(); userDetails.setUser(user);LOGGER.info(userDetails.getUsername() + " got is connected ");PrintWriter writer = response.getWriter(); mapper.writeValue(writer, user); writer.flush(); } } Overriding the AuthenticationFailureHandler The AuthenticationFaillureHandler is responsible of what to after a failed authentication, by default it will redirect to the login page URL, but in our case we just want it to send an HTTP response with the 401 UNAUTHORIZED code. @Component public class AuthFailureHandler extends SimpleUrlAuthenticationFailureHandler { @Override public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException { response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);PrintWriter writer = response.getWriter(); writer.write(exception.getMessage()); writer.flush(); } } Overriding the LogoutSuccessHandler The LogoutSuccessHandler decide what to do if the user logged out successfully, by default it will redirect to the login page URL, because we don’t have that I did override it to return an HTTP response with the 20 OK code. @Component public class HttpLogoutSuccessHandler implements LogoutSuccessHandler { @Override public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException { response.setStatus(HttpServletResponse.SC_OK); response.getWriter().flush(); } } Spring security configuration This is the final step, to put all what we did together, I prefer using the new way to configure Spring Security which is with Java no XML, but you can easily adapt this configuration to XML. @Configuration @EnableWebSecurity public class WebSecurityConfig extends WebSecurityConfigurerAdapter { private static final String LOGIN_PATH = ApiPaths.ROOT + ApiPaths.User.ROOT + ApiPaths.User.LOGIN;@Autowired private NuvolaUserDetailsService userDetailsService; @Autowired private HttpAuthenticationEntryPoint authenticationEntryPoint; @Autowired private AuthSuccessHandler authSuccessHandler; @Autowired private AuthFailureHandler authFailureHandler; @Autowired private HttpLogoutSuccessHandler logoutSuccessHandler;@Bean @Override public AuthenticationManager authenticationManagerBean() throws Exception { return super.authenticationManagerBean(); }@Bean @Override public UserDetailsService userDetailsServiceBean() throws Exception { return super.userDetailsServiceBean(); }@Bean public AuthenticationProvider authenticationProvider() { DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider(); authenticationProvider.setUserDetailsService(userDetailsService); authenticationProvider.setPasswordEncoder(new ShaPasswordEncoder());return authenticationProvider; }@Override protected void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(authenticationProvider()); }@Override protected AuthenticationManager authenticationManager() throws Exception { return super.authenticationManager(); }@Override protected void configure(HttpSecurity http) throws Exception { http.csrf().disable() .authenticationProvider(authenticationProvider()) .exceptionHandling() .authenticationEntryPoint(authenticationEntryPoint) .and() .formLogin() .permitAll() .loginProcessingUrl(LOGIN_PATH) .usernameParameter(USERNAME) .passwordParameter(PASSWORD) .successHandler(authSuccessHandler) .failureHandler(authFailureHandler) .and() .logout() .permitAll() .logoutRequestMatcher(new AntPathRequestMatcher(LOGIN_PATH, "DELETE")) .logoutSuccessHandler(logoutSuccessHandler) .and() .sessionManagement() .maximumSessions(1);http.authorizeRequests().anyRequest().authenticated(); } } This was a sneak peak at the overall configuration, I attached in this article a Github repository containing a sample project https://github.com/imrabti/gwtp-spring-security. I hope this will help some of you developers struggling to figure out a solution, please feel free to ask any questions, or post any enhancements that can make this solution better.Reference: Secure REST services using Spring Security from our JCG partner Idriss Mrabti at the Fancy UI blog....
enterprise-java-logo

Analysing the performance degradation/improvements of a Java EE application with interceptors

When you are developing a Java EE application with certain performance requirements, you have to verify that these requirements are fulfilled before each release. An Hudson job that nightly executes a bunch of test measurements on some specific hardware platform is what you may think about. You can check the achieved timings and compare them with the given requirements. If the measured values deviate from the requirements too much, you can either break the build or at least send an email to the team. But how do you measure the execution time of your code? The very first thought might be to add thousands of insertions of time measuring code into your code base. But this is not only a lot of work, but also has an impact on the performance of your code, as now the time measurements are also executed in production. To get rid of the many insertions you might want to leverage an aspect oriented framework (AOP) that introduces the code for time measurements at compile time. Using this way you have at least two versions of your application: the one with and the one without the additional overhead. To measure performance at some production site still requires a redeployment of your code. And you have to decide which methods you want to observe already at compile time. Java EE comes therefore with an easy to use alternative: Interceptors. This is were the inversion of control pattern plays out its advantages. As the Application Server invokes your bean methods/web service calls, it is easy for it to intercept these invocations and provide you a way of adding code before and after each invocation. Using interceptors is then fairly easy. You can either add an annotation to your target method or class that references your interceptor implementation or you can add the interceptor using the deployment descriptor: @Interceptors(PerformanceInterceptor.class) public class CustomerService { ... } The same information supplied in the deployment descriptor looks like this: <interceptor-binding> <target-name>myapp.CustomerService</target-name> <interceptor-class>myapp.PerformanceInterceptor.class</interceptor-class> </interceptor-binding> The interceptor itself can be a simple POJO class with a method that is annotated with @AroundInvoke and one argument: @AroundInvoke public Object measureExecutionTime(InvocationContext ctx) throws Exception { long start = System.currentTimeMillis(); try { return ctx.proceed(); } finally { long time = System.currentTimeMillis() - start; Method method = ctx.getMethod(); RingStorage ringStorage = RingStorageFactory.getRingStorage(method); ringStorage.addMeasurement(time); } } Before the try block and in the finally block we add our code for the time measurement. As can be seen from the code above, we also need some in-memory location where we can store the last measurement values in order to compute for example a mean value and the deviation from the mean value. In this example we have a simple ring storage implementation that overrides old values after some time. But how to expose these values to the world outside? As many other values of the Application Server are exposed over the JMX interface, we can implement a simple MXBean interface like shown in the following code snippet: public interface PerformanceResourceMXBean { long getMeanValue(); }public class RingStorage implements PerformanceResourceMXBean { private String id;public RingStorage(String id) { this.id = id; registerMBean(); ... } private void registerMBean() { try { ObjectName objectName = new ObjectName("performance" + id + ":type=" + this.getClass().getName()); MBeanServer platformMBeanServer = ManagementFactory.getPlatformMBeanServer(); try { platformMBeanServer.unregisterMBean(objectName); } catch (Exception e) { } platformMBeanServer.registerMBean(this, objectName); } catch (Exception e) { throw new IllegalStateException("Problem during registration:" + e); } } @Override public long getMeanValue() { ... } ... } Now we can start the jconsole and query the exposed MXBean for the mean value:Writing a small JMX client application that writes the sampled values for example into a CSV file, enables you to later on process these values and compare them with later measurements. This gives you an overview of the evolution of your application’s performance. Conclusion Adding dynamically through the deployment descriptor performance measurement capabilities to an existing Java EE application is with the use of interceptors easy. If you expose the measured values over JMX, you can apply further processing of the values afterwards.Reference: Analysing the performance degradation/improvements of a Java EE application with interceptors from our JCG partner Martin Mois at the Martin’s Developer World blog....
software-development-2-logo

5 Things I Do to Stay Relevant

I have noticed that some Finnish IT professionals are complaining that being just a good employee isn’t good enough anymore. These people argue that they cannot get a job because:Their work experience isn’t worth anything because they have no experience from technology X that is hot right now. They are too old (over 40). They have a life outside work and that is why they don’t have time to learn new technologies.    I could argue that these reasons are just excuses and these people just aren’t good enough. I am not going to do this because:I don’t want to be a dick. I am getting older (I am 36 at the moment) and if age discrimination is a real problem, I should definitely be worried about it.On the other hand, I think that is stupid to worry about something and not do anything about it. That is why I decided to take my destiny into my own hands and ensure that I am still relevant when I am over 40 years old. I give you five things I do to stay relevant: 1. I Learn at Work I spend 8 hours of every business day at work. That is a lot of time, and I want to take advantage of this time. Does this mean that I spend all this time learning new things and ignore my work? No. It means that I learn new things when I am doing my work. My main priority is to keep my customers happy. The thing is that learning new things at work will help me to achieve this goal. This might sound a bit weird because learning new things takes time. Shouldn’t I spend this time working for my customer? I claim that I can learn new things, work for my customer, and save my customer’s money (or provide more value) at the same time. I can do this because I am constantly looking for ways to work smarter. If I see something that helps me to achieve this, I will start using it. However, this doesn’t mean that I make this decision lightly. I will evaluate the pros and cons of each new technology and use it only if its pros are greater than its cons. Luckily, I don’t have to do this alone. We have a lot of great developers and I can always ask their opinion when I need it. I don’t always like their answers but that is a good thing because it helps me to see things from another perspective. Here are some examples of libraries/frameworks/programming languages that I have learned at work during the last three years:Frontend: Javascript, Bower, Gulp, NPM, jQuery, Backbone.js, Marionette.js, Angular.js, Twitter Bootstrap, and a lot of other libraries that have weird names. Backend: Spring Batch, Spring Data JPA, Spring Data Solr, and Spring Social. Testing: AssertJ, Hamcrest, Spring MVC Test, and Spring-Test-DbUnit. Software Development: software design, automated testing techniques, agile, and using common sense.I am sorry that I turned this example into a buzzword bingo but that was necessary so that I could demonstrate to you how much a developer can learn at work. 2. I Read (a Lot) I think that if I want to stay relevant, I need to be able to identify “hot” technologies. Also, I need to improve my technical, business, and human skills. One way to do this is to read, and since I love reading, I read a lot. At the moment I am reading:I follow relevant “news” sites such as Dzone, Reddit, and HackerNews. I won’t read every popular article or discussion but these sites help me to identify trends and see what technologies are “hot” right now. Also, sometimes I find an article or discussion that teaches me something new. I read interesting blogs. When I feel like learning something new, I open my feed reader and pick one or two blog posts that I read right away. When I am done, I mark all other blog post as read. The reason why I do this is that at the moment I have about 100 blogs in my feed reader and it would take too much time to read every blog post. Thus, I prioritize. I read 5-10 software development books in a year. I love blogs but a good software development book fulfils a totally different need. If I want to get as much information about X as possible, I read a book (or books) because it is a lot easier than trying to find all this information from the internet. Also, I know that this is a bit of old fashioned, but when I buy a book that is published by a respected publisher, I can trust that the book contains correct information. I read 5-10 other non-fiction books in a year. Although software development is a my passion, I am interested in other things as well. Typically I read books about entrepreneurship, marketing, psychology, product development, and agile “processes”. Also, I think that reading these books will make me a better software developer because writing code is only a small part of my job. I think that if I want to add value to my customers, I need to understand a lot of other things as well. Reading non-fiction books help me to achieve that goal.3. I Write a Blog I started writing a blog because it felt like a fun thing to do. I was right. It is fun but writing a blog has other benefits as well:It helps me to learn new things. There are three ways how writing a blog helps me to learn something new:The truth is that I write some of my tutorials because I want to learn a new library/framework/tool and writing a tutorial is a good way to ensure that I actually do it. Writing helps me to clarify my thoughts and often I notice something I haven’t thought before. I answer to the comments left to my blog posts, and since I don’t usually know the answer right away, I have to do some investigation before I can write a helpful answer. In other words, I learn new things by answering to the questions of my readers.It helps me to get feedback from other developers. I know that I don’t know everything and that I can be wrong. When I publish my thoughts on my blog, everyone who reads it can say his/her opinion about my thoughts. Sometimes these comments help me to understand that I am not right, and this is very valuable to me because my goal is not be right. My goal is to make people think and hope that they return the favor by leaving a comment to my blog post. It helps me to build an online presence and a “brand”. Let’s assume I am applying for a new job or trying to find a new business partner. What happens when these persons google me and find nothing? This might not be a deal breaker, but I think that my blog gives me an edge over persons who are otherwise “as good as I am” but don’t have a blog. I think this way because I believe that my blog “proves” thatI can learn new things. If this person takes the time to read some of my older blog posts and compare them with my newer posts, he/she will see that my thinking has evolved. I am an expert in my field. This sounds a bit narcissistic but I think that my blog posts gives an impression that I know what I am talking about. If I wouldn’t write a blog this person would just have to take my word for it.4. I Am Active on Social Media I use social media for sharing the content created by other people, sharing my own content, and having fun. The social media “gurus” state that this should help to brand myself as an expert, but I have to admit that I haven’t really paid any attention to this. In other words, I don’t have a social media strategy. At the moment I am using the following social media services:Github is kind of a no-brainer if you are a developer. At the moment I publish the example applications of my blog posts on Github and I use it to follow interesting projects created by other developers. Google+ is a bit of a mystery to me but I decided to try it out because having civilized discussions is so much easier when I can use more than 140 characters. Also, I really like Google+ communities because they provide me an easy way to find interesting content and have civilized discussions. I am also the owner of the Google+ community called Java Testing Society. LinkedIn is a place to be if you want to connect with other professionals. Although the recruitment spam has made LinkedIn a bit less interesting to me, I think that I can still benefit from sharing my blog posts on LinkedIn. Also, I haven’t used LinkedIn groups yet, and I am going to pay more attention to this in the future. Twitter is a great place to find and share interesting content. I use it mostly because it is fun and it doesn’t really take that much time. The downside of Twitter is that it is “impossible” to have civilized discussions because you cannot use more than 140 characters. Youtube is the place to be if you want to publish video tutorials (or watch them). I have published a few video tutorials but I have to admit that at the moment I want to concentrate on other things. However, I will record more video tutorials some day. I promise.so, how does this help me to stay relevant? I think that social media helps me to discover “hot” technologies and learn new things. Also, it helps me to grow my network and having a large network is useful if you looking for a job or a business partner. 5. I Work Out This is the last thing on my list but it isn’t the least important one. I have noticed that working out helps me to reduce stress and avoid physical problems caused by sitting at work. I go to the gym three times a week and do aerobic exercise twice a week (I don’t do any aerobic exercise when I am on holiday though). I know that this sounds a bit excessive but it works for me, and that is all that matters. By the way, there was a time when I hated physical exercise. At that time I was stressed out, I had very low energy levels and I had weird pain between my ribs. In other words, I was a wreck. Then I decided to start working out. It was one of the best decisions I have ever made. Now I am stress free, my energy levels have skyrocketed, and the pain is gone. I feel great and this helps me to concentrate on other things that will help me to stay relevant. Is This Good Enough? Who knows. I don’t know what happens in the future. However, I do know that doing something is a lot better than doing nothing. I admit that I am lucky because I don’t have to do these things. I can do these things because I enjoy it, and that is why I think that no matter what happens in the future, I can feel proud of myself.Reference: 5 Things I Do to Stay Relevant from our JCG partner Petri Kainulainen at the Petri Kainulainen blog....
software-development-2-logo

The next IT revolution: micro-servers and local cloud

Have you ever counted the number of Linux devices at home or work that haven’t been updated since they came out of the factory? Your cable/fibre/ADSL modem, your WiFi point, television sets, NAS storage, routers/bridges, media centres, etc. Typically this class of devices hosts a proprietary hardware platform, an embedded proprietary Linux and a proprietary application. If you are lucky you are able to log into a web GUI often using the admin/admin credentials and upload a new firmware blob. This firmware blob is frequently hard to locate on hardware supplier’s websites. No wonder the NSA and others love to look into potential firmware bugs. They are the ideal source of undetected wiretapping.   The next IT revolution: micro-servers The next IT revolution is about to happen however. Those proprietary hardware platforms will soon give room for commodity multi-core processors from ARM, Intel, etc. General purpose operating systems will replace legacy proprietary and embedded predecessors. Proprietary and static single purpose apps will be replaced by marketplaces and multiple apps running on one device. Security updates will be sent regularly. Devices and apps will be easy to manage remotely. The next revolution will be around managing millions of micro-servers and the apps on top of them. These micro-servers will behave like a mix of phone apps, Docker containers, and cloud servers. Managing them will be like managing a “local cloud” sometimes also called fog computing. Micro-servers and IoT? Are micro-servers some form of Internet of Things. Yes they can be but not all the time. If you have a smarthub that controls your home or office then it is pure IoT. However if you have a router, firewall, fibre modem, micro-antenna station, etc. then the micro-server will just be an improved version of its predecessor. Why should you care about micro-servers? If you are a mobile app developer then the micro-servers revolution will be your next battlefield. Local clouds need “Angry Bird”-like successes. If you are a telecom or network developer then the next-generation of micro-servers will give you unseen potentials to combine traffic shaping with parental control with QoS with security with … If you are a VC then micro-server solution providers is the type of startups you want to invest in. If you are a hardware vendor then this is the type of devices or SoCs you want to build. If you are a Big Data expert then imagine the new data tsunami these devices will generate. If you are a machine learning expert then you might want to look at algorithms and models that are easy to execute on constraint devices once they have been trained on potentially thousands of cloud servers and petabytes of data. If you are a Devop then your next challenge will be managing and operating millions of constraint servers. If you are a cloud innovator then you are likely to want to look into SaaS and PaaS management solutions for micro-servers. If you are a service provider then this is the type of solutions you want to have the capabilities to manage at scale and easily integrate with. If you are a security expert then you should start to think about micro-firewalls, anti-micro-viruses, etc. If you are a business manager then you should think about how new “mega micro-revenue” streams can be obtained or how disruptive “micro- innovations” can give you a competitive advantage. If you are an analyst or consultant then you can start predicting the next IT revolution and the billions the market will be worth in 2020. The next steps… It is still early days but expect some major announcements around micro-servers in the next months…Reference: The next IT revolution: micro-servers and local cloud from our JCG partner Maarten Ectors at the Telruptive blog....
java-logo

Named parameters in Java

Creating a method that has many parameters is a major sin. Whenever there is need to create such a method, sniff in the air: it is code smell. Harden your unit tests and then refactor. No excuse, no buts. Refactor! Use builder pattern or even better use Fluent API. For the latter the annotation processor fluflu may be of great help. Having all that said we may come to a point in our life when we face real life and not the idealistic pattern that we can follow in our hobby projects. There comes the legacy enterprise library monster that has the method of thousands parameters and you do not have the authority, time, courage or interest (bad for you) to modify … ops… refactor it. You could create a builder as a facade that hides the ugly API behind it if you had the time. Creating a builder is still code that you have to unit test even before you write (you know: TDD) and you just may not have the time. The code that calls the monstrous method is also there already, you just maintain it. You can still do some little trick. It may not be perfect, but still something. Assume that there is a method: public void monster(String contactName, String contactId, String street, String district, ... Long pT){ ... } The first thing is to select your local variables at the location of the caller wisely. Pity the names are already chosen and you may not want to change it. There can be some reason for that, for example there is an application wide naming convention followed that may make sense even if not your style. So the call: monster(nm, "05300" + dI, getStrt(), d, ... , z+g % 3L ); is not exactly what I was talking about. That is what you have and you can live with it, or just insert new variables into the code: String contactName = nm; String contactId = "05300" + dI; String street = getStrt(); Street district = d; ... Long pT = z+g % 3L; monster(contactName, contactId, street, district, ... ,pT ); or you can even write it in a way that is not usual in Java, though perfectly legal: String contactName, contactId, street, district; ... Long pT; monster(contactName = nm, contactId = "05300" + dI, street = getStrt(), district = d, ... ,pT = z+g % 3L ); Tasty is it? Depends. I would not argue on taste. If you do not like that, there is an alternative way. You can define auxiliary and very simple static methods: static <T> T contactName(T t){ return T;} static <T> T contactId(T t){ return T;} static <T> T street(T t){ return T;} static <T> T district(T t){ return T;} ... static <T> T pT(T t){ return T;}monster(contactName(nm), contactId("05300" + dI), street(getStrt()(, district(d), ... ,pT(z+g % 3L) ); The code is still ugly but a bit more readable at the place of the caller. You can even collect static methods into a utility class, or to an interface in case of Java 8 named like with, using, to and so on. You can statically import them to your code and have some method call as nice as: doSomething(using(someParameter), with(someOtherParameter), to(resultStore)); When all that is there you can feel honky dory if you answer the final question: what the blessed whatever* is parameter pT. (* “whatever” you can replace with some other words, whichever you like)Reference: Named parameters in Java from our JCG partner Peter Verhas at the Java Deep blog....
agile-logo

Managers Manage Ambiguity

I was thinking about the Glen Alleman’s post, All Things Project Are Probabilistic. In it, he says, Management is Predictionas a inference from Deming. When I read this quote, If you can’t describe what you are doing as a process, you don’t know what you’re doing. –Deming I infer from Deming that managers must manage ambiguity. Here’s where Glen and I agree. Well, I think we agree. I hope I am not putting words into Glen’s mouth. I am sure he will correct me if I am. Managers make decisions based on uncertain data. Some of that data is predictive data. For example, I suggest that people provide, where necessary, order-of-magnitude estimates of projects and programs. Sometimes you need those estimates. Sometimes you don’t. (Yes, I have worked on programs where we didn’t need to estimate. We needed to execute and show progress.) Now, here’s where I suspect Glen and I disagree:Asking people for detailed estimates at the beginning of a project and expecting those estimates to be true for the entire project. First, the estimates are guesses. Second, software is about learning, If you work in an agile way, you want to incorporate learning and change into the project or program. I have some posts about estimation in this blog queue where I discuss this. Using estimation for the project portfolio. I see no point in using estimates instead of value for the project portfolio, especially if you use agile approaches to your projects. If we finish features, we can end the project at any time. We can release it. This makes software different than any other type of project. Why not exploit that difference? Value makes much more sense. You can incorporate cost of delay into value. If you use your estimate as a target, you have some predictable outcomes unless you get lucky: you will shortchange the feature by decreasing scope, incur technical debt, or increase the defects. Or all three.What works for projects is honest status reporting, which traffic lights don’t provide. Demos provide that. Transparency about obstacles provides that. The ability to be honest about how to solve problems and work through issues provides that. Much has changed since I last worked on a DOD project. I’m delighted to see that Glen writes that many government projects are taking more agile approaches. However, if we always work on innovative, new work, we cannot predict with perfect estimation what it will take at the beginning, or even through the project. We can better our estimates as we proceed. We can have a process for our work. Regardless of our approach, as long as we don’t do code-and-fix, we do. (In Manage It! Your Guide to Modern, Pragmatic Project Management, I say to choose an approach based on your context, and to choose any lifecycle except for code-and-fix.) We can refine our estimates, if management needs them. The question is this: why does management need them? For predicting future cost for a customer? Okay, that’s reasonable. Maybe on large programs, you do an estimate every quarter for the next quarter, based on what you completed, as in released, and what’s on the roadmap. You already know what you have done. You know what your challenges were. You can do better estimates. I would even do an EQF for the entire project/program. Nobody has an open spigot of money. But, in my experience, the agile project or program will end before you expect it to. (See the comments on Capacity Planning and the Project Portfolio.) But, the project will only end early if you evaluate features based on value and if you collaborate with your customer. The customer will say, “I have enough now. I don’t need more.” It might occur before the last expected quarter. It might occur before the last expected half-year. That’s the real ambiguity that managers need to manage. Our estimates will not be correct. Technical leaders, project managers and product owners need to manage risks and value so the project stays on track. Managers need to ask the question: What if the project or program ends early? Ambiguity, anyone?Reference: Managers Manage Ambiguity from our JCG partner Johanna Rothman at the Managing Product Development blog....
software-development-2-logo

PL/SQL backtraces for debugging

For many PL/SQL developers, this might be common sense, but for one of our customers, this was an unknown PL/SQL feature: Backtraces. When your application raises an error somewhere deep down in the call stack, you don’t get immediate information about the exact source of the error. For large PL/SQL applications, this can be a pain. One workaround is to keep track of statement numbers that were last executed before any error occurred:         DECLARE v_statement_no := 0; BEGIN v_statement_no := 1; SELECT ...v_statement_no := 2; INSERT ...v_statement_no := 3; ... EXCEPTION WHEN OTHERS THEN -- Log error message somewhere logger.error(module, v_statement_no, sqlerrm); END; The above looks an awful lot like println-debugging, a thing that isn’t really known to Java developers! But println-debugging isn’t necessary in PL/SQL either. Use the DBMS_UTILITY.FORMAT_ERROR_BACKTRACE function, instead! An example: DECLARE PROCEDURE p4 IS BEGIN raise_application_error(-20000, 'Some Error'); END p4; PROCEDURE p3 IS BEGIN p4; END p3; PROCEDURE p2 IS BEGIN p3; END p2; PROCEDURE p1 IS BEGIN p2; END p1;BEGIN p1; EXCEPTION WHEN OTHERS THEN dbms_output.put_line(sqlerrm); dbms_output.put_line( dbms_utility.format_error_backtrace ); END; / The above PL/SQL block generates the following output: ORA-20000: Some Error ORA-06512: at line 3 ORA-06512: at line 6 ORA-06512: at line 9 ORA-06512: at line 12 ORA-06512: at line 16 You can see exactly what line number generated the error. If you’re not using local procedures in anonymous blocks (which you quite likely aren’t), this gets even more useful: CREATE PROCEDURE p4 IS BEGIN raise_application_error(-20000, 'Some Error'); END p4; / CREATE PROCEDURE p3 IS BEGIN p4; END p3; / CREATE PROCEDURE p2 IS BEGIN p3; END p2; / CREATE PROCEDURE p1 IS BEGIN p2; END p1; /BEGIN p1; EXCEPTION WHEN OTHERS THEN dbms_output.put_line(sqlerrm); dbms_output.put_line( dbms_utility.format_error_backtrace ); END; / The above now outputs: ORA-20000: Some Error ORA-06512: at "PLAYGROUND.P4", line 2 ORA-06512: at "PLAYGROUND.P3", line 2 ORA-06512: at "PLAYGROUND.P2", line 2 ORA-06512: at "PLAYGROUND.P1", line 2 ORA-06512: at line 2 To learn more about the DBMS_UTILITY package, please consider the manual. True to the nature of all things called “UTILITY”, it really contains pretty much random things that you wouldn’t expect there!Reference: PL/SQL backtraces for debugging from our JCG partner Lukas Eder at the JAVA, SQL, AND JOOQ blog....
agile-logo

Metrics: Good VS Evil

Pop quiz: What do earned value, burn-down charts, and coverage reports have in common? They are all reporting a metric, sure. But you could have gotten that from the title. Let’s dig deeper. Let’s start with earned value. Earned value is a project tracking system, where you get value points as you’re getting along the project. That means, if you’re 40% done with the task, you get, let’s say, 40 points. This is pre-agile thinking, assuming that we know everything about the task, and nothing can’t change on the way, and therefore those 40 points mean something. We know that we can have a project 90% done, running for 3 years without a single demo to the customer. From experience, the feedback will change everything. But if we believe the metrics, we’re on track. Burn-down charts measure how many story points we’ve got left in our sprint. It can forecast if we’re on track or how many story points we’ll complete. In fact, it assumes that all stories are pretty much the same size. First, the forecast may not tell the true story, if for example the big story doesn’t get completed. And somehow the conclusion is that we need to improve the estimation, rather than cut the story to smaller pieces. Test coverage is another misleading metric. You can have a 100% covered non-working code. You can show increment in coverage on important, risky code, and you can also show drop in safe code. Or you can do the other way around, and get the same numbers, with the misplaced confidence. These metrics, and others like them have a few things in common.They are easy to measure and track They already worked for someone else They are simple enough to understand and misinterpret Once we start to measure them we forget the “what if” scenarios, and return to their “one true meaning”In our ever going search for simplicity, metrics help us minimize a whole uncertain world into a number. We like that. Not only we don’t need to tire our mind with different scenarios, numbers always come with the “engineering” halo. And we can trust those engineers, right? I recently heard that we seem to forget that the I in KPI is indicator. Meaning, it points in some direction, but can also take us off course, if we don’t look around, and understand the environment. Metrics are over-simplification. We should use them like that. They may have a halo, but they can also be pretty devilish.Reference: Metrics: Good VS Evil from our JCG partner Gil Zilberfeld at the Geek Out of Water blog....
java-logo

Java Numeric Formatting

I can think of numerous times when I have seen others write unnecessary Java code and I have written unnecessary Java code because of lack of awareness of a JDK class that already provides the desired functionality. One example of this is the writing of time-related constants using hard-coded values such as 60, 24, 1440, and 86400 when TimeUnit provides a better, standardized approach. In this post, I look at another example of a class that provides the functionality I have seen developers often implement on their one: NumberFormat. The NumberFormat class is part of the java.text package, which also includes the frequently used DateFormat and SimpleDateFormat classes. NumberFormat is an abstract class (no public constructor) and instances of its descendants are obtained via overloaded static methods with names such as getInstance(), getCurrencyInstance(), and getPercentInstance(). Currency The next code listing demonstrates calling NumberFormat.getCurrencyInstance(Locale) to get an instance of NumberFormat that presents numbers in a currency-friendly format. Demonstrating NumberFormat’s Currency Support /** * Demonstrate use of a Currency Instance of NumberFormat. */ public void demonstrateCurrency() { writeHeaderToStandardOutput("Currency NumberFormat Examples"); final NumberFormat currencyFormat = NumberFormat.getCurrencyInstance(Locale.US); out.println("15.5 -> " + currencyFormat.format(15.5)); out.println("15.54 -> " + currencyFormat.format(15.54)); out.println("15.345 -> " + currencyFormat.format(15.345)); // rounds to two decimal places printCurrencyDetails(currencyFormat.getCurrency()); }/** * Print out details of provided instance of Currency. * * @param currency Instance of Currency from which details * will be written to standard output. */ public void printCurrencyDetails(final Currency currency) { out.println("Concurrency: " + currency); out.println("\tISO 4217 Currency Code: " + currency.getCurrencyCode()); out.println("\tISO 4217 Numeric Code: " + currency.getNumericCode()); out.println("\tCurrency Display Name: " + currency.getDisplayName(Locale.US)); out.println("\tCurrency Symbol: " + currency.getSymbol(Locale.US)); out.println("\tCurrency Default Fraction Digits: " + currency.getDefaultFractionDigits()); } When the above code is executed, the results are as shown next: ================================================================================== = Currency NumberFormat Examples ================================================================================== 15.5 -> $15.50 15.54 -> $15.54 15.345 -> $15.35 Concurrency: USD ISO 4217 Currency Code: USD ISO 4217 Numeric Code: 840 Currency Display Name: US Dollar Currency Symbol: $ Currency Default Fraction Digits: 2 The above code and associated output demonstrate that the NumberFormat instance used for currency (actually a DecimalFormat), automatically applies the appropriate number of digits and appropriate currency symbol based on the locale. Percentages The next code listings and associated output demonstrate use of NumberFormat to present numbers in percentage-friendly format. Demonstrating NumberFormat’s Percent Format /** * Demonstrate use of a Percent Instance of NumberFormat. */ public void demonstratePercentage() { writeHeaderToStandardOutput("Percentage NumberFormat Examples"); final NumberFormat percentageFormat = NumberFormat.getPercentInstance(Locale.US); out.println("Instance of: " + percentageFormat.getClass().getCanonicalName()); out.println("1 -> " + percentageFormat.format(1)); // will be 0 because truncated to Integer by Integer division out.println("75/100 -> " + percentageFormat.format(75/100)); out.println(".75 -> " + percentageFormat.format(.75)); out.println("75.0/100 -> " + percentageFormat.format(75.0/100)); // will be 0 because truncated to Integer by Integer division out.println("83/93 -> " + percentageFormat.format((83/93))); out.println("93/83 -> " + percentageFormat.format(93/83)); out.println(".5 -> " + percentageFormat.format(.5)); out.println(".912 -> " + percentageFormat.format(.912)); out.println("---- Setting Minimum Fraction Digits to 1:"); percentageFormat.setMinimumFractionDigits(1); out.println("1 -> " + percentageFormat.format(1)); out.println(".75 -> " + percentageFormat.format(.75)); out.println("75.0/100 -> " + percentageFormat.format(75.0/100)); out.println(".912 -> " + percentageFormat.format(.912)); } ================================================================================== = Percentage NumberFormat Examples ================================================================================== 1 -> 100% 75/100 -> 0% .75 -> 75% 75.0/100 -> 75% 83/93 -> 0% 93/83 -> 100% .5 -> 50% .912 -> 91% ---- Setting Minimum Fraction Digits to 1: 1 -> 100.0% .75 -> 75.0% 75.0/100 -> 75.0% .912 -> 91.2% The code and output of the percent NumberFormat usage demonstrate that by default the instance of NumberFormat (actually a DecimalFormat in this case) returned by NumberFormat.getPercentInstance(Locale) method has no fractional digits, multiplies the provided number by 100 (assumes that it is the decimal equivalent of a percentage when provided), and adds a percentage sign (%). Integers The small amount of code shown next and its associated output demonstrate use of NumberFormat to present numbers in integral format. Demonstrating NumberFormat’s Integer Format /** * Demonstrate use of an Integer Instance of NumberFormat. */ public void demonstrateInteger() { writeHeaderToStandardOutput("Integer NumberFormat Examples"); final NumberFormat integerFormat = NumberFormat.getIntegerInstance(Locale.US); out.println("7.65 -> " + integerFormat.format(7.65)); out.println("7.5 -> " + integerFormat.format(7.5)); out.println("7.49 -> " + integerFormat.format(7.49)); out.println("-23.23 -> " + integerFormat.format(-23.23)); } ================================================================================== = Integer NumberFormat Examples ================================================================================== 7.65 -> 8 7.5 -> 8 7.49 -> 7 -23.23 -> -23 As demonstrated in the above code and associated output, the NumberFormat method getIntegerInstance(Locale) returns an instance that presents provided numerals as integers. Fixed Digits The next code listing and associated output demonstrate using NumberFormat to print fixed-point representation of floating-point numbers. In other words, this use of NumberFormat allows one to represent a number with an exactly prescribed number of digits to the left of the decimal point (“integer” digits) and to the right of the decimal point (“fraction” digits). Demonstrating NumberFormat for Fixed-Point Numbers /** * Demonstrate generic NumberFormat instance with rounding mode, * maximum fraction digits, and minimum integer digits specified. */ public void demonstrateNumberFormat() { writeHeaderToStandardOutput("NumberFormat Fixed-Point Examples"); final NumberFormat numberFormat = NumberFormat.getNumberInstance(); numberFormat.setRoundingMode(RoundingMode.HALF_UP); numberFormat.setMaximumFractionDigits(2); numberFormat.setMinimumIntegerDigits(1); out.println(numberFormat.format(234.234567)); out.println(numberFormat.format(1)); out.println(numberFormat.format(.234567)); out.println(numberFormat.format(.349)); out.println(numberFormat.format(.3499)); out.println(numberFormat.format(0.9999)); } ================================================================================== = NumberFormat Fixed-Point Examples ================================================================================== 234.23 1 0.23 0.34 0.35 1 The above code and associated output demonstrate the fine-grain control of the minimum number of “integer” digits to represent to the left of the decimal place (at least one, so zero shows up when applicable) and the maximum number of “fraction” digits to the right of the decimal point. Although not shown, the maximum number of integer digits and minimum number of fraction digits can also be specified. Conclusion I have used this post to look at how NumberFormat can be used to present numbers in different ways (currency, percentage, integer, fixed number of decimal points, etc.) and often means no or reduced code need be written to massage numbers into these formats. When I first began writing this post, I envisioned including examples and discussion on the direct descendants of NumberFormat (DecimalFormat and ChoiceFormat), but have decided this post is already sufficiently lengthy. I may write about these descendants of NumberFormat in future blog posts.Reference: Java Numeric Formatting from our JCG partner Dustin Marx at the Inspired by Actual Events blog....
Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
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