Monthly Archives: February 2012

JAVA : StAX Basics : XMLStreamWriter

Source Code

package test;

import java.io.File;
import java.io.FileWriter;

import javax.xml.stream.*;
import javax.xml.stream.XMLOutputFactory;

public class XmlWriter {
	public static void main(String[] args) throws Exception {		
		XMLOutputFactory outputFactory = XMLOutputFactory.newInstance();
		FileWriter output = new FileWriter(new File("hb1.xml"));
		XMLStreamWriter writer = outputFactory.createXMLStreamWriter(output);
		writer.writeStartDocument();
		writer.writeStartElement("agiml");
		writer.writeStartElement("header");
		writer.writeEndElement();
		writer.writeEndElement();
		writer.flush();
		writer.close();
	}

}

Xml File : hb1.xml

<?xml version="1.0" ?><agiml><header></header></agiml>

JAVA : StAX basics : XMLEventReader

Source Code

package test;

import java.io.InputStream;
import java.io.FileInputStream;
import java.io.File;

import javax.xml.stream.*;
import javax.xml.stream.XMLInputFactory;

public class XmlReader {
	public static void main(String[] args) throws Exception {
		XMLInputFactory inputFactory = XMLInputFactory.newInstance();
		InputStream input = new FileInputStream(new File("hb.xml"));
		XMLEventReader reader = inputFactory.createXMLEventReader(input);
		while (reader.hasNext()) {
			System.out.println(reader.next().toString());
		}
	}
}

Output

<?xml version="1.0" encoding='UTF-8' standalone='no'?>
<agiml>

	
<header>

		
<interface>
HEART_BEAT
</interface>

	
</header>


</agiml>
ENDDOCUMENT

XML File : hb.xml

<?xml version="1.0" ?>
<agiml>
	<header>
		<interface>HEART_BEAT</interface>
	</header>
</agiml>

JAVA : Tomcat DataSources

How to create a MySQL DB Connection pool with Tom Cat

Inside META-INF folder create context.xml file and add following lines

<?xml version="1.0" encoding="UTF-8"?>
<Context>
	<!-- Test datasource -->
	<Resource name="jdbc/test" auth="Container" type="javax.sql.DataSource"
		username="root" password="" driverClassName="com.mysql.jdbc.Driver"
		url="jdbc:mysql://localhost:3306/test" maxActive="2" maxIdle="1" />
</Context>

Inside WEB-INF folder open web.xml and add following lines (Child of web-app element)

<resource-ref>
    <description>Factory for java.sql.Connection</description>
    <res-ref-name>jdbc/test</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
  </resource-ref>

Usage


private static final String INIT_CONTEXT_LOOKUP = "java:/comp/env";
private static final String ENV_CONTEXT_LOOKUP = "jdbc/test";

public static Connection getConnection() {
		Connection connection = null;
		try {
			Context initContext = new InitialContext();
			Context envContext = (Context) initContext
					.lookup(INIT_CONTEXT_LOOKUP);
			DataSource dataSource = (DataSource) envContext
					.lookup(ENV_CONTEXT_LOOKUP);
			return dataSource.getConnection();
		} catch (Exception ex) {
			log.error("connection", ex);
		}
		return connection;
	}

JAVA : Socket Basics – Loop

Server.java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

	private int port = 45234;
	ServerSocket serverSocket;
	Socket clientSocket;
	private PrintWriter out;
	private BufferedReader in;
	private String inputLine;
	private String outputLine;

	private void start() {
		try {
			serverSocket = new ServerSocket(port);
			clientSocket = serverSocket.accept();
			out = new PrintWriter(clientSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(
					clientSocket.getInputStream()));
			while ((inputLine = in.readLine()) != null) {
				if (inputLine.equals("bye")) {
					out.println("closing");
					break;
				}
				out.println("srv: " + inputLine);
			}
			System.out.println("server closing");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				in.close();
				clientSocket.close();
				serverSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Server().start();
	}

}

Client.java


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {

	private int port = 45234;
	private Socket clientSocket;
	private PrintWriter out;
	private BufferedReader in;
	private BufferedReader stdIn;
	private String inputLine;
	private String outputLine;
	private void start() {

		try {
			clientSocket = new Socket("localhost", port);
			out = new PrintWriter(clientSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(
					clientSocket.getInputStream()));
			stdIn = new BufferedReader(new InputStreamReader(System.in));
			while ((inputLine = stdIn.readLine()) != null) {
				out.println(inputLine);
				outputLine = in.readLine();
				if(outputLine.equals("closing")) {
					break;
				}
				System.out.println(outputLine);
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				out.close();
				in.close();
				stdIn.close();
				clientSocket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		new Client().start();
	}

}

JAVA : Socket Basics

Server

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class TestServer {
	private ServerSocket serverSocket;
	private Socket clientSocket;
	private PrintWriter out;
	private BufferedReader in;
	private String inputLine;
	private String outputLine;

	public void runServer() {
		try {
			serverSocket = new ServerSocket(55556);
			clientSocket = serverSocket.accept();
			out = new PrintWriter(clientSocket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(
					clientSocket.getInputStream()));
			out.println("Test Server...");
		} catch (Exception ex) {
			System.err.println("err in server");
		} finally {
			try {
				out.close();
				in.close();
				clientSocket.close();
				serverSocket.close();
			} catch (Exception e) {				
				System.err.println("err res closing in server");
			}
		}
	}

	public static void main(String[] args) {
		new TestServer().runServer();
	}

}

Client

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class TestClient {

	Socket socket;
	PrintWriter out;
	BufferedReader in;
	String fromServer;

	public void runClient() {
		try {
			socket = new Socket("myComp", 55556);
			out = new PrintWriter(socket.getOutputStream(), true);
			in = new BufferedReader(new InputStreamReader(
					socket.getInputStream()));
			if ((fromServer = in.readLine()) != null) {
				System.out.println("from server" + fromServer);
			}
		} catch (Exception e) {
			System.err.println("err in client");
		} finally {
			try {
				out.close();
				in.close();
				socket.close();
			} catch (Exception e) {
				System.err.println("err res closing in client");
			}
		}
	}

	public static void main(String[] args) {
		new TestClient().runClient();
	}

}

Change myComp to your Computer name, to find the name of your computer run following code.

String computername = InetAddress.getLocalHost().getHostName();

Original Reference
All About Sockets – Oracle Tutorials

JAVA : JAXB Basics

import java.io.FileReader;
import java.io.FileWriter;
import java.io.Writer;

import javax.swing.text.StyledEditorKit.BoldAction;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement(name = "dog")
@XmlType(propOrder = { "name", "owner" })
public class Dog {

	private String name;
	private String owner;

	@XmlElement(name = "dogoName")
	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getOwner() {
		return owner;
	}

	public void setOwner(String owner) {
		this.owner = owner;
	}

	public static void main(String[] args) {
		Dog dog = new Dog();
		dog.setName("pinky");
		dog.setOwner("sam");
		Writer wrt = null;
		try {
			JAXBContext cntx = JAXBContext.newInstance(Dog.class);
			Marshaller mrsh = cntx.createMarshaller();
			mrsh.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
			wrt = new FileWriter("./doggy.xml");
			// mrsh.marshal(dog, System.out);
			mrsh.marshal(dog, wrt);
			Unmarshaller umrsh = cntx.createUnmarshaller();
			Dog doggy = (Dog) umrsh.unmarshal(new FileReader("./doggy.xml"));
			System.out.println("name: " + doggy.getName());
			
		} catch (Exception e) {
		} finally {
			if (wrt != null) {
				try {
					wrt.close();
				} catch (Exception e) {
				}
			}
		}

	}

}

And if you want to disable xml declaration

mrsh.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);

Original Reference
vogella
and
stackoverflow

PHP : First Unit Test

Code to be tested

// Check.php
class Check {
	public function spitFalse() {
		return false;
	}	
	public function spitTrue() {
		return true;
	}
}

Test Code

// CheckTest.php
require_once('Check.php');
class CheckTest extends PHPUnit_Framework_TestCase
{
	public function setUp(){ }
	public function tearDown(){ }
	public function testSpitFalse() {
		$chk = new Check();
		$this->assertFalse($chk->spitFalse());
	}	
	public function testSpitTrue() {
		$chk = new Check();
		$this->assertTrue($chk->spitFalse());
	}
}

Run Test Code

phpunit CheckTest

Result

OK (2 tests, 2 assertions)

PHP : Installing PhpUnit

Execute CMD as administrator

Go to php directory

pear install phpunit/PHPUnit
(Optional)
pear channel-discover pear.phpunit.de
pear install --alldeps phpunit/PHPUnit