Wednesday, March 5, 2014

Spring security using Java configuration

Authentication can be done in 2 ways in spring - using context xml files or using the latest java based configuration. This article explains how to implement spring security using java configurations.
The below steps need to be followed in order to configure security in spring applications.

  • Define spring security security filter chain.
  • Create custom user details service
  • Security configuration


1Define spring security security filter chain.
       public class WebAppInitializer implements WebApplicationInitializer {
              public void onStartup(ServletContext servletContext)
                     throws ServletException {

              .
              .
              .
             
              servletContext.addFilter("springSecurityFilterChain",
                           new DelegatingFilterProxy("springSecurityFilterChain"))
                     .addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class),
                                         true, "/*");
              .
              .
              .
              }
       }
TThe above approach eliminates the need for using a web.xml. The springsecurityfilterchain is defined in this java
fifile instead of web.xml.


Create custom user details service class.
       @Service
       public class AppUserDetailsService implements UserDetailsService {

              @Autowired
              private AppUserRepository appUserRepository;

              @Override
              @Transactional
              public UserDetails loadUserByUsername(String userId)
                     throws UsernameNotFoundException {
                     UserValue userValue = null;
                     List<GrantedAuthority> grantedAuthorities = new  ArrayList                               <GrantedAuthority>();
                     AppUser appUser = null;
                     appUser = appUserRepository.findByUserId(userId);
                     if (appUser != null) {
                            grantedAuthorities.add(new SimpleGrantedAuthority(appUser
                                  .getAppRole().getName()));
                            userValue = new UserValue(
                                  appUser.getId(), appUser. getUserId(),
                                  appUser.getPassword(), grantedAuthorities,
                                   appUser.getFirstName(), appUser.getLastName());
                     }
                     return userValue;
              }
       }
 There are different ways to configure security, this approach uses a custom User details service which loads the user and role information from the db and returns it to the framework, the framework then stores the user and role information in the session for further processing

1Create security configuration java class

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

       @Autowired
       AppUserDetailsService appUserDetailsService;

       @Autowired
       public void configureGlobal(AuthenticationManagerBuilder auth)
                     throws Exception {
              auth.userDetailsService(appUserDetailsService);
       }

       @Override
       public void configure(WebSecurity builder) throws Exception {
              builder.expressionHandler(webexpressionHandler()).ignoring()
                           .antMatchers("/resources/**");
       }

       @Bean(name = "webexpressionHandler")
       public DefaultWebSecurityExpressionHandler webexpressionHandler() {
              return new DefaultWebSecurityExpressionHandler();
       }

       @Override
       protected void configure(HttpSecurity http) throws Exception {
              http.csrf().disable().authorizeRequests().
                                  .antMatchers("/loginPage").permitAll().
                                  anyRequest().fullyAuthenticated().and()                                                   .formLogin().loginPage("/loginPage").
                                  loginProcessingUrl("/j_spring_security_check")
                                  .usernameParameter("j_username")
                                   .passwordParameter("j_password").
                                  failureUrl("/errorPage")
                                   .defaultSuccessUrl("/myhome").permitAll().and().
                                  logout().logoutUrl("/j_spring_security_logout")
                     .logoutSuccessUrl("/loginPAge").deleteCookies("JSESSIONID")
                           .invalidateHttpSession(true);
       }
}



The configure method can be used to define the loginpage, logout page, the success url, failure url and whether to delete cookies and invalidate session while logout. 
  • The configure method which accepts WebSecurity can be used to tell the resource folders so that those can be ignored by the security frameworks.
  •  Now all the urls except the one in the resources folder will be intercepted by the security framework and will be redirected to the login page
  •  Once the user enters the user id and password, the AppUserDetailsService.loadUserByUsername will be called by passing the current login userid. This method loads user information and passes it to the security framework
  •  The framework then validates the credentials and if it is successful, then displays the home page based on the configuration defined in the security config class.
  •  When the user logs out, the session is invalidated and the controls goes back to the login page. 


Friday, February 28, 2014

NER using Stanford NLP

Named Entity Recognition - NER helps in identifying meaningful information from the textual content. 
There are different ways to get NER (place, name, organization) out of text, the below example uses Stanford NLP library to obtain NER.

Ensure you have the required Stanford NLP jars for running the below example, if you are using maven, then the following dependencies can be used. 

<!-- Stanford NLP -->
              <dependency>
                     <groupId>edu.stanford.nlp</groupId>
                     <artifactId>stanford-corenlp</artifactId>
                     <version>3.2.0</version>
              </dependency>
              <dependency>
                     <groupId>edu.stanford.nlp</groupId>
                     <artifactId>stanford-corenlp</artifactId>
                     <version>3.2.0</version>
                     <classifier>models</classifier>
              </dependency>
              <dependency>
                     <groupId>com.io7m.xom</groupId>
                     <artifactId>xom</artifactId>
                     <version>1.2.10</version>
              </dependency>
              <dependency>
                     <groupId>joda-time</groupId>
                     <artifactId>joda-time</artifactId>
                     <version>2.1</version>
              </dependency>
              <dependency>
                     <groupId>de.jollyday</groupId>
                     <artifactId>jollyday</artifactId>
                     <version>0.4.7</version>
              </dependency>
              <dependency>
                     <groupId>com.googlecode.efficient-java-matrix-library</groupId>
                     <artifactId>ejml</artifactId>
                     <version>0.23</version>
              </dependency>

High level steps include the following: 

1. Create StanfordCoreNLP object. 
2. Mention the models that might be used for the program
3. Get the annotation article by passing the text. 
4. Get the sentences of the articles. 
5. Get the words from the sentences. 
6. For each of the word from the sentences, 
    obtain NER using the NLP api: 

Code: 

public class NERClient {
      
       static String ARTICLE = "A day after resigning as Navy Chief in New Delhi, Admiral D.K. Joshi on Thursday wrote to his colleagues, saying he was “firm” on taking responsibility for the mishaps that have taken place. ";
       StanfordCoreNLP pipeline = null;
       public static void main(String args[]) {
              NERClient sc = new NERClient();
              sc.go();
       }

       private void getSentences() {
       }

       private void go() {
              Properties props = new Properties();
           props.put("annotators", "tokenize, ssplit, pos, lemma, ner, parse");
           pipeline = new StanfordCoreNLP(props);
          
              Annotation annotation = new Annotation(ARTICLE);
              pipeline.annotate(annotation);
              List<CoreMap> sentences = annotation.get(SentencesAnnotation.class);
             
              for (CoreMap coreMap : sentences) {
                     List<CoreLabel> coreLabels = coreMap.get(TokensAnnotation.class);
                     System.out.println(coreLabels.toString());
                      for (CoreLabel token: coreLabels) {
                            String word = token.get(TextAnnotation.class);
                            String ner = token.get(NamedEntityTagAnnotation.class);
                            String pos = token.get(PartOfSpeechAnnotation.class);
                            System.out.print(word + "(" + ner + ")" + "  ");
                            //System.out.println("pos :" + pos);
                      }
              }

       }

}

Output:
[A, day, after, resigning, as, Navy, Chief, in, New, Delhi, ,, Admiral, D.K., Joshi, on, Thursday, wrote, to, his, colleagues, ,, saying, he, was, ``, firm, '', on, taking, responsibility, for, the, mishaps, that, have, taken, place, .]

A(DURATION)  day(DURATION)  after(O)  resigning(O)  as(O)  Navy(ORGANIZATION)  Chief(O)  in(O)  New(LOCATION)  Delhi(LOCATION)  ,(O)  Admiral(O)  D.K.(PERSON)  Joshi(PERSON)  on(O)  Thursday(DATE)  wrote(O)  to(O)  his(O)  colleagues(O)  ,(O)  saying(O)  he(O)  was(O)  ``(O)  firm(O)  ''(O)  on(O)  taking(O)  responsibility(O)  for(O)  the(O)  mishaps(O)  that(O)  have(O)  taken(O)  place(O)  .(O)  

Hope this helps someone

Tuesday, February 25, 2014

Regular expression using Java

Regular expression (regex or regexp) is used for searching using String pattern matching. Regex is a sequence of characters that forms a search pattern .

JDK comes up with built-in api for regex manipulation.Regex can be implemented using the “Pattern” and the “Matcher” class.

Sample program: 

       public static void main(String args[]) {
             
               boolean gotit = false;
               // -------------------------------------
             String line = "Rubesh is a technology (XYZ technology solutions) !. mail - samson@gmail.com mobile - 754-543-5843";
             String pattern = "[^a-z]";
            

             // Create a Pattern object
             Pattern r = Pattern.compile(pattern);

             // Now create matcher object.
             Matcher matcher = r.matcher(line);
             while (matcher.find()) {
                  System.out.print(matcher.group());
              gotit = true;
          }
          if(!gotit){
              System.out.println("No results !!!");
          }
       }
If you want to get the start & end index of a selected letter in the output you can use the matcher.start() and matcher.end().

Input / output samples:

Regex pattern                Output
[a-z]                              ubeshisatechnologytechnologysolutionsmailsamsongmailcommobile
[A-Z]                            RXYZ
[A-Za-z]                       RubeshisatechnologyXYZtechnologysolutionsmailsamsongmailcommobile
[a-z0-9_-]                    ubeshisatechnologytechnologysolutionsmail-samsongmailcommobile-754-543-5843
[a-z0-9_-]{4,10}         ubeshtechnologytechnologysolutionsmailsamsongmailmobile754-543-58


You can try out regex directly using www.regexpal.com

Wednesday, August 28, 2013

Tesseract is an open source OCR engine available, currently maintained by google. Tesseract can be deployed in server. It can also be deployed in Android. This article concentrates on how to deploy Tesseract in Android.

Overview: Tesseract is written using C/C++, hence you might need to use Android NDK for it. Instead of developing from scratch, we will use an existing code written by Robert thesis (https://github.com/rmtheis).

Installation / setup Prerequisites:
This article assumes the reader is aware of android, hence the following should be preconfigured in order to use tesseracct android – JDK 1.7, android sdk and ndk, latest eclipse and adt eclipse plugin.

Source /configuration :
1.       Download https://github.com/rmtheis/tess-two
Tess-two is the tesseract library project written in cpp. 

2.       Import the project within eclipse.
3.       Compile the tess-two project.
Linux or windows with cygwin is not required for compiling the tesseract - However you might need to have the latest  NDK builder.
Hence ensure that you have downloaded the latest Android NDK
a.       Configure your eclipse to use the ndk (similar to SDK configuration).
Windows -> preferences -> Android -> NDK. Give your NDK installation directory.

b.      Go to project properties of tess-two project and add the android ndk builder as follows:



4.       Compile the tess-two project, this should take some time. 



Once compiled you should see the following in the libs folder.
 


5.       Now download the android-ocr project in https://github.com/rmtheis/android-ocr
Android-ocr is a client test project which interacts with tesseract ocr library.

6.       Add the project to the workspace.
7.       Ensure that you have added tess-two project as a reference in android-ocr project.


8.       Now build the project. And run the app in your android phone, you should get the Android ocr project running in your android phone with no issues.