Category: Uncategorized

  • Triming leading and trailing new lines with regex.

    Here is some regex to trim leading/trailing newlines carriage and spaces returns from some text.

    Without replacing 'spaces' just new lines/carriage returns.
    ^(\n|\r)+|(\n|\r)+\Z
    
    This will trim also spaces
    ^(\n|\r|\s)+|(\n|\r|\s)+\Z
    

    Quick explanation might be in order. This regex consists of two parts, first one start at the beginning of the the line and follows consuming ‘\n’ or ‘\r’ one ore more times. Second part consumes ‘\n’ or ‘\r’ one or more times followed by end of input string or new line.

    Example Input

    
            
     
    Some text bla
    
    
    
    More text after some breaks in between.
    
    
    
    
    
    
    

    Output

    Some text bla
    
    
    
    More text after some breaks in between.
    
  • No Dialect mapping for JDBC type: -4

    Yet another fun day with hibernate.
    While working on ResourcePhaseListener for JSF attachment problem I run into following problem while trying to retrieve BLOB from MySQL db.

    org.hibernate.MappingException: No Dialect mapping for JDBC type: -4 No Dialect mapping for JDBC type: -4
    

    Here is the offending code:

    SerializableBlob result= null;
    Session hibSession=(Session) em.getDelegate();
    result = (SerializableBlob)	
    hibSession.createSQLQuery("Select DATA from Table")	
    .addScalar("DATA", Hibernate.BLOB)			
    .uniqueResult();				
    

    Adding the mapping addScalar("DATA", Hibernate.BLOB) solved the problem.

  • Modulo based counters

    Sometimes we need counters that wrap around at certain intervals ex:

    1,2,3,1,2,3,1,2,3


    One way of doing this would be to increment our ‘counter’ and then reset it when it reaches our number

    int N = 3;
    int counter = 0;
    if (counter == N){
      counter = 0;
    }
    counter++;
    

    But there are also couple other ways this same could be achieved.

    Modulus

    Using modulus operator ‘%’ we can divide the counter and get our wrapped value, where N is the value we will wrap at.

    counter = (counter+1) % N;
    

    Binary AND

    This is almost this same approach as modulus but we are ‘AND’ing the counter with a power of 2. ex 1, 2, 4, 8, 16 … 2^n . Only problem here is that we have to AND with a power of 2.

    counter = (counter+1) & 0x1;
    

    produces 0,1,0,1,0,1

    Test program

    /**
     * Test program  for testing Modulus, Binary AND increments
     * @author greg
     *
     */
    public class ModulePowerCounter {
    
    	private static final int MAX_LOOP = 100000000;
    	private static final int N = 2;
    	private static final int POWER_OF_2 = 0x1;
    	
    	public static void main(String[] args) {
    		long modTime = modulo();
    		long counterTime = counter();
    		long po2Time = powerOf2();		
    		
    		System.out.println(String.format("modTime = %s", modTime));
    		System.out.println(String.format("counterTime = %s", counterTime));
    		System.out.println(String.format("po2Time = %s", po2Time));
    	}
    	
    	private static long powerOf2(){
    		long start = System.currentTimeMillis();
    		int counter = 0;
    		for (int i = 0; i < MAX_LOOP; i++) {
    			counter = (counter+1) & POWER_OF_2;
    		}				
    		return System.currentTimeMillis() - start;
    	}
    	
    	private static long modulo(){
    		long start = System.currentTimeMillis();
    		int counter = 0;
    		for (int i = 0; i < MAX_LOOP; i++) {
    			counter = (counter+1) % N;
    		}				
    		return System.currentTimeMillis() - start;
    	}
    	
    	private static long counter(){
    		long start = System.currentTimeMillis();
    		int counter = 0;
    		for (int i = 0; i < MAX_LOOP; i++) {
    			if(counter == N)counter = 0;
    			counter++;
    		}				
    		return System.currentTimeMillis() - start;
    	}
    }
    
    

    Performance

    This is the fun part, so we have 3 different ways to achieve same thing but how do they perform.

    Lets think about it, division is much more expensive than 'addition and test' which is more expensive than binary manipulation, our test program confirms our assumption.

    modTime = 1258
    counterTime = 449
    po2Time = 108
    

    As we see Power of 2 outperforms other methods by far, but its only for powers of 2, also our plain counter is almost 2.5 times faster than modulus as well. So why would we like to use modulus increments at all? Well in my opinion I think they provide a clean code and if used properly they are a great tool to know of.

  • GLSurfaceView queueEvent and onTouchEvent seams broken!!!

    What a title, I know but thats exactly what it is.

    This issue is happening on Android 1.6 so it might already been fixed. Just as per documentation i have implemented my GLSurfaceView as GameGLSurfaceView and overridden public boolean onTouchEvent(final MotionEvent event) method as so.

    /**
    	 * Capture touch event and delegate it to our renderer
    	 */
    	public boolean onTouchEvent(final MotionEvent event) {
    		// This method will be called on the rendering thread
    		Log.i(TAG, "GOT EVENT : "+event.getAction());
    		//mRenderer.onTouchEvent(event);
    		queueEvent(new Runnable(){
    			public void run() {
    				mRenderer.onTouchEvent(event);
    		}});
    		return true;
    	}
    

    and in my renderer I simply print that I received the event.

    06-09 15:16:37.456: INFO/GameSurfaceView(14749): GOT EVENT : 0
    06-09 15:16:37.466: INFO/GameSurfaceView(14749): GOT EVENT : 2
    06-09 15:16:37.486: DEBUG/com.fivebrothers.engine.scene.AbstractRenderer(14749): RECIVED EVENT : 2
    06-09 15:16:37.486: DEBUG/com.fivebrothers.engine.scene.AbstractRenderer(14749): RECIVED EVENT : 2
    06-09 15:16:37.506: INFO/GameSurfaceView(14749): GOT EVENT : 2
    06-09 15:16:37.506: INFO/GameSurfaceView(14749): GOT EVENT : 1
    06-09 15:16:37.566: DEBUG/com.fivebrothers.engine.scene.AbstractRenderer(14749): RECIVED EVENT : 1
    06-09 15:16:37.566: DEBUG/com.fivebrothers.engine.scene.AbstractRenderer(14749): RECIVED EVENT : 1
    

    As you can see we have never recived event that MotionEvent.ACTION_DOWN have fired. So I really don’t know what might be the problem here.

    One solution I have found is to call directly as so

            /**
    	 * Capture touch event and delegate it to our renderer
    	 */
    	public boolean onTouchEvent(final MotionEvent event) {	
    		return mRenderer.onTouchEvent(event);
    	}
    

    this does work but is it correct ?

  • Expanding Rich tree nodes programmatically

    I have found two different methods for expanding nodes in Rich tree  from code, they both take  advantage of component binding and component state.

    Tree Setup

    
    	 
    		        
    	 
    
    

    Only thing to note here is the binding attribute that we setup in our backing bean.

    	protected org.richfaces.component.UITree sampleTreeBinding; 
    

    for both solutions after we changed the sampleTree we need to update the binding with new value whitch is
    value="#{ourbean.sampleTree}"

    // Make sure that we set the new TreeModel on current binding
    sampleTreeBinding.setValue(sampleTree);
    

    Solution 1 : Expanding all nodes

    TreeState componentState = (TreeState) sampleTreeBinding.getComponentState();
    try {
    	componentState.expandAll(sampleTreeBinding);
    } catch (IOException e) {
    	e.printStackTrace();
    }
    

    This will expand all levels of the nodes.

    Solution 2 : Expanding only nodes that meet our criteria

    try {
    	final TreeState state = (TreeState) sampleTreeBinding.getComponentState();
    	sampleTreeBinding.walk(FacesContext.getCurrentInstance(), new DataVisitor(){
    		@SuppressWarnings("unchecked")
    		public void process(FacesContext context, Object rowKey, Object argument)
    		throws IOException {
    			TreeRowKey row = (TreeRowKey)rowKey;
    			if(row.depth() == 1){
    				state.expandNode(sampleTreeBinding, (TreeRowKey)rowKey);
    			}
    		}
    	});
    }
    catch (IOException e) {
    	e.printStackTrace();
    }
    
    

    Here we are only expanding nodes at depth 1 but it could be anything. Idea is that we are walking the tree
    and checking if we are interested in the doing something with that node if so then we can modify it here.

    I hope this helps.

  • Quitsomething.com has been launched

    Finally I have launched quitsomething.com a website dedicated to helping quitting bad habits.

    The site is in its infancy stage so I assume there are bugs, also if you thing you like it please spread the word via Twitter, Facebook etc…

    Quitsomething.com Homepage
    Quitsomething.com Homepage

  • Show last executed query SQL Server – Disected

    I found this online, without explanation so I will dissect the query and explain what is happening.

    SELECT deqs.last_execution_time AS [Time], dest.TEXT AS [Query]
    FROM sys.dm_exec_query_stats AS deqs
    CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
    ORDER BY deqs.last_execution_time DESC
    

    This beautifully crafter query will show us last few queries executed on they db, very usefull for seeing what is Hibernate generating for us.

  • Including spaces/html entities in JSF component output.

    Rather a silly problem but a problem nevertheless, including html entities as spaces special charactes etc… causes them to be escaped by the jsf.

    So something like getSpacedName(){return "Hello   world";} will be outputed in the pages exactly as we have entered in out method above. On regulat h:outputText we can use ‘escape’ attribute and set it to false and get what we desire but with other components that output a dropdown or something where formating is in need thats not possible.

    Solution is to use the Unicode characters

    getSpacedName(){
      String space  = "\u00a0";
      return String.format("Hello%s%s%%sworld",space, space, space);
    }
    

    I know that we should not be doing crazy things like this in our backingbeans but when you have to you have to.
    space_screen

  • Why do I get a java.sql.SQLException: “Unable to get information from SQL Server” when trying to connect to an SQL Server instance?

    Possible solution 1

    I am using jtds driver so I would suggest checkingout their proposed solution first here http://jtds.sourceforge.net/faq.html#instanceGetInfo

    Possible solution 2

    Their solution did not for me so here is what I did :
    From cmd prompt run
    sqlcmd -L and make sure that the server you are connecting is listed in the returned list, if its not then there is your problem.
    Simply restarting ‘SQL Browser’ and ‘SQL Server’ should work, run you sqlcmd -L command and make sure that your server is visible in the list.

  • org.hibernate.HibernateException: The chosen transaction strategy requires access to the JTA TransactionManager

    While setting up a simple web app on JBoss 5 using container manager transaction I run into following exception

    Caused by: org.hibernate.HibernateException: The chosen transaction strategy requires access to the JTA TransactionManager
    	at org.hibernate.impl.SessionFactoryImpl.(SessionFactoryImpl.java:361)
    	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1327)
    
    

    Well after some research I figured out that the cause of this were two simple configuration options in persistence.xml

    First we need to make sure we are using JTA as transaction-type (by default)

      
    

    Second make sure we have following line under properties node

      
    

    Thats it, I hope this helps someone.