Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Wednesday, June 16, 2010

Glassfish v2 Cluster,HA, Load-balancing

I happen to come accross this link which explains Cluster/Load-balancing(Sun Java System Web server 7.0)/HA on Glassfish v2 in a single page. There is sample app called 'clusterjsp' which tests the cluster setup too.


Monday, June 15, 2009

Java.Util.Logging Example

This example is a simple illustration for using Java.Util.Logging. Java.Util.logging comes with J2SE.

create the following directory structure

->loggingdemo
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp|->Main.java
&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp|->logging.properties

logging.properties

# Java Logging Properties
# Author : Deepak Dhanukodi
handlers=java.util.logging.FileHandler, java.util.logging.ConsoleHandler
# Default global logging level.
.level=SEVERE
# Loggers.
loggingdemo.level=ALL
# --- ConsoleHandler ---
# Override of global logging level
java.util.logging.ConsoleHandler.level=ALL
java.util.logging.ConsoleHandler.formatter=java.util.logging.SimpleFormatter
# --- FileHandler ---
# Override of global logging level
java.util.logging.FileHandler.level=ALL
java.util.logging.FileHandler.formatter=java.util.logging.SimpleFormatter
# Unlimiting size for output file
java.util.logging.FileHandler.limit=0
# Number of output files to cycle through, by appending an
# integer to the base file name:
java.util.logging.FileHandler.count=1
# Append to already existing file
java.util.logging.FileHandler.append=true
java.util.logging.FileHandler.pattern=system.log

Main.java

package loggingdemo;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.logging.Filter;
import java.util.logging.Level;
import java.util.logging.LogManager;
import java.util.logging.LogRecord;
import java.util.logging.Logger;

/**
* Java.utils.logging Demo
* @author Deepak Dhanukodi
*/
public class Main {
static String LOGGING_PROPERTIES = "loggingdemo/logging.properties";
private LogManager logManager;
private Logger logger;
/**
* @param args the command line arguments
*/
public void initialize() throws IOException
{
logManager = LogManager.getLogManager();
Properties prob = new Properties();
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(LOGGING_PROPERTIES);
logManager.readConfiguration(inputStream);
logger = Logger.getLogger(this.getClass().getName());
}
public void log()
{
logger.log(Level.WARNING, "I have hit a warning here.");
logger.warning("Same warning again");
//User defined filter
Filter filter= new Filter() {

public boolean isLoggable(LogRecord record) {
// Allow only FINE and filter the rest
if(Level.FINE == record.getLevel())
return true;
return false;
}
};
Filter oldFilter = logger.getFilter();
logger.setFilter(filter);
logger.severe("You can't reach me.");
logger.finer("You can't reach me, either.");
logger.fine("Horray,I am through.");
logger.setFilter(oldFilter);
logger.severe("You can reach me.");
logger.finer("You can reach me, either.");
logger.fine("Horray,I am through,again.");
}
public static void main(String[] args) throws IOException {
Main main = new Main();
// Initialize logger
main.initialize();
main.log();
}
}

Run

D:\>javac /loggingdemo/Main.java -d .

D:\>java -cp . loggingdemo.Main
15 Jun, 2009 5:10:53 PM loggingdemo.Main log
WARNING: I have hit a warning here.
15 Jun, 2009 5:10:53 PM loggingdemo.Main log
WARNING: Same warning again
15 Jun, 2009 5:10:53 PM loggingdemo.Main log
FINE: Horray,I am through.
15 Jun, 2009 5:10:53 PM loggingdemo.Main log
SEVERE: You can reach me.
15 Jun, 2009 5:10:53 PM loggingdemo.Main log
FINER: You can reach me, either.
15 Jun, 2009 5:10:53 PM loggingdemo.Main log
FINE: Horray,I am through,again.

D:\>

system.log

This log file is created in the same dir where you had executed java process.

15 Jun, 2009 5:10:53 PM loggingdemo.Main log
WARNING: I have hit a warning here.
15 Jun, 2009 5:10:53 PM loggingdemo.Main log
WARNING: Same warning again
15 Jun, 2009 5:10:53 PM loggingdemo.Main log
FINE: Horray,I am through.
15 Jun, 2009 5:10:53 PM loggingdemo.Main log
SEVERE: You can reach me.
15 Jun, 2009 5:10:53 PM loggingdemo.Main log
FINER: You can reach me, either.
15 Jun, 2009 5:10:53 PM loggingdemo.Main log
FINE: Horray,I am through,again.

Saturday, June 9, 2007

Commanding Threads in Java


Following are source to command threads in java

Command.java

package tekzgeek.thread;

public class Command
{
public static int PAUSE=0;
public static int RESUME=1;
public static int EXIT=2;
int state=RESUME;
int command=RESUME;

synchronized public int getCommand()
{
if(this.state==this.command)
return this.state;

if((this.state==RESUME)&&(this.command==PAUSE))
{
this.state=PAUSE;
notify();
while((this.command!=Command.RESUME)&&(this.command!=Command.EXIT))
{
try
{
wait();
}
catch(InterruptedException e)
{}
}
if(this.command==Command.RESUME)
this.state=Command.RESUME;
else if(this.command==Command.EXIT)
this.state=Command.EXIT;


}
else if((this.state==Command.RESUME)&&(this.command==Command.EXIT))
{
this.state=Command.EXIT;
notify();
}
return this.state;
}

synchronized public void setCommand(int command_temp)
{
this.command=command_temp;

if(state==command)
return;

if((this.state==Command.RESUME)&&(this.command==Command.PAUSE))
{
while(this.state!=Command.PAUSE)
{
try
{
wait();
}
catch(InterruptedException e)
{}
}
}
else if((state==PAUSE)&&(command==RESUME))
{
notify();
}
else if((this.state==Command.RESUME)&&(this.command==Command.EXIT))
{
while(this.state!=Command.EXIT)
{
try
{
wait();
}
catch(InterruptedException e)
{}
}
}
else if((this.state==Command.PAUSE)&&(this.command==Command.EXIT))
{
notify();
}
}
}

WorkerThread.java
package tekzgeek.thread;
import tekzgeek.thread.Command;

public class WorkerThread extends Thread
{
Command command;
public WorkerThread(Command command)
{
this.command=command;
}
public void run()
{
boolean EXIT=false;
while(!EXIT)
{
// Do Some Work

System.out.println("Worker Thread Running.");
try
{
Thread.sleep(200);
}catch(InterruptedException e)
{}

int cmd=command.getCommand();
if(cmd==Command.EXIT)
EXIT=true;
}
System.out.println("I am done.");

}
}

Main.java
package tekzgeek.thread;
import tekzgeek.thread.Command;
import tekzgeek.thread.WorkerThread;

public class Main
{
public static void main(String args[])throws InterruptedException
{
Command command=new Command();
WorkerThread workerThread=new WorkerThread(command);
workerThread.start();

Thread.sleep(1000);

System.out.println("Main Thread is trying to Pause Worker Thread.");
command.setCommand(Command.PAUSE);
System.out.println("Main Thread Paused Worker Thread.");

Thread.sleep(1000);

System.out.println("Main Thread is trying to Resume Worker Thread.");
command.setCommand(Command.RESUME);
System.out.println("Main Thread Resumed Worker Thread.");

Thread.sleep(1000);

System.out.println("Main Thread is trying to Stop Worker Thread.");
command.setCommand(Command.EXIT);
System.out.println("Main Thread stopped Worker Thread.");
}
}


Command.java- The basic core for transfering messages between threads.
Main.java- Main Thread that commands Worker Thread.
WorkerThread.java- This thread does the work and is controlled by Main Thread.

pl note : One way command is only implemented. To go for two way communication or for feedback,create
one more command for getting feedback from worker thread.

Configure Log4j/ Log4j Example


Steps to configure Log4j and to run a simple application are
1. Download Log4j from http://www.apache.org/
2. Extract all the contents to a directory.
3. In the directory find the jar file log4j-X.X.XX.jar under directory \dist\lib. Make sure ur class path points to this jar file.
4. Create a file named Log4jDemo.java and put the following contents in it.

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;


public class Log4jDemo
{
static Logger logger = Logger.getLogger(Log4jDemo.class);
public static void main(String args[])
{
PropertyConfigurator.configure("log4j.properties"); // or u can use file name with path eg. D:\\Demo\\log4j.properties
logger.debug("DEBUG Message");
logger.info("INFO Message");
logger.warn("WARN Message");
logger.error("ERROR Message");
logger.fatal("FATAL Message");
}

}

5. Create a new file named log4j.properties at the same directory where u have put the Log4jDemo.class file. Put the following contents in to it.


log4j.rootLogger=DEBUG, MF ,CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.CONSOLE.layout.ConversionPattern=[%t] %C at %L %-5p %c %x - %m%n

log4j.appender.MF=org.apache.log4j.RollingFileAppender
log4j.appender.MF.File=Main.log

log4j.appender.MF.MaxFileSize=100KB
# Keep one backup file
log4j.appender.MF.MaxBackupIndex=1

log4j.appender.MF.layout=org.apache.log4j.PatternLayout
log4j.appender.MF.layout.ConversionPattern=[%t] %C at %L %-5p %F (%L) %c %x - %m%n

6.Now when u run the Log4jDemo.java u get a console ouput and also saved to a file called Main.log

Writing a Content to a file in Java


import java.io.*;

public class FileWriterDemo
{
public static void main(String args[]) throws FileNotFoundException,IOException
{
File file=new File("Demo.txt"); // or u can use file name with path eg. D:\\Demo\\Demo.txt
if(!file.exists())
file.createNewFile();

BufferedWriter out = new BufferedWriter(new FileWriter(file,true));// true flag tells us to append to the exiting file.
out.write("Hello World.");
out.newLine();
out.close();
}

}
Save above contents in a file called FileWriterDemo.java

Reading a Content of a file in java


import java.io.*;

public class FileReaderDemo
{
public static void main(String args[]) throws FileNotFoundException,IOException
{
File file1=new File("Demo.txt"); // or u can use file name with path eg. D:\\Demo\\Demo.txt
BufferedReader in = new BufferedReader(new FileReader(file1));
String str;
while ((str = in.readLine()) != null) {
System.out.print(str);
}
in.close();
}

}

Save above contents in a file called FileReaderDemo.java