Thursday, November 16, 2006

GlassFish + JNDI + LDAP + JAVA

STEP 1: Create JNDI LDAP Resource

In the GlassFish admin console create a JNDI Custom Resource with the following parameters:

1. Give it a JNDI name such as myLDAP
2. Resource Type: javax.naming.directory.Directory
3. Factory Class: com.sun.jndi.ldap.LdapCtxFactory

Add the following as additional parameters:

1. Name: java.naming.security.principal Value: the reader dn

2. Name:java.naming.security.credentials Value: the password

3. Name: URL Value: ldap://servername/baseDN

STEP 2: JAVA code to access the LDAP

Use code similar to the following to access the LDAP:

try {
Context initCtx = new InitialContext();
DirContext ctx = (DirContext) initCtx.lookup("myLDAP");

SearchControls ctls = new SearchControls();
ctls.setSearchScope(SearchControls.SUBTREE_SCOPE);

String searchfilter = "(mail="+ email +")";
NamingEnumeration answer = ctx.search("", searchfilter, ctls);

if(answer.hasMore()){
SearchResult entry = (SearchResult) answer.next();
Attributes attrs = entry.getAttributes();
......

} else {
success = false;
}
} catch (NamingException e) {
e.printStackTrace();
}

Tuesday, November 14, 2006

Scripting FTP in BASH

The following code snippet can be embedded in a bash script to ftp a file or script other ftp functions. It also includes error checking if the ftp of the file fails.

function ftpfile {
# failure or success flag
#
FLAG=0 # assume success
# Start the actual ftp of the file
RETUR=$(ftp -n <>${LOGFILE}
open $SERVER
user $USERNAME $PASSWORD
ascii
put file.txt
bye
EOF
)

# End of the actual ftp process
if [ "$RETUR" != "" ]
then
FLAG=1
fi
return $FLAG
#
}
# END FTP FUNCTION
# call function to ftp file
ftpfile $file
FLAG=$?
if [ "$FLAG" -eq "0" ]
then
echo "------> File transfer completed"
else
echo "------x File transfer failed"
fi

Saturday, November 4, 2006

JDBC via JNDI

// define sql query
String sql = "select firstname from users";

// initialize database connection objects
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;

// get JNDI JDBC connection
InitialContext ctxt = new InitialContext();
DataSource ds = (DataSource) ctxt.lookup("jdbc/TrackIt");
conn = ds.getConnection();

// run sql objects
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);

// retrieve results
while (rs.next()) {
rs.getInt("firstname"));
}