Showing posts with label java example. Show all posts
Showing posts with label java example. Show all posts

Tuesday, February 23, 2010

Command line Reader Sample

import java.io.*;
import java.lang.*;

public class DecimalToOctal {
public static void main(String[] args) throws IOException{
BufferedReader buff = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the decimal number:");
String deci = buff.readLine();
int value = Integer.parseInt(deci);
String str = Integer.toString(value,8);
System.out.println("octal:=" + str);
}
}

Monday, February 22, 2010

Blocking Queue Sample

import java.util.*;
import java.util.concurrent.*;
import java.io.*;


public class BlockingQueue {
    private static List waitingCustomerList = null;
    private static final String filePath = "/home/serkans/phoneNumbersOnly.txt";
    private static ArrayBlockingQueue waitingCustomersQueue = null;


    public static void main (String[] args)  {


        loadNumbers();


        initializeBlockingQueue();


        Runnable callcenterGirl = new Runnable (){
            public void run () {
                while (true) {


                 String phoneNumber = null;
                 try {
                     phoneNumber = waitingCustomersQueue.poll (10000L, TimeUnit.MILLISECONDS);
                     if (null != phoneNumber){
                         System.out.println (" -- Callcenter girl is helping to : " + phoneNumber);
                     }else{
                         System.out.println ( " -- Callcenter girl is waiting  : " + phoneNumber);
                     }
                 } catch (InterruptedException ex) {
                     System.out.println ("  -- Callcenter girl is interrupted ex:");
                     ex.printStackTrace();
                 }
             }


         }
        };


        Thread t = new Thread (callcenterGirl);
        t.start();




    }


    private static ArrayBlockingQueue initializeBlockingQueue () {
        try {
            waitingCustomersQueue = new ArrayBlockingQueue(waitingCustomerList.size (), true, waitingCustomerList);
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(1);
        }
        return waitingCustomersQueue;
    }


    private static void loadNumbers () {
        Properties props = new Properties();
        try {
            props.load (new FileInputStream (new File (filePath)));
            System.out.println (" -- item count in file is :" + props.size());
            waitingCustomerList = new ArrayList (props.keySet());
        } catch (IOException ex) {
            System.out.println (" -- Unable to find file : "+filePath);
        }
    }
}

Wednesday, February 17, 2010

Are you sickened with QUARTZ database ??

import java.io.*;
import java.util.*;

public class WorkHourChecker {

private final static long MILLSECS_PER_HOUR = 1L * 60L * 60L * 1000L;

public static void main (String[] args) throws IOException, InterruptedException {
String workHours = "2-5,19-23,14-15";
checkTimeAndWork (workHours);
System.exit(0);
}

private static void checkTimeAndWork (String workHours) throws InterruptedException,
NumberFormatException {
Date now = new Date();
boolean isWorkhour = false;
StringTokenizer hoursTokenizer = new StringTokenizer(workHours,",");

while (hoursTokenizer.hasMoreTokens()) {
String duration = (String) hoursTokenizer.nextElement();
StringTokenizer durationTokenizer = new StringTokenizer(duration,"-");
int startHour = -1;
int endHour = -1;
while (durationTokenizer.hasMoreElements()) {
startHour = Integer.parseInt((String)durationTokenizer.nextElement()) ;
endHour = Integer.parseInt((String)durationTokenizer.nextElement()) ;
}
if (now.getHours() >= startHour && now.getHours() <= endHour){
isWorkhour = true;
break;
}else{
isWorkhour = false;
}

}

if (isWorkhour){
System.out.println ("-- In the work hours ..");
doSomeBusiness ();
System.out.println ("-- I am very tired i will get some rest!!");
Thread.currentThread().sleep (MILLSECS_PER_HOUR);
checkTimeAndWork (workHours);
}else{
System.out.println(" -- Not in the work hours yet, sleep 1 hour");
Thread.currentThread().sleep (MILLSECS_PER_HOUR);
checkTimeAndWork (workHours);
}
}

private static void doSomeBusiness (){
System.out.println (" -- I have started to work..");
}

}

Monday, February 15, 2010

Sample Jmeter Java Test

package sunels;

import java.io.Serializable;
import org.apache.jmeter.protocol.java.sampler.*;
import org.apache.jmeter.config.Arguments;
import org.apache.jmeter.protocol.java.sampler.JavaSamplerContext;
import org.apache.jmeter.samplers.SampleResult;
import java.util.List;
import java.util.Properties;
import java.io.IOException;
import java.util.ArrayList;
import java.io.FileInputStream;
import com.mycompany.myproduct.um.msgstore.MessagestoreFactory;
import com.mycompany.myproduct.um.profile.ProfileFactory;
import java.util.Date;
import com.mycompany.myproduct.um.common.Language;
import com.mycompany.myproduct.um.profile.Subscriber;
import java.util.Random;

public class JmeterTest implements JavaSamplerClient , Serializable {

private static List msisdns = new ArrayList();
private static int totalRecordCount = 0;
private static java.util.Date startDate = new java.util.Date();
private static final String umModuleName = "UM";
private ProfileFactory profilefactory = ProfileFactory.getInstance (umModuleName);
private MessagestoreFactory msgstoreFactory = MessagestoreFactory.getInstance (umModuleName);
private Random randomGenerator = new Random();
private static int testType = 1;

static {
try {
Properties props = new Properties();
props.load (new FileInputStream ("/tmp/phoneNumbers.txt"));
msisdns = new ArrayList (props.keySet());
totalRecordCount = msisdns.size();
System.out.println (" -- Msisdns are loaded ....");
}
catch (IOException e) {
e.printStackTrace ();
System.exit (1);
}
}

public void setupTest(JavaSamplerContext context) {
}

public Arguments getDefaultParameters() {
Arguments params = new Arguments();
return params;
}

public synchronized String getMsisdn (){
String subscriberMsisdn = (String) msisdns.get(randomGenerator.nextInt(totalRecordCount));
return subscriberMsisdn;
}

public Subscriber playWithSubscriber (String subscriberPhoneNumber) throws Exception {
Subscriber subscriber = null;
subscriber = (Subscriber) profilefactory.querySubscriberByPhoneNumber (profilefactory.getCommonFactory ().createPhoneNumber (subscriberPhoneNumber));

if (subscriber != null) {
if(testType != 1){
Language subscriberLanguage = subscriber.getLanguage ();
if (subscriberLanguage == Language.ENGLISH) {
subscriber.setLanguage (Language.UKRAINIAN);
}
else {
subscriber.setLanguage (Language.ENGLISH);
}
Date currDate = new java.util.Date ();
subscriber.getSubscription ().setLastLoginDate (currDate);
subscriber.getSubscription ().setLastMessageActivityDate (currDate);
subscriber.save ();
}
}
else {
System.out.println (" -- Unable to find subscriber with msisdn :" + subscriberPhoneNumber);

}
return subscriber;
}

public SampleResult runTest(JavaSamplerContext context) {
SampleResult results = new SampleResult();
results.sampleStart();
String msisdn = getMsisdn();
try{

playWithSubscriber (msisdn);
results.setSuccessful(true);
results.setResponseCodeOK();
results.setResponseMessage("Subscriber found:" + msisdn);
} catch (Exception ex){
ex.printStackTrace();
results.setSuccessful(true);
results.setResponseCode("Exception*");
results.setResponseMessage("Subscriber not found:" + msisdn);
}
results.sampleEnd();
return results;
}

public void teardownTest(JavaSamplerContext context) {
}
}

Executing some jobs in parallel

import java.util.*;
import java.io.*;

public class Test {

public static void main (String[] args) {
Runnable r = new Runnable () {

public void run () {
while (true) {
try {
System.out.println ("-- this lines are being printed in another thread.."+Thread.currentThread().getName());
Thread.currentThread().sleep(130);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
};

new Thread (r).start();
while (true) {
System.out.println (" -- this lines are bing printed in main thread.."+Thread.currentThread().getName());
try {
Thread.currentThread ().sleep (60);
} catch (InterruptedException ex) {
//noop
}
}
}
}

-- this lines are being printed in another thread..Thread-0
-- this lines are bing printed in main thread..main
-- this lines are bing printed in main thread..main
-- this lines are bing printed in main thread..main
-- this lines are being printed in another thread..Thread-0
-- this lines are bing printed in main thread..main
-- this lines are bing printed in main thread..main
-- this lines are being printed in another thread..Thread-0
-- this lines are bing printed in main thread..main
-- this lines are bing printed in main thread..main
-- this lines are being printed in another thread..Thread-0
-- this lines are bing printed in main thread..main
-- this lines are bing printed in main thread..main
-- this lines are being printed in another thread..Thread-0

Tuesday, February 9, 2010

Built In Java Tools & JProfiler

List Java Processes
[serkans@serkanslnx smartconnect] jps -l
16563 sun.tools.jps.Jps
8765 ReporterGeneratePdf
Getting Thread Dump of a process with the given id

[root@serkanslnx telco]# jstack 1009
Attaching to process ID 1009, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 1.5.0_10-b03

Thread 1079: (state = IN_NATIVE)
- java.lang.UNIXProcess.waitForProcessExit(int) @bci=0 (Interpreted frame)
- java.lang.UNIXProcess.access$900(java.lang.UNIXProcess, int) @bci=2, line=20 (Interpreted frame)
- java.lang.UNIXProcess$1$1.run() @bci=165, line=132 (Interpreted frame)

JVM Arguments for Profiling and Debugging
-Xdebug -Xrunjdwp:transport=dt_socket,address=1980,server=y,suspend=n
OR
-Xdebug -Xrunjdwp:transport=dt_socket,address=1980,server=y,suspend=y

JVM_ARGS and LD_LIBRARY_PATH for JProfiler Debugging
-Xint -Xrunjprofiler:port=8849 -Xbootclasspath/a:/space/tools/jprofiler3/bin/agent.jar
and also
export LD_LIBRARY_PATH=/opt/jprofiler3/bin/linux-x86:$LD_LIBRARY_PATH