Archive for category Java

Spring 3 on App Engine

Before writing this note, I referenced the site http://www.ardentlord.com/apps/blog/show/829881-spring-3-0-on-google-app-engine and would like to supplement some steps here.

1. Setup a Google App Engine project

2. Copy following .jar files, and add it in eclipse build path

org.springframework.asm-3.0.2.RELEASE.jar
org.springframework.beans-3.0.2.RELEASE.jar
org.springframework.context-3.0.2.RELEASE.jar
org.springframework.core-3.0.2.RELEASE.jar
org.springframework.expression-3.0.2.RELEASE.jar
org.springframework.web-3.0.2.RELEASE.jar
org.springframework.web.servlet-3.0.2.RELEASE.jar

3. Spring also depends on the following jars, which you can search for around the internet, or download from my Spring Example git repository:
antlr-3.0.1.jar
asm-2.1.jar
asm-commons-2.1.jar
commons-logging-1.1.1.jar

5. Finally, you’ll need to rename the commons-logging-1.1.1 jar to something else.

6. Since using RESTFul style URL, we would like to map /app/* to dispatcher servlet, (but not /* because we don’t want to redirect views (.jsp) also back to dispatcher).  Add the following in web.xml under /WEB-INF/ folder


<servlet>
<servlet-name><span style="color: #ff6600;">dispatcher</span></servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>

</servlet>
<servlet-mapping>
<servlet-name>dispatcher</servlet-name>
<url-pattern>/app/*</url-pattern>
</servlet-mapping>

7. dispatcher-servlet.xml  <- the “dispatcher” should be the same as the

servlet-name defined in web.xml

Following is the sample of the file


<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

<context:component-scan base-package="com.allenkan.appengine.blog.controllers" />

<bean id="viewResolver" p:prefix="/WEB-INF/views/" p:suffix=".jsp" />

</beans>

8. Now we’re all done with setup! Just create a controller and a view. I made a simple hello.jsp view that outputs the request parameter “name”. Here’s the controller:

<pre>package example.controllers.hello;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController {

@RequestMapping("/hello/{name}")
public String hello(@PathVariable String name, Model model) {
model.addAttribute("name", name);
return "hello/hello";
}
}
</pre>

9. Last but not least, the jsp file have to enable EL (Expression Language) by

defining isELIgnored=”false” in the page header.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"  isELIgnored="false"  %>

No Comments

Java Code Querying AD


import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.Control;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;

public class TestLogin
{
private String domain;
private String ldapHost;
private String searchBase;

public static void main(String[] args){
TestLogin a = new TestLogin();
Map umap = a.authenticate("username", "password");

if (umap == null)
System.out.println("Login Failed");
else {
String s = umap.get("givenName").toString();
System.out.println("GIVEN NAME=" + s);
}
}

public TestLogin()
{
this.domain = "hkesprit";
this.ldapHost = "ldap://<DC Server>";
this.searchBase = "dc=<domain name>,dc=com";
}

public TestLogin(String domain, String host, String dn)
{
this.domain = domain;
this.ldapHost = host;
this.searchBase = dn;
}

public Map authenticate(String user, String pass)
{
String returnedAtts[] ={ "sn", "givenName", "mail" };
String searchFilter = "(&(objectClass=user)(sAMAccountName=" + user + "))";

//Create the search controls
SearchControls searchCtls = new SearchControls();
searchCtls.setReturningAttributes(returnedAtts);

//Specify the search scope
searchCtls.setSearchScope(SearchControls.SUBTREE_SCOPE);

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, ldapHost);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, user + "@" + domain);
env.put(Context.SECURITY_CREDENTIALS, pass);

LdapContext ctxGC = null;

try
{
ctxGC = new InitialLdapContext(env, null);

//Search objects in GC using filters
NamingEnumeration answer = ctxGC.search(searchBase, searchFilter, searchCtls);
while (answer.hasMoreElements())
{
SearchResult sr = (SearchResult) answer.next();
Attributes attrs = sr.getAttributes();
Map amap = null;
if (attrs != null)
{
amap = new HashMap();
NamingEnumeration ne = attrs.getAll();
while (ne.hasMore())
{
Attribute attr = (Attribute) ne.next();
amap.put(attr.getID(), attr.get());
}
ne.close();
}
return amap;
}
}
catch (NamingException ex)
{
ex.printStackTrace();
}

return null;
}
}

No Comments

Integrated Windows Authentication in Java

http://spnego.sourceforge.net/

Integrated Windows Authentication in Java

The intent of this project is to provide an alternative library (.jar file) that application servers (like Tomcat) can use as the means for authenticating clients (like web browsers).

If your organization is running Active Directory (AD) and all of your web applications go through Microsoft’s Internet Information Services (IIS), and IIS has Integrated Windows Authentication enabled, and everyone in your organization is using Internet Explorer (IE), then this project may not be of any interest to you.

This project may also not be of any interest to you if your organization is using jCIFS as the means to achieve Single Sign-On (SSO); there are other 3rd party products as well as open-source projects that will silently authenticate (no username/password prompt) browser requests to a protected web page. Perhaps some of these are more suitable for your organization’s needs.

However, if your organization uses java based web/application servers, and you prefer Kerberos/SPNEGO instead of NTLM as the authentication protocol, and you would rather have a Java Servlet Filter (JSR-53) based implementation instead of a container specific authentication module (JSR-196), and you want SSO
(no username/password prompt), then this project may be of some interest to you.

The most effective way to get started is to first go through the pre-flight checklist. One of the goals of the checklist is to identify configuration parameter values necessary during installation and configuration of the SPNEGO HTTP Servlet Filter. There are really only two steps to the install: 1) copy jar file and 2) modify web.xml file.

Unfortunately, that’s just the servlet filter install. You may also need to create two configuration files that your Java Runtime (JRE) will need as a part of Java’s security technology framework. Specifically, creating configuration files for the Java Authentication and Authorization Service (JAAS) package/extension and for the Java Generic Security Services (Java GSS) API. The pre-flight has instructions for these as well.

Finally, there’s nothing in the code base that is specific to AD. Theoretically, this code should also work with MIT Kerberos. There is also nothing in the code base that is specific to Tomcat or IE, or Windows or UNIX (but feel free to post messages in the Forum about any successes and/or failures).

No Comments

Including Sub-project in Eclipse Maven

Try running first mvn install in the sub project (in order to put the sub-project in your local maven repository), and then add the dependency to Parent project’s pom.xml.

,

No Comments

Setup JDK in Maven Project in Eclipse

Change the POM.xml


<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>Test</groupId>
<artifactId>test</artifactId>
<packaging>jar</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>test</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.1</version>
<span style="color: #3366ff;"><strong><configuration>
<source>1.5</source>
<target>1.5</target>
</configuration></strong></span>
</plugin>
</plugins>
</build>
</project>

,

No Comments

Spring Hibernate Integration

Spring Hibernate Integration

, ,

No Comments

Spring 3.0 MVC Tutorial

Spring 3 mvc tutorial

-> Use tuckey.org urlrewrite to rewrite the URL, only pass the java request to Spring dispatcher servlet

-> Also include log4j, slf, hibernate validator jar files for using normal MVC features

1 Comment

Using Maven in Eclipse

Install Java and Maven

First off, make sure you have a Java JDK installed and that your JAVA_HOME environment variable points to it. You can check by typing “echo %JAVA_HOME%” in Windows or “echo $JAVA_HOME” in Linux. You’ll next want to download and install Maven by following the directions on their website.  Once Maven is installed, you’ll want to create a settings.xml file in your .m2 directory, which is located at ~/.m2 in Linux or C:\Documents and Settings\%USER%\.m2 on Windows.  You can do this by copying the settings.xml file from the directory where Maven in installed to you .m2 directory.

Install m2eclipse

You’ll want to make sure your Eclipse installation is pointint at your JDK.  You can check by going to Window > Preferences > Java > Installed JREs.  You’ll also want to set the -vm flag in your eclipse.ini file which is located at the root of your Eclipse installation.  Here’s what my file looks like:

-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
256M
-framework
plugins\org.eclipse.osgi_3.4.0.v20080605-1900.jar
-vm
C:\Program Files\Java\jdk1.6.0_11\bin\javaw.exe
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Xms40m
-Xmx512m

Finally, you get to install m2eclipse by opening up Eclipse and selecting Help > Software Updates… > Available Software > Add Site…  Then enter http://m2eclipse.sonatype.org/update/, check the newly added boxes, and press Install.

Create Your First Maven Project

Now for the fun.  You can create a Maven project in Eclipse by selecting New > Project… > Maven > Maven Project.  Check “Create a simple project” on the first screen and hit Next.  Enter the Group Id, Artifact Id, and Name.  For example, “com.benmccann.robot”, “window-robot”, “Window Robot”.  Now, at long last, you can do some actual programming.

Add Dependencies

It won’t be long before you’ll want to add dependancies.  Open the Maven Indexes View by selecting Window > Show View > Other… > Maven > Maven Indexes.  You’ll want to make sure you have the Maven Central Repository, so right-click the view and choose “Add Index”.  Enter http://repo1.maven.org/maven2/ for the Repository URL and hit Retrieve to fill in the Repository Id of central.  Now you can right-click the project and choose Maven > Add Dependancy.  We’ll add jUnit since you’ll probably want it anyway.  Type junit and you should see it populated into the box below.  Use the dropdown at the bottom to set a scope of “test” and hit OK.

,

No Comments

How to start and stop Tomcat from ANT

Filed under: java — Peter Thomas @ 12:04 am

This approach is not based on the Tomcat Ant Tasks or a brute force <exec dir=”${tomcat.home}/bin” executable=”startup.bat”/> kind of approach.

After wading through startup.bat and catalina.bat I figured that they boil down to the following:

<pre><target name="tomcat-start">
    <java jar="${tomcat.home}/bin/bootstrap.jar" fork="true">
        <jvmarg value="-Dcatalina.home=${tomcat.home}"/>
    </java>
</target>

<target name="tomcat-stop">
    <java jar="${tomcat.home}/bin/bootstrap.jar" fork="true">
        <jvmarg value="-Dcatalina.home=${tomcat.home}"/>
        <arg line="stop"/>
    </java>
</target></pre>

You can have in build.properties, something like the following entry:

tomcat.home=E:/peter/opt/apache-tomcat-5.5.12

It works great and in Eclipse and NetBeans the stack traces within the log window hyperlink to the source code just as you would expect. You would normally combine these ant targets with a “war” task. The Tomcat Reload Ant task can also be used to speed up development time.

One of the advantages of this approach is that you can extend it to start Tomcat for remote debugging

<pre><target name="tomcat-start-debug">
    <java jar="${tomcat.home}/bin/bootstrap.jar" fork="true">
        <jvmarg value="-Dcatalina.home=${tomcat.home}"/>
        <jvmarg value="-Xdebug"/>
        <jvmarg
value="-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n"/>
    </java>
</target>

,

No Comments

Installing Spring Tool Suite (STS) under Eclipse 3.5 Galileo

Firstly you need to install Eclipse 3.5 Galileo, then once that’s up and running you can use the Spring update site to install the Spring Tool Suite (STS). Follow these simple step-by-step instructions. I’m assuming that you are the only Java developer using this machine.

  1. Go to http://www.eclipse.org/downloads/
  2. Follow the link for Eclipse IDE for Java EE Developers (189 MB) for Windows.
  3. Select a mirror and download the file.
  4. Create a folder called c:\java.
  5. Move the Eclipse archive (eclipse-jee-galileo-win32.zip) into c:\java and extract here.
  6. Folder c:\java\eclipse will be created.
  7. Drag the executable eclipse.exe on to the desktop (or quick launch) and make a shortcut.
  8. The workspace dialogue will pop up and ask you where you would like to keep your workspace. Spaces in file names (or directories) are always a bad idea especially when developing under a Windows environment which is why I don’t accept the default workspace location, so enter c:\java\workspace.

That was easy wasn’t it?. STS is now free so you can just install it from their update site.

  1. Install Eclipse 3.5 Galileo mentioned above.
  2. Open the preferences page Windows->Preferences.
  3. Expand the Install/Update tree on the right hand side and select Available Software Sites.
  4. Highlight all the Enabled sites and click Disable.
  5. Click the Import button and enter http://dist.springsource.com/snapshot/TOOLS/sts-update-sites.xml. Eclipse spots this is a website then downloads and installs the xml. It may take a couple of seconds, but when it finishes click Ok.
  6. From the file menu, go to Help->Install New Software….
  7. Set Work with to AJDT – http://download.eclipse.org/tools/ajdt/35/dev/update. At the time of writing this there were no new updates so skip it and move to the next step.
  8. Set Work with to Mylyn Extras – http://download.eclipse.org/tools/mylyn/update/extras.
  9. Expand Mylyn Integration and check Mylyn Connector: JIRA, Next will become active to click it.
  10. After a bit of rumbling (to work out dependencies which there are none) click Next.
  11. Accept the License agreement and click Finish.
  12. After installation you are asked to restart Eclipse, so click Yes.
  13. Back into the Help->Install New Software….
  14. Set Work with to Spring IDE Update Site – http://dist.springframework.org/snapshot/IDE/nightly.
  15. Select all the components and click Next. More rumbling then click Next again. Accept the license and click Finish.
  16. Back into the Help->Install New Software….
  17. Set Work with to SpringSource dm Server Tools Update Site – http://dist.springsource.com/snapshot/DMS-TOOLS/nightly
  18. Back into the Help->Install New Software….
  19. Set Work with to SpringSource Tool Suite Update Site – http://dist.springsource.com/snapshot/STS/nightly/e3.4

Close down Eclipse and zip up the whole of c:\java\eclipse. Rename it to eclipse-3.5-sts.zip. If there is one thing I have learnt, it’s take a back up of a fixed working installation. Every one and his dog can write eclipse features and plugins. It is easy for one plugin to screw up another, so its really handy to have a “last known good position” to rollback to. Otherwise you may well find that you are going through this whole process again.

Original SpringSource instructions can be found here.

Ref: http://www.bigsoft.co.uk/blog/index.php/2009/07/01/installing-sts-under-eclipse-3-5-galileo

1 Comment