Sorting a HashTable

I am trying to sort a HashTable accoring to values . But i am getting compilation errors on
String hasKey =(String) entries.getKey();
String siteDesc =(String)entries.getValue();
The Error is cananot resolve symbol getKey and getValue.
The follwing is the code.
import java.util.*;
public class HashSort
     public static void main(String as[])
          Map ht = new Hashtable();
          ht.put("ABC", "1");
          ht.put("XYZ", "1");
          ht.put("MNO", "0");
          Set set = ht.entrySet();
          Map.Entry [] entries = (Map.Entry[])set.toArray(new Map.Entry[set.size()]);
          Arrays.sort(entries, new Comparator()
          public int compare(Object o1, Object o2)
               Object v1 = ((Map.Entry)o1).getValue();
               Object v2 = ((Map.Entry)o2).getValue();
               return ((Comparable)v1).compareTo(v2);
          for(int i=0; i<entries.length; i++)
               String hasKey =(String) entries.getKey();
               String siteDesc =(String)entries.getValue();
rgards
AShok

I think you mean TreeMap instead of TreeSet.
Sorting the contents of the Hashtable has no effect on the Hashtable.
The TreeMap sorts the elements for you. However if you where to so the same sorting code, it would not alter the TreeMap and thus the time to search the TreeMap would be uneffected.

Similar Messages

  • Sorting in HashTable

    Hi,
    Is there any possibility of sorting HashTable.
    Regards,
    Ravi.

    yeah, typically there is no real need to sort a Hashtable since it is intended to be used for retrieving values via keys, rather then via some element's position in the collection. If you find a need to have it sorted, you may not be using the best collection or you may not be storing your values in the most sensible way. It might be best to wrap the keys and the values into a single class, use the keys as your identifier for each instance and then store every thing in a Set, e.g.:
    //can't be sorted
    HashMap dictionary = new HashMap();
    dictionary.put("dog", "a fury animal");
    //can be sorted
    HashSet set = new HashSet();
    set.put(new Word("dog", "a fury animal"));

  • Need help Sorting a Hashtable using values??

    I have a hastable whose keys are unique but values are not. The problem is that i have to sort the hashtable by values.

    You can't really sort a Hashtable by values, at least not directly. What you probably want is a way to be able to iterate through all the values contained in the Hashtable in a way that is consistent with some order defined on those values. An easy way to do this goes as follows:
    Map  m;   // let that be your Hashtable
    List  vals = new ArrayList(m.values());
    Collections.sort(vals);  // uses the values natural order OR
    Collections.sort(vals, my_comparator);  // uses the order defined by my_comparator
    // this will iterate in the order defined on the values
    Iterator  it = vals.iterator();
    while(it.hasNext()) {
      Object val = it.next();
    }

  • Urgent help: sort hashtable

    can anyone please show me som code that sort a Hashtable, like the one below, by its keys.
    Hashtable ole = new Hashtable();
    ole.put(new Integer(2),"erik2");
    ole.put(new Integer(1),"erik1");
    ole.put(new Integer(4),"erik4");
    ole.put(new Integer(3),"erik3");
    ( yes I need to access the items in a particular order )

    http://forum.java.sun.com/thread.jsp?forum=31&thread=151707
    Don't post identical questions. You will make ppl angry and no one will want to help you.

  • Sort hashtable

    How can i sort an hashtable ??

    HI ,
    Use a TreeMap instead of a Hastable. TreeMap is something similar to a hastable, but an added advantage is that it sorts automatically based on the keys.
    You can also make use of the sort() in the Arrays class, which takes in an Object array as parameters.
    Hope this helps you.
    ciao
    Amit Chhajed
    ([email protected])

  • How to make sorting in hash table efficient

    Hi guys,
    I am relatively new to collections.
    I have a HashTable which has 100000 records in it, when I sort it, it takes a lot of time to get it done.
    As the Hashtable methods are synchronised so even I can't use threads to perform this quickely for me.
    Can any one provide any solution using multi threading or any other method to achieve the optimization in
    sorting the hashtable.
    Thanks,
    Atul

    As already suggested, use TreeMap if you want to build your table in sorted key order. Otherwise, if you want to sort after the fact, you could do one of the following:
    SortedSet sortedKeys = new TreeSet(map.keySet());
    // or
    List sortedKeys = new TreeSet(map.keySet());
    Collections.sort(sortedKeys);Note that this will NOT affect that order in the map. It only affects the order of the extracted keys.
    Also not that if sorting 100,000 items is taking "a long time," then you probably wrote your own sort algorithm and it's probably O(n^2) or something.

  • List Sorting

    Hello everone,
    I am currently attemting to sort a Hashtable of vectors mapped by keywords, each keyword is mapped to a vector of Elements read in from an xml file, i need to know how to sort the keys alphabetically can anyone please lend a hand as i do not want to program a sorting function. so that you have a better idea of what my Hashtable contains here is the code that constructs it.
         private void addProdByKey(String keys, Element pE)
              StringTokenizer st = new StringTokenizer(keys, ",");
              while(st.hasMoreTokens())
                   String key = st.nextToken().trim();
                   Vector v = (Vector)prodByKeyHT.get(key);
                   if(v == null)
                        v = new Vector();
                        prodByKeyHT.put(key,v);
                        kV.add(key);
                   v.addElement(pE);
    Thanks
    Arnold Oree

    This has to be about the easiest duke dollars ever :)
    Simply change the Collection you are using from Hashtable to TreeMap.
    Look in the JavaDoc's for java.util.TreeMap.
    Amongst other things, TreeMap ensures that the order of keys is ascending. As you are using Strings as keys, you have no need to worry about a comparator, String is a Comparable class.
    Take note of the way in which a synchronized instance of TreeMap can be created.
    Tip: unless you really need the Vector class synchronized characteristics, use an ArrayList instead. You gain substantial performance benefits this way. I am assuming that you need indexed access to the elements you add to it.
    your addProdByKey method can remain unchanged if you like, although your member variable name prodByKeyHT contains data type information that in Java is more of a hindrance than a help. Don't have HT in the name, prodByKey is more appropriate.

  • Sorting Hashtable by value

    All,
    I have a Hashtable with key (String) and value(float) now I want to sort it by value without disturbing the key value match
    I know, it can be done by sorting the keys... and then calling get() to obtain the value for the key but I want exactly opposite..
    Thanks
    Vishal

    Set set = map.entrySet();
    Map.Entry[] entries = (Map.Entry[]) set.toArray(new Map.Entry[set.size()]);
    Arrays.sort(entries, new Comparator() {
              public int compare(Object o1, Object o2) {
         Object v1 = ((Map.Entry) o1).getValue();
         Object v2 = ((Map.Entry) o2).getValue();
         return ((Comparable) v1).compareTo(v2);
    });And how would one genericise(?) the above code snippet?
    I have the following attempt but I continue to receive one unchecked warning.
    Set<Map.Entry<String, String>> set = map.entrySet();
    Map.Entry[] entries = set.toArray(new Map.Entry[set.size()]);
    Arrays.sort(entries, new Comparatorlt;Map.Entry<String, String>>() {
                public int compare(Map.Entry<String, String> e1, Map.Entry<String, String> e2) {
                String v1 = e1.getValue();
                String v2 = e2.getValue();
                return v1.compareTo(v2);
            });

  • How to sort elements in Hashtable.

    I am adding elements in sorted order in Hashtable. But when I iterate through the Hashtable using 'Enumeration' on the keys the the elements are not fetched in sorted order. I want to retrieve the keys in sorted order. How can we fetch the keys on sorted order?
    import java.util.* ;
    public class temp
         public static void main(String [] abc)
              Hashtable hashList = new Hashtable();
              hashList.put("1","One");
              hashList.put("2","Two");
              hashList.put("33","Three");
              hashList.put("44","Four");
         Enumeration keys = hashList.keys();
         while(keys.hasMoreElements() )
                        System.out.println("Key: " + keys.nextElement());
    Output for this is -
    Key: 2
    Key: 1
    Key: 33
    Key: 44

    obtain a set view of the keys contained in this Hashtable and sort it.

  • Sorting a vector of hashtables

    I have a vector of hashtables that I need to sort.
    The hashtables contain several keys such as FirstName, LastName, ID. I need to sort this vector by the values for the LastName and FirstName keys stored in the hashtables. For example...
    Vector containing the following three hashtables.
    hashtable1 = {FirstName = Jill, LastName = Smyth, ID=5}
    hashtable2 = {FirstName = James, LastName = Smith, ID=6}
    hashtable3 = {FirstName = Jill, LastName = Smith, ID=7}
    The vector needs to be sorted so the order is:
    Hashtable2 (James Smith)
    Hashtable3 (Jill Smith)
    Hashtable1 (Jill Smyth)
    Any ideas on how to do this efficiently?
    Any help would be much appreciated
    Thanks
    --Evan                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

    Write a comparator which can determine if one hashtable is greater than another.
    Arrays.sort(myVector, myComparator);

  • Sorting JComboBox with Hashtable

    Hi,
    I'm using a JComboBox and add some items via
    new JComboBox(somehashtable.values().toArray());
    Does anybody know how to sort this JComboBox?
    I don't know how to write a ComboBoxModel.

    You still haven't given a lot of info.
    As I said, one option is to define a class that holds both the value and the id, and store objects of that class in the hashtable:public class MyDbaseValue {
        private String value, id;
        public MyDbaseValue(String id, String value) {
            this.id = id;
            this.value = value;
        public String getValue() {return value;}
        public String getId()    {return id;}   
        public String toString() {return id + ": " + value;}
    //and when you populate the hashtable:
        MyDbaseValue v = new MyDbaseValue(result.nextID(), result.nextValue);
        hashtable.put(v.getId(), v);
    //and when something gets selected in the combobox:
        MyDbaseValue v = (MyDbaseValue)combo.getSelected();
        String selectedID = v.getID();Other options is to do a lookup in the database for the ID when you get the value from the JComboBox. Or you can find a way to make do without the ID at that point. And there are probably other solutions as well.

  • Hashtable sorting

    I have a Hashtable that I want to sort according to the "values" and then comapre the hshtable with the array of strings to get a new hashtable with the unique values.Pl let me know if somebody has come across similar issue..
    Thanks ..

    I have this code I need to sort but the problem is that i need to add an hashtable along with the vector. So there they run in sync. The reason in doing this is to bypass the primary key. The program deals with many cases. The ones i am sorting is missing files and duplicate files. I have sorted out the missing files with a vector. Note this is a long code. So you are warned. I had trouble sorting the missing files bit. I only added 8 lines
    package com.whw;
    //import com.intex.*;
    //import com.Kidson.*;
    import com.sql.*;
    import com.web.*;
    import com.whw.*;
    import java.sql.SQLException;
    import java.util.*;
    import java.lang.*;
    import java.io.*;
    import java.text.*;
    import java.sql.*;
    //     J2EE     API
    import javax.mail.*;
    import javax.mail.internet.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.Hashtable; //added
    import java.util.Enumeration; //added
    //     Oracle API
    import oracle.sql.*;
    import oracle.jdbc.driver.OracleResultSet;
    import oracle.jdbc.driver.*;
    import oracle.jdbc.OraclePreparedStatement;
    //     Java Excel API
    import jxl.*;
    import jxl.format.*;
    import jxl.write.*;
    import jxl.biff.*;
    import jxl.read.biff.*;
    import jxl.write.biff.*;
    public class WHWBean{
         // for customer info
         public int WHW_Right=0;
         public int Staff_Right=0;
        public String status=null;
        public String usrcod=null;
        public String lognam=null;
        public String ErrFlg=null;
        public String grpnam=null;
        public String ctyfun=null;
        public String cusnam=null;
        public String agtcod=null;     //     agtcod: this is asocod
        public String agtnam=null;
        public String whwtyp=null;     //     whwtyp
        public String corcod=null;     //     corcod
        public String ibpgrp=null;     //     ibpgrp
        public String ibpnam=null;
        public String sucmsg=null;
        //public String ibpnam=null;
        public String WorkBook=null;
        public String Authorised=null;
        public byte[] WHWFile=null;
        public Vector WHWData=null;
        public String fname=null;
        public int WHWexist=0;
        public Vector Err_WHWData=null;
        public Vector WHW_File_List=null;
        public Vector WHW_File_List_err=null;
        //     TTL WHW
        public String TTLPRVORD=null;
        public String TTLPRVWHW=null;
        public String TTLCURORD=null;
        public String TTLCURWHW=null;
         // Inquiry
        public String iq_usrcod=null;
        public String iq_lognam=null;
        public String iq_agtcod=null;     //     agtcod
        public String iq_agtnam=null;
        public String iq_ibpgrp=null;     //     ibpgrp
        public String iq_ibpnam=null;
        public String iq_ctyfun=null;
        public String iq_whwtyp=null;
        public String sDublicate="";  //dublicate string declaration
        public Connection conn=null;
            public WHWBean() {
    //     -----     Methods        -----     //
              public void iq_DataClear(){
                   this.iq_agtcod=null;
                   this.iq_agtnam=null;
                   this.iq_ibpgrp=null;
                   this.iq_ibpnam=null;
                   this.iq_ctyfun=null;
                   this.iq_whwtyp=null;
                   //System.out.println("this.iq_whwtyp: "+this.iq_whwtyp);
              public void DataClear(){
                   this.agtcod=null;
                   this.agtnam=null;
                   this.ibpgrp=null;
                   this.ibpnam=null;
                   this.ctyfun=null;
                   this.WHWFile=null;
                   this.WHWData=null;
                   this.fname=null;
                   this.WHWexist=0;
                  this.TTLPRVORD=null;
                  this.TTLPRVWHW=null;
                  this.TTLCURORD=null;
                  this.TTLCURWHW=null;
                  this.status=null;
                  this.sucmsg=null;
                  this.ErrFlg=null;
                  this.Err_WHWData=null;
              public void ClearAll(){
                   this.whwtyp=null;
                   this.agtcod=null;
                   this.agtnam=null;
                   this.ibpgrp=null;
                   this.ibpnam=null;
                   this.ctyfun=null;
                   this.WHWFile=null;
                   this.WHWData=null;
                   this.fname=null;
                   this.WHWexist=0;
                  this.TTLPRVORD=null;
                  this.TTLPRVWHW=null;
                  this.TTLCURORD=null;
                  this.TTLCURWHW=null;
                  this.status=null;
                  this.sucmsg=null;
                  this.ErrFlg=null;
                  this.Err_WHWData=null;
                  this.WHW_File_List=null;
                  this.WHW_File_List_err=null;
              public String getParam(String param, MultipartRequest mr){
                   if ( (param.length()>=0)&&(mr!=null) ){
                        String [] values = mr.getParameterValues( param.trim() );
                        String value = values[0];          
    //                    System.out.println(param+": "+value);     
                        return (value==null)? null:value;
                   } else {
                        return null;
              public Connection getConnection(){
                   Connection con = null;
                   try{
                             com.sql.query dbBean=new com.sql.query();
                             con=dbBean.getConnection("WHW");
                             con.setAutoCommit(false);
                   }catch(Exception e){
                             e.printStackTrace();
                   return con;
              public int Chk_WHW_Rignt( String[] User_Data ){
                   if ( (User_Data[3]!=null)&&(User_Data[3].equals("AGT")) ){
                        this.WHW_Right=1;
                        this.Staff_Right=0;
                        return 1;
                   } else if ( (User_Data[6]!=null)&&(User_Data[6].indexOf("W")>-1) ){
                        this.WHW_Right=1;
                        this.Staff_Right=1;
                        return 1;
                   } else if ( (User_Data[16]!=null)&&(User_Data[16].indexOf("D")>-1) ){
                        this.WHW_Right=1;
                        this.Staff_Right=1;
                        return 1;
                   } else {
                        this.WHW_Right=0;
                        this.Staff_Right=0;
                        return 0;
                    public int CheckExist(String lognam, String ibpgrp, String ctyfun, String agtcod){
                   int Result=-1;
                   Statement stmt = null;
                   ResultSet rs = null;
                   Connection con = null;
                   PreparedStatement pstmt = null;
                   String SQLstatement = null;
                   //StringBuffer option = new StringBuffer("");
                   try {
                        con=getConnection();
                        //String SQLstatement = "select dstfun from adm_dw1.saldmdst where dstkey=? ";
                        if ( (lognam!=null)&&(ibpgrp!=null)&&(ctyfun!=null) ){
                             SQLstatement ="SELECT count(b.crtlog) FROM adm_web.whwhddsk b "+
                                                 "WHERE b.lognam=? and b.ibpgrp=? and b.ctyfun=? and b.asocod=? and b.uplerr='N' and b.tsfusr is null";
    //                         System.out.println("CheckExist() - SQLstatement :\n"+SQLstatement);
                             pstmt = con.prepareStatement(SQLstatement);
                             pstmt.setString(1, lognam.trim());
                             pstmt.setString(2, ibpgrp.trim());
                             pstmt.setString(3, ctyfun.trim());
                             pstmt.setString(4, agtcod.trim());
                                rs = pstmt.executeQuery();
                             if (rs.next()) {
                                  Result = rs.getInt(1);
                        return Result;
                   } catch (Exception ex) {
                        System.out.println("CheckExist() ----- " + ex);
                        return -1;
                   } finally {
                        try {
                             if (rs != null) {
                                  rs.close();
                             if (stmt != null) {
                                  stmt.close();
                             if (pstmt != null) {
                                  pstmt.close();
                             if (con != null) {
                                  con.close();
                        } catch (SQLException ex) {
                             System.out.println("CheckExist() ----- " + ex);
              public String GetCusInfo(String usrcod){
                   Statement stmt = null;
                   ResultSet rs = null;
                   Connection con = null;
                   PreparedStatement pstmt = null;
                   String SQLstatement = null;
                   try {
                        con=getConnection();
                        //String SQLstatement = "select dstfun from adm_dw1.saldmdst where dstkey=? ";  
                        if ( (usrcod!=null)&&(usrcod.length()>0)){               
                             SQLstatement ="SELECT a.cusnam, a.grpnam, a.grpcod, b.ctyfun "+
                                  "from adm_dw1.saldmcus a, adm_dw1.saldmcty b where a.grpste=b.stecod and a.cuscod=?";
    //                    System.out.println("WebBean.GetCusInfo() - SQLstatement :\n"+SQLstatement);
                        pstmt = con.prepareStatement(SQLstatement);
                        pstmt.setString(1, usrcod.trim());
                           rs = pstmt.executeQuery();
                        if (rs.next()) {
                             this.cusnam=rs.getString(1);
                             this.grpnam=rs.getString(2);
                             this.ibpgrp=rs.getString(3);
                             this.ctyfun=rs.getString(4);
                             System.out.println("cusam:"+rs.getString(1)+" grpnam:"+rs.getString(2)+" ibpgrp:"+rs.getString(3)+" ctyfun:"+rs.getString(4));
                             return "T";
                        } else {
                             System.out.println("No customer information");
                             return "F";
                   } catch (Exception ex) {
                        System.out.println("WebBean.GetCusInfo() ----- " + ex);
                        return "F";
                   } finally {
                        try {
                             if (rs != null) {
                                  rs.close();
                             if (stmt != null) {
                                  stmt.close();
                             if (pstmt != null) {
                                  pstmt.close();
                             if (con != null) {
                                  con.close();
                        } catch (SQLException ex) {
                             System.out.println("WebBean.GetCusInfo() ----- " + ex);
                    public Vector getWHWData( int[] item, int[] prd, int[] mon, int[] n_item, int[] n_prd, int[] n_mon, byte[] bf ){
                   String Err=null;
                   int exit=-1;
                   int Complete=0;
                   int rows=0;
                   int columns=0;
                   String Sname="";
                   String version="";
                   Vector tb=new Vector();
                   String Valid="";
                   int r_diff= n_item[1]-item[1];
                   int r_whw=mon[1]-item[1];
                   int prow=0;
                   int p_item=0;
                   int p_prd=0;
                   int p_whw=0;
                   try{
                        //System.out.println("bf.length: "+bf.length);
                        ByteArrayInputStream bis= new ByteArrayInputStream( bf );
                        Workbook w = Workbook.getWorkbook( bis );
                        version=w.getVersion();
                        //System.out.println("whw.xls-sheets: "+w.getNumberOfSheets());
                        Sheet s= w.getSheet(0);
                        Sname=s.getName();
                        rows=s.getRows();
                        columns=s.getColumns();
                                  //  System.out.println("Inside get WHW");
                        System.out.println("Columns: "+s.getColumns()+" \tRows: "+s.getRows());
                        if (s.getRows()>12){
                             Cell[] CellA4=s.getRow(3);
                             String str_c4=CellA4[0].getContents();
                             if ( (str_c4.lastIndexOf(":")>-1)&&(str_c4.lastIndexOf("-")>-1) ){
                                  String str_whw_typ=str_c4.substring(0, str_c4.lastIndexOf(":") ).trim();
                                  //System.out.println( "WHW type:"+str_whw_typ );
                                  if ( str_whw_typ.equalsIgnoreCase("Associate Country") ){
                                       String str_whw=str_c4.substring(str_c4.lastIndexOf(":")+1 ).trim();
                                       //System.out.println( "WHW Country:"+str_whw );
                                       String str_asocod=str_whw.substring( 0, str_whw.indexOf("-") ).trim();
                                       //System.out.println( "asocod:"+str_asocod );
                                       String str_ctyfun=str_whw.substring( str_whw.indexOf("-")+1 ).trim();
                                       //System.out.println( "ctyfun:"+str_ctyfun );
                                       this.ctyfun=str_ctyfun;
                                       this.agtcod=(str_asocod.equals(""))?" ":str_asocod;
                                       this.whwtyp="Country";
                                  } else if ( str_whw_typ.equalsIgnoreCase("Customer")|| str_whw_typ.equalsIgnoreCase("IBP Group")) {
                                       String str_whw=str_c4.substring(str_c4.lastIndexOf(":")+1 ).trim();
                                       //System.out.println( "WHW IBP:"+str_whw );
                                       String str_ibpgrp=str_whw.substring( 0, str_whw.lastIndexOf("-") ).trim();
                                       //System.out.println( "ibpgrp:"+str_ibpgrp );
                                       this.ibpgrp=str_ibpgrp;
                                       this.whwtyp="Customer";
                                  } else {
                                       Valid=Valid+"Unknown customer or country";
                             } else {
                                  Valid=Valid+"Unknown upload type";
                             Cell[] hdcs=null;
                             NumberCell nfc=null;
                             hdcs=s.getRow(1);
                             if (hdcs[mon[0]+13].getType()==CellType.NUMBER_FORMULA){
                                  this.TTLPRVORD=hdcs[mon[0]+13].getContents();
                                  //System.out.println("TTLPRVORD - Celltype:"+hdcs[mon[0]+13].getType()+"\n hdcs["+(mon[0]+13)+"].getContents():"+hdcs[mon[0]+13].getContents());
                             } else {
                                  //System.out.println("Valid:"+hdcs[mon[0]+13].getType());
                                  Valid=Valid+"Error in TTLPRVORD";
                             hdcs=s.getRow(2);
                             if (hdcs[mon[0]+13].getType()==CellType.NUMBER_FORMULA){
                                  this.TTLPRVWHW=hdcs[mon[0]+13].getContents();
                                  //System.out.println("TTLPRVWHW - Celltype:"+hdcs[mon[0]+13].getType()+"\n hdcs["+(mon[0]+13)+"].getContents():"+hdcs[mon[0]+13].getContents());
                             } else {
                                  //System.out.println("Valid:"+hdcs[mon[0]+13].getType());
                                  Valid=Valid+", TTLPRVWHW";
                             hdcs=s.getRow(3);
                             if (hdcs[mon[0]+13].getType()==CellType.NUMBER_FORMULA){
                                  this.TTLCURORD=hdcs[mon[0]+13].getContents();
                                  //System.out.println("TTLCURORD - Celltype:"+hdcs[mon[0]+13].getType()+"\n hdcs["+(mon[0]+13)+"].getContents():"+hdcs[mon[0]+13].getContents());
                             } else {
                                  //System.out.println("Valid:"+hdcs[mon[0]+13].getType());
                                  Valid=Valid+", TTLCURORD";
                             hdcs=s.getRow(4);
                             if (hdcs[mon[0]+13].getType()==CellType.NUMBER_FORMULA){
                                  this.TTLCURWHW=hdcs[mon[0]+13].getContents();
                                  //System.out.println("TTLCURWHW - Celltype:"+hdcs[mon[0]+13].getType()+"\n hdcs["+(mon[0]+13)+"].getContents():"+hdcs[mon[0]+13].getContents());
                             } else {
                                  //System.out.println("Valid:"+hdcs[mon[0]+13].getType());
                                  Valid=Valid+", TTLCURWHW";
                        if (Valid.length()>0) {
                             Err=Valid;
                        if ((s.getRows()>12)&&(Valid.equals(""))){
                             //exit=-1;
                             while( true ){
                                  String[] r = new String[15];
                                  if ( exit==-1 ) {
                                       //prow=fr_item;
                                       //System.out.println("Exit:-1, prow:7");
                                       prow=item[1];
                                       exit=0;
                                  //     TEXT -> CellType.EMPTY
                                                    //First row
                                  Cell[] cs=s.getRow( prow );
                                  //System.out.println( "before: cs[2]: "+ cs[2].getContents()+" cs[3]: "+ ((cs[3].getContents()=="")?"Null":cs[3].getContents()) );
                                  if (  (cs[item[0]].getContents()!="")&&(cs[item[0]].getType()!=CellType.EMPTY) ){
                                       Cell[] cs1=s.getRow( prow+r_whw );
                                       r[0]=cs[item[0]].getContents();
                                       r[1]=(cs[prd[0]].getType()==CellType.EMPTY)?null:cs[prd[0]].getContents();
                                       //System.out.println( "before: cs1[mon[0]] Type: "+ cs1[mon[0]].getType() );
                                       if ( (cs1[mon[0]-2].getContents()).equals("Cur. whw") ){
                                            //System.out.println("Getting the WHW data!");
                                       //searching for product code     
                                            r[2]=(cs1[mon[0]].getType()==CellType.EMPTY)?"0":cs1[mon[0]].getContents();
                                            r[3]=(cs1[mon[0]+1].getType()==CellType.EMPTY)?"0":cs1[mon[0]+1].getContents();
                                            r[4]=(cs1[mon[0]+2].getType()==CellType.EMPTY)?"0":cs1[mon[0]+2].getContents();
                                            r[5]=(cs1[mon[0]+3].getType()==CellType.EMPTY)?"0":cs1[mon[0]+3].getContents();
                                            r[6]=(cs1[mon[0]+4].getType()==CellType.EMPTY)?"0":cs1[mon[0]+4].getContents();
                                            r[7]=(cs1[mon[0]+5].getType()==CellType.EMPTY)?"0":cs1[mon[0]+5].getContents();
                                            r[8]=(cs1[mon[0]+6].getType()==CellType.EMPTY)?"0":cs1[mon[0]+6].getContents();
                                            r[9]=(cs1[mon[0]+7].getType()==CellType.EMPTY)?"0":cs1[mon[0]+7].getContents();
                                            r[10]=(cs1[mon[0]+8].getType()==CellType.EMPTY)?"0":cs1[mon[0]+8].getContents();
                                            r[11]=(cs1[mon[0]+9].getType()==CellType.EMPTY)?"0":cs1[mon[0]+9].getContents();
                                            r[12]=(cs1[mon[0]+10].getType()==CellType.EMPTY)?"0":cs1[mon[0]+10].getContents();
                                            r[13]=(cs1[mon[0]+11].getType()==CellType.EMPTY)?"0":cs1[mon[0]+11].getContents();
                                            r[14]=(cs1[mon[0]+12].getType()==CellType.EMPTY)?"0":cs1[mon[0]+12].getContents();
                                       } else {
                                            Err="WHW data of "+r[0]+" - "+r[1]+" was not found on row: "+(prow+r_whw+1)+" !" ;
                                       //System.out.println("r[0]: "+ r[0]+" r[1]: "+r[1]+" r[2]: "+r[2]);
                                       //System.out.println("prow-> "+prow+"; Rows-> "+rows);
                                  } else {
                                       Err="Item number not found on row: "+(prow+1)+" !";
                                  if ( Err==null ){
                                            //     valid data was added into the vector
                                       if ( (r[0]!=null)&&(!r[14].equals("0")) ){
                                            tb.addElement(r);
    public static void main(String args[]){                                                       
                                      hashtable hashtable[] = new hashtable();
                                                            tb.addElement(r);
                                                                   if (hashtable.get(p_item+p_prd)==null) {
                                                                           Enumeration e = hashtable1.keys();
                                                                           while( e. hasMoreElements() ){
                                                                            System.out.println( e.nextElement() );
                                                                   } else {
                                                            System.out.println(r[0]);
                                      hashtable hashtable[] = new hashtable();
                                                            tb.addElement(r);
                                                                   if (hashtable.get(p_item+p_prd)==null) {
                                                                           Enumeration e = hashtable1.keys();
                                                                           while( e. hasMoreElements() ){
                                                                            System.out.println( e.nextElement() );
                                                                   } else {
                                                            System.out.println(r[0]);
                                       //System.out.println("r add into tb: "+tb.size());
                                       prow=prow+r_diff;
                                       Cell[] cs3=s.getRow( prow+1 ); {//if the program cannot find item number then it would go to the next line down
                                       System.out.println("cs3 "+(prow+1));
                                                            System.out.println(cs3.length); // checking the size of the cs3 then go through the reach line and see the dump of type
                                                           // for(int i=0;i<cs3.length;i++){
                                                              //  System.out.println("cs3"+i+" "+cs3);
    // if (cs3[20].getContents().equals("TOTAL :") ){ //orginal code
                                       if (cs3.length>=21 && cs3[20].getContents().equals("TOTAL :")){  //edited code
    //System.out.println("cs3[20].getContents()"+cs3[20].getContents()+"*");
    //System.out.println("[20]!=0?"+cs3[20].getContents()!="0");
    // if (cs3[20].getType()=CellType.EMPTY || cs3[20].getContents().equals("Total: ")) { //edited by Antony                                              
    System.out.println("Complete sucessfully!- Total");
                                            Complete=1;
                                            break;
                                       } else if ( prow>=(rows-2) ){
                                            System.out.println("Complete sucessfully!");
                                            //this.status="Complete sucessfully!";
                                            Complete=1;
                                            break;                         
                                       } else {
                                            //System.out.println("prow-> "+prow+"; Rows-> "+rows); //another test in seeing it moving onto the next line
                                            Cell[] cs2=s.getRow( prow ); //this will get the row from the excel sheet
    System.out.println("Row number: "+prow);
    System.out.println("rows: "+rows);
                                            //System.out.println("cs2[4]-> "+cs2[4].getContents());
                                            if ( (cs2[item[0]].getContents()=="")||(cs2[item[0]].getType()==CellType.EMPTY) ) {// original code     
                                                 //System.out.println("In first empty row!");
                                                 cs2=s.getRow( prow+1 ); //check next product code and break due to error
                                                 //System.out.println("added 1");
    //At this point the programs deals with the next row
    if ( cs2[item[0]].getContents()=="" || cs2[item[0]].getType()==CellType.EMPTY) {     
    Err="There is nothing on next row:"+(prow+1+1)+" !";
    System.out.println("break on error! ->"+ Err);
                                                      break;
                                                 } else {
                                                      prow=prow+1;
    //System.out.println("prow+1-> "+prow+"; rows-> "+rows);
    //check if the program would jump to the next line if it cant find the item code from the excel.
                                            } else if
    //( (cs2[0].getType()==CellType.EMPTY)&&(cs2[4].getType()==CellType.EMPTY) ){ //original code
    // Referring to the description and the A column in excel, Linked to Item Code
    ( (cs2[0].getType()==CellType.EMPTY)&&(cs2[4].getType()==CellType.EMPTY)&&(cs2[2].getType()==CellType.EMPTY) ){
                                                 //System.out.println("Missing Description!"); //changed to missing description because it is not the last row.
    //System.out.println("Last Row!"); //edited by Antony
                                                 cs2=s.getRow( prow+1 );
    //if (cs2[item[18]].getContents()=="Total";)) //orignal code
    //change to
    if ( (cs2[22].getContents()=="TOTAL :") ){
    //Previous error conjured was array index out of bounds exception edited by Antony
                                                      Err="";
                                                      System.out.println("WHW Complete!");
                                                      break;
                             } else {
                                       System.out.println("break on error! ->"+ Err);
                                       break;
                        w.close();
                        //fis.close();
                        bis.close();
                        //System.out.println("Err: "+Err);
                        this.status=Err;
                        if ( Complete==1 ) {
                                  System.out.println("tb in getWHWData(): "+tb.size());
                                  return tb;
                        } else {
                             //System.out.println("getWHWData() get data fail!");
                             return null;
                   } catch (IOException e){
                   this.status="File is loaded in error.";
                   System.out.println(e.toString());
                   //e.printStackTrace();
                   //err=1;
                   return null;
                   } catch (BiffException t){
                        System.out.println(t.toString());
                        t.printStackTrace();
                        this.status="Version may be not supported or file may be corrupted.";
                        try{
                             Workbook w = Workbook.getWorkbook( new java.io.File("D:\\excel\\Empty.xls"));
                             w.close();
         //                    err=2;
                             System.out.println("Excel file is being loaded in error!");
                        } catch (IOException a){
                        System.out.println(a.toString());
                        } catch (BiffException b){
                             System.out.println(b.toString());
                             b.printStackTrace();
                        return null;
    public String WHW_to_DB( Connection conn, Vector itm_data, String lognam, String ibp, String cty, String Now, String asocod )throws SQLException{
                   ResultSet rs = null;
                   PreparedStatement pstmt = null;
                   Statement stmt = null;
                   String SQLstatement=null;
                   String[] Cursor=null;
                   try{
                        conn=getConnection();
                        conn.setAutoCommit(false);
                        //SQLstatement ="INSERT INTO adm_web.whwdtdsk values ( ?, ?, ?, to_date( ?, 'dd-mm-yyyy HH24:MI:SS'), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ? )";
                        SQLstatement ="INSERT INTO adm_web.whwdtdsk "+
                                       " ( lognam, ibpgrp, ctyfun, crtlog, itmcod, prdcod, pjtd01, pjtd02, pjtd03, pjtd04, pjtd05, pjtd06, pjtd07, pjtd08, pjtd09, pjtd10, pjtd11, pjtd12, dirqty, asocod) "+
                                       "values ( ?, ?, ?, to_date( ?, 'dd-mm-yyyy HH24:MI:SS'), ?, ?, to_number(?,'9,999,999'), to_number(?,'9,999,999'), to_number(?,'9,999,999'), to_number(?,'9,999,999'), to_number(?,'9,999,999'), to_number(?,'9,999,999'), to_number(?,'9,999,999'), to_number(?,'9,999,999'), to_number(?,'9,999,999'), to_number(?,'9,999,999'), to_number(?,'9,999,999'), to_number(?,'9,999,999'), to_number(?,'999,999,999'), ? )";
                        pstmt = conn.prepareStatement(SQLstatement);
                        for (int n=0; n<itm_data.size(); ++n){
                             Cursor=(String[])itm_data.elementAt(n);
    System.out.println( "Lognam: "+lognam.trim()+" itmcod: "+Cursor[0]+" prdcod:"+Cursor[1]+" listed!" );
    // System.out.println( "Lognam: "+lognam.trim()+" itmcod: "+Cursor[0]+" prdcod:"+Cursor[1]+" in error!" );
                             //pstmt = conn.prepareStatement(SQLstatement);
    System.out.println("********************************************Start");
                             pstmt.setString( 1, lognam.trim() );
    System.out.println("1 "+lognam.trim()); //print login name
                             pstmt.setString( 2, ibp.trim() );
    System.out.println("2 "+ibp.trim()); // print ibp
                             pstmt.setString( 3, cty.trim() );
    System.out.println("3 "+cty.trim()); //print city name
                             pstmt.setString( 4, Now.trim() );
    System.out.println("4 "+Now.trim()); //print out now //what is now???
                             pstmt.setString( 5, Cursor[0].trim() );
    System.out.println("5 " +Cursor[0].trim());
    pstmt.setString( 6, (Cursor[1]==null)?" ":Cursor[1].trim() );
    System.out.println("6" +(Cursor[1]==null?" ":Cursor[1].trim()));
    pstmt.setString( 7, Cursor[2].trim() );
    System.out.println("7 " +Cursor[2].trim());
    pstmt.setString( 8, Cursor[3].trim() );
    System.out.println("8 "+Cursor[3].trim());;
    pstmt.setString( 9, Cursor[4].trim() );
    System.out.println("9 "+Cursor[4].trim());
                             pstmt.setString( 10, Cursor[5].trim() );
    System.out.println("10 "+Cursor[5].trim());
    pstmt.setString( 11, Cursor[6].trim() );
    System.out.println("11 "+Cursor[6].trim());
    pstmt.setString( 12, Cursor[7].trim() );
    System.out.println("12 "+Cursor[7].trim());
    pstmt.setString( 13, Cursor[8].trim() );
    System.out.println("13 "+Cursor[8].trim());
    pstmt.setString( 14, Cursor[9].trim() );
    System.out.println("14 "+Cursor[9].trim());
    pstmt.setString( 15, Cursor[10].trim() );
    System.out.println("15 "+Cursor[10].trim());
    pstmt.setString( 16, Cursor[11].trim() );
    System.out.println("16 "+Cursor[11].trim());
    pstmt.setString( 17, Cursor[12].trim() );
    System.out.println("17 "+Cursor[12].trim());
    pstmt.setString( 18, Cursor[13].trim() );
    System.out.println("18 "+Cursor[13].trim());
    pstmt.setString( 19, Cursor[14].trim() );
    System.out.println("19 "+Cursor[14].trim());
    pstmt.setString( 20, asocod ); //duplicate error
    System.out.println("20 "+asocod.trim());
    pstmt.executeUpdate();
    System.out.println("********************************************END");
    //System.out.println("SQLstatement "+SQLstatement);
                        //conn.commit();
    return "T";
                   /*} catch (SQLException se) {
                        System.out.println( "Lognam: "+lognam.trim()+" itmcod: "+Cursor[0]+" prdcod:"+Cursor[1]+" in error!" );
                        System.out.println("WHW_to_DB() ----- " + se);
                        return "F";
                   }catch(Exception e){
                        System.out.println("WHW_to_DB() ----- " + e);
                        //return e.toString();
                        return "F";*/
                   } finally {
                        try {
                             if (rs != null) {
                                  rs.close();
                             if (stmt != null) {
                                  stmt.close();
                             if (pstmt != null) {
                                  pstmt.close();
                        } catch (SQLException ex) {
                             System.out.println("WHW_to_DB() ---

  • Reading .log file & Sorting input

    Hello all
    Currently I'm working on a projekt were I have to read a "in.log" file, sort it and save it to another "out.log" file, the contents of the in.log file is:
    [204.0.44.73]: Dir: path
    [204.0.44.73]: Dir: path
    [204.0.44.74]: Dir: path
    [204.0.44.73]: Dir: path
    [204.0.44.74]: Dir: path
    and so on, now what I have to end up with is this in the out.log:
    #1
    [204.0.44.73]: Dir: path
    [204.0.44.73]: Dir: path
    [204.0.44.73]: Dir: path
    Count = 3
    #2
    [204.0.44.74]: Dir: path
    [204.0.44.74]: Dir: path
    Count = 2
    It's for the system administrator at school who doesn't want to do it himself but wants to pay an amount for me to do it (very small amount). I'll pay max duke dollars for a reply which can help me..
    Please help, thx in advance

    I must be really bored... Use it with "java Parser <logname>"
    import java.io.*;
    import java.util.*;
    public class Parser{
         public void splitLog( File input ){
              try{
                   FileInputStream fis = new FileInputStream( input );
                   BufferedReader br = new BufferedReader( new InputStreamReader( fis ) );
                   Hashtable hosts = new Hashtable();
                   String line;
                   while( ( line = br.readLine() ) != null ){
                        StringTokenizer st = new StringTokenizer( line, "]" );
                        if( st.hasMoreTokens() ){
                             String host = st.nextToken();
                             if( host.trim().startsWith("[") ){
                                  host = host.trim().substring(1);
                             if( !hosts.containsKey( host ) ){
                                  hosts.put( host, new Vector() );
                             Vector v = (Vector)hosts.get( host );
                             v.addElement( line );
                   Enumeration enum = hosts.keys();
                   while( enum.hasMoreElements() ){
                        String host = (String)enum.nextElement();
                        Vector v = (Vector)hosts.get(host);
                        FileOutputStream fos = new FileOutputStream( host + ".log" );
                        for( int i = 0; i < v.size(); i++ ){
                             line = (String)v.elementAt( i );
                             fos.write( (line + "\r\n").getBytes());
                        fos.close();
              catch( Exception e ){
                   e.printStackTrace();
         public static void main( String[] args ){
              File input = new File( args[0] );
              Parser parser = new Parser();
              parser.splitLog( input );
    }

  • How can I use active user session that's in an application scope Hashtable?

    First of all, is it possible to use the same session after a user exits and then returns?
    Second, if it is possible, then please tell me what I need to do. So far, this is what I have been doing...
    1.) The user submits login credentials
    2.) The user is authenticated.
    3.) The user does not have an existing session, so a new one is created.
    4.) The user closes the browser.
    5.) The user returns to login page and submits login credentials.
    6.) The user is authenticated.
    7.) The user has an existing session, so it should be used.
    This is where I'm having trouble. All active sessions for my application are stored in a Hashtable. I have been using <%@ page session="false" %> so that a new session is not automatically created. Each time before I create a new session, I check my Hashtable to see if that user has an existing session. If a session exists for that user, then I would like to continue using that session if possible. I have used the methods request.getSession() and request.getSession(false), but a new session is always returned.
    I could create a new session, copy the attributes from the old session(which is stored in my Hashtable) to the new session, and then invalidate the old session, but I'd rather not do that.
    Is there a way that I can use existing sessions that I have stored in my Hashtable?

    First of all, is it possible to use the same session after a user exits and then returns?No, I don't think so. Let me explain why. When the server creates a session object for each client, it needs to know which client is making the request. Remember that HTTP is a stateless protocol. Every time a client makes a request, it sends some sort of session id to the server to let the server know who is trying to make the request. The server will then check to see if a session object exists for that particular client and if so, it will make sure that the max inactive interval (maximum time alloted for that client's session) has not been exceeded. If every thing is okay, then the client can access the session object to get values that were previously placed there. There are many ways that servers try to keep track of clients. One way is to have the clients write the session ID using cookies. But, many people like disallow cookies. So some servers do what is known as URL rewriting. That is, they will write the session ID on the end of the query string. This can also be accomplished programmatically, but it can be taxing to do. Anways, the point is that the client and the server have to have some sort of link between each other and that link is the session ID. So, if the browser is closed, the session ID is lost. That particular client will be forced to get a new session ID the next time the following code is executed:
    //create a session object and set its values
    HttpSession session = request.getSession(true);>
    Second, if it is possible, then please tell me what I
    need to do. So far, this is what I have been doing...
    1.) The user submits login credentials
    2.) The user is authenticated.
    3.) The user does not have an existing session, so a
    new one is created.
    4.) The user closes the browser.
    5.) The user returns to login page and submits login
    credentials.
    6.) The user is authenticated.
    7.) The user has an existing session, so it should
    be used.If you really want to do something like this, you could make up your own ID and store it as a cookie on the client. I've never tried anything like this before so you would have to do your own research. Are you sure you want to do something like this. There is a reason why it works the way it does. There is also a reason why you want to keep the session timeout value some what small. Let me give you an example of some craziness with sessions. A client we once had wanted to keep their sessions open for 4 hours because they said there clients simply did not like to log in all the time. I nearly gasped when I was told we needed to do this. When you make the session time out large (i.e. the maxInactiveInterval( )), then session objects stick around longer in the server. Let's say a client logs into the server and receives a session object. Then, the client makes a few requests. The server knows to keep the session alive as long as the time between requests has not exceeded 4 hours. Then the client closes the browser. How is the server suppose to know that the browser was closed. Well, it doesn't. It just knows to check times between requests. So, that particular session object won't be garbage collected until the session times out. What if a whole bunch of clients did this. Yucko. The server would have a whole bunch of session objects living in memory. What a waste. This is all above and beyond the typical security problems that can arise from having a session open for so long. To make a long story short, you really shouldn't do what you are trying to do unless it is the nature of the app.
    >
    This is where I'm having trouble. All active sessions
    for my application are stored in a Hashtable. I have
    been using <%@ page session="false" %> so that a new
    session is not automatically created. Each time
    before I create a new session, I check my Hashtable
    to see if that user has an existing session. If a
    session exists for that user, then I would like to
    continue using that session if possible. I have used
    the methods request.getSession() and
    request.getSession(false), but a new session is
    always returned.
    I could create a new session, copy the attributes from
    the old session(which is stored in my Hashtable) to
    the new session, and then invalidate the old session,
    but I'd rather not do that.
    Is there a way that I can use existing sessions that I
    have stored in my Hashtable?

  • Sort order in list wrong: in CAML and in view

    Hello,
    When I order my list with document sets by ID, the order is wrong. It is wrong in the list and with caml.
    This is my view (I just set the sort on the ID column):
    The first 4 objects are created by the Client Object Model; the last 4 are created by a SharePoint webpart that I developped myself...
    My code for creating document sets in COM is something like this:
    ListItemCreationInformation newItemInfo = new ListItemCreationInformation
    UnderlyingObjectType = FileSystemObjectType.Folder,
    LeafName = _strLeafname // = date in format YYYYMMDDhhmmss
    ListItem newListItem = myList.AddItem(newItemInfo);
    newListItem["ContentTypeId"] = targetDocumentSetContentType.Id.ToString();
    newListItem["Title"] = title;
    newListItem.Update();
    clientContext.Load(myList);
    clientContext.ExecuteQuery();
    The code in the webpart is this:
    SPContentType docsetCt = myLst.ContentTypes[p.GetFromResourcefile("xxxxxxxxxxxxxx")];
    Hashtable properties = new Hashtable
    {"DocumentSetDescription", ""},
    {"Title", txtTitle.Text}
    SPFolder parentFolder = myLst.RootFolder;
    int newId = GetLastId(myLst) + 1;
    DocumentSet ds = DocumentSet.Create(parentFolder, newId.ToString(CultureInfo.InvariantCulture), docsetCt.Id, properties, true);
    ds.Item["Title"] = title
    ds.Item.Update();
    why is the sort order wrong?
    if i do this query in the U2U Caml builder, the order is also wrong
    <OrderBy><FieldRef Name='ID' Ascending='FALSE' /></OrderBy>
    if i order by "created", the order is also wrong....
    i don't get it....

    Document Sets are great tools for grouping multiple documents together. However, if every set has exactly one document, it would be better to just upload the file and not place it within a Document Set:
    Uploading documents using object model - http://msdn.microsoft.com/en-us/library/office/ms454491(v=office.14).aspx
    Uploading documents using web services -
    http://cecildt.blogspot.com/2010/10/upload-documents-to-sharepoint-2010.html
    If you have requirements to use Document Sets, keep in mind that this adds a layer of complexity beyond a simple Document Library. Behind the scenes, each Document Set is treated as a separate folder, and although can you query items within it, there might
    be extra steps for getting the sort order to ignore the folder structure. Can you try setting the Scope to be "Recursive" and also specify that you are looking only for files and not folders:
    <Eq><FieldRef Name='FSObjType'/><Value Type='Lookup'>1</Value></Eq></Where>
    Dimitri Ayrapetov (MCSE: SharePoint)

Maybe you are looking for