Monday, June 10, 2013

getCurrentDate in Java

    public String getCurrentDate(String format) {
        String date = "";
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        date = sdf.format(new Date());
        return date;
    }

RemDupFromList.java

RemDupFromList.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
package java4s;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
public class RemDupFromList {
    public static void main(String[] args)
    {
        List li = new ArrayList();
              li.add("one");
              li.add("two");
              li.add("three");
              li.add("one");//Duplicate
              li.add("one");//Duplicate
             // We have facility to pass a List into Set constructor and vice verse to cast     
                List li2 = new ArrayList(new HashSet(li)); //no order
             // List li2 = new ArrayList(new LinkedHashSet(li)); //If you need to preserve the order use 'LinkedHashSet'
             Iterator it= li2.iterator();
             while(it.hasNext())
             {
                 System.out.println(it.next());
             }
    }
}

Explanation

  • Take your normal List object
  • Pass that List li object to Set [Line number 22]  => So finally we have Set object in our hand, just pass this current Set object as argument to ArrayList, so we got new List object li2 without duplicate
  • But if you would like to preserve the order of data use LinkedHashSet rather HashSet

How to find duplicate values in ArrayList with out iterarting..?

  1. List list = new ArrayList();  
  2.     list.add("a");  
  3.     list.add("a");  
  4.     list.add("b");  
  5.     list.add("c");  
  6.     list.add("c");   
  7.     System.out.println(list);  
  8.     Set s = new HashSet(list);  
  9.     System.out.println("Set :- " +s); 

findDuplicates in a list and return them

public Set<Integer> findDuplicates(List<Integer> listContainingDuplicates)
{ 
  final Set<Integer> setToReturn = new HashSet(); 
  final Set<Integer> set1 = new HashSet();

  for (Integer yourInt : listContainingDuplicates)
  {
   if (!set1.add(yourInt))
   {
    setToReturn.add(yourInt);
   }
  }
  return setToReturn;
}
 
 have a List of type Integer eg:

[1, 1, 2, 3, 3, 3]

I would like a method to return all the duplicates eg:
[1, 3]
 
 ----------------
 
List<Item> list = ...;
list.removeAll(new HashSet<Item>(list));
return new HashSet<Item>(list); 
  ----------------
public static Set<Integer> findDuplicates(List<Integer> input) {
    List<Integer> copy = new ArrayList<Integer>(input);
    for (Integer value : new HashSet<Integer>(input)) {
        copy.remove(value);
    }
    return new HashSet<Integer>(copy );
} 
 ----------------
public static void main(String[] args) {
        List<Integer> list = new LinkedList<Integer>();
        list.add(1);
        list.add(1);
        list.add(1);
        list.add(2);
        list.add(3);
        list.add(3);
        Map<Integer,Integer> map = new HashMap<Integer, Integer>();
        for (Integer x : list) { 
            Integer val = map.get(x);
            if (val == null) { 
                map.put(x,1);
            } else {
                map.remove(x);
                map.put(x,val+1);
            }
        }
        List<Integer> result = new LinkedList<Integer>();
        for (Entry<Integer, Integer> entry : map.entrySet()) {
            if (entry.getValue() > 1) {
                result.add(entry.getKey());
            }
        }
        for (Integer x : result) { 
            System.out.println(x);
        }

    } 
 ----------------
public void testFindDuplicates() {

    List<Integer> list = new ArrayList<Integer>();
    list.add(1);
    list.add(1);
    list.add(2);
    list.add(3);
    list.add(3);
    list.add(3);

    Set<Integer> result = new HashSet<Integer>();
    int currentIndex = 0;
    for (Integer i : list) {
        if (!result.contains(i) && list.subList(currentIndex + 1, list.size()).contains(i)) {
            result.add(i);
        }
        currentIndex++;
    }
    assertEquals(2, result.size());
    assertTrue(result.contains(1));
    assertTrue(result.contains(3));
}
-----------
ublic List<int> GetDuplicates(int max)
{   
    //allocate and clear memory to 0/false
    bit[] buckets=new bit[max]
    memcpy(buckets,0,max);
    //find duplicates
    List<int> result=new List<int>();
    foreach(int val in List)
    {
        if (buckets[val])
        {
            result.add(value);
        }
        else
        {
            buckets[val]=1;
        }
    }
    return  result
}  
----------
private <T> Set<T> findDuplicates(Collection<T> list) {

    Set<T> duplicates = new LinkedHashSet<T>();
    Set<T> uniques = new HashSet<T>();

    for(T t : list) {
        if(!uniques.add(t)) {
            duplicates.add(t);
        }
    }

    return duplicates;
}
-------
 
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
 
public class CrunchifyFindDuplicateInList {
 
    /**
     * @author Crunchify.com
     */
 
    public static void main(String[] args) {
        List<String> list = new LinkedList<String>();
        for (int i = 0; i < 10; i++) {
            list.add(String.valueOf(i));
        }
        for (int i = 0; i < 5; i++) {
            list.add(String.valueOf(i));
        }
 
        System.out.println("My List : " + list);
        System.out.println("\nHere are the duplicate elements from list : " + findDuplicates(list));
    }
 
    public static Set<String> findDuplicates(List<String> listContainingDuplicates) {
 
        final Set<String> setToReturn = new HashSet<String>();
        final Set<String> set1 = new HashSet<String>();
 
        for (String yourInt : listContainingDuplicates) {
            if (!set1.add(yourInt)) {
                setToReturn.add(yourInt);
            }
        }
        return setToReturn;
    }
}
Output
1
2
3
My List : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4]
 
Here are the duplicate elements from list : [3, 2, 1, 0, 4]
 
  
CREATE OR REPLACE procedure insert_auw_into_temp() is
cursor air_cur is select distinct temp.reg_no,air.max_allup_wt from tc_temp_log temp,tc_aircraft_mt air where temp.max_allup_wt is null and trim(temp.reg_no)=trim(air.reg_no);
   v_temp air_cur%rowtype;
begin
   open air_cur;
   loop
      fetch air_cur into v_temp;
      exit when air_cur%notfound;
      update tc_temp_log set max_allup_wt=v_temp.max_allup_wt where trim(reg_no)=trim(v_temp.reg_no);
   end loop;
   close air_cur;
end;
/

get_nextcode

/* Formatted on 2013/06/10 17:43 (Formatter Plus v4.8.8) */
CREATE OR REPLACE FUNCTION get_nextcode (
   p_table_name   VARCHAR,
   p_col_name     VARCHAR,
   p_length       NUMBER
)
   RETURN VARCHAR
IS
   v_query      VARCHAR (200);
   v_autocode   VARCHAR (50);
BEGIN
   v_query :=
         'select lpad(nvl(max(to_number('
      || p_col_name
      || '))+1,1),'
      || p_length
      || ',0) code from '
      || p_table_name;

   EXECUTE IMMEDIATE v_query
                INTO v_autocode;

   RETURN v_autocode;
END;
/

gettimeslot

/* Formatted on 2013/06/10 17:42 (Formatter Plus v4.8.8) */
CREATE OR REPLACE FUNCTION vabb.gettimeslot (vtime IN VARCHAR2)
   RETURN VARCHAR2
IS
   RESULT   VARCHAR2 (10);
BEGIN
   IF (vtime >= '0000' AND vtime <= '0100')
   THEN
      RESULT := '0531-0630';
   ELSIF (vtime >= '0101' AND vtime <= '0200')
   THEN
      RESULT := '0631-0730';
   ELSIF (vtime >= '0201' AND vtime <= '0300')
   THEN
      RESULT := '0731-0830';
   ELSIF (vtime >= '0301' AND vtime <= '0400')
   THEN
      RESULT := '0831-0930';
   ELSIF (vtime >= '0401' AND vtime <= '0500')
   THEN
      RESULT := '0931-1030';
   ELSIF (vtime >= '0501' AND vtime <= '0600')
   THEN
      RESULT := '1031-1130';
   ELSIF (vtime >= '0601' AND vtime <= '0700')
   THEN
      RESULT := '1131-1230';
   ELSIF (vtime >= '0701' AND vtime <= '0800')
   THEN
      RESULT := '1231-1330';
   ELSIF (vtime >= '0801' AND vtime <= '0900')
   THEN
      RESULT := '1331-1430';
   ELSIF (vtime >= '0901' AND vtime <= '1000')
   THEN
      RESULT := '1431-1530';
   ELSIF (vtime >= '1001' AND vtime <= '1100')
   THEN
      RESULT := '1531-1630';
   ELSIF (vtime >= '1101' AND vtime <= '1200')
   THEN
      RESULT := '1631-1730';
   ELSIF (vtime >= '1201' AND vtime <= '1300')
   THEN
      RESULT := '1731-1830';
   ELSIF (vtime >= '1301' AND vtime <= '1400')
   THEN
      RESULT := '1831-1930';
   ELSIF (vtime >= '1401' AND vtime <= '1500')
   THEN
      RESULT := '1931-2030';
   ELSIF (vtime >= '1501' AND vtime <= '1600')
   THEN
      RESULT := '2031-2130';
   ELSIF (vtime >= '1601' AND vtime <= '1700')
   THEN
      RESULT := '2131-2230';
   ELSIF (vtime >= '1701' AND vtime <= '1800')
   THEN
      RESULT := '2231-2330';
   ELSIF (vtime >= '1801' AND vtime <= '1900')
   THEN
      RESULT := '2331-0030';
   ELSIF (vtime >= '1901' AND vtime <= '2000')
   THEN
      RESULT := '0031-0130';
   ELSIF (vtime >= '2001' AND vtime <= '2100')
   THEN
      RESULT := '0131-0230';
   ELSIF (vtime >= '2101' AND vtime <= '2200')
   THEN
      RESULT := '0231-0330';
   ELSIF (vtime >= '2201' AND vtime <= '2300')
   THEN
      RESULT := '0331-0430';
   ELSE
      RESULT := '0431-0530';
   END IF;

   RETURN (RESULT);
END gettimeslot;
/

getistdays

/* Formatted on 2013/06/10 17:42 (Formatter Plus v4.8.8) */
CREATE OR REPLACE FUNCTION vabb.getistdays (
   mon       IN   VARCHAR2,
   tue       IN   VARCHAR2,
   wed       IN   VARCHAR2,
   thu       IN   VARCHAR2,
   fri       IN   VARCHAR2,
   sat       IN   VARCHAR2,
   sun       IN   VARCHAR2,
   utctime        VARCHAR2
)
   RETURN VARCHAR2
IS
   RESULT   VARCHAR2 (20);
   p_mon    VARCHAR2 (2)  := '--';
   p_tue    VARCHAR2 (2)  := '--';
   p_wed    VARCHAR2 (2)  := '--';
   p_thu    VARCHAR2 (2)  := '--';
   p_fri    VARCHAR2 (2)  := '--';
   p_sat    VARCHAR2 (2)  := '--';
   p_sun    VARCHAR2 (2)  := '--';
BEGIN
   IF (utctime >= '1830' AND utctime <= '2359')
   THEN
      IF (   mon != 'Y'
          OR tue != 'Y'
          OR wed != 'Y'
          OR thu != 'Y'
          OR fri != 'Y'
          OR sat != 'Y'
          OR sun != 'Y'
         )
      THEN
         IF (mon = 'Y')
         THEN
            IF sun != 'Y'
            THEN
               p_mon := '--';
            END IF;

            p_tue := '2';
         END IF;

         IF (tue = 'Y')
         THEN
            IF mon != 'Y'
            THEN
               p_tue := '--';
            END IF;

            p_wed := '3';
         END IF;

         IF (wed = 'Y')
         THEN
            IF tue != 'Y'
            THEN
               p_wed := '--';
            END IF;

            p_thu := '4';
         END IF;

         IF (thu = 'Y')
         THEN
            IF wed != 'Y'
            THEN
               p_thu := '--';
            END IF;

            p_fri := '5';
         END IF;

         IF (fri = 'Y')
         THEN
            IF thu != 'Y'
            THEN
               p_fri := '--';
            END IF;

            p_sat := '6';
         END IF;

         IF (sat = 'Y')
         THEN
            IF fri != 'Y'
            THEN
               p_sat := '--';
            END IF;

            p_sun := '7';
         END IF;

         IF (sun = 'Y')
         THEN
            IF sat != 'Y'
            THEN
               p_sun := '--';
            END IF;

            p_mon := '1';
         END IF;
      ELSE
         p_mon := '1';
         p_tue := '2';
         p_wed := '3';
         p_thu := '4';
         p_fri := '5';
         p_sat := '6';
         p_sun := '7';
      END IF;
   ELSE
      IF mon = 'Y'
      THEN
         p_mon := '1';
      ELSE
         p_mon := '--';
      END IF;

      IF tue = 'Y'
      THEN
         p_tue := '2';
      ELSE
         p_tue := '--';
      END IF;

      IF wed = 'Y'
      THEN
         p_wed := '3';
      ELSE
         p_wed := '--';
      END IF;

      IF thu = 'Y'
      THEN
         p_thu := '4';
      ELSE
         p_thu := '--';
      END IF;

      IF fri = 'Y'
      THEN
         p_fri := '5';
      ELSE
         p_fri := '--';
      END IF;

      IF sat = 'Y'
      THEN
         p_sat := '6';
      ELSE
         p_sat := '--';
      END IF;

      IF sun = 'Y'
      THEN
         p_sun := '7';
      ELSE
         p_sun := '--';
      END IF;
   END IF;

   RESULT :=
         p_mon
      || ' '
      || p_tue
      || ' '
      || p_wed
      || ' '
      || p_thu
      || ' '
      || p_fri
      || ' '
      || p_sat
      || ' '
      || p_sun;
   RETURN (RESULT);
END getistdays;
/

getistday

/* Formatted on 2013/06/10 17:41 (Formatter Plus v4.8.8) */
CREATE OR REPLACE FUNCTION getistday (DAY IN VARCHAR2, utctime VARCHAR2)
   RETURN VARCHAR2
IS
   RESULT   VARCHAR2 (20);
   p_day    VARCHAR2 (3)  := ' ';
BEGIN
   IF (utctime >= '1830' AND utctime <= '2359')
   THEN
      IF (DAY = 'MON')
      THEN
         p_day := 'TUE';
      END IF;

      IF (DAY = 'TUE')
      THEN
         p_day := 'WED';
      END IF;

      IF (DAY = 'WED')
      THEN
         p_day := 'THU';
      END IF;

      IF (DAY = 'THU')
      THEN
         p_day := 'FRI';
      END IF;

      IF (DAY = 'FRI')
      THEN
         p_day := 'SAT';
      END IF;

      IF (DAY = 'SAT')
      THEN
         p_day := 'SUN';
      END IF;

      IF (DAY = 'SUN')
      THEN
         p_day := 'MON';
      END IF;
   ELSE
      p_day := DAY;
   END IF;

   RESULT := p_day;
   RETURN (RESULT);
END getistday;
/

getfinancialyear (strdate VARCHAR)

/* Formatted on 2013/06/10 17:40 (Formatter Plus v4.8.8) */
CREATE OR REPLACE FUNCTION getfinancialyear (strdate VARCHAR)
   RETURN VARCHAR
AS
   v_month   VARCHAR2 (10);
   v_year    VARCHAR2 (10);
BEGIN
   --strDate format should be Mon/YYYY
   v_month := UPPER (SUBSTR (strdate, 1, 3));
   v_year := SUBSTR (strdate, 5);

   IF (INSTR ('JAN|FEB|MAR', v_month) > 0)
   THEN
      v_year := (TO_NUMBER (v_year) - 1) || '-' || SUBSTR (v_year, 3);
   ELSE
      v_year := v_year || '-' || SUBSTR (TO_CHAR (TO_NUMBER (v_year) + 1), 3);
   END IF;

   RETURN v_year;
END;
/

how to compare two datetime objects in Java

        //Create First Date Object
        DateFormat sdf = new java.text.SimpleDateFormat("dd/MMM/yyyy HHMM");
        Date date1 = null;
        Date date2 = null;
//        @SuppressWarnings({"unchecked", "varargs"});
       
        try {
           
            date1 = sdf.parse("18/MAR/2013 2310");
            date2 = sdf.parse("18/MAR/2013 2315");
            System.out.println("First Date  : " + date1.toString());
            System.out.println("Second Date : " + date2.toString());
           
        } catch (ParseException e1) {
            e1.printStackTrace();
        }
        /*
         Use compareTo method of java Date class to compare two date objects.
         compareTo returns value grater than 0 if first date is after another date,
         returns value less than 0 if first date is before another date and returns
         0 if both dates are equal.
         */

        int results = date1.compareTo(date2);

        if (results > 0)
            System.out.println("First Date is after second" + results);
        else if (results < 0)
            System.out.println("First Date is before second" + results);
        else
            System.out.println("Both dates are equal" + results);

Two Dates Difference in days Using Java

    public long getDateDifference(String date1, String date2) {
        long noOfDays = 0;
        int days = 0;
        Date validatDt1 = new Date();
        Date validatDt2 = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
        try {
            validatDt1 = sdf.parse(date1);
            validatDt2 = sdf.parse(date2);

            noOfDays = (validatDt2.getTime() - validatDt1.getTime());
            noOfDays = (noOfDays / (1000L * 60L * 60L * 24L * 365));
       
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return noOfDays;

    }

Minutes display in 24hr Time Format

    public String timediffinminutes(String minutes) {
            int totalMinutesInt = Integer.valueOf(minutes.toString());
       
            int hours = totalMinutesInt / 60;
            int mins= (totalMinutesInt % 60 *100) /60;
            System.out.println(" & mins : "+mins);
            int hoursToDisplay = hours;
       
            if (hours > 12) {
                hoursToDisplay = hoursToDisplay - 12;
            }
       
            int minutesToDisplay = totalMinutesInt - (hours * 60);
       
            String minToDisplay = null;
            if(minutesToDisplay == 0 )
                minToDisplay = "00";    
            else
            if( minutesToDisplay < 10 )
                minToDisplay = "0" + minutesToDisplay ;
            else
                minToDisplay = "" + minutesToDisplay ;
       
            String displayValue = hoursToDisplay + ":" + minToDisplay;
            System.out.println(" ****** displayValue : "+displayValue);
            return displayValue;
           
        }

Order by DATETIME in SQL

order by to_timestamp(ENTRYDATE||':'||ENTRYTIME,'dd-mm-yyyy:HH24:MI:SS') ASC

how to find the first and last values in a List in JAVA

        String first=list.get(0).toString();
        String last=
list.get(l1.size()-1).toString();

replacing space in special characters when ajax Loading

 function replaceSpace(obj)
 {
   obj.value=obj.value.replace(/^\s*|\s(?=\s)|\s*$/g, "");
 }

How to find the number is even without using arithmetic Operators

public class EvenOrOddWithoutArithOprs {

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner in = new Scanner(System.in);

        System.out.println("Enter any number : ");

        // return the user input as integer
        int number = in.nextInt();

        // Finding Even and Odd number using Bitwise AND operator in Java.

        System.out.printf("Finding number if its even or odd using bitwise AND operator %n");

        // For Even numbers
        // XXX0
        // 0001 AND
        // 0000
        if ((number & 1) == 0) {
            System.out.println("number %d is even number %n" + number);
        } else {
            System.out.println("number %d is odd number %n" + number);
        }
    }

}

Friday, June 7, 2013

A QUERY FOR TWO DIFFERENT DATE AND TIMES BETWEEN TWO DATES

Select (To_Date(Decode('01/MAY/2013', '', '01/Jan/1910', '01/MAY/2013') ||
                                                ' 0001',
                                                'DD-MON-YYYY HH24MI')) +
                                       (Rownum - 1) / 24 FromDate,
                                       (To_Date(Decode('31/MAY/2013', '', '31/Dec/9990', '31/MAY/2013') ||
                                                ' 0000',
                                                'DD-MON-YYYY HH24MI')) +
                                       (Rownum / 24) ToDate,
                                       'F' Type,
                                       'XXXX' Operator,
                                       '' FlightNature
                                  From tab
                                 Where Rownum <= 24

QUERY FOR DATE AND TIME SLOT

Select to_char((To_Date(Decode('01/MAY/2013', '', '01/Jan/1910', '01/MAY/2013') ||
                ' 0001',
                'DD-MON-YYYY HH24MI')) + (Rownum - 1) / 24 ,'DD-MON-YYYY HH:MI:SS AM') FromDate,
       to_char((To_Date(Decode('31/MAY/2013', '', '31/Dec/9990', '31/MAY/2013') ||
                ' 0000',
                'DD-MON-YYYY HH24MI')) + (Rownum / 24),'DD-MON-YYYY HH:MI:SS AM') ToDate,
       'F' Type,
       'XXXX' Operator,
       '' FlightNature
  From tab
 Where Rownum <= 24

Tuesday, June 4, 2013

Connecting the database and return values using hibernate session


public class InvPersonalInformationDAO {
    private static InvPersonalInformationDAO invPersonalInformationDAO;
    public InvPersonalInformationDAO(){}
   
    public static InvPersonalInformationDAO getInstance(){
        if(invPersonalInformationDAO == null){
            invPersonalInformationDAO = new InvPersonalInformationDAO();
        }
        return new InvPersonalInformationDAO();
    }
 

public List getInventoryList()throws EPASException{
        List inventoryList = new ArrayList();
        try {
            Session session = HibernateSessionFactory.getSession();
            Query query = session.createQuery("SELECT invEmpPiBasicDet FROM InvEmpPiBasicDet invEmpPiBasicDet WHERE invEmpPiBasicDet.invEmpMstStatus = '1' ");
            Iterator iterator = query.list().iterator();
            while(iterator.hasNext()){
                InvEmpPiBasicDet invEmpPiBasicDet = (InvEmpPiBasicDet)iterator.next();
                System.out.println("invEmpPiBasicDet.getBasicsalary() : "+invEmpPiBasicDet.getBasicsalary());
                inventoryList.add(EntityToBeanConverter.convertInvEmpPiBasicDetToInvPersonalInformationBean(invEmpPiBasicDet));
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new EPASException(e);
        }finally{
            HibernateSessionFactory.closeSession();
        }
        return inventoryList;
    }

public static void main(String[] args) {
        InvPersonalInformationDAO id=new InvPersonalInformationDAO();
   //or //
        //InvPersonalInformationDAO id=InvPersonalInformationDAO.getInstance();
        try {
            List l1=id.getInventoryList();
        } catch (EPASException e) {
            e.printStackTrace();
        }
    }
}


retNodeValue(req,node) in AJAX

function retNodeValue(req,node)
{
     if(req.responseXML.getElementsByTagName(node)[0].firstChild!=null||req.responseXML.getElementsByTagName(node)[0].firstChild!="")
        return req.responseXML.getElementsByTagName(node)[0].firstChild.nodeValue;
    else
        return ' ';
}

Monday, June 3, 2013

In Struts-config.xml file form names having multiple but id value must be unique other wise we will get id is already defined error will get when strut-config.xml file is loaded

       
 In Struts-config.xml file form names having multiple but id value must be unique other wise we will get id is already defined error will get when strut-config.xml file is loaded

 <form-bean name="loginValidation" type="org.apache.struts.validator.DynaValidatorForm" id="i1" >
            <form-property name="userId" type="java.lang.String" />
            <form-property name="password" type="java.lang.String" />
            <form-property name="dept" type="java.lang.String" />
        </form-bean>
        <form-bean name="loginValidation" type="org.apache.struts.validator.DynaValidatorForm"  
id="i2">
            <form-property name="userId" type="java.lang.String" />
            <form-property name="password" type="java.lang.String" />
            <form-property name="dept" type="java.lang.String" />
        </form-bean>