Monday, August 8, 2011

TIBCO BW custom functions


/************************************************************************************************
* Program : Util
* Description : Helper x-path functions
* Date : 02/12/04
* Author : arun.nagargoje@gmail.com
* Change History:
* Date/Change: 02/20/2011
************************************************************************************************/
import java.util.*;
import java.io.*;
import java.sql.*;
import java.net.*;
import java.security.*;
import java.math.BigInteger;
import com.tibco.sdk.*;

public class Util
{
//Initialization variables
static private Properties _props = new Properties();
static private final String PROCESS_NAME = "ProcessName";
static private Connection _conn = null;
static private Properties _errors = new Properties();
static private final String ARGUMENT_SEPARATOR = "%%"; //assumed that the length is 2

//Duplicate Checking
static private Properties _cmtable=null;
static int _radix = 16;
static String _file = "cmseq";

//GUID Generation
static private SecureRandom seeder;
static private int timeLow; //32 bits
static private int node; // 32 bits
static private String hexInetAddress; //32 bits
static private String thisHashCode; // 32 bits
static private String midValue;
        static private InetAddress inet;
static private int seednum = 0;
static private String lzeros = "0000000000000000000";
static private String currguid = "";


public static final String[][] HELP_STRINGS =
{
{"loadProps", "Load properties for a particular process id", "loadProps($_processContext/ProcessId, 'myprocessname', 'c:\\sf\\propertyfiles\\process.cfg','Env,,Service','DEV,,7500',',,')" },
{"cleanProps", "Unload properties for a particular process id", "cleanProps($_processContext/ProcessId)" },
{"getProcessName", "Get process definition name for a particular process id", "getProcessName($_processContext/ProcessId)" },
{"getProperty", "Get property for a particular process id", "getProperty($_processContext/ProcessId, 'name')", "value" },
{"setProperty", "Set property for a particular process id", "setProperty($_processContext/ProcessId, 'name', 'value')" },
{"addMessage", "Add code, category and description to in-memory hashtable", "addMessage(exceptioncode, category, description)" },
{"getCategory", "Retrieve category for a given exception code", "getCategory(exceptioncode)", "category" },
{"getDescription", "Retrieve Description for a given exception code", "getDescription(exceptioncode, 'arg1,,arg2', ',,')", "description" } ,
{"removeEntryFromDuplicateFile", "Remove a sequence number entry from the duplicate check file.", "removeEntryFromDuplicateFile('SF.DEV.TEST', '1020394994E202030', 'portal')", "true"},
{"isDuplicate", "Check if the incoming message is duplicate message based on the subject, sender and sequence.", "isDuplicate('SF.DEV.TEST', POSDetail,'1020394994E202030')", "false"},
{"setDuplicateCheckFilePath", "Set the location where the duplicate check file is stored.", "setDuplicateCheckFilePath('c:\\dupmsg')", "true" },
{"trackingId", "Create and return a TIBCO SDK Tracking ID", "trackingId", "unqiue identifier" },
{"getGUID", "Create and return a globally unique identifier", "getGUID()", "a unique hex string" },
{"getPIDs", "Returns a comma separated list of process ids running in the engine", "getGUID()", "a unique hex string" }
};

static
{
        try
{
            inet = InetAddress.getLocalHost();
            byte[] bytes = inet.getAddress();
            hexInetAddress = formatIpAddress(bytes);
            seeder = new SecureRandom();
            thisHashCode = formatHashCode(System.identityHashCode(new Object()), 4);
            node = seeder.nextInt();
        }
catch (Exception e)
{
            e.printStackTrace();
        }
    }

    /**
     * Initialze the properties --- names & values are default properties
     *
     */
public static boolean loadProps(String pkey, String names, String values, String sep)
{
try
{
if (_props.get(pkey)!=null)
{
return false;
}

Properties keyProps = new Properties();

StringTokenizer stNames = new StringTokenizer(names, sep);
StringTokenizer stValues = new StringTokenizer(values, sep);

while (stNames.hasMoreTokens())
{
String defName = (String)stNames.nextToken();

//System.out.println("Name=" + defName);
String defValue = (String)stValues.nextToken();
if ("BLANKS".equals(defValue))
{
defValue="";
}
//System.out.println("Value=" + defValue);

keyProps.put(defName, defValue);
}

keyProps.put("INITIALIZED", "true");

/*
File f = new File(filePath);
if (f.exists())
{
FileInputStream fstream = new FileInputStream(f);
keyProps.load(fstream);
fstream.close();
}
*/
_props.put(pkey, keyProps);
return true;

}
catch (Exception e)
{
e.printStackTrace();
throw new RuntimeException(e.toString() + ":" + e.getMessage());
}
}


/**
     * Cleanup Properties
     *
     */
public static boolean cleanProps(String pkey)
{
_props.remove(pkey);
return true;
}

/**
     * Get Property
     *
     */
public static String getProperty(String pkey, String key)
{
if (_props.get(pkey)==null)
{
return "-1";
}
Properties props = (Properties) _props.get(pkey);
if (props.containsKey(key))
{
return props.getProperty(key);
}
else
return "-1";
}

public static boolean setProcessName(String pid, String pName)
{
return setProperty(pid, PROCESS_NAME, pName);
}

public static String getProcessName(String pid)
{
try{
return getProperty(pid, PROCESS_NAME);
}
catch(Exception e)
{
return "-1";
}
}

/**
     * Set Property
     *
     */
public static boolean setProperty(String pkey, String key, String value)
{
Properties props;
if (_props.get(pkey)==null)
{
props = new Properties();
_props.put(pkey, props);
}
props = (Properties) _props.get(pkey);
props.setProperty(key, value);
return true;
}


public static boolean addMessage(String code, String category, String description)
{
try
{
Properties m = new Properties();
m.put("CATEGORY", category);
m.put("DESCRIPTION", description);

_errors.put(code, m);
return true;
}
catch (Exception e)
{
e.printStackTrace();
throw new RuntimeException(e.toString() + ":" + e.getMessage());
}
}

public static String getCategory(String code)
{
try
{
Properties m = (Properties)_errors.get(code);
return (String)m.get("CATEGORY");
}
catch (Exception e)
{
e.printStackTrace();
throw new RuntimeException(e.getMessage());
}
}

public static String getDescription(String code, String args, String sep)
{
try
{
StringTokenizer st = new StringTokenizer(args, sep);
Properties m = (Properties)_errors.get(code);
if (m==null)
{
System.out.println("Invalid code:" + code);
}
String desc = (String)m.get("DESCRIPTION");
if (st.countTokens()<=0)
{
return desc;
}
else
{
StringTokenizer stP = new StringTokenizer(desc, ARGUMENT_SEPARATOR, true);
String newDesc="";
String argsub = ARGUMENT_SEPARATOR.substring(0, 1);

while (stP.hasMoreTokens())
{
String token = stP.nextToken();
//System.out.println("Token=" + token);
if (token.equals(argsub))
{
stP.nextToken();
String nextToken = stP.nextToken();
while (!(nextToken = stP.nextToken()).equals(argsub) && stP.hasMoreTokens());
stP.nextToken();
//if (!stP.hasMoreTokens()) throw new Exception("Invalid Message Description");
newDesc += st.nextToken();
}
else newDesc += token;
}
return newDesc;
}
}
catch (Exception e)
{
System.out.println("exception occured here");
e.printStackTrace();
throw new RuntimeException(e.toString() + ":" + e.getMessage());
}
}

    /**
     * Set the physical location of duplicate check file.
     *
     */
public static boolean setDuplicateCheckFilePath(String filePath)
{
_file = filePath;
return true;
}

    /**
     * Remove an existing Sequence Entry from the duplicate check file.
     *
     */
public static boolean removeEntryFromDuplicateFile(String subject, String sender, String seqno)
{
try
{
if (sender==null)
{
sender="";
}
if (subject==null || subject.equals(""))
{
throw new RuntimeException("Input subject cannot be blank");
}
String key = subject + "-" + sender;
String obj = (String) _cmtable.getProperty(key);
if (obj!=null)
{
_cmtable.remove(key);

FileOutputStream out = new FileOutputStream(_file);
_cmtable.store(out, null);
out.close();
}
return true;
}
catch (Exception e)
{
            e.printStackTrace();
throw new RuntimeException(e.toString() + ":" + e.getMessage());
//return false;
}
}

    /**
     * Checks for duplicate messages.
     *
     */
public static boolean isDuplicate(String subject, String sender, String seqno)
{
try
{
if (sender==null)
{
sender="";
}
if (subject==null || seqno==null || subject.equals("") || seqno.equals(""))
{
throw new RuntimeException("Input subject or seqno cannot be blank");
}
boolean dup = false;
if (_cmtable==null)
{
_cmtable = new Properties();
File f = new File(_file);
if (f.exists())
{
FileInputStream fstream = new FileInputStream(f);
_cmtable.load(fstream);
fstream.close();
}
}
String key = subject + "-" + sender;
String obj = (String) _cmtable.getProperty(key);

BigInteger seqnum = new BigInteger(seqno, _radix);

if (obj!=null)
{
BigInteger objint = new BigInteger(obj, _radix);
if(objint.compareTo(seqnum) >= 0) dup = true;
}

if (!dup || obj==null)
{
//String sseq = String.valueOf(seqnum);
_cmtable.put(key, seqno);
FileOutputStream out = new FileOutputStream(_file);
_cmtable.store(out, null);
out.close();
}
return dup;
}
catch (Exception e)
{
e.printStackTrace();
throw new RuntimeException(e.toString() + ":" + e.getMessage());
//return false;
}
}

    private static String formatString(String instr, int length) throws NumberFormatException
{      
        int len = instr.length();

//System.out.println("len=" + len + ",length=" + length);
        if (len <= length) {
            for (int i = 0; i < (length - len); i++) {
                instr = "0" + instr;
            }
            return instr;
        } else
            return instr.substring(len - length);      
    }


    private static String formatHashCode(int hashCode, int length) throws NumberFormatException
{      
        String intStr = Integer.toHexString(hashCode);
        int len = intStr.length();

//System.out.println("len=" + len + ",length=" + length);
        if (len <= length) {
            for (int i = 0; i < (length - len); i++) {
                intStr = "0" + intStr;
            }
            return intStr;
        } else
            return intStr.substring(len - length);      
    }
   
    private static String formatIpAddress(byte[] bytes) throws NumberFormatException
{
        String str = "";
        for (int i = 0; i < bytes.length; i++) {
            String tmp = Integer.toHexString(bytes[i]);
            if (null == tmp) {
                tmp = "00";
            } else if (tmp.length() < 2) {
                tmp = "0" + tmp;
            }
           
            str = str + tmp;
        }
//System.out.println("IP Address=" + str);
        return str;
    }

    public static long timestamp()
    {
return System.currentTimeMillis();
    }


    public static synchronized String trackingID()
    {
com.tibco.sdk.MTrackingInfo mInfo = new com.tibco.sdk.MTrackingInfo();
        return mInfo.getTrackingId();
    }

    public static synchronized String getPIDs()
    {

        if (_props==null) return "";
String ret="";
  for (Enumeration e=_props.keys(); e.hasMoreElements();)
{
ret = ret + (String)e.nextElement() + ",";
}
ret = ret.substring(0, ret.length()-1);
return ret;
    }


    public static synchronized boolean store(String key, String value)
    {

if (_props==null) _props=new Properties();
        if (_props.get(key)==null)
{
Properties props1 = new Properties();
_props.put(key, props1);
}
Properties props = (Properties)_props.get(key);
if (props.get("count")==null)
{
props.put("count", new Integer(0));
}
int num = ((Integer)props.get("count")).intValue();
props.put("count", new Integer(num+1));

if (props.get("values")==null)
{
Vector v1 = new Vector();
props.put("values", v1);
}
Vector v = (Vector)props.get("values");
v.add(value);


return true;
    }

    public static synchronized String cleanstore(String key)
    {
if (_props==null) return "true";
        if (_props.get(key)==null) return "true";
Properties props = (Properties)_props.get(key);
props.put("count", new Integer(0));
if (props.get("values")!=null)
{
Vector v = (Vector)props.get("values");
v=null;
}
//props.put("values", null);
return "true";

    }

    public static synchronized String getNext(String key)
    {

if (_props==null) return "";
        if (_props.get(key)==null)
{
return "";
}
Properties props = (Properties)_props.get(key);
if (props.get("pointer")==null)
{
props.put("pointer", new Integer(0));
}
int index = ((Integer)props.get("pointer")).intValue();
int num = ((Integer)props.get("count")).intValue();
if (index > num) return "END";
props.put("pointer", new Integer(index+1));

if (props.get("values")==null)
{
return "";
}
Vector v = (Vector)props.get("values");
return (String)v.get(index);
    }

    public static synchronized String getCount(String key)
    {

if (_props==null) return "";
        if (_props.get(key)==null)
{
return "0";
}
Properties props = (Properties)_props.get(key);
if (props.get("count")==null)
{
return "0";
}
int num = ((Integer)props.get("count")).intValue();
return "" + num;
     }


    /**
     * Gets a globally unique identifier
     *
     */
    public static synchronized String getGUID()
{
        String ret = null;
        try
{          
            long timeNow = System.currentTimeMillis() << 8;

            node = seeder.nextInt();
            ret = hexInetAddress.substring(0,8) +
formatString(Long.toHexString(timeNow), 16) +
//formatHashCode(timeLow, 8) +
thisHashCode +
formatHashCode(node, 4);

String newret = ret.substring(0,22);
//System.out.println("currguid=" + currguid);
//System.out.println("ret     =" + newret);
if (currguid.equals(newret))
{
int timeLow = Integer.parseInt(ret.substring(22,24), _radix);
//System.out.println("timeLow=" + timeLow);
ret = ret.substring(0,22) + formatString(Integer.toHexString(++seednum+timeLow),2) + ret.substring(24);
}
else
seednum = 0;

currguid = ret.substring(0,22);

        }
catch (Exception e)
{
            e.printStackTrace();
throw new RuntimeException(e.toString() + ":" + e.getMessage());
        }
        return ret;
    }

public static String getMachineName()
{
return inet.getHostName();
}

public static String getIPAddress()
{
return inet.getHostAddress();
}

public static void main(String[] args)
{

try
{
//readErrorTable("sun.jdbc.odbc.JdbcOdbcDriver", "jdbc:odbc:ORACLE", "tibco", "tibco", "en-us", "BW");

/* Initialization Tests */
/*
Util.addMessage("INVALID_PRODUCT", "CAT1", "Invalid Product ID %%PRODUCTID%% and Product Name %%NAME%% problem");
Util.addMessage("DOES_NOT_EXIST", "CAT1", "%%ID%% does not exist");
Util.addMessage("INVALID_PRODUCT_1", "CAT1", "Invalid Product ID %%ID%%");
System.out.println(Util.getDescription("INVALID_PRODUCT", "", ""));
System.out.println(Util.getDescription("INVALID_PRODUCT", "1234,,MILK", ",,"));
System.out.println(Util.getDescription("DOES_NOT_EXIST", "", ""));
System.out.println(Util.getDescription("DOES_NOT_EXIST", "1234", ",,"));
System.out.println(Util.getDescription("INVALID_PRODUCT_1", "1234", ",,"));

Util.loadProps("1234", "testproc", "z:/dump/test.cfg", "c,,d,,e","33,,BLANKS,,44",",,");
Util.loadProps("1234", "testproc", "z:/dump/test.cfg", "","","");
System.out.println("a=" + Util.getProperty("1234", "a"));
System.out.println("b=" + Util.getProperty("1234", "b"));
System.out.println("name=" + Util.getProcessName("1234"));
System.out.println("c=" + Util.getProperty("1234", "c"));
Util.cleanProps("1234");
*/

/* GUID Generation */

System.out.println(getGUID());
System.out.println(getGUID());
System.out.println(getGUID());
String oldguid="";
String newguid=getGUID();
for (int i=0;i<10;i++ )
{
oldguid = newguid;
newguid = getGUID();
if(newguid.equals(oldguid)) System.out.println("ERROR>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
System.out.println(newguid);
}

/* Duplicate Checking */


String newID = getGUID();
System.out.println(Util.isDuplicate("SF.DEV.TEST", "sender1", newID));
System.out.println(Util.isDuplicate("SF.DEV.TEST", "sender1", newID));
System.out.println(Util.isDuplicate("SF.DEV.TEST1", "sender1", newID));
System.out.println(Util.isDuplicate("SF.DEV.TEST1", "sender2", newID));
for (int i=0; i<20;i++ )
{
String guid=getGUID();
System.out.println("Check Duplicate for " + guid + "=" + Util.isDuplicate("SF.DEV.TEST", "sender1", guid));
}


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

Saturday, November 20, 2010

XML Schema For Table Creation

<?xml version='1.0' encoding='UTF-8' ?>

<!ELEMENT TABLE (TR* , TD* , TH* , TABLE*)>

<!ATTLIST TABLE  BORDER CDATA  '1'
                   WIDTH  CDATA  '100%' >
<!ELEMENT TH (FONT? , TD* , TR* , TABLE*)>

<!ELEMENT TD (FONT? , TD* , TR* , TABLE*)>

<!ELEMENT TR (FONT? , TD* , TH* , TABLE*)>

<!ATTLIST TR  ALIGN CDATA  #IMPLIED >
<!ELEMENT FONT (#PCDATA)>

<!ATTLIST FONT  COLOR CDATA  '#0000' >

Saturday, October 16, 2010

tibco scripted deployment

To Generate Configuration XML Use this:
$TIBCO_HOME/tra/5.4/bin/AppManage -export -out ../$2.xml -app $1/$2 -cred domain.properties -domain $DOMAIN

Thursday, September 30, 2010

Find The PID-Port In UNIX Without lsof

#P (PID con Port)
# v1.07 20/05/2008 sam@unix.ms
#
# If you have a Solaris 8, 9 or 10 box and you can't
# install lsof, try this. It maps PIDS to ports and vice versa.
# It also shows you which peers are connected on which port.
# Wildcards are accepted for -p and -P options.
#
# The script borrows Eric Steed's excellent "getport.sh" script.
#
if [ $# -lt 1 ]
then
echo >&2 "usage: $0 [-p PORT] [-P PID] [-a ALL ] (Wildcards OK)"
exit 1
fi
while getopts :p:P:a opt
do
case "${opt}" in
p ) port=${OPTARG};;
P ) pid=${OPTARG};;
a ) all=all;;
[?]) # unknown flag
echo >&2 "usage: $0 [-p PORT] [-P PID] [-a ALL ] (Wildcards OK) "
exit 1;;
esac
done
shift `expr $OPTIND - 1`
if [ $port ]
then
# Enter the port number, get the PID
#
port=${OPTARG}
echo "PID\tProcess Name and Port"
echo "_________________________________________________________"
for proc in `ptree -a | grep -v ptree | awk '{print $1};'`
do
result=`pfiles $proc 2> /dev/null| grep "port: $port"`
if [ ! -z "$result" ]
then
program=`ps -fo comm -p $proc | tail -1`
echo "$proc\t$program\t$port\n$result"
echo "_________________________________________________________"
fi
done
elif [ $pid ]
then
# Enter the PID, get the port
#
pid=$OPTARG
# Print out the information
echo "PID\tProcess Name and Port"
echo "_________________________________________________________"
for proc in `ptree -a | grep -v ptree | grep $pid| awk '{print $1};'`
do
result=`pfiles $proc 2> /dev/null| grep port:`
if [ ! -z "$result" ]
then
program=`ps -fo comm -p $pid | tail -1`
echo "$proc\t$program\n$result"
echo "_________________________________________________________"
fi
done
elif [ $all ]
then
# Show all PIDs, Ports and Peers
#
echo "PID\tProcess Name and Port"
echo "_________________________________________________________"
for pid in `ptree -a | grep -v ptree |sort -n | awk '{print $1};'`
do
out=`pfiles $pid 2>/dev/null| grep "port:"`
if [ ! -z "$out" ]
then
name=`ps -fo comm -p $pid | tail -1`
echo "$pid\t$name\n$out"
echo "_________________________________________________________"
fi
done
fi
exit 0

Wednesday, September 29, 2010

SFTP With com.jcraft.jsch

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
import com.jcraft.jsch.UserInfo;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Properties;
import java.util.Vector;
import org.apache.log4j.Logger;

public class SCPUtil
{
  private static final Logger _logger = Logger.getLogger(SCPUtil.class);

  static FileInputStream utilConf = null;
  static Properties props = null;

  public static void main(String[] args) {
    if (args.length < 1)
    {
      System.out.println("Usage SCPUtil <config file name> ");
    }
    else
    {
      System.out.println("Property File " + args[0]);
      try {
        utilConf = new FileInputStream(new File(args[0]));
        props = new Properties();
        props.load(utilConf);
        String server = props.getProperty("hostname");
        String loginId = props.getProperty("login");
        System.out.println(server);
        String passwd = props.getProperty("passowrd");
        String localdrv = props.getProperty("localdrv");
        String remotedrv = props.getProperty("remotedrv");
        String file = props.getProperty("file");

        get(server, loginId, passwd, localdrv, remotedrv, file);
      } catch (FileNotFoundException e) {
        e.printStackTrace();
      } catch (IOException e) {
        e.printStackTrace();
      }
      catch (Exception e) {
        e.printStackTrace();
      }
    }
  }

  public static void get(String server, String loginId, String passwd, String localdrv, String remotedrv, String file)
    throws Exception
  {
    boolean downloadStatus = false;
    Session session = null;
    try
    {
      JSch jsch = new JSch();
      System.out.println(loginId);
      session = jsch.getSession(loginId, server, 22);
      UserInfo ui = new MyUserInfo();
      session.setUserInfo(ui);
      session.setPassword(passwd);
      session.connect();
      session.getHost();
      session.getHostKey();
      _logger.info("Connected to [" + server + "] with login " + loginId);
      Channel channel = session.openChannel("sftp");
      channel.connect();
      _logger.info("Connected to Server :::" + server);
      ChannelSftp c = (ChannelSftp)channel;
      c.cd(remotedrv);
      _logger.info("Remote address " + remotedrv);
      Vector lst = c.ls(remotedrv);
      for (int i = 0; i < lst.size(); i++)
      {
        ChannelSftp.LsEntry le = (ChannelSftp.LsEntry)lst.get(i);
        _logger.info("if dirctory :::" + le.getAttrs().isDir());
        if (le.getAttrs().isDir())
          continue;
        String fName1 = le.getFilename();
        _logger.info("fName1::::" + fName1);
        System.out.println("file name " + fName1);
        if (!fName1.equals(file))
          continue;
        downloadStatus = true;
        _logger.info("Downloading" + fName1);
        System.out.println("Downloading file name ::" + fName1);
        c.get(fName1, localdrv);
        String name = null;
        System.out.println("Downloaded file name ::" + fName1);
      }

      if (!downloadStatus)
        throw new Exception("File not Found in Remote Directory", new FileNotFoundException());
      c.quit();
    }
    catch (SftpException e) {
      _logger.fatal("Problem with SFTP -" + e.getMessage());
      throw e;
    } catch (JSchException e) {
      _logger.fatal("Problem with Connection  -" + e.getMessage());
      throw e;
    }
    catch (Exception e) {
      _logger.fatal("Unknown Exception -" + e.getMessage());
      throw e;
    }
    finally
    {
      if (session != null)
        session.disconnect();
    }
  }

  public static class MyUserInfo
    implements UserInfo
  {
    public String getPassphrase()
    {
      return null;
    }

    public String getPassword()
    {
      return null;
    }

    public boolean promptPassword(String a)
    {
      return true;
    }

    public boolean promptPassphrase(String a)
    {
      return true;
    }

    public boolean promptYesNo(String a)
    {
      return true;
    }

    public void showMessage(String s)
    {
    }
  }
}