Tuesday, 20 December 2016

JAR extract & replace class and create JAR

JAR extract & replace class and create JAR

By following the below steps we can extract the JAR files without any software installation. 

Before you going to use below steps check the class path if not please set.

echo %path%

Extract the JAR File:

cmd> jar  -xf  <file_name.jar>;

By following the below steps we can create the JAR files without any software installation. 

Create JAR File:

cmd> jar  -cf  <file_name.jar>  *;

Note: * represents it takes all files in the current directory and create JAR with given name.

Saturday, 10 January 2015

Parsing an XML file with DOM in Java

Below program describes that, reading the data from network xml resource. And it describe how to get particular  node value and display it in console.

In java we have by default javax.xml library which contains the several class to manage the Document Object Model (xml) data. But it is too lengthy. By using the third party libraries such as JDOM etc we can manage the xml content very easily.


package files;

import java.io.IOException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class ReadXML {

public static void main(String[] args) {

try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();

Document doc = builder.parse("http://services.explorecalifornia.org/rss/tours.php");
NodeList nodeList = doc.getElementsByTagName("title");

System.out.println("Total elements " +nodeList.getLength()+" are presented");

for (int i = 0; i < nodeList.getLength(); i++) {

Element item = (Element)nodeList.item(i);

System.out.println(item.getFirstChild().getNodeValue());

}
}catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (DOMException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}

}

Reading a text file from a networked resource

Reading the content from network resource

package files;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class ReadNetworkFile {

public static void main(String[] args) {

try {
URL url = new URL("http://services.explorecalifornia.org/rss/tours.php");

InputStream in = url.openStream();
BufferedInputStream bis = new BufferedInputStream(in);

StringBuilder sb = new StringBuilder();

while (true) {
int val = bis.read(); //reading byte by byte

if (val == -1){ // -1 represents it reached EOF
break;
}else{
sb.append((char)val);
}
}

System.out.println(sb);

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

}

}

Managing files with Apache Commons FileUtils


Managing files with Apache Commons FileUtils, First we need to download commons-io-2.4.jar file from the above site. Add the jar file to eclipse java build path.

I have written the simple file reading/writing  program

package files;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

public class Main {

public static void main(String[] args) {
try {
File f1 = new File("loremipsum.txt");
File f2 = new File("target.txt");

FileUtils.copyFile(f1, f2);

System.out.println("File copied!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}

}
}

Simple way to read and write files in java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class CopyFile {

public static void main(String[] args) {

try {
File f1 = new File("loremipsum.txt");
File f2 = new File("target.txt");

InputStream in = new FileInputStream(f1);
OutputStream out = new FileOutputStream(f2);

byte[] buf = new byte[1024];

int len;

while (((len = in.read(buf)) > 0)) {

out.write(buf, 0, len);

}

in.close();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
}

Thursday, 24 July 2014

Maintaing Flex Session

package com.d.menu.model
{

    import flash.net.SharedObject;
    import flash.net.registerClassAlias;
   
    import mx.collections.ArrayCollection;

    /**
     * Manager for accessing the SharedObjects for the menu.  Helps
     * with the loading and saving of state variables so uses can navigate to
     * and from the menu without losing cart information
     */
    public class SOManager
    {
        public static const SO_APP_STATE:String = "d_SO_App_State";
        public static const SO_CATEGORY_ID:String = "d_SO_Category_ID";
        public static const SO_STORE_ID:String = "d_SO_Store_ID";
        public static const SO_SELECTED_MENU_ITEM_ID:String = "d_SO_Selected_Menu_Item_ID";
        public static const SO_SELECTED_COUPON_CODE:String = "d_SO_SELECTED_COUPON_CODE";
        public static const SO_ORDER:String = "d_SO_ORDER";
        public static const SO_CUSTOMER:String = "d_SO_CUSTOMER";
        public static const SO_PAYMENT:String = "d_SO_PAYMENT";
        public static const SO_PAYMENT_TYPE:String = "d_SO_PAYMENT_TYPE";
        public static const SO_GIFTCARDS:String = "d_SO_GIFTCARD";
        public static const SO_APPlIED:Array = new Array();
        public var giftCards:Array = new Array();
       
        public static const SO_ORDER_ID_TO_LOAD:String = "d_SO_ORDER_TO_LOAD";
        public static const SO_TIMESTAMP:String = "d_SO_TIMESTAMP";
        public static const SO_CUSTOMER_ID:String = "d_SO_CUSTOMER_ID";
       
        public var giftCardCount:int = 0;

        private var _isReady:Boolean = false;

        public function get isReady():Boolean
        {
            return _isReady;
        }

        // main shared object variable that is used for storage of menu variables
        private var _so:SharedObject;

        public function get SO():SharedObject
        {
            return _so;
        }

        public function set SO(value:SharedObject):void
        {
            _so = value;
        }

        /**
         * Constructor
         */
        public function SOManager():void
        {
        }

        /**
         * Creates a reference to the shared object based on the user's customer ID
         */
        public function createSharedObject(loadedCustomerID:int):void
        {
            // grab anon profile
            var anonSO:SharedObject = getAnonSO();

            // get current time
            var now:Date = new Date();

            // if user is anonymous, check for timestamp expiration to reset
            if (loadedCustomerID == -1)
            {
                // assign the _so the anonymous value
                _so = anonSO;

                // grab current timestamp for this user
                var timestamp:Date = getValue(SOManager.SO_TIMESTAMP);

                if (timestamp && isTimestampExpired(timestamp))
                {
                    // the timestamp is too old.  clear cookie
                    //Debug.log( "Deleting SO for anon user b/c timestamp has expired");
                    deleteSharedObject();

                    // session is expired. update timestamp and continue
                    //Debug.log( "Setting new timestamp for anon user");
                    saveValue(SOManager.SO_TIMESTAMP, now);
                }
            }
            else
            {
                // we have a non-anon customer.  this customer could have been
                // anonymous last load....so we need to check and assign this
                // user the anon profile if necessary.

                // check for user-specific cookie
                _so = SharedObject.getLocal(formatName(loadedCustomerID), "/");


                if (anonSO.data.timestamp && !isTimestampExpired(anonSO.data.timestamp))
                {
                    // anon SO was not expired, so can't we assume that
                    // the incoming user was anonymous but now is not??
                    transferAnonToCustomer(anonSO);
                }

                //Debug.log( "Setting new timestamp for current Customer (" + loadedCustomerID + ")");
                saveValue(SOManager.SO_TIMESTAMP, now);
            }

            // check to see if there is a store to load
            var storeSO:SharedObject = SharedObject.getLocal("dStoreToLoad", "/");
            if (storeSO.data.storeID && storeSO.data.storeID != -1)
            {
                saveValue(SO_STORE_ID, storeSO.data.storeID);
                storeSO.data.storeID = -1;
                storeSO.flush();
            }

            // check to see if there is an order to load
            var orderSO:SharedObject = SharedObject.getLocal("dOrderToLoad", "/");
            if (orderSO.data.orderHeaderID && orderSO.data.orderHeaderID != -1)
            {
                saveValue(SO_ORDER_ID_TO_LOAD, orderSO.data.orderHeaderID);
                orderSO.data.orderHeaderID = -1;
                orderSO.flush();
            }

            // set soManager to READY!
            _isReady = true;
        }

        public function getAnonSO():SharedObject
        {
            // grab anon profile
            return SharedObject.getLocal(formatName(-1), "/");
        }

        /**
         * Compares cookie timestamp to current time
         */
        public function isTimestampExpired(timestamp:Date):Boolean
        {
            // grab session timeout variable
            var timeout:Number = Model.getInstance().assetProxy.config..system.sessiontimeout;

            // create expiration date by adding config.xml minutes to timestamp
            var expirationTime:Number = timestamp.setMinutes(timestamp.minutes + timeout);

            //Debug.log( "Expires at " + expirationTime + "; currently is " + new Date().time); // expired if the expiration time is less than now
            return expirationTime < new Date().time;
        }


        /**
         * Deletes the active shared object from storage
         */
        public function deleteSharedObject():void
        {
            _so.clear();
        }

        /**
         * Deletes the gift card shared object from storage
         */
        public function deleteGiftCards():void
        {
            _so.data.giftcards = null;
            giftCards = new Array();
            giftCards.length = 0;
        }
       
        /**
         * Returns the specified property of the data object from the
         * customer's SharedObject
         */
        public function getValue(soName:String):*
        {
            var data:*;

            // return data
            switch (soName)
            {
                case SO_SELECTED_MENU_ITEM_ID:
                    data = _so.data.selectedMenuItemID as String;
                    if (!data)
                        data = "-1";
                    break;
               
                case SO_SELECTED_COUPON_CODE:
                    data = _so.data.selectedCouponCode as String;
                    if (!data)
                        data = "-1";
                    break;
               
                           
                case SO_GIFTCARDS:
                data = _so.data.giftcards as Array;
                if (!data)
                    data = null;
                break;
               
                case SO_CATEGORY_ID:
                    data = _so.data.categoryID as int;
                    if (!data)
                        data = "-1";
                    break;

                case SO_CUSTOMER_ID:
                    data = _so.data.customerID as int;
                    if (!data)
                        data = -1;
                    break;

                case SO_STORE_ID:
                    data = _so.data.storeID as int;
                    if (!data)
                        data = -1;
                    break;

                case SO_APP_STATE:
                    data = _so.data.appState as int;
                    if (!data)
                        data = ApplicationStateType.MENU;
                    break;

                case SO_ORDER:
                    data = _so.data.order as Object;
                    break;
               
                case SO_PAYMENT:
                    data = _so.data.payment+giftCardCount as Object;
                    if (!data)
                        data = "-1";
                    break;
               
                case SO_PAYMENT_TYPE:
                    data = _so.data.selectedPaymentType as String;
                    if (!data)
                        data = "-1";
                    break;

                case SO_CUSTOMER:
                    data = _so.data.customer as Object;
                    break;

                case SO_ORDER_ID_TO_LOAD:
                    data = _so.data.orderHeaderID as int;
                    if (!data)
                        data = -1;
                    break;

                case SO_TIMESTAMP:
                    data = _so.data.timestamp as Date;
                    break;
            }

            return data;
        }

        /**
         * Saves a value to the specified property of the active shared object
         */
        public function saveValue(soName:String, value:Object):void
        {
            Debug.log(value.toString());
            switch (soName)
            {
                case SO_SELECTED_MENU_ITEM_ID:
                    _so.data.selectedMenuItemID = value;
                    break;
               
                case SO_SELECTED_COUPON_CODE:
                    _so.data.selectedCouponCode = value;
                    break;

                case SO_CATEGORY_ID:
                    _so.data.categoryID = value;
                    break;

                case SO_CUSTOMER_ID:
                    _so.data.customerID = value;
                    break;

                case SO_STORE_ID:
                    _so.data.storeID = value;
                    break;

                case SO_APP_STATE:
                    _so.data.appState = value;
                    break;

                case SO_ORDER:
                    _so.data.order = Order.compress(value);
                    break;

                case SO_CUSTOMER:
                    _so.data.customer = Customer.compress(value);
                    break;
               

                case SO_PAYMENT:
                    _so.data.payment = Payment.compress(value);
                    break;
               
                case SO_PAYMENT_TYPE:
                    _so.data.selectedPaymentType = value;
                    break;


                case SO_TIMESTAMP:
                    _so.data.timestamp = value;
                    break;
            }

            // save object immediately
            _so.flush();
        }

        /**
         * Creates a standardized naming convention based on customer ID and name of the
         * SharedObject
         */
        private const NAME_TOKEN:String = "dOMS%CID%";

        private function formatName(cid:int):String
        {
            return NAME_TOKEN.replace("%CID%", cid.toString());
        }

        /**
         * Transfers data from the anon profile to the user profile.
         */
        private function transferAnonToCustomer(anonSO:SharedObject):void
        {
            if (anonSO.data.storeID)
                saveValue(SO_STORE_ID, anonSO.data.storeID);

            if (anonSO.data.order)
            {
                var orderObj:Object = anonSO.data.order;
                var order:Order = new Order();
                if (orderObj)
                {
                    order = Order.decompress(orderObj);
                }
                else
                {
                    order = new Order();
                }

                saveValue(SO_ORDER, order);
            }

            if (anonSO.data.categoryID)
            {
                saveValue(SO_CATEGORY_ID, anonSO.data.categoryID);
            }
        }
    }
}

Tuesday, 15 July 2014

access ref cursor as out parameter in procedure in oracle

create or replace package localdbpackage_pkg as
procedure pz_populate_emp_table;
end localdbpackage_pkg;

create or replace package body localdbpackage_pkg as
procedure pz_populate_emp_table as
c_localrefcursor sys_refcursor;
v_empno number := 7369;
emp_rec emp%rowtype;
  begin  --7369
  remotedbpackage_pkg.pz_return_refcursor(v_empno,c_localrefcursor);
  for i in c_localrefcursor
    loop
      dbms_output.put_line(i.empno);
    end loop;
--  loop
/*  fetch c_localrefcursor into emp_rec;
  exit when c_localrefcursor%notfound;
  insert into emp_temp values emp_rec;
  end loop;  */
 -- commit;
 -- close c_localrefcursor;
   end pz_populate_emp_table;
   begin
     null;
end localdbpackage_pkg;

----------------------------------------------------------------
create or replace package remotedbpackage_pkg as
procedure pz_return_refcursor(p_empno in number, p_emp_refcursor out sys_refcursor);
end remotedbpackage_pkg;

create or replace package body remotedbpackage_pkg as
 procedure pz_return_refcursor(p_empno in number, p_emp_refcursor out sys_refcursor) as
  begin
    open p_emp_refcursor for select * from emp where empno = p_empno;
  end pz_return_refcursor;
  begin
    null;
end remotedbpackage_pkg;