: Java




HTTP Digest Authentication: A Java Client

October 23rd, 2009 admin Posted in Java Comments Off

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HeaderElement;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.GetMethod;

public class BrowserAuth {

	public static void main(String[] args) {
		try {

			// 
			String urlStr = “http://example.com:8080/abc/”;
			String host = “example.com”;
			String realm = “ExampleRealm”;
			String userName = “user”;
			String password = “password”;
			// 

			HttpClient client = new HttpClient();

			GetMethod getMethod = new GetMethod(urlStr);

			int status = client.executeMethod(getMethod);
			System.out.println(”status: ” + status);
			String responseBody = getMethod.getResponseBodyAsString();
			System.out.println(”responseBody: ” + responseBody);

			Header wwAuthHeader = getMethod.getResponseHeader(”WWW-Authenticate”);
			for (HeaderElement element : wwAuthHeader.getElements()) {
				System.out.println(element.getName() + “: ” + element.getValue());
			}

			UsernamePasswordCredentials upc = new UsernamePasswordCredentials(userName, password);
			AuthScope as = new AuthScope(host, 8080, realm);
			client.getState().setCredentials(as, upc);
			status = client.executeMethod(getMethod);
			System.out.println(”status: ” + status);
			responseBody = getMethod.getResponseBodyAsString();
			System.out.println(”responseBody: ” + responseBody);

			getMethod.releaseConnection();

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

}
AddThis Social Bookmark Button

NTLM Authentication: Java Client Code

October 23rd, 2009 admin Posted in Java Comments Off

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;

public class NtlmTest01 {

	public static void main(String[] args) throws Exception {

		String urlStr = “http://example.com/root/action.dll?p1=value1″;
		String domain = “”; // May also be referred as realm
		String userName = “CHANGE_ME”;
		String password = “CHANGE_ME”;		

		String responseText = getAuthenticatedResponse(urlStr, domain, userName, password);

	    System.out.println(”response: ” + responseText);
	}

	private static String getAuthenticatedResponse(final String urlStr, final String domain, final String userName, final String password) throws IOException {

	    StringBuilder response = new StringBuilder();

		Authenticator.setDefault(new Authenticator() {
	        @Override
	        public PasswordAuthentication getPasswordAuthentication() {
	            return new PasswordAuthentication(domain + “\\” + userName, password.toCharArray());
	        }
	    });

	    URL urlRequest = new URL(urlStr);
	    HttpURLConnection conn = (HttpURLConnection) urlRequest.openConnection();
	    conn.setDoOutput(true);
	    conn.setDoInput(true);
	    conn.setRequestMethod(”GET”);

	    InputStream stream = conn.getInputStream();
	    BufferedReader in = new BufferedReader(new InputStreamReader(stream));
	    String str = “”;
	    while ((str = in.readLine()) != null) {
	        response.append(str);
	    }
	    in.close();		

	    return response.toString();
	}

}

Notest: NTLM Handshack
————————————————-

GET …

401 Unauthorized
WWW-Authenticate: NTLM
————————————————-
GET …
Authorization: NTLM TlRMTVNTUAABAAAAA7IAAAoACgApAAAACQAJACAAAABMSUdIVENJVFlVUlNBLU1JTk9S

401 Unauthorized
WWW-Authenticate: NTLM TlRMTVNTUAACAAAAAAAAACgAAAABggAAU3J2Tm9uY2UAAAAAAAAAAA==
————————————————-
GET …
Authorization: NTLM TlRMTVNTUAADAAAAGAAYAHIAAAAYABgAigAAABQAFABAAAAADAAMAFQAAAASABIAYAAAAAAAAACiAAAAAYIAAFUAUgBTAEEALQBNAEkATgBPAFIAWgBhAHAAaABvAGQATABJAEcASABUAEMASQBUAFkArYfKbe/jRoW5xDxHeoxC1gBmfWiS5+iX4OAN4xBKG/IFPwfH3agtPEia6YnhsADT

200 Ok
————————————————-

Ref: http://www.innovation.ch/personal/ronald/ntlm.html

AddThis Social Bookmark Button

Get Exception StackTrace as a String

June 25th, 2009 admin Posted in Java Comments Off

public static String getStackTraceString(Exception e) {
	StringWriter writer = new StringWriter();
	PrintWriter pw = new PrintWriter(writer);
	e.printStackTrace(pw);
	StringBuffer sb = writer.getBuffer();
	return sb.toString();
}
AddThis Social Bookmark Button

HtmlUnit: A Simple Example: Check Yahoo Email

August 26th, 2008 admin Posted in Java Comments Off

by Muneeb Ahmad


package com.examples.htmlunit;

import java.io.IOException;
import java.net.URL;
import java.util.List;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.Page;
import com.gargoylesoftware.htmlunit.RefreshHandler;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlForm;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTable;
import com.gargoylesoftware.htmlunit.html.HtmlTableRow;

public class YahooMail {

	public static void main(String[] args) throws Exception {

		// Create and initialize WebClient object
	    WebClient webClient = new WebClient(BrowserVersion.FIREFOX_2);
	    webClient.setThrowExceptionOnScriptError(false);
	    webClient.setRefreshHandler(new RefreshHandler() {
			public void handleRefresh(Page page, URL url, int arg) throws IOException {
				System.out.println("handleRefresh");
			}

	    });

	    // visit Yahoo Mail login page and get the Form object
	    HtmlPage page = (HtmlPage) webClient.getPage("https://login.yahoo.com/config/login_verify2?.intl=us&.src=ym");
	    HtmlForm form = page.getFormByName("login_form");

	    // Enter login and passwd
	    form.getInputByName("login").setValueAttribute("@@@@@@@");
	    form.getInputByName("passwd").setValueAttribute("@@@@@@@");

	    // Click "Sign In" button/link
	    page = (HtmlPage) form.getInputByValue("Sign In").click();

	    // Click "Inbox" link
	    HtmlAnchor anchor = (HtmlAnchor) page.getHtmlElementById("WelcomeInboxFolderLink");
	    page = (HtmlPage) anchor.click();

	    // Get the table object containing the mails
	    HtmlTable dataTable = (HtmlTable) page.getHtmlElementById("datatable");

	    // Go through each row and count the row with class=msgnew
	    int newMessageCount = 0;
	    List rows = (List) dataTable.getHtmlElementsByTagName("tr");
	    for (HtmlTableRow row: rows) {
	    	if (row.getAttribute("class").equals("msgnew")) {
	    		newMessageCount++;
	    	}
	    }	    

	    // Print the newMessageCount to screen
	    System.out.println("newMessageCount = " + newMessageCount);

	    //System.out.println(page.asXml());	   	     	    

	}
}
AddThis Social Bookmark Button

TimerFilter : A Simple HTTP Servlet Filter

July 7th, 2008 admin Posted in Java Comments Off


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class TimerFilter implements Filter {

	public void destroy() {
		System.out.println("destroy");
	}

	public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
		System.out.println("doFilter");
		long startTime = System.currentTimeMillis();
		filterChain.doFilter(req, res);
		long stopTime = System.currentTimeMillis();
		System.out.println("took " + (stopTime-startTime) + " milli seconds.");

	}

	public void init(FilterConfig arg0) throws ServletException {
		System.out.println("init");
	}

}

<web-app>

    <filter>
        <filter-name>Timer</filter-name>
        <filter-class>com.msa.filter.TimerFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>Timer</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>    

</web-app>

AddThis Social Bookmark Button

A JSP to Pre-Compile JSPs

July 7th, 2008 admin Posted in Java Comments Off

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="javax.servlet.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.jsp.*"%>
<%@ page import="java.util.Set,java.util.Iterator,java.io.IOException"%>

<%! private void compileAllJsps(PageContext pageContext, JspWriter out, HttpServletRequest request,HttpServletResponse response, String uripath)
         throws IOException, ServletException {

     Set set = pageContext.getServletContext().getResourcePaths(uripath);
     for (Iterator iter = set.iterator(); iter.hasNext();) {
         String uri = (String) iter.next();
         if (uri.endsWith(".jsp")) {
             out.write("<li>"+ uri +"</li>");
             out.flush();
             RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);
             if (rd == null) {
                 throw new Error(uri +" - not found");
                 }
             rd.include(request, response);
         }
         else if (uri.endsWith("/")) {
             compileAllJsps(pageContext, out, request, response, uri);
         }
     }
   }
%>

<html>
<head>
<title>Precompiling *.JSPs</title>
</head>
<body>
<h4>Precompiling *.JSPs:</h4>
<ul>
<%
  HttpServletRequest req = new HttpServletRequestWrapper(request) {
  	public String getQueryString() {
          	//return "jsp_precompile";
          	return "jsp_precompile=true";
       };
  };
  compileAllJsps(pageContext, out, req, response, "/");
%>
</ul>
<h4>Done.</h4>
</body>
</html>
AddThis Social Bookmark Button

A Simple Reflection Example

July 2nd, 2008 admin Posted in Java Comments Off


import java.lang.reflect.Method;
public class SimpleReflection {
	public static void main(String[] args) throws Exception {
		// ================================================
		// The code in this method is equivalent to the following lines of code
		// ————————————————-
		// reflection.Echo echo = new reflection.Echo()
		// String retStr = echo.echo("Muneeb")
		// =================================================

		String className = "reflection.Echo";
		String methodName = "echo";
		Class clazz = Class.forName(className);
		Object obj = clazz.newInstance();

		Class methodParamTypes[] = new Class [1];
		Object methodParamObjects[] = new Object[1];

		methodParamTypes[0] = String.class;
		methodParamObjects[0] = new String("Muneeb");

		Method classMethod = clazz.getMethod(methodName, methodParamTypes);
		Object retObj = classMethod.invoke(obj, methodParamObjects);

		String retStr = (String) retObj;		

		System.out.println("respStr = " + retStr);

	}
}
AddThis Social Bookmark Button

Logon to a Remote Machine and Write File using jCifs

July 2nd, 2008 admin Posted in Java Comments Off

import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;

public class Logon {
    public static void main( String argv[] ) throws Exception {
    	String user = "user:password";
        NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(user);
        String path = "smb://my_machine_name/D/MyDev/test.txt";
        SmbFile sFile = new SmbFile(path, auth);
        SmbFileOutputStream sfos = new SmbFileOutputStream(sFile);
        sfos.write("Muneeb Ahmad".getBytes());
        System.out.println("Done");
    }
}
AddThis Social Bookmark Button

Ntlm Password Authentication using jCifs

July 1st, 2008 admin Posted in Java Comments Off


// Dependencies
// (1) jcifs-1.2.9.jar

import java.net.UnknownHostException;

import jcifs.UniAddress;
import jcifs.smb.NtlmPasswordAuthentication;
import jcifs.smb.SmbAuthException;
import jcifs.smb.SmbException;
import jcifs.smb.SmbSession;

public class Test01 {

public static void main(String[] args) {
	boolean userAuthenticated = false;
	String authenticationMessage = "";
	try {
		String domainController = "subdomain.domain.com";
		UniAddress dc = UniAddress.getByName(domainController, true);
		NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication("Domain", "user", "password");
		SmbSession.logon(dc, auth);
		userAuthenticated = true;
	} catch (SmbAuthException sae) {
		authenticationMessage = "SmbAuthException : " + sae.getMessage();
	} catch (UnknownHostException uhe) {
		authenticationMessage = "UnknownHostException : " + uhe.getMessage();
	} catch (SmbException smbe) {
		authenticationMessage = "SmbException : " + smbe.getMessage();
	}
	if (userAuthenticated)
		System.out.println("User Authenticated");
	else
		System.out.println("Authenticated failed : " + authenticationMessage);
}
}
AddThis Social Bookmark Button

Retrieve Database Table Names

July 1st, 2008 admin Posted in Java Comments Off


import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.util.HashSet;
import java.util.Set;

public class TableNames {

public static void main(String[] args) {
	Connection conn = null;
	try {
		conn = getConnection();
		Object tableNames[] = getTableNames(conn).toArray();
		for (int i=0; i<tableNames.length; i++) {
			System.out.println(tableNames[i]);
		}
	} catch (Exception e) {
		e.printStackTrace();
	} finally {
		try {
			if (conn!=null) {
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

public static Connection getConnection() throws Exception {

	Connection conn = null;
	String driverName = "org.hsqldb.jdbcDriver";
	String databaseUrl = "jdbc:hsqldb:hsql://mymachine:9001/mydatabase";
	String user = "username";
	String pwd = "password";
	Driver driver = (Driver) Class.forName(driverName).newInstance();
	DriverManager.registerDriver(driver);
	conn = DriverManager.getConnection(databaseUrl, user, pwd);
	return conn;
}

public static Set<String> getTableNames(Connection conn) throws Exception
{
	Set<String> tableNames = new HashSet<String>();
	DatabaseMetaData dbMetaData = conn.getMetaData();
	ResultSet resultSet = null;
	try
	{
		resultSet = dbMetaData.getTables(null, getDefualtSchemaName(conn), "%", new String [] { "TABLE" });
		if(resultSet != null)
		{
			while(resultSet.next())
			{
				String tableName = resultSet.getString("TABLE_NAME");
				tableNames.add(tableName);
			}
		}
	}
	finally
	{
		if(resultSet != null)
		{
			resultSet.close();
		}
	}
	return tableNames;
}

public static String getDefualtSchemaName(Connection conn) {
	String defualtSchemaName = "public";
	try {
		DatabaseMetaData dbMetaData = conn.getMetaData();
		String url = dbMetaData.getURL();
		if (url.startsWith("jdbc:hsqldb")) {
			defualtSchemaName = "PUBLIC";
		} else if (url.startsWith("jdbc:postgresql")) {
			defualtSchemaName = "public";
		} else if (url.startsWith("jdbc:oracle")) {
			defualtSchemaName = "public";
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return defualtSchemaName;
}

}
AddThis Social Bookmark Button

Similar Posts