Saturday, July 28, 2012

Simple Parsing Scripts

-------------------------------------------------------------------
1) Simple perl script to extract ip address from ipconfig command:


#!/usr/bin/perl

use File::Find;
use File::Copy;
use File::Path;

system ("ipconfig > test.txt");

$filename = "test.txt";
$strToFind = "IPv4";

open(INFILE, $filename) || die "Cannot open file";

$matchFound = 0;

while ($line = )
{
   if ($line =~ /$strToFind/)
    {
      print "$line";
      $matchFound = 1;
    }
}

close(INFILE);

print "\n";

if ($matchFound eq 1)
{
    print "$strToFind was found: $matchFound \n";
}
else
{
    print "$strToFind not found in $filename \n";
}


-----> Simple Ruby Script to parse IP address from ipconfig command <------------


--------------------------------------------------------------------------------------
2) Simple VB Script to parse MAC address and ip address from ipconfig command:

' VBScript Source File 
'
' NAME: myIPfunc.vbs
'
' AUTHOR: Swati Kher
'
' COMMENT: How to parse IPConfig command with vbscript 
'======================================================

Option Explicit


wscript.echo "Mac Address = ["& GetMac() & "]"

wscript.quit(0)

' ********************************************************************************************
' ******** GetMac ********
' ********************************************************************************************

Function GetMac()

   Dim WshShell, oExec , physaddr, macaddr, ipaddr
   Dim iLocation, name, strInputFile, iLoc2, name2

   Dim FSO, objFile
   Dim strLine

   Set WshShell = CreateObject("WScript.Shell") 

   set oExec = WshShell.Exec("cmd.exe /c ipconfig /all")

   physaddr = oExec.StdOut.ReadAll()
   name    = "Physical Address"
   name2   = "IPv4 Address"
   macaddr = "tbd"
  

   iLocation = InStr (physaddr, name)
   iLoc2 = InStr(physaddr, name2)
   
   
   WScript.Echo iLocation
   
   if (iLocation) then

       macaddr = Right(physaddr, Len(physaddr)  - iLocation)
       ipaddr = Right(physaddr, Len(physaddr) - iLoc2)
       
       'WScript.Echo "First Pass: " & macaddr
       iLocation = InStr (1, macaddr, ":")
       iLoc2 = InStr(1, ipaddr, ":")
       
       macaddr = Right(macaddr, Len(macaddr) - iLocation)
       ipaddr = Right(ipaddr, Len(ipaddr) - iLoc2)
       
       Trim(macaddr)
       Trim(ipaddr)
       
       'WScript.Echo "Second : " & macaddr
       'macaddr = Right(macaddr, Len(macaddr) - 17)
       iLocation = InStr (1, macaddr, vbNewLine)
       iLoc2 = InStr(1, ipaddr, vbNewLine)
       
       macaddr = Left(macaddr, iLocation)
       ipaddr = Left(ipaddr, iLoc2)
       
       macaddr = replace(macaddr, "-", "")
       GetMac = macaddr
       'WScript.Echo "Mac address " & macaddr
       WScript.Echo "IP ADDR: " & ipaddr

   end If

   GetMac = macaddr
   set WshShell = Nothing
   Set oExec = Nothing
End Function

------------------------------------------------------
3)  C++ functions to check palindromes and matching strings:


bool isItPali(char *a)
{
int length, mid, j;
    bool match = true;


if (a==NULL)
{
cout<<"Got a NULL String!!"<
return false;
}

length = strlen(a)-1;
mid = length/2;
j = 0;

if (strlen(a)==1)
{
cout<<"Only 1 char!!"<
return true;
}

if (length<=0)
{
cout<<"String was blank!!"<
return false;
}


    while(j<= mid)
{
if (*(a+j) != *(a+length-j))
match = false;
j++;
}


  return match;
}


bool ExpressionMatch(char *a, char *b)
{
int lenA, lenB, i, j, indWld;
bool match = false, done = false;

lenA = strlen(a);
lenB = strlen(b);

i = j = indWld = 0;

    if ((lenA == 0) || (lenB == 0))
return false;


while (!done)
{
if (*(b + j) == '*')
{
j++;
indWld = j;
}
else if (*(b + j) == *(a+i))
{
match = true;
j++;
i++;
}
else if(*(b+j) != *(a+i))
{
i++;
match = false;
if (indWld == 0)
i = lenA;
else if (i< lenA)
j= indWld;
}
if (indWld == lenB)
{
done = true;
if (indWld == 1)
match = true;
}
if (i == lenA)
done = true;
}

return match;
}
-----------------------------------------------------------
4) Java code to compute string LCM

import java.util.*;
import java.util.regex.*;

public class LCMstr {

/**
* @param args
*/
public static String lcm(String a, String b) {
int c = a.length();
int d = b.length();
if (a.charAt(c-1)==b.charAt(0)) {
return(a.concat(b.substring(1))); 
}
if (c >= d) {
    if (a.contains(b)) return a;
}
if (d > c) {
if (b.contains(a)) return b;
}
return a.concat(b);
//System.out.println(a.charAt(0));
//System.out.println("len" + c + a.charAt(c-1));
   //return "err";
}
public static void main(String[] args) {

LCMstr l = new LCMstr();
        System.out.println( l.lcm("ab", "bacd"));
        System.out.println( l.lcm("abcc", "cd"));
        System.out.println( l.lcm("ab", "bad"));
        System.out.println( l.lcm("aba", "abacd"));
        System.out.println(l.lcm("x1", "1x"));
        System.out.println(l.lcm("swati", "1swati"));
        System.out.println(l.lcm("swati1", "swati"));
        System.out.println(l.lcm("x1", "x2"));
        System.out.println(l.lcm("ab", "ab"));
}

}
--------------------------------------------------------
5) java code to compute LCM of two numbers:

public class myLCM {
private void calculateLCM(int x, int y) {

        int lcm = x*y/getGCD(x, y);

        System.out.println(lcm);

 }


private int getGCD(int x, int y) {

       // Make sure, n1 is the bigger number

       int n1 = x > y ? x : y;

       int n2 = x > y ? y : x;

       while(n1%n2 != 0) {

              int remainder = n1%n2;

              n1 = n2;

              n2 = remainder;
       }

       return n2;

}


    public static void main(String[] argv) {

        myLCM x = new myLCM();
        
        x.calculateLCM(2, 3);
        x.calculateLCM(8, 16);
        x.calculateLCM(3,15);
        //x.calculateLCM(10,0);
        x.calculateLCM(11,12);
        x.calculateLCM(15, 20);
        x.calculateLCM(17, 51);

 }
}
---------------------------------------------




Friday, July 27, 2012

Example of Simple HTTPClient in Java


/* compile the following in eclipse : run as java application with the simpleHTTPServer listening on port 5000 (from previous example) */

/* to compile the following external jars are required: commons-codec-1.5.jar, commons-httpclient-3.0.1.jar
              commons-logging-1.1.1.jar, commons-logging-1.1.1-adapters.jar, commons-logging-1.1.1-api.jar
             commons-logging-1.1.1-tests.jar, jackson-core-asl-1.9.2.jar, json-20080701.jar, log4j-1.2.15.jar
              and log4j-1.2.16-sources.jar */

import org.apache.*;
import javax.xml.parsers.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import org.w3c.dom.*;
import org.json.*;
import org.xml.sax.*;
import java.io.*;
import java.net.*;
import java.util.*;
import javax.xml.transform.stream.StreamResult;
import javax.xml.ws.http.HTTPException;
import org.apache.log4j.*;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.methods.EntityEnclosingMethod;
import org.apache.commons.httpclient.methods.PostMethod;

public class myClient {

public myClient() {
System.out.println("myclient");
Logger log = Logger.getLogger("wbs");
}

public Document getTemplateDocument(String fName) {
Document doc = null;
try {
DocumentBuilderFactory docFac = DocumentBuilderFactory.newInstance();

DocumentBuilder docBld = docFac.newDocumentBuilder();

if (!fName.equals(null)) {
File file = new File(fName);
doc = docBld.parse(file);
}
else {
System.out.println("null file");
}
}catch (ParserConfigurationException pce){
pce.printStackTrace();
}catch (IOException ioe) {
ioe.printStackTrace();
}catch (SAXException sxe) {
sxe.printStackTrace();
}
return doc;
}

public String convertDocToString(Document doc){
String xmls = null;

try {
Transformer trans = TransformerFactory.newInstance().newTransformer();
trans.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult res = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
trans.transform(source, res);
xmls = res.getWriter().toString();
}catch(TransformerConfigurationException tce){
tce.printStackTrace();
}catch(TransformerException te) {
te.printStackTrace();
}
return xmls;
}

public static String execReq(String xmls, String url) {
HttpClientParams cparam = new HttpClientParams();
DefaultHttpMethodRetryHandler retry_H = new DefaultHttpMethodRetryHandler();
cparam.setParameter(HttpClientParams.RETRY_HANDLER, retry_H);
cparam.setParameter(HttpClientParams.HEAD_BODY_CHECK_TIMEOUT, 600000);
cparam.setSoTimeout(600000);
cparam.setConnectionManagerTimeout(600000);
String strXMLFile = xmls;
File input = new File(xmls);
System.out.println("File length: " + input.length());
PostMethod post = null;
try {
post = new PostMethod(url);
HttpClient hc = new HttpClient();
hc.setConnectionTimeout(600000);
post.setRequestBody(new FileInputStream(input));
if (input.lastModified() < Integer.MAX_VALUE){
post.setRequestContentLength((int)input.length());
}
else {
post.setRequestContentLength(EntityEnclosingMethod.CONTENT_LENGTH_CHUNKED);
int stc = hc.executeMethod(post);
System.out.println(post.getResponseBodyAsString());
post.releaseConnection();
System.out.println("statusline: " + post.getStatusLine());
try {
Thread.sleep(100);
}catch(InterruptedException ie) {
System.out.println(ie.getMessage());
}
if(stc == HttpStatus.SC_OK) {
xmls = post.getResponseBodyAsString();
}else {
System.out.println(post.getStatusCode());
}
}
}catch(FileNotFoundException ffe) {
ffe.printStackTrace();
}catch(HTTPException he) {
he.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}finally {
post.releaseConnection();
}
return xmls;
}



public void sendtest() {
Document doc = getTemplateDocument("\\test.xml");
//String request = convertDocToString(doc);
//String response = execReq(request, "http://localhost:5000");

}




public static void main(String[] args) {
// TODO Auto-generated method stub

myClient mc = new myClient();
Document d = mc.getTemplateDocument("\\test.xml");
String request = mc.convertDocToString(d);
System.out.println(request);

        //File inp = new File(request);
     

PostMethod pos = null;
pos = new PostMethod("http://localhost:5000");
HttpClient hc = new HttpClient();
hc.setConnectionTimeout(600000);

try{
//pos.setRequestBody(new FileInputStream(inp));
   //pos.setRequestContentLength((int)inp.length());
 
int stc = hc.executeMethod(pos);
System.out.println(pos.getResponseBodyAsString());
pos.releaseConnection();
System.out.println("statusline: " + pos.getStatusLine());
}catch(HTTPException he) {
he.printStackTrace();
}catch(IOException ioe){
ioe.printStackTrace();
}finally {
pos.releaseConnection();
}
}

}

/* sample test message test.xml file  :

*/

Example of A Simple HTTP Server In Java


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

/* This code opens a PFINET TCP socket and listens over port 5000 - to communicate - see following
    client code or simply open a browser and go to http://localhost:5000  which should return HTTP OK code = 200 -> try to figure out how to generate the various error codes below for fun!! */

/* compile this code as follows:  javac myHTTPServer.java
                            then to run it:  java myHTTPServer
                                    To test:  open browser and go to http://localhost:5000  */

public class myHTTPServer extends Thread implements Runnable{


static final String HTML_START =
"" +
"HTTP Server in java" +
"";

static final String HTML_END =
"" +
   "";

  /** http://www.w3.org/Protocols/rfc2616/rfc2616.html **/
  /** 2XX: generally "OK" */
  public static final int HTTP_OK = 200;
  public static final int HTTP_CREATED = 201;
  public static final int HTTP_ACCEPTED = 202;
  public static final int HTTP_NOT_AUTHORITATIVE = 203;
  public static final int HTTP_NO_CONTENT = 204;
  public static final int HTTP_RESET = 205;
  public static final int HTTP_PARTIAL = 206;

  /** 3XX: relocation/redirect */
  public static final int HTTP_MULT_CHOICE = 300;
  public static final int HTTP_MOVED_PERM = 301;
  public static final int HTTP_MOVED_TEMP = 302;
  public static final int HTTP_SEE_OTHER = 303;
  public static final int HTTP_NOT_MODIFIED = 304;
  public static final int HTTP_USE_PROXY = 305;

 /** 4XX: client error */
  public static final int HTTP_BAD_REQUEST = 400;
  public static final int HTTP_UNAUTHORIZED = 401;
  public static final int HTTP_PAYMENT_REQUIRED = 402;
  public static final int HTTP_FORBIDDEN = 403;
  public static final int HTTP_NOT_FOUND = 404;
  public static final int HTTP_BAD_METHOD = 405;
  public static final int HTTP_NOT_ACCEPTABLE = 406;
  public static final int HTTP_PROXY_AUTH = 407;
  public static final int HTTP_CLIENT_TIMEOUT = 408;
  public static final int HTTP_CONFLICT = 409;
  public static final int HTTP_GONE = 410;
  public static final int HTTP_LENGTH_REQUIRED = 411;
  public static final int HTTP_PRECON_FAILED = 412;
  public static final int HTTP_ENTITY_TOO_LARGE = 413;
  public static final int HTTP_REQ_TOO_LONG = 414;
  public static final int HTTP_UNSUPPORTED_TYPE = 415;

  /** 5XX: server error */
  public static final int HTTP_SERVER_ERROR = 500;
  public static final int HTTP_INTERNAL_ERROR = 501;
  public static final int HTTP_BAD_GATEWAY = 502;
  public static final int HTTP_UNAVAILABLE = 503;
  public static final int HTTP_GATEWAY_TIMEOUT = 504;
  public static final int HTTP_VERSION = 505;


int count = 0;

/* create server socket here */

     Socket conn = null;
     BufferedReader inFromClient = null;
     DataOutputStream outToClient = null;

     public myHTTPServer (Socket client)
     {
         conn = client;
         count = 0;
     }

     public void sendFile(FileInputStream fin, DataOutputStream out) throws Exception {
    byte[] buffer = new byte[1024];
    int bytesRead;

    while ((bytesRead = fin.read(buffer)) != -1)
    {
out.write(buffer, 0, bytesRead);
}
fin.close();
}

     public void sendResponse (int statusCode, String resp, boolean isFile) throws Exception
     {

String statusLine = null;
String serverdetails = "Server: Java HTTPServer";
String contentLengthLine = null;
String fileName = null;
String contentTypeLine = "Content-Type: text/html" + "\r\n";
FileInputStream fin = null;

/* expand this code by providing a handler for each of the error codes above - this example only handles
    error code 200 success, 404 file not found, and 400 bad request  */

if (statusCode == 200) {
statusLine = "HTTP/1.1 200 OK" + "\r\n";
}
else if (statusCode == 404){
statusLine = "HTTP/1.1 404 Not Found" + "\r\n";
}
else {
statusLine = "HTTP/1.1 400 Bad Request" + "\r\n";
}

/* expand this if loop to add support for additional file extensions. */

         if (isFile)
         {
fileName = "c:" + "\\" + resp;
//System.out.println("fName: " + fileName);
fin = new FileInputStream(fileName);
System.out.println("isThere: " + fin.available());
contentLengthLine = "Content-Length: " + Integer.toString(fin.available()) + "\r\n";
if (!fileName.endsWith(".htm") && !fileName.endsWith(".html"))
   contentTypeLine = "Content-Type: \r\n";
if (fileName.endsWith(".jpg"))
   contentTypeLine = "Content-Type: image/jpeg\r\n";
if (fileName.endsWith(".gif"))
   contentTypeLine = "Content-Type: image/gif\r\n";
if (fileName.endsWith(".bmp"))
   contentTypeLine = "Content-Type: image/bmp\r\n";
if (fileName.endsWith(".txt"))
   contentTypeLine = "Content-Type: text/html\r\n";
if (fileName.endsWith(".exe"))
   contentTypeLine = "Content-Type: application/octet-stream";
if (fileName.endsWith(".wav"))
   contentTypeLine = "Content-Type: audio/x-wav";

System.out.println("Setting ContentTypeLine To: " + contentTypeLine);
}
else
{
           resp = myHTTPServer.HTML_START + resp + myHTTPServer.HTML_END;
           contentLengthLine = "Content-Length: " + resp.length() + "\r\n";
    }

outToClient.writeBytes(statusLine);
outToClient.writeBytes(serverdetails);
outToClient.writeBytes(contentTypeLine);
outToClient.writeBytes(contentLengthLine);
outToClient.writeBytes("Connection: close\r\n");
outToClient.writeBytes("\r\n");

if (isFile) sendFile(fin, outToClient);
         else outToClient.writeBytes(resp);

outToClient.close();
}

/*start the listener - can also implement this with worker threads */

     public void run()
     {

try {

conn.getInetAddress();
conn.getPort();


inFromClient = new BufferedReader(new InputStreamReader (conn.getInputStream()));
outToClient = new DataOutputStream(conn.getOutputStream());

String request = inFromClient.readLine();
String header = request;
System.out.println("-------");
System.out.println("Thread PID: " + this.getId() );
System.out.println("Server Received: " + header);
StringTokenizer tok = new StringTokenizer(header);
String httpMeth = tok.nextToken();
System.out.println("METHOD: " + httpMeth);
String httpQuery = tok.nextToken();

StringBuffer response = new StringBuffer();

/* customize your own response message here !! */

response.append("Hello!!");
response.append("Goodbye");
response.append("RFC2616 HTTP Spec");
response.append("Sample Web Server Code");
response.append("By Swati Kher
");



while (inFromClient.ready())
{
response.append(request + "
");
System.out.println(request);
    request = inFromClient.readLine();
}

              /** http://www.w3.org/Protocols/rfc2616/rfc2616.html **/
              /** Response Message - refer to rfc2616 for more information!! **/
if (httpMeth.equals("GET"))
{
                if (httpQuery.equals("/"))
                {
 //sendResponse(HTTP_OK, "SWATI KHER PAGE", false);
 sendResponse(HTTP_OK, response.toString(), false);
   }
   else
   {
String fileN = httpQuery.replaceFirst("/", "");
fileN = URLDecoder.decode(fileN);
fileN = "\\" + fileN;
System.out.println("Send File: " + fileN);
//System.out.println("Found: " + (new File(fileN).isFile()));
if (new File(fileN).isFile()) {
sendResponse(HTTP_OK, fileN, true);
   }
else {
sendResponse(HTTP_BAD_REQUEST, "404 Requested file not found", false);
}
}
}
else
{
   sendResponse(HTTP_NOT_FOUND, "400 Resource not found", false);
}

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


     public static void main(String[] args) throws Exception {

ServerSocket Serv = new ServerSocket (5000, 10, InetAddress.getByName("127.0.0.1"));
System.out.println("Server is listening on port 5000...");

while (true) {
 Socket con = Serv.accept();
 (new myHTTPServer(con)).start();
 }
}
}