Saturday, 21 September 2013

Quick Notes : Practical usage of collections

Different Types of Collections and when to Use them

Set

HashSet : 

  • When you want unique set to objects. 
  • Make sure equals and hashcode is implemented.
  • This does not maintain the order of object addition. As the name says it is Hashed

TreeSet:
  • You can have the list ordered the way you want, by passing in a comparator.
  • Example: new TreeSet(String.CASE_INSENSITIVE_ORDER)
  • It automatically orders the objects that you add accordingly

LinkedHashSet
  • This gives us the flexibility of HashSet (uniqueness) and 
  • also maintains the insertion-order of objects

Map

HashMap :
  • Easier way of holding Key Value Pair
  • Does not maintain the insertion-order (Hashed)
TreeMap:
  • Sorted Map, Sorting of keys determined by the comparator in the constructor
  • Quickly create a map of case insensitive keys as follows
    new TreeMap(String.CASE_INSENSITIVE_ORDER)
  • Throws a NullPointerException if you use get without a null check.
    treemap.get(null), so better add a null check before invoking get()
LinkedHashMap:
  • Extends HashMap. But, preserves of the insertion order

List:

ArrayList:
  • Quicker way of maintaining a list of objects
  • can add duplicate values.
  • It is advisable to use this collection if we expect more number of gets() than add() or set()
LinkedList:
  • Performs better when you have more additions and insertions than searching the list

Tuesday, 13 August 2013

Deleting Public Keys from GPG and RPM key rings



In order to delete the public keys from the key ring, we would require the key_id. The key_id can be idenfied using the below steps using the file where the public key is stored.

To get the Key Details

gpg --throw-keyids < [Key-File-Absolute Path]

pub  1021D/1689B887 2005-03-11 ABC Company 
sub  1048f/47E5X96D 2005-03-11  [expires: 2015-03-09]

To get the Key-ID from the keyfile

key_id=${gpg --throw-keyids < [Key-File-Absolute Path] | head -1 |  awk {'print $2'} |  cut -d '/' -f2 |  tr [A-Z] [a-z]}

1689B887

Delete from GPG keyring

gpg --delete-key  --yes $key_id

Delete from RPM keyring

rpm -e --allmatches gpg-pubkey-$key_id

Wednesday, 17 July 2013

Linux script to display tree structure of directory

ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'


Output from  a folder. This displays "ONLY" directories
 .
   |-resources
   |-src
   |---java
   |-target


(or)


yum install tree

tree -A
.
├── resources
├── src
│   ├── Hello.java
│   └── java
└── target

-A to be used if you use garbage chars as follows

.
âââ resources
âââ src
â   âââ Hello.java
â   âââ java
âââ target



Reference
http://ssteiner.wordpress.com/2009/05/12/quick-linux-tree-view-of-directory-contents/



Sunday, 7 July 2013

Regex to find non-quoted string match

Created a below regex to  identify , that is not quoted. 

(,) (?=(?:[^\"]|\"[^\"]*'\")*$),

(,) 
    (?=   
           (?:                               # non capturing group
                 [^\"]|                     # string not quoted 
                 \"[^\"]*'\"           # string inside quotes
            )*$                            # many a times until end of string
     )


This has a an issue when you really run it with a lengthy string
positive lookahead  + alteration +  * + lengthy string  +  heap size crunch.




So the below regex will fetch you the 

(,)(?=(?:[^"]*"[^"]*")*[^"]*$)

(,)
   (?=                            # look ahead
       (?:                         # non capturing group, ignore string within group 
           [^"]*                 # group of non-quoted text  
           "[^"]*"               # followed by quoted quote + non quoted (*)+ quote  
        )*                        # this group can be 0 or many
    [^"]*                       # capturing group    (non quoted)
   $)                            # till end of string



Regex Tester Online: http://regexpal.com/


String used to Test 
(state "locked" OR state" not active" NOT state"pending or " OR state"running" AND state" and completed" OR state"error" OR state"warning") AND NOT hidden"true" AND NOT type"Background" AND NOT cycle"true" AND parent"null" AND test"asdfasdf asdfhasd fha sdfhas udfhuasdhfu asudfhasudfhuas fhuihas udfhuashd ufhasuidfhua shdfuas hduhuhasd fuhasdufhas duhuhu hasufhuasdhfdfsdfasdfsdasdsad7777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777aasda777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777sd7777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777as7777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777777d7end")





Wednesday, 12 June 2013

Map with Case-Insensitive Keys

Below is the easy way, for case-insensitive key searches in a Map.


Map<String, String[]> treemap = new TreeMap<String, String[]>(String.CASE_INSENSITIVE_ORDER);

treemap.put("name1","value1");
treemap.put("NAME2","value2");
 
treemap.get("NAME1")   //you get "value1"
treemap.get("naME2")   //you get "value2"



[WARNING]  treemap.get(null) throws NulllPointerException in certain versions of Java

Tuesday, 16 April 2013

Hibernate supporting case-insensitive search with Postgres citext

There are issues with  Hibernate supporting case-insensitive search on citext, with Hibernate Criteria’s and Bind Parameters

Problem :

Assume this is the table structure with the data

CREATE TABLE parententity
(
  id character varying(255) NOT NULL,
  firstname citext,
  lastname character varying(255),
  CONSTRAINT parententity_pkey PRIMARY KEY (id)
)

                  id                                                           |   firstname  |  lastname
--------------------------------------+-----------+------------
AB83B745-BDCE-4033-ADF9-4C8FBC2071A5 |  vidhya         |  shanker
D753F492-F9BA-417E-ABA9-3CE50D90D65A  |  Srividhya    |  Umashanker

Here are our queries

Same Case value
Query q = dao.getSession().createSQLQuery("select * from ParentEntity where firstName=:name")
              .addEntity(ParentEntity.class)
              .setString("name", "Srividhya");
      List l = q.list();
Hibernate fetches  AB83B745-BDCE-4033-ADF9-4C8FBC2071A5 | Srividhya | Umashanker

Where as

Different value
Query q = dao.getSession().createSQLQuery("select * from ParentEntity where firstName=:name")
              .addEntity(ParentEntity.class)
              .setString("name", "SRIVIDHYA");
      List l = q.list();

Hibernate does not fetch any records

which is expected to do a case insensitive fetch,  does not seem to fetch any record. Internally it converts to varchar and does a case sensitive check.
Looks like this is a known  as per Postgres JDBC implementation

package org.postgresql.jdbc2;
    public abstract class AbstractJdbc2Statement implements BaseStatement
   {
       
protected AbstractJdbc2Connection(String host, int port, String user, String database, Properties info, String url) throws SQLException
     {
          String stringType = info.getProperty("stringtype");
        if (stringType != null) {
            if (stringType.equalsIgnoreCase("unspecified"))
                bindStringAsVarchar = false;
            else if (stringType.equalsIgnoreCase("varchar"))
                bindStringAsVarchar = true;
            else
                throw new PSQLException(GT.tr("Unsupported value for stringtype parameter: {0}", stringType),
                PSQLState.INVALID_PARAMETER_VALUE);
        }
     }
    
    public void setString(int parameterIndex, String x) throws SQLException
    {
….
setString(parameterIndex, x, (connection.getStringVarcharFlag() ? Oid.VARCHAR : Oid.UNSPECIFIED));
    }



SOLUTION:


There also seems to be an option now in the postgres JDBC documentation, that allows you to add a connection option stringtype. The option is set in the connection url as
jdbc:postgresql://localhost/test?stringtype=unspecified. The postgres documentation says…

stringtype = String
Specify the type to use when binding PreparedStatement parameters set via setString(). If stringtype is set to varchar (the default), such parameters will be sent to the server as varchar parameters. If stringtype is set to
unspecified, parameters will be sent to the server as untyped values, and the server will attempt to infer an appropriate type. This is useful if you have an existing application that uses setString() to set parameters that
are actually some other type, such as integers, and you are unable to change the application to use an appropriate method such as setInt().


When tried as follows in hibernate.properties  the functionality seems to work both for citext, varchar and text

hibernate.connection.url=jdbc:postgresql://192.168.1.1:5432/test?stringtype=unspecified