Kamis, 31 Juli 2014

When to make a method static in Java




Making a method static in Java is an important decision . Though, static
keyword
is one of the fundamental concepts, many times programmers gets
confused to make a particular method static or not. In Java programming, main
motivation for making a method static is convenience.
You can call a static method without creating any object, just by using it's
class name. So if you need a method, which you want to call directly by class
name, make that method static. Utility classes e.g.
java.lang.Math or StringUtils, are good
examples of classes, which uses static methods. Before making a method static,
you should look into limitation of static methods as well, as you
can not override static method in Java
. By keeping these properties in
mind, we can make few rules, which will help to decide when to make a method static in Java and when to use them. In this
Java article, we will learn more about benefits and limitation of making a method
static, and also see couple of examples of static methods from JDK to learn
when and how to use static method in Java.







What does static method do in Java



When you see a static method in Java code, What do you assume? What
reasoning and assumptions a reader make, when he sees a static method? This is
important to learn to  ensure we are
using static method correctly.





1) Static method doesn't modify state of object. Since state of object is
maintained as instance variables, and Java doesn't allow non static variables
on static context
.
Modern days IDE like Netbeans also shows static
method in italics to differentiate it from other methods.





2) Static method mostly operates on arguments, almost all static method
accepts arguments, perform some calculation and return value.











Rules
to make a method static in Java




There is no hard and fast, well written rules, to decide when to make a
method static or not, But there are few observations based upon experience,
which not only help to make a method static but also teaches when to use static
method in Java. You should consider making a method static in Java :





1) If a method doesn't modify state of object, or not using any instance variables.




2) You want to call method without creating instance of that class.




3) A method is good candidate of being static, if it only work on
arguments provided to it e.g.
public int factorial(int number){}, this
method only operate on number provided as argument.





4) Utility methods are also good candidate of being static e.g. StringUtils.isEmpty(String
text)
, this a utility method to check if a String is empty or not.





5) If function of method will remain static across class hierarchy e.g. equals() method is not a good
candidate of making static because every Class can redefine equality.









When to use static method in Java



How to use static method in JavaNow, we know the benefits and limitation of making a method static in
Java, we can see couple of scenarios where we can use static methods. Factory
design pattern provides a good use of static method. You can use static method
to create instance of a class. Even Effective Java advises about
using static factory method, couple of example of these in Java library is
creating thread pool from Executors class.
Executors provides
lots of static methods to create different types of thread pool e.g.
public
static ExecutorService newCachedThreadPool()
, public static
ExecutorService newFixedThreadPool(int nThreads)
etc. Another interesting
use of static methods from JDK is collection classes e.g.
Collections and Arrays which
provides lot of static utility methods to operate on different kinds of
collection. Static method can also be combined with variable arguments to
create a collection of explicitly elements e.g.
EnumSet.of(E first,
E... rest)
.
Apart from these, if you loot at Apache commons lang library, you will
find a pattern of utils class e.g.
StringUtils, ArrayUtils, which
provides utility methods to operate on
String and
arrays. One more interesting use of static method I have seen is
valueOf() method
inside different value classes e.g.
java.lang.String, though
this is also an example of factory method, but it's also
a nice way to convert one type to another. For example
valueOf() can also
be used to convert String to Integer in Java. In short, it make sense to use
static methods :





1) Along with creational design pattern e.g. Factory and Singleton.




2) As utility method, which operate on arguments.




3) A conversion tool e.g. valueOf().





That's all about when to make a method static in Java. We have seen
benefits and limitation of making a method static, and few examples of static
methods from JDK. JDK examples will also help you to decide when to use static
method in Java.








Mentioned books in this article


Effective Java 2nd Edition from Joshua Bloch



























Source:http://javarevisited.blogspot.com/2013/07/when-to-make-method-static-in-java.html

ZEEF: the official Beta release!




Source:http://balusc.blogspot.com/2013/07/zeef-official-beta-release.html

Best practices for Maximo projects

Today I have received the following questions from one of our customers.
  • Are there any best practices or recommendations on how to develop and maintain different versions of a Maximo based solution?
  • How can we do source control?
  • Are there any compare tool/utility to find differences in various version of application (available in different environments)?
Expanding a little, in this article I will present my own recipes to cook successful Maximo projects.


Development Methodology

I am a strong fan of Agile philosophy and less enthusiastic adopter of Agile software development methodologies like Scrum, XP or Crystal.
I really believe that the right way to seek success and perfection in software development project is to strive to align your processes, organization and culture to the four value statements of the Agile manifesto whatever methodology you are using.

Individuals and interactions over processes and tools
Working software over comprehensive documentation
Customer collaboration over contract negotiation
Responding to change over following a plan

There is no silver bullet here. Every project is different. Every customer is different. You have to experiment and improve keeping in mind those principles.
My own motto is: Start Small, Grow Fast. I always use this as a very simple guiding principle.





Workspace structure

I suggest to keep all the files and documents in a single place. There is no need to create boundaries between development, test or project management people. Everybody is on the same ship and a great collaboration is fundamental for an efficient and productive team. If possible, give access to the customer to entire set of files and documents. Foster mutual trust and establish a partnership.
This is a common set of directories in a project folder.
  • Mbo: Home of an Eclipse project for Mbo Java code (aka businessobjects).
  • Web: Home of an Eclipse project for UI Java code (aka maximouiweb).
  • Applications: Applications definitions exported in XML files. Any time a change is made, the app definition must be exported and stored here.
  • Scripts: TPAE 7.5 scripts.
  • Database: Custom database triggers and SQL scripts.
  • Docs: Requirements, plans and procedures as well as architectural and design documents. All the team members should use this folder to collaborate for a lean workgroup.
I know that some of these files are stored in a safe place in the Maximo database. However, I think it is better to keep together all the custom code in a common repository where you can also search for previous versions of a specific file.


Collaboration, Backup, Versioning

The workspace described above must be shared across all the team members including specialists, architects, developers, project managers and stakeholders.
Avoid using email to exchange documents. This could quickly become a nightmare. Break old habits. Share a list of tasks on Google Docs and ask everyone to keep it updated. Create a design document and edit it in real time during a review session. Many times we don't need strict rules and processes.

Regarding the technology for storage and versioning of the workspace it really depends on the size of the team. As a general rule:
  • 1-3 members: A shared folder with a weekly backup is enough. Cloud services like Google Drive, SkyDrive, DropBox, etc. are great and free. Google platform enable a powerful collaboration platform with chat, email, real time document collaboration and sharing.
  • 4-6 members : Here you will need some versioning system like CVS, SVN or Git. You may decide to setup your own server or to go cloud.
  • 7 or more: You need some requirement/bug management system. Those systems are typically called ALM (Application Lifecycle Management). IBM Rational Team Concert is a great and powerful tool but can be a little complex to administer. There are tons of ALM services on the cloud


Tools

First of all, share a common set of productivity tools. Look at Maximo specialist Swiss Army Knife for my selection of tools.
If you have to develop Java customization you have to set some coding standards.
In real world scenarios you will always face some challenges to keep in sync development, test and production environments. Unfortunately, there is no tool to compare two different Maximo environments. That's why I have develop my own method.
An effective technique is to periodically clone the production environment to the test and development environments with a procedure like this.
On the other side it is important to use Migration Manager to move packages to be released from dev to test to production.


Source:http://maximodev.blogspot.com/2013/07/best-practices-for-maximo-projects.html

Top 5 JQuery books for Beginners and Web developers - Best of lot




jQuery is a open source JavaScript library, which has completely changed
the way, client side web development was done using HTML, CSS and JavaScript.
With growing popularity of jQuery, it become imperative for web developers to
learn and take advantage of jQuery and books are one of the best way to learn
jQuery. In this article, I am going to share you top 5 jQuery books from my
personal collection, which I have looked and researched before purchasing my
first book on jQuery, Head First JQuery. Since I like to follow one book at a time, I didn't bother to look
into another must read book, JQuery in Action, until I have finished former.
After finishing my first book on jQuery, I am quite comfortable with jQuery
magic, which means doing things like DOM Selection, traversal, DOM manipulation
based on CSS selector, animation and cool effects, and responding to use
actions (event handling) in couple of lines. In short jQuery is powerful, yet easy
to understand, very succinct and a must have skill for web programmers and web
developers in there resume. I personally believe that you at least to read
couple of jQuery books to not only gain confidence, but also to be familiar
with subtle details of jQuery library itself. Though nothing beats
documentation, as they are the one, which is most up-to-date, but following a
book with simple examples is totally different learning experience, especially
if you are beginners and not an expert of HTML, CSS and JavaScript.







5 Must read jQuery Books to learn jQuery




Head
First jQuery




Best jQuery book for web developersI am big fan of Head first series, having already read couple of there
best titles like Head first design pattern, I didn't take me long to purchase
my first jQuery book, Head First jQuery and as always I am pretty satisfied. There are lot of good things
about this book, but one thing which differentiate this jQuery book with others
is quality of exercise. Head first examples are more like real life projects
than a trivial example from no where, you feel doing real work, while following
this jQuery book. Apart from that, they also provides code including HTML and
CSS and promotes best practices around structuring your HTML documents and
Cascading style sheets. Another worth mentioning thing about this jQuery book
is focusing on most important details and bringing them forward, if you are in
hurry, then this is the book to follow. You will also find lots of puzzles,
interesting questions, fireside talk (simply fantastic for comparative
learning) and usual head first ways to teach concepts. In short a must read
jQuery book for any beginner, which is familiar with HTML, CSS and bit of
JavaScript. If you are completely new in web development and not very confident
with HTML, CSS or JavaScript then you can also take a look Head First HTML and CSS and Head First JavaScript,
completely worth of money. I think you might also get a discounted offer, if
you buy more than one books on Amazon.





jQuery in
Action - Manning


Good jQuery books for beginnersSimilar to head first series, another series which I like is Manning
"Action" series, they have published several best selling titles
under this series and "jQuery in Action, Second Edition" is one of them. I read this book because of
there authors Bear Bibeault and Yehuda Katz, which are real jQuery and
JavaScript experts and knows subtle details of both. Yehuda Katz has been
contributing to jQuery and heading up there plug-in development team, while
Bear Bibeault is very senior in the area of web application development and already
co-author books like Ajax in Practice. This jQuery book is really good for both beginners and developer
with some experience, it's well structured with lots of useful examples, which
are easy to follow. One of thing, which I personally like is there explanation
of jQuery Event handling and how that works internally using JavaScript. They
have also done a good job on explaining, how jQuery can be used to Crete web
pages, which can handle cross browser compatibility issues. In short, one of
the best jQuery book in the market.










Learning
jQuery Fourth Edition



Must read jQuery book for Web Programmers

"Learning jQuery 1.3 : Better Interaction Design and Web Development with Simple JavaScript Techniques" By Karl Swedberg and Jonathan Chaffer is
another good jQuery books for beginners. This book teach jQuery in really nice
ways, building on your previous experience and knowledge, there contextual
examples and explanation, makes it easy to learn and comprehend jQuery
functions. Though this book assumes, you should have a fair knowledge of HTML
and CSS, and comfortable with the syntax of JavaScript, no knowledge of jQuery
is assumed, which is what works in beginners 
favours. I wouldn't say a must
read jQuery book, if you have already read previous two books, but if you
connect with this book, after reading sample chapters, than it's worth buying. Currently latest edition of this books is fourth edition, which brings few more changes from recent jQuery releases. If you have not yet purchased this book then its better to go for fourth edition rather than third or second edition, of-course until you are not getting them FREE or dirt cheap price.







jQuery
Cookbook


best jQuery book for developersjQuery Cookbook: Solutions & Examples for jQuery Developers by Cody Lindley is
an ideal book for both jQuery beginners and JavaScript experts alike. It's a
cookbook, which starts with fundamentals and then explores more practical uses
cases with tested solution and using best practices to overcome common web
development issues. Like Head First and "Action" series, Cookbook
series from O'Reilly is also a popular series and can be a valuable addition to
any web developer's bookshelf. Since jQuery cookbook is written to accommodate
common problems and there tried and tested solution, three is good chance that
you will find solution of your practical problems there. In short, if you like
cookbooks and enjoy reading them, than this is one of the best jQuery book for
you. It's also a very good book for busy developers, who like to try out examples rather than reading theories. By following simple examples and how to do in jQuery sort of code snippet, you will automatically learn what is needed to implement them. In short, if you are a busy developer, go for this jQuery book.





jQuery:
Novice to Ninja



advanced jQuery book

jQuery:Novice to Ninja By Earle Castledine and Craig Sharkie is a comprehensive
jQuery book of 480 pages. First Edition of this book was hugely popular and now
Second Edition is also available. I haven't read this book completely, but
whatever I read, I found them really interesting. This books mixes JavaScript
best practices and explains subtle details with ease. This also presents lots
of advanced stuff including jQuery plug-ins, which is good, once you are
familiar with basics. Overall, I suggest reading couple of sample chapters and
if you connect with this book, than consider buying it. By the way don't god
with title, from novice to Ninja, don't expect to become master of jQuery by
just reading this book :), you need to lot of jQuery coding, before coming
close to efficiently use them.














That's all on this list of best
jQuery books for beginners and intermediate web developers
. Since jQuery is
very popular in modern day web development, there are many books and material
available. One thing, which you start using, once you have basic knowledge of
jQuery is there API documentation. They
also have working examples and demo, which can be handy along with following
any of these jQuery books. Senior web programmers and jQuery developers, let us
know if you come across a good book on jQuery, which is not included in this
list.



























Source:http://javarevisited.blogspot.com/2013/07/top-5-jquery-books-for-web-developers-learn.html

Rabu, 30 Juli 2014

Commodity Codes in Maximo

Commodity codes are standard classification codes for products and services used to detail where money is spent within a company.

In Maximo commodity codes are used to define similar types of items, tools, or services. Commodity codes are also grouped together in commodity groups. A commodity group contains a grouping of individual commodity codes.
Commodity groups and codes can be created and managed selecting the Add/Modify Commodity Codes action in the one of following applications: Companies, Item Master, Purchase Orders, Service Items, Tools. This IBM TechNote describes how to manually enter commodity codes.

Once you have defined commodities you can associate them with company, contract, and item records. You can also associate commodities with individual purchase order or requisition lines for items, service items, or tools that do not have commodity codes assigned to them, including special order materials or services.


Classifying items, tools, services with commodity groups and commodity codes provides a way to analyze and optimize spending by product type. To support such spending review process, Maximo provides the Commodity Analysis report in the Item Master application.


The Commodity Analysis report shows a summary list of items received during a given time period grouped by commodity groups and vendors. The first part of the report shows the received cost by commodity groups presented as a bar chart.



The second part of the report shows data in a table format. For each commodity group, the cost summary for each vendor is computed and shown as subtotal.


This report is useful in identifying what commodities made up the bulk of purchase costs and thus, are critical for cost controls. For large organizations it can be used to compare price points from different vendors in order to restructure and optimize expenditures across sites and divisions.


There are several standards for commodities classifications like UNSPSC, HS, NIGP. Many clients define their own classifications codes and groups in Maximo.
The UNSPSC (United Nations Standard Products and Services Code) standard is well known and is translated into many languages. Codes can be downloaded for free in PDF format or purchased in Excel format. Is it also possible to search and browse codes with a simple search engine.

It may be also interesting to hear something from you.
What is your preferred commodity codes structure in Maximo?
Do you use standard codes or have you defined you own structure?


Source:http://maximodev.blogspot.com/2013/07/commodity-codes-in-maximo.html

At&T Is Preparing to Follow Other Companies and Sell Your Data

From Fierce Wireless:
AT&T (NYSE:T) said it "may" begin selling anonymous information about its customers' wireless and Wi-Fi locations, U-verse usage, website browsing, mobile application usage and "other information" to other businesses. The carrier said it will protect its customers' privacy by providing the data in aggregate so it cannot be used to identify an individual. The carrier also said its customers can opt out of the program.

AT&T is not the first company to sell anonymous information about its customers' location and behavior. Facebook (NASDAQ:FB), Google (NASDAQ:GOOG) and most other Internet companies have long sold such data. In the wireless industry, Verizon Wireless (NYSE:VZ) launched its Precision Market Insights business last year, which also anonymizes and sells customer location and usage information. Further, companies such as AirSage and SAP have recently begun selling aggregated location and usage information from wireless carriers.

Source:http://blog.agupieware.com/2013/07/at-is-preparing-to-follow-other.html

How to import Failure Codes from Excel into Maximo

This article is outdated! Checkout MxLoader tool.

This entry is part of the Maximo Integration Framework series.

Creating and maintaining the hierarchy of failure codes can be quite complex using the standard Failure Codes application. Unfortunately there is no common solution to import Maximo failure codes. This evening I have worked on creating an Excel spreadsheet that can help in such cases.

This is an experimental tool. Use with care on development environments.
Leave a comment on this page both if you have problem (I'll try to fix them) and if you are able to use it successfully in your environment.


Data Model

Before going on, we need to understand how Maximo stores failure codes and their hierarchy of problems, causes and remedies.
The FAILURELIST table stores the hierarchy of problems, causes and remedies. The PARENT field holds the parent-child relationship while the FAILURECODE field points to another table called FAILURECODE that stores the descriptions of the failure codes in the various languages.
It is important to understand that a specific failure code can be attached to several places of the failure list hierarchy. This makes quite complex to manage this structure.


Export Failure List

A simple way of exporting failure codes and list is through SQL queries.

 
select orgid, failurecode, description, langcode from failurecode;


select f.orgid, f.failurelist classid, f.failurecode class, p.failurelist problemid, p.failurecode problem, c.failurelist causeid, c.failurecode cause, r.failurelist remedyid, r.failurecode remedy
from failurelist f
left outer join failurelist p on p.parent=f.failurelist and p.type='PROBLEM'
left outer join failurelist c on c.parent=p.failurelist and c.type='CAUSE'
left outer join failurelist r on r.parent=c.failurelist and r.type='REMEDY'
where f.parent is null
order by f.failurecode, p.failurecode, c.failurecode, r.failurecode;


Import

Create the following Object Structures.
    Object Structure: FLL-FAILURECODE
    • Consumed By: Integration
    • Object: FAILURECODE
      Object Structure: FLL-FAILURELIST
      • Consumed By: Integration
      • Object: FAILURELIST

      Now download the FailureCodesLoader Excel spreadsheet and open it. Go on the Config sheet and set the correct hostname of your Maximo server. Clicking of the link the browser will open and should display the following message: Servlet is running. Please use HTTP POST to post data.
      Now you are ready.

      The Failure Codes and Failure List sheets allow to upload data into the two tables described before.
      The Failure Codes sheet is straightforward to use. Just fill the worksheet with your failure codes descriptions and click on the little arrow on the toolbar.


      This will execute a VBA macro that will call the FLL-FAILURECODE Object Service through an HTTP POST request.

      The Failure List sheets represents the the failure codes hierarchy in a flat table with the same structure as exported by the above SQL query.
      The Excel macro will handle the necessary logic to manage the failure list hierarchy. Once the objects are created and the hierarchy is populated, the macro will fill the 'ID' columns with the correct values. Once the ID values (greyed cells) are filled, the failure node is created in the hierarchy and shouldn't be changed.

      At first it may seem a little tricky at the beginning, but after having played a little bit with the tool, it will be easy to create a complete failure list hierarchy of 1000 codes and more.


      Source:http://maximodev.blogspot.com/2013/07/how-to-import-failure-list-from-excel.html

      How SSL, HTTPS and Certificates works in Java web applications






      Basic knowledge of SSL, HTTPS and Certificates are must for any Java
      programmer, especially who is working in financial and security sensitive applications,
      which are accessed over internet. In this article, I am giving you an overview
      of these three key concept and How SSL,
      HTTPS and certificates work together
      , to provide secure communication
      between client and server. Security is major concern while developing web
      application, which is accessible using HTTP protocol. Since HTTP protocol
      transfer data in plain text format, its not safe for transferring sensitive
      information like username, password, social security number (SSN) or credit
      card details for online shopping. HTTP protocol, also doesn't guarantee that a website,
      you are communicating is the one who claims i.e. if URL redirection is enable
      than instead of genuine website you may be routed to malicious websites and HTTP
      can't prevent or alert you.






      How SSL and HTTPS works





      HTTPS and SSL address these two issue. HTTPS is HTTP over SSL and SSL
      stands for secure socket layer,  which
      provides both encryption and verification of websites. That's why almost all
      banks or commercial portals like travels or airline bookings, movie booking or
      online shopping portal uses https protocol. When data is transmitted using HTTPS
      protocol, they are encrypted before transmission from both client and server
      end, so anyone who can intercept or trap https traffic can see the data, but
      not in meaningful format. By the way since request is encrypted and decrypted
      at both ends, this does increase response time on server but provides security
      against eavesdropping threat. SSL also facilitate verification of website by using
      certificates issued by third party issuer like VeriSign, godaddy, thwate etc.
      You might have looked at your browser’s address bar, when you access any site using
      https it say something verified by VeriSign or verified by thwate etc. You can
      also read SSL and TLS: Designing and Building Secure Systems by Eric Rescorla to understand How SSL works and how to build secure system using SSL.  





      How SSL uses Certification for
      Identification



      How this certification works?  when
      client (browser) connect to Server using https, Server returns certificates issued
      by trusted third party issuer, if it’s Java application, it can access certs
      stored in its keystore and truststore, browser
      also has those certificate in his trusted certificate store and validates any
      certificate presented by server against those. If browser or any Java client,
      doesn't find the those certificates, it can alert you by saying certificates
      not recognized and recommend you not to visited the site. You can also manually
      trust any website and ask browser to include certificate presented by server in
      its trusted certificate store. This is the case with development when Tomcat
      returns either self-signed or test certificates. For Java programmers,  JDK comes with a keytool command, which can be
      used to create self signed certs and store those in keystore and truststore for
      use.





      That’s all on this rather quick overview of SSL, HTTPS and Certifications
      and How they work together. Purpose of this article was to give at least basic
      knowledge of how client server communication occurs in secure fashion. If you
      are developing secure applications in Java programming language, it’s good to
      have some knowledge of underlying fundamental concepts of SSL, HTTPS and Certificates.



























      Source:http://javarevisited.blogspot.com/2013/07/how-ssl-https-and-certificates-works-in-java-web-application.html

      Selasa, 29 Juli 2014

      Tech and Civil Rights Groups to Protest Dragnet Government Surveillance on Fourth of July

      Tomorrow, the Fourth of July, a new campaign is being launched to restore the Fourth Amendment to the Constitution of the United States, and reign in the rampant abuses against illegal search and seizure that have become all too routine in the United States.  Find a protest site in your area here.  PC World reports on the campaign:

      A large coalition of civil rights and privacy groups and potentially thousands of websites will stage protests on the Fourth of July to protest surveillance programs at the U.S. National Security Agency.

      As part of the Restore the Fourth campaign, many website members of the 30,000-member Internet Defense League plan to display a protest of NSA surveillance and the text of the Fourth Amendment to the U.S. Constitution.

      Websites participating include Reddit, where Restore the Fourth originated, WordPress, 4chan, Mozilla, Fark, and Cheezburger.com.  Organizers of Restore the Fourth are also planning live protests in dozens of U.S. cities, including New York, Philadelphia, Los Angeles, Boston, Washington, D.C., San Francisco, Houston and Atlanta.

      Source:http://blog.agupieware.com/2013/07/tech-and-civil-rights-groups-to-protest.html

      Role based Access control using Spring Security and MVC, Mapping LDAP Groups to Authorities for Authorization



      Authentication and Authorization is integral part of any Java enterprise
      or web application. Since most of the company uses LDAP Active directory for authentication, authorization and Role based access control (RBAC), it's good
      to know How to implement Role based
      access control using Spring MVC and Spring Security
      . This is the second
      part of my articles on using Spring Security for authentication and
      authorization in Spring MVC based Java application. In last part, we have
      learned about doing LDAP authentication against Windows
      active directory
      , a
      nd in this Spring
      Security tutorial
      , we will learn How to map LDAP groups to authorities for
      implementing Role based access control or authorization. If you are developing
      an application, whose access is controled by adding user to a particular LDAP
      group, then you need a mechanism to load those LDAP group after successful
      authentication. Spring Secuirty uses
      GrantedAuthority class for
      holding all roles for a particular user. Based upon these roles, a particular
      user can perform certain functionality in your application. For example, a read
      only user can only see data, but a user with ADMIN role, can add or remove data
      from your application. After implementing Role based access control, you are free
      of user management task, those will be taken care by respective team which
      manages LDAP groups and access, usually Windows support teams. In this
      article, we will all the steps required to map LDAP groups to granted authorities in Spring Security. If you love to read books, than you may want to
      check Spring Security 3.1 By Robert Winch,Peter Mularien, a great book, which teaches all good features of
      Spring security including LDAP authentication and authorization in great
      details. If you are developing secure enterprise application in Java and
      considering spring security, this is the one of the best and must read book on
      Spring Security.





        


      Steps to Map LDAP groups to Authorities for
      Role based Access Control (RBAC)



      Mapping LDAP authorities into role based access Java spring security example1) Create an Application specific Authority classes, usually an enum with
      values like APP_USER, APP_ADMIN





      2) Create Authority Mapper which will Map LDAP groups to application
      specific authority for example if group in LDAP is "Application Access
      (Gn)" than mapping that to APP_USER.





      3) If you are authenticating against Active directory than provide your
      custom Authority mapper to
      ActiveDirectoryLdapAuthenticationProvider. After
      successful authentication, it will load all the groups for which authenticated
      user_id is member of, and map with application specific authority.





      4) Use application specific authorities or roles as APP_USER or APP_ADMIN
      to secure your URL's by using


      <intercept-url pattern="/secure/admin/**" access="hasRole('APP_ADMIN')"/>

       

      <intercept-url pattern="/secure/user/**" access="hasRole('APP_USER')"/>

      <intercept-url pattern="/secure/**" access="isAuthenticated()" />









      Java code for Mapping LDAP Groups to
      Authorities using Spring Security



      Here is the Java code, required to map LDAP groups into granted
      authorities of Spring Security. We need one class, usually enum to create roles
      supported by our application, this must implement
      GrantedAuthority interface,
      which is used to represent role in Spring Security. Now we need a Mapper class
      to map LDAP groups into granted authorities, this class must implement
      GrantedAuthoritiesMapper interface.
      We create instance of this class using Spring and provide names of LDAP groups
      for mapping with a particular role. For example, if application has two  roles USER and ADMIN and LDAP group
      "Application
      User Access (Gn)"
      is for User and "Application Admin
      Access (Gn)"
      is for Admin, then this information is configured
      in Spring configuration file and this authority mapper is provided to LDAP authentication provider. Keeping application role separate from LDAP groups
      allows you to cope up with any change in LDAP group name, you just need to
      change your spring configuration file.





      LDAPGrantedAuthoritiesMapper.java


      import java.util.Collection;

      import java.util.EnumSet;

      import java.util.Set;

      import org.springframework.security.core.GrantedAuthority;

      import org.springframework.security.core.authority.mapping.GrantedAuthoritiesMapper;

       

      /**

       * LDAP Authorities mapper, Maps LDAP groups to APP_USER and APP_ADMIN

       */

      public class LDAPGrantedAuthoritiesMapper implements GrantedAuthoritiesMapper {

          private final String APP_USER ="Ldap User Group";   //default user ldap group

          private final String APP_ADMIN ="Ldap Admin Group"; //default adming ldap group

       

          public ADGrantedAuthoritiesMapper(String userGroup, String adminGroup) {

              APP_USER = userGroup;

              APP_ADMIN = adminGroup;

       

          }

       

          public Collection  mapAuthorities(

                  final Collection authorities) {

       

              Set roles = EnumSet.noneOf(LDAPAuthority.class); //empty EnumSet

       

              for (GrantedAuthority authority : authorities) {

                  if (APP_USER.equals(authority.getAuthority())) {

                      roles.add(LDAPAuthority.APP_USER);

                  } else if (APP_ADMIN.equals(authority.getAuthority())) {

                      roles.add(LDAPAuthority.APP_ADMIN);

                  }

              }

              return roles;

          }

      }






      LDAPAuthority.java


      import org.springframework.security.core.GrantedAuthority;

       

      /**

       * Maps LDAP Group application roles

       */

      public enum LDAPAuthority implements GrantedAuthority{

          APP_USER, APP_ADMIN; //roles used in application

         

          public String getAuthority() {

              return name();

          }

         

      }






      Spring Security Configuration for Role based
      Access and Mapping LDAP groups



      As stated above, first configuration is creating an instance of LDAPGrantedAuthoritiesMapper and
      mapping LDAP groups to application roles, so that when a user is successfully
      authenticated and comes with all LDAP groups, he is member of, those groups
      are read and converted into corresponding roles. Second configuration is to
      provide this mapper to
      ActiveDirectoryLdapAuthenticationProvider, this is
      similar to our last example of LDAP authentication, except <
      beans:property
      name="authoritiesMapper" ref="ldapAuthoritiesMapper"/>
      , which is
      requite to map LDAP groups to granted authorities for role based access
      control.






      <beans:bean id="ldapAuthoritiesMapper" class="com.abc.web.security.LDAPGrantedAuthoritiesMapper">

              <beans:constructor-arg value="Ldap User Group" />

              <beans:constructor-arg value="Ldap Admin Group" />

      beans:bean>   

       

      <beans:bean id="LdapAuthProvider"  class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">

              <beans:constructor-arg ref="domain" />

              <beans:constructor-arg ref="url" />

              <beans:property name="convertSubErrorCodesToExceptions" value="true"/>

              <beans:property name="authoritiesMapper" ref="ldapAuthoritiesMapper"/>   //LDAP authority mapper

              <beans:property name="useAuthenticationRequestCredentials" value="true"/>

      beans:bean


       




      That's all you need to implement Role based access control on your Spring
      MVC, Spring Security based Java web application. Like other features, LDAP
      authorization doesn't come out of box from Spring Security and you need to
      follow above steps to map LDAP groups to granted authorities.





      Recommended
      Book:


      Spring Security 3.1 By Robert Winch,Peter Mularien is one of the best and must read book on Spring
      security. It takes application development approach to teach basics of
      enterprise security, LDAP concepts, authentication, authorization and several
      other spring security features with non trivial examples.



























      Source:http://javarevisited.blogspot.com/2013/07/role-based-access-control-using-spring-security-ldap-authorities-mapping-mvc.html