10 Minute Mail

Have you ever wanted to have an e-mail for 10 minutes? Just to activate a subscription or receive a coupon. Well, I came across 10 Minute Mail which does that.. pretty nice…

Leave a Comment

Amazon S3 and EC2

This post will probably be a work in progress. But this will serve as a collection of references and examples on Amazon S3 and EC2. A nice example to show (and give you a feeling for) what we can do with the S3 and EC2 combo can be seen here.

Leave a Comment

Convert Dos files to Unix

A cool little utility to convert dos files to unix files: dos2unix. This is a substitute for a more complex tr or awk commands.

Note: to get utility in Unix Mint (or Ubuntu), you need to: sudo apt-get install tofrodos

Leave a Comment

Get Resource

What is the difference between:

this.getClass().getResource and this.getClass().getClassLoader().getResource

for ClassLoader getResource, the API explains:

getResource

public URL getResource(String name)
Finds the resource with the given name. A resource is some data (images, audio, text, etc) that can be accessed by class code in a way that is independent of the location of the code.
The name of a resource is a ‘/’-separated path name that identifies the resource.

This method will first search the parent class loader for the resource; if the parent is null the path of the class loader built-in to the virtual machine is searched. That failing, this method will invoke findResource(String) to find the resource.

Parameters:
name – The resource name
Returns:
A URL object for reading the resource, or null if the resource could not be found or the invoker doesn’t have adequate privileges to get the resource.
Since:
1.1

while

I will let the unit test explain:

package blog.resource;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import junit.framework.TestCase;

public class TestResource extends TestCase {

	public void setUp() {
		try {
			/*
			 * create a properties file in a directory at the top package level
			 * our package is blog.resource, we are creating a directory @
			 * the blog package level
			 */
			if (!new File("bin/config/aResourse.properties").exists()) {
				boolean dirSuccess = (new File("bin/config")).mkdir();
				if (dirSuccess) {
					boolean success = (new File(
							"bin/config/aResourse.properties")).createNewFile();
				}
			}
			/*
			 * create a properties file in a directory at the *.class level
			 */
			if (!new File("bin/blog/resource/config/aResourse.properties")
					.exists()) {
				boolean dirSuccess = (new File("bin/blog/resource/config"))
						.mkdir();
				if (dirSuccess) {
					boolean success = (new File(
							"bin/blog/resource/config/aResourse.properties"))
							.createNewFile();
				}
			}

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

	public void testGetClassLoaderGetResource() {
		/*
		 * class loader looks at the top class level (with blog package as a
		 * base) or any where in the classpath
		 */
		URL ourResource = this.getClass().getClassLoader().getResource(
				"config/aResourse.properties");
		assertEquals(ourResource.getFile(),
				"/C:/Users/Zaid/workspace/TestPrograms/bin/config/aResourse.properties");
	}

	public void testGetResource() {
		/*
		 * if we add "/" then it would look at the root (similar to classloader)
		 */
		URL ourResource = this.getClass().getResource(
				"config/aResourse.properties");
		System.out.println(ourResource.getFile());
		assertEquals(
				ourResource.getFile(),
				"/C:/Users/Zaid/workspace/TestPrograms/bin/blog/resource/config/aResourse.properties");
	}
}

Leave a Comment

ActiveMQ Security Plugin

This is an ActiveMQ security plugin -which I worked on sometime ago- developed to provide dynamic authentication and authorization capabilities such as:

1. User names added/deleted/modified dynamically to ActiveMQ server.
2. User passwords can be changed modified dynamically
3. User passwords are encrypted
4. Automatic detection of security updates to the security file containing credentials and permissions (authentication and authorization)
5. Queues added/deleted/modified dynamically to the ActiveMQ server.
6. Queue permissions added/modified dynamically to the ActiveMQ server

The code is written under Apache License 2.0.

You can browse the source and the documentation @ http://code.google.com/p/z-activemq-security-plugin/

The plugin is currently tested on ActiveMQ 5.1

Thanks to http://ttmsolutions.com/ for their ActiveMQ guide

Leave a Comment

Securing JasperServer Database Passwords

1. Change context.xml in C:\Program Files\jasperserver-3.1\apache-tomcat\webapps\jasperserver\META-INF:

    <Resource name="jdbc/jasperserver" auth="Container" type="javax.sql.DataSource"
        maxActive="100" maxIdle="30" maxWait="10000"
            username="jasperdb" password="enenenenenen" driverClassName="com.mysql.jdbc.Driver"
			factory="com.isone.tomcat.TomcatEncrypt"
            url="jdbc:mysql://127.0.0.1:3306/jasperserver?useUnicode=true&amp;characterEncoding=UTF-8"/>

2. Create a class:

import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.Name;

import org.apache.tomcat.dbcp.dbcp.BasicDataSource;

public class TomcatEncrypt extends
		org.apache.tomcat.dbcp.dbcp.BasicDataSourceFactory
{
	public Object getObjectInstance(Object obj, Name name, Context nameCtx,
			Hashtable environment) throws Exception
	{
		Object o = super.getObjectInstance(obj, name, nameCtx, environment);
		if (o != null)
		{
			BasicDataSource ds = (BasicDataSource) o;
			if (ds.getPassword() != null &amp;&amp; ds.getPassword().length() &gt; 0)
			{
				String pwd = unscramblePassword(ds.getPassword());
				ds.setPassword(pwd);
			}
			return ds;
		} else
		{
			return null;
		}
	}

	private String unscramblePassword(String password)
	{
		// TODO Auto-generated method stub
		return "password";
	}
}

3. Place the JAR file of the class (1.5 Java) in a folder on the classpath e.g. C:\Program Files\jasperserver-3.1\apache-tomcat\common\lib

4. Restart JasperServer

note: when it fails, it fails

Thanks to http://stackoverflow.com/questions/129160/how-to-avoid-storing-passwords-in-the-clear-for-tomcats-server-xml-resource-defi

Leave a Comment

Dynamically updating a JTextArea

1. First, define your objective clearly.

My objective is to update a JTextArea frequently on a sequential basis. Say: add a word every 2 seconds to the JTextArea without any trigger from the user.

2. Analyse your objective.

As Swing is (mostly) event driven, we can update the JTextArea with an event but this is not our objective. Our update for the Text Area has to leave the actionPerformed call, otherwise the UI will become unresponsive.

So we need somehow to run this task in a new thread and have this thread update the UI.

3. Code it.

TextAreaUpdate.java

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;

public class TextAreaUpdate implements ActionListener{

	JTextArea tArea = null;
	JButton jBut = null;
	JFrame jFrame = null;
	JPanel jPanel = null;

	private void setUpTextArea()
	{
		tArea = new JTextArea(20,100);
		jPanel = new JPanel();
		jBut = new JButton("Start");
		tArea.setText("this is an initial content: ");
		tArea.setEditable(false);
		tArea.setLineWrap(true);
		jPanel.add(tArea);
		jPanel.add(jBut);
		jBut.addActionListener(this);
		jFrame = new JFrame();
		jFrame.add(jPanel);
		jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jFrame.pack();
		jFrame.setVisible(true);
	}

	@Override
	public void actionPerformed(ActionEvent arg0) {
		// TODO Auto-generated method stub
		tArea.append("We will start updating the text area ");
		updateTextAreaContinuously();
	}

	private void updateTextAreaContinuously() {
		UpdateThread ut = new UpdateThread(tArea);
		Thread t = new Thread(ut);
		t.start();
		System.out.println("thread is off to work");
	}

	public static void main(String[] args)
	{
		TextAreaUpdate taUpdate = new TextAreaUpdate();
		taUpdate.setUpTextArea();
	}
}

UpdateThread.java

import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class UpdateThread implements Runnable {

	JTextArea tArea = new JTextArea();

	UpdateThread(JTextArea jt) {
		tArea = jt;
	}

	public void run() {
		for (int i = 0; i < 10; i++) {
			Runnable aRunnable = new Runnable() {
				public void run() {
					tArea.append("Hello from inside the EDT ");
				}
			};
			SwingUtilities.invokeLater(aRunnable);
			try {
				Thread.sleep(2000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

Leave a Comment

Modal

Swing is event driven (in contrast to sequential or conditional execution of code). There is a way to make Swing behave in a kind-of sequential way. That is using JDialog and setting modal to true.

An example:

import javax.swing.*;

public class TestDialogModal {

	public TestDialogModal() {
	}

	public boolean processLogin() {
		JDialog loginObj = new JDialog();
		loginObj.setTitle("Login");
		loginObj.setLocation(350, 300);
		loginObj.setModal(true);

		JLabel label = new JLabel("Username");
		JTextField username = new JTextField(10);
		JLabel labelpassword = new JLabel("Password");
		JPasswordField password = new JPasswordField(10);

		JPanel myPanel = new JPanel();
		myPanel.add(label);
		myPanel.add(username);
		myPanel.add(labelpassword);
		myPanel.add(password);
		loginObj.setContentPane(myPanel);
		loginObj.pack();
		loginObj.setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
		loginObj.setVisible(true);

		//Will only be printed after we close the window
		System.out.println("This will only be printed once window is closed");
		return true;
	}

	public static void main(String[] args) {
		try {
			TestDialogModal mainObj = new TestDialogModal();
			mainObj.processLogin();
			System.exit(0);
		} catch (Exception e) {
			e.printStackTrace();
			System.exit(1);
		}
	}
}

Leave a Comment

My First JFreeChart Program

I had my first encounter with JFreeChart and I was impressed. It was simple, productive.

The process to design and create a chart is a 3-step process:

1. create a dataset
2. populate a dataset
3. create a chart
4. draw the chart to some target output

We needed to provide an ability to drill down within charts, say it’s a daily chart and we you click on a specific hour, we expect a 5 minute chart for that hour and so on.

This was acheived by adding a listener chartMouseClicked and parsing the ChartMouseEvent Object with getEntity().getToolTipText(). Once data was acquired, by using substring, the new graph would be drawn.

The graphs could also retrieve its data from a database. A major plus for the JFreeChart.

This should serve as a short example for using JFreeChart:

import org.jfree.data.general.DefaultPieDataset;
import org.jfree.chart.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;

public class MyFirstChart implements ChartMouseListener {
	JFrame chartFrame = new JFrame();
	JPanel chartPanel;
	JPanel firstPanel;
	boolean firstTime = true;

	public void chart(String type1, String type2, String type3, double val1,
			double val2, double val3) {
		// create a dataset
		// note: there are different Dataset values
		// such as:
		// DefaultPieDataset: Pie charts
		// DefaultCategoryDataset: for line charts
		// XYSeriesCollection: also for line charts
		// :it holds mutiple XYSeries (mutiple lines)
		// :it is casted to XYDataSet
		// TimeSeriesCollection: for dates and numbers (X: date, Y: a number)
		// : will contain one or more TimeSeries

		DefaultPieDataset dataset = new DefaultPieDataset();

		// note: the below numbers are fraction of a chart whose area if equal
		// to the sum of all so the first would be: 10.2 out of (10.2 + 27.9 +
		// 19.5)

		dataset.setValue(type1, val1);
		dataset.setValue(type2, val2);
		dataset.setValue(type3, val3);

		// create a chart
		JFreeChart chart = ChartFactory.createPieChart("Select One!", // title
				dataset, // pass the dataset
				true, // legend?
				true, // tooltips?
				false // URLs?
				);

		// we will use ChartPanel to display the chart
		// ChartPanel extends JPanel
		// get the panel
		ChartPanel chartPanel = new ChartPanel(chart);

		// add a mouse listener to the panel (only can be added to the panel)
		chartPanel.addChartMouseListener(this);

		JFrame chartFrame = new JFrame();
		chartFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		chartFrame.getContentPane().add(chartPanel, BorderLayout.CENTER);
		chartFrame.pack();
		chartFrame.setVisible(true);
	}

	public static void main(String[] args) {
		try {
			// Set cross-platform Java L&amp;F (also called "Metal")
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (Exception e) {
			// handle exception
			e.printStackTrace();
		}
		MyFirstChart myChart = new MyFirstChart();
		myChart.chart("Apples", "Oranges", "Donuts", 10, 18, 10);
	}

	public void chartMouseClicked(ChartMouseEvent chartMouseEvent) {
		String type = chartMouseEvent.getEntity().getToolTipText().substring(0,
				chartMouseEvent.getEntity().getToolTipText().indexOf(":"))
				.trim();

		if (type.compareTo("Apples") == 0) {
			chart("Red Apples", "Green Apples", "Yellow Apples", 12.2, 13.6,
					44.5);
		} else if (type.compareTo("Oranges") == 0) {
			chart("Florida Oranges", "California Oranges", "Local Oranges",
					22.2, 23.6, 24.5);
		} else if (type.compareTo("Donuts") == 0) {
			chart("Chocolate Frosted", "Apple Donuts", "Boston Creme", 22.2,
					33, 14.5);
		}
	}

	public void chartMouseMoved(ChartMouseEvent chartMouseEvent) {
	}
}

Leave a Comment

To JUnit a Hierarchical Database

I was inspired recently by ‘Pragmatic Unit Testing’ to perform unit testing during my development process. In my work space, I work usually with Habitat databases which is an hierarchical database provided by Areva.

The method which I wanted to test would get a password from a habitat database. This database would store all passwords, URLs, usernames, etc needed for application: JMS, Oracle, SFTP, etc.

My first led me to consider building the whole Habitat database in Java (which took me on some intriguing trails with all ending with “It can’t be this hard”). The fact is it isn’t. It then came to me that mock objects are just that: mock objects; they are disposable objects which are meant to perform one task.

So to actually test my method, I started with a mock object until I realized that all I need is some arrays. Since we read the contents of the habitat database into arrays. After structuring the arrays, I needed to inject them into the object. Since these are not values which are meant to be ’set’, no ’set’ and ‘get’ methods were implemented. Note that injecting those values into objects without a ’set’ method will be affected by the access modiefiers.

But to continue on my first thought, we can test a database query by creating a the result and returning it. For example, if the query says: “select * from some_table”, we can create a ResultSet and return that with the expected output (say: lastname = ‘Mohammed’, etc). True, that might need testing…

The main refactoring done was to include an empty constructor.

After this experiment, Junit is starting to look more applicable. I will leave you with the test.

import junit.framework.TestCase;

/**
* TestWooph class:
*
* @author: ztuffaha
* Date: Feb 9, 2009
* Time: 2:21:10 PM
*/
public class WoophTest extends TestCase {
	Wooph w = null;

	public WoophTest(String method) {
		super(method);
	}

	public void setUp() throws WoophException {
		int[] parentArray = { 1, 1, 1, 2, 3, 3 };
		String[] idArray = { "URL", "PASSWORD", "USERNAME", "URL",
				"PASSWORDTESTPROG", "USERNAMETESTPROG" };
		String[] dataArray = {
				"http://crwapdv2/crowapi/service.asmx",
				"password123",
				"crow_web_service@ne.com",
				"jdbc:oracle:thin:asdgf/asdf123@(description=(FAILOVER=ON)...(connect_data=  (service_name=fcstdbd.world)))",
				"password12345", "test" };
		// injecting the arrays into an object
		w = new Wooph();
		w.parentArray = parentArray;
		w.idArray = idArray;
		w.dataArray = dataArray;
		w.indexOfProg = 2;
		w.connectionType = "TESTPROG";
	}

	public void testGetPassword() throws Exception {
		assertEquals("password12345", w.getPassword());
	}
}

Leave a Comment

Older Posts »