Wednesday, March 13, 2013

Search LDAP User using Java

This example shows how to search a LDAP user using Java.

import java.util.Hashtable; import javax.naming.Context; import javax.naming.directory.SearchControls; import javax.naming.directory.SearchResult; import javax.naming.NamingEnumeration; import javax.naming.NamingException; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; class LdapUserChecker { public static void main(String[] args) { boolean result = false; String ldapDomain = args[0]; String ldapHost = args[1]; String ldapSearchbase = args[2]; String ldapLookupUserID = args[3]; String ldapLookupUserPwd = args[4]; String userID = args[5]; String url = ldapHost.endsWith("/") ? ldapHost + ldapSearchbase : ldapHost + "/" + ldapSearchbase; Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, url); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, ldapLookupUserID + "@" + ldapDomain); env.put(Context.SECURITY_CREDENTIALS, ldapLookupUserPwd); LdapContext context = null; NamingEnumeration results = null; try { context = new InitialLdapContext(env, null); SearchControls controls = new SearchControls(); controls.setSearchScope(SearchControls.SUBTREE_SCOPE); results = context.search("", "(sAMAccountName="+userID+")", controls); if (results.hasMore()) { result = true; } } catch (NamingException e) { System.out.println("LDAP authenication failed for lookup user: " + ldapLookupUserID); System.out.println(e.getMessage()); } finally { if (results != null) { try { results.close(); } catch (Exception e) { } } if (context != null) { try { context.close(); } catch (NamingException e) { throw new RuntimeException(e); } } } if (result) { System.out.println("User '" + userID + "' exists!"); } else { System.out.println("User '" + userID + "' does not exist!"); } } }

LDAP Authentication using Java

This example shows how to authenticate a LDAP user using Java.

import java.util.Hashtable; import javax.naming.Context; import javax.naming.NamingException; import javax.naming.ldap.InitialLdapContext; import javax.naming.ldap.LdapContext; class LdapAuthenticator { public static void main(String[] args) { String ldapDomain = args[0]; String ldapHost = args[1]; String ldapSearchbase = args[2]; String userName = args[3]; String password = args[4]; String url = ldapHost.endsWith("/") ? ldapHost + ldapSearchbase : ldapHost + "/" + ldapSearchbase; Hashtable env = new Hashtable(); env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); env.put(Context.PROVIDER_URL, url); env.put(Context.SECURITY_AUTHENTICATION, "simple"); env.put(Context.SECURITY_PRINCIPAL, userName + "@" + ldapDomain); env.put(Context.SECURITY_CREDENTIALS, password); LdapContext context = null; try { context = new InitialLdapContext(env, null); System.out.println("LDAP authenication succeed for user: " + userName); } catch (NamingException e) { System.out.println("LDAP authenication failed for user: " + userName); System.out.println(e.getMessage()); } finally { if(context != null) { try { context.close(); } catch (NamingException e) { throw new RuntimeException(e); } } } } }

Install and Configure Maven in Eclipse

Installation

  1. Install and Configure Maven
    1. Download and unzip the Maven zip file into the installation directory.  For example, in Windows, it could be c:\maven, or /usr/local/maven in Linux.
    2. Add the following environment variables:
      1. M2_HOME
        The installation directory of Maven, e.g. c:\maven in Windows.
      2. M2
        The bin directory under the Maven installation directory, e.g. %M2_HOME%\bin.

  2. Install Maven plugin in Eclipse
    1. In Eclipse, add a new software site in "Help" -> "Install New Software…".  Next to the "Work with" dropdown list, press the "Add…" button.
    2. In the popup dialog (see Figure 2), input the followings:
      Name: Maven Location: http://m2eclipse.sonatype.org/sites/m2e
      Figure 2: Add a software site for installing new software/plugin
    3. Select the newly added Maven site from the “Work with” dropdown list.
    4. Check the option “Maven Integration for Eclipse (Required)” from the list (see Figure 3).
    5. Press the “Next” button.

    Figure 3: Available Software in Eclipse

References

  1. Maven, http://maven.apache.org/

CSS

  1. An example to distinguish between Fire Fox, IE6, IE7 and IE8.

    HTML

    <!DOCTYPE html> <html> <head> <title>Test CSS</title> <style> #summary { background:red; /* Firefox */ background:blue \9; /* IE8 */ *background:yellow; /* IE7 */ _background:orange; /* IE6 */ } </style> </head> <body> <h1 id="summary">Hello World!!!</h1> </body> </html>

    Output

    Figure 1: Fire Fox
    Figure 2: IE6
    Figure 3: IE7
    Figure 4: IE8

How to Show Your Profile with Photo in the Google Search Results

Figure 1: Google Search Result with Profile Photo
  1. Create a Google+ account if you don't have one.
  2. Add your name and photo to the Google+ profile.
  3. Establish your authorship
    Authorship can be explicitly established via two primary methods: email verification or rel=author markup.
    • Email verification,
      1. Make sure that each article or post you publish on that domain has a clear byline identifying you as the author (for example, "By Ada Cheng" or "Author: Ada Cheng").
      2. Verify your email address in the Google+ Authorship page.
    • rel=author markup
      Create a link to your Google+ profile from your webpage, like: <a href="[profile_url]?rel=author">Google+ Profile</a> Replace [profile_url] with the your Google+ profile URL, like this: <a href="https://plus.google.com/110814153133954972941?rel=author">Google+ Profile</a> Your link must contain the ?rel=author parameter. If it's missing, Google won't be able to associate your content with your Google+ profile.
    However, if you wish to establish your authorship for Blogger posts, all you have to do is to upgrade/switch your Blogger Profile to Google+ Profile.
    Figure 2: rel=author markup has successfully established authorship
  4. To see what author data Google can extract from your page, use Google's Structured Data Testing Tool. Note that It takes some time, maybe a few days, for Google to begin to associate your posts with your profile.
    Figure 3: Preview of Google Search Results in Structured Data Testing Tool
  5. Wait for Google to associate your posts with your profile. In my experience, it may take a few days.
References

  1. Google Authorship, Webmaster Tools from Google.
  2. Author information in search results, Webmaster Tools from Google.
  3. Instructions on how to Link a Google+ Profile to Content Created

Using Apache Derby in Eclipse

  1. Installations You may skip this part if you are using Eclipse 3.7 (Indigo) or above, as they are pre-installed.
    1. Eclipse DTP (Data Tools Platform)
      Figure 1: Install Data Tools Platform
      Install the Data Tools Platform via the Eclipse update manager. Install "Data Tools Platform Enablement Extender SDK".
    2. Apache Derby Download the latest Derby version from the Apache website http://db.apache.org/derby/. Choose the binary distribution.
  2. Configurations
    1. Establish a connection to an embedded Derby. Define the driver for the Derby access.
      Go to Window-> Preferences and select "Data Management" -> Connectivity -> Driver Definition. Press Add. Select Derby and the version you want to use. If your Derby version is not listed selected the highest number displayed.
      Figure 2: New Driver Definition
  3. Implementation
    1. Create a Data Development Project.
      1. Invoke the "New Project" wizard from the menu "File -> "New" -> "Project...".  In the "New Project" wizard, select "Data Development Project".
        Figure 3: Create a Data Development Project
      2. In the "New Data Development Project" wizard, input a Project Name.  Click the "Next" button.
        Figure 4: Data Development Project wizard - Project Name
      3. Click the "New" button to create a new connection.
        Figure 5: Select Connection
      4. In the "New Connection" wizard, select "Embedded Derby JDBC Driver" as the JDBC driver.  Click the "Next" button.
        Figure 6: Connection Parameters
      5. Click the "Next" button.
        Figure 7
      6. A new database connection is created.
        Figure 8: New database connection created
      7. In the "Default Application Process Setting" dialog, check the option "Omit default schema in generated statements".
        Figure 9: Default Application Process Settings

      8. Figure 10: Database Development Project

      9. Note that a Database Development Project is created.

Tuesday, March 12, 2013

First Hello World Web Application using Maven

To create a simple Servlet web application using Maven in Eclipse.
In this example, a simple web application is created using Maven in Eclipse. A servlet is created to output a "Hello World~~~" sentance when called.
Maven/Jetty plugin is used for running the application.
Implementation
  1. Create a Maven Project in Eclipse.
    By following the procedures below, an Eclipse project with the followings:
    1. A Java source folder, /src/main/java;
    2. A Resource source folder, /src/main/resources;
    3. A Java source folder for testing, /src/test/java;
    4. A Resource source folder for testing, /src/test/resources;
    5. A Web Application source folder, /src/main/webapp;
    6. A WEB-INF folder, /src/main/webapp/WEB-INF; and
    7. pom.xml.

    Figure 1: Created Maven Project
    Procedures
    1. Select "File"->"Project..." from the menu. In the "New Project" dialog, select "Maven Project". Click the "Next" button.
      Figure 2: New Maven Project
    2. In the "New Project - Select project name and location" dialog, check the option "Create a simple project (skip archetype selection)". Click the "Next" button.
      Figure 3: New Maven Project - Select project name and location.
    3. In the "New Project - Configure Project" dialog, input the Group Id, Artifact Id and Name.  Select "war" as the "Packaging". Click the "Next" button. The project will then be created.
      Figure 4: New Project - Configure Project
  2. Update the pom.xml.
    • If context is not defined, <artifactId> will be used as the context of the application.
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.blogspot.adaprognotebook</groupId> <artifactId>helloweb</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>Hello World Webapp</name> <repositories> <repository> <id>java.net2</id> <name>Repository hosting the Java EE artifacts</name> <url>http://download.java.net/maven/2</url> </repository> <repository> <id>sonatype-nexus-snapshots</id> <name>Sonatype Nexus Snapshots for the jetty-maven plugin</name> <url>https://oss.sonatype.org/content/repositories/snapshots</url> <releases> <enabled>false</enabled> </releases> <snapshots> <enabled>true</enabled> </snapshots> </repository> </repositories> <dependencies> <dependency> <groupId>javax</groupId> <artifactId>javaee-web-api</artifactId> <version>${javaee.version}</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>${jetty.version}</version> <configuration> <scanIntervalSeconds>30</scanIntervalSeconds> <stopPort>7788</stopPort> <stopKey>foo</stopKey> <webApp> <descriptor>${basedir}/src/main/webapp/WEB-INF/web.xml</descriptor> </webApp> </configuration> </plugin> </plugins> </build> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <javaee.version>6.0</javaee.version> <jetty.version>8.1.9.v20130131</jetty.version> </properties> </project>
  3. Create the Java Servlet in /src/main/java.
    package com.blogspot.adaprognotebook; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloWorld extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { PrintWriter out = resp.getWriter(); out.println("<html>"); out.println("<head>"); out.println("<title>Hello World Servlet</title>"); out.println("</head>"); out.println("<body>"); out.println("<h2>Hello World~~~</h2>"); out.println("</body>"); out.println("</html>"); out.close(); } }
  4. Modify web.xml in /src/main/webapp/WEB-INF.
    <?xml version="1.0" encoding="UTF-8"?> <web-app id="HelloWebApp" version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="true"> <servlet> <display-name>First Hello World Servlet</display-name> <servlet-name>Hello</servlet-name> <servlet-class>com.blogspot.adaprognotebook.HelloWorld</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>Hello</servlet-name> <url-pattern>/hello.view</url-pattern> </servlet-mapping> </web-app>
  5. Start Jetty by running a new configuration with goal "jetty:run", and view the web page in browser using URL http://localhost:8080/helloweb/hello.view.
    Figure 5: Hello World Servlet