Author: greg

  • 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.

  • How to read the files placed in WEB-INF from JSF

    Reading files from WEB-INF in JSF

    This no different than reading files from a Servlet except it involves a extra step of getting ServletContext from FacesContext

    FacesContext context = FacesContext.getCurrentInstance();
    ExternalContext externalContext = context.getExternalContext();
    ServletContext sc = (ServletContext)externalContext.getContext();
    String sc.getRealPath("/WEB-INF/somefile.xml");
    

    Here we are getting the path to the file but you could read it if you like.

  • UnsatisfiedLinkError: javaxpcomglue.dll: Can’t find dependent libraries

    While playing around with JavaXPCOM I have run into couple issues. I am running on window 7 64 bit.

    When trying to initialize my GRE (Gecko Runtime Environment) I got following exception

    Exception in thread "main" java.lang.UnsatisfiedLinkError: D:\xulrunner-sdk\bin\javaxpcomglue.dll: Can't find dependent libraries
    	at java.lang.ClassLoader$NativeLibrary.load(Native Method)
    	at java.lang.ClassLoader.loadLibrary0(ClassLoader.java:1803)
    	at java.lang.ClassLoader.loadLibrary(ClassLoader.java:1699)
    	at java.lang.Runtime.load0(Runtime.java:770)
    	at java.lang.System.load(System.java:1003)
    	at org.mozilla.xpcom.internal.JavaXPCOMMethods.registerJavaXPCOMMethods(JavaXPCOMMethods.java:57)
    	at org.mozilla.xpcom.internal.MozillaImpl.initialize(MozillaImpl.java:48)
    	at org.mozilla.xpcom.Mozilla.initialize(Mozilla.java:668)
    	at SampleBroswer.init(SampleBroswer.java:69)
    	at SampleBroswer.main(SampleBroswer.java:45)
    

    What is strange on my other dev machine same configuration I don’t have this problem, very strange.

    Problem is that the file mozcrt19.dll can’t be found. So what I did is that I copied that file from xulrunner-sdk\bin to my C:\Windows\SysWOW64 folder and that fixed the problem. Still little puzzled over why my other machine is not throwing this exception.

  • 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.

  • Preventing ViewExpiredException in JSF

    When our page is idle for x amount of time the view will expire and throw javax.faces.application.ViewExpiredException to prevent this from happening
    one solution is to create CustomViewHandler that extends ViewHandler
    and override restoreView method all the other methods are being delegated to the Parent

    import java.io.IOException;
    import javax.faces.FacesException;
    import javax.faces.application.ViewHandler;
    import javax.faces.component.UIViewRoot;
    import javax.faces.context.FacesContext;
    import javax.servlet.http.HttpServletRequest;
    
    public class CustomViewHandler extends ViewHandler {
    	private ViewHandler parent;
    
    	public CustomViewHandler(ViewHandler parent) {
    		//System.out.println("CustomViewHandler.CustomViewHandler():Parent View Handler:"+parent.getClass());
    		this.parent = parent;
    	}
    
        @Override public UIViewRoot restoreView(FacesContext facesContext, String viewId) {
    	/**
    	 * {@link javax.faces.application.ViewExpiredException}. This happens only  when we try to logout from timed out pages.
    	 */
    	UIViewRoot root =null; 
    	root = parent.restoreView(facesContext, viewId);
    	if(root == null) {			
    		root = createView(facesContext, viewId);
    	}
    	return root;
     }
     
     @Override
    	public Locale calculateLocale(FacesContext facesContext) {
    		return parent.calculateLocale(facesContext);
    	}
    
    	@Override
    	public String calculateRenderKitId(FacesContext facesContext) {
    		String renderKitId = parent.calculateRenderKitId(facesContext);
    		//System.out.println("CustomViewHandler.calculateRenderKitId():RenderKitId: "+renderKitId);
    		return renderKitId;
    	}
    
    	@Override
    	public UIViewRoot createView(FacesContext facesContext, String viewId) {
    		return parent.createView(facesContext, viewId);
    	}
    	
    	
        @Override
    	public String getActionURL(FacesContext facesContext, String actionId) {
    		return parent.getActionURL(facesContext, actionId);
    	}
    
    	@Override
    	public String getResourceURL(FacesContext facesContext, String resId) {
    		return parent.getResourceURL(facesContext, resId);
    	}
    
    	@Override
    	public void renderView(FacesContext facesContext, UIViewRoot viewId) throws IOException, FacesException {
    		parent.renderView(facesContext, viewId);
    
    	}
    
    	@Override
    	public void writeState(FacesContext facesContext) throws IOException {
    		parent.writeState(facesContext);
    	}
    
    	public ViewHandler getParent() {
    		return parent;
    	}
    
    }
    

    Then you need to add it to your faces-config.xml

     		
    com.demo.CustomViewHandler
    

    This will prevent you from getting ViewExpiredException’s

  • Use argument in EL expression

    There is couple ways about doing that, you could use JBoss EL expression implementation they support method calls with parameters check out Seam, or use similar approach as @digitaljoel suggested.
    This is what I created for that purpose, you can call static and static methods, not a great solution but it does the job.

        
              Hello Panel    
          
    

    @Util is just an alias to com.mycomp.util where

    **Example 2**

                        
            #{t:call(session, 'org.apache.catalina.session.StandardSessionFacade', 'removeAttribute', t:params(t:param(item,'')))}      
        
    

    t:call, t:params, t:param are function defined in project-taglib.xml as so

        	
    		call
    		util.Functions
    		java.lang.Object call(java.lang.Object, java.lang.String, java.lang.String, java.lang.Object[])
    	
    	
    		param
    		.util.Functions
    		java.lang.String param(java.lang.Object, java.lang.String)
    		
    	
    	
    		params
    		util.Functions
    		java.lang.Object[] params(java.lang.String)
    		
    

    Here is the implementation

        package mycompany.web.util;
    
    import java.beans.XMLDecoder;
    import java.beans.XMLEncoder;
    import java.io.BufferedOutputStream;
    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.ObjectOutputStream;
    import java.io.StringWriter;
    import java.lang.reflect.Array;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    
    import javax.el.MethodNotFoundException;
    
    
    public class Functions {
    	
    	private  static HashMap alliasMap;
    	static{
    		alliasMap=new HashMap();
    		alliasMap.put("@DateUtil", "com.americanbanksystems.compliance.util.DateUtil");
    		//Match anything following the dot(.)
    		alliasMap.put("@Util.*", "com.americanbanksystems.compliance.util");
    		
    		alliasMap.put("@Application.*", "com.americanbanksystems.compliance.application");
    		
    	}
    	
    
    
    	
    	public static String param(Object obj, String cls) {	
    		//make sure that passed in object is not null
    		if(obj==null){
    			obj="";
    		}
    	
    		ByteArrayOutputStream baut=new ByteArrayOutputStream();
    		XMLEncoder encoder=new XMLEncoder( baut );
    		//Bug in the JDK
    		//http://bugs.sun.com/bugdatabase/view_bug.do;jsessionid=c993c9a3160fd7de44075a2a1fa?bug_id=6525396
    		if(obj instanceof java.sql.Timestamp){
    			Date o = new Date(((java.sql.Timestamp)obj).getTime());
    			obj=o;
    		}		
    		//Checking if this is possible 
    		if(String.class.isAssignableFrom(obj.getClass())){
    			//removed trailing +" " because it was causing indexOf return invalid value
    			//Unknown side effects
    			obj=FacesUtil.get(obj.toString());			
    		}
    			encoder.writeObject( obj );
    		encoder.close();
    		return new String(baut.toByteArray());
    	}
    	
    	private static Object decode(String str){
    		ByteArrayInputStream bais=new ByteArrayInputStream(str.getBytes());
    		XMLDecoder decoder=new XMLDecoder(bais);
    		return decoder.readObject();
    	}
    	
    	public static Object[] params(String str){
    		// (?<=)\s*(?=)\\s*(?=-1){
    			String subpackage=qualifiedClassname;
    			String originalClass=qualifiedClassname;
    			//Split at the dot
    			boolean isPackageAllias=false;
    			String[] sp=subpackage.split("\\.");	
    			if(sp.length>1){
    				subpackage=sp[0]+".*";
    				isPackageAllias=true;
    			}
    			if(alliasMap.containsKey(subpackage)){
    				String value = alliasMap.get(subpackage);
    				if(isPackageAllias){
    					qualifiedClassname=subpackage.replace(sp[0], value);
    					qualifiedClassname=qualifiedClassname.replace(".*", originalClass.replace(sp[0],""));
    				}else{
    					qualifiedClassname=value;
    				}
    			}else{
    				throw new IllegalArgumentException("Allias name '"+qualifiedClassname+"' not found");
    			}
    		}
    		Class clazz;
    		try {
    			clazz = Class.forName(qualifiedClassname);
    			//Find method by methodName,Argument Types
    			Class[] argumentTypes=new Class[methodArguments.length];	
    
    			for(int i=0;i -1) {
    					String arg = methodArguments[i].toString();
    					arg = arg.substring(2, arg.length());
    					try {
    						int outchar = Integer.parseInt(arg, 16);
    						if (Character.isDefined(outchar)) {
    							methodArguments[i] = String.valueOf((char) outchar);
    						}
    					} catch (NumberFormatException nfe) {
    						// Suppress error and continue assuming this is a regular string
    					}
    				}
    			}
    			
    			Method methodToInvoke = null;
    			try{
    				methodToInvoke  = clazz.getMethod(methodName, argumentTypes);
    			}catch(NoSuchMethodException nsm){//Find by method name/ argument count
    				for (Method method : clazz.getMethods()) {
    					if (method.getName().equals(methodName)  && method.getParameterTypes().length == methodArguments.length) {
    						if (null == owningObject) {
    							owningObject = clazz.newInstance();
    						}
    						methodToInvoke=method;
    						break;
    					}
    				}
    			}
    		
    			if(methodToInvoke!=null){								
    				return methodToInvoke.invoke(owningObject, methodArguments);
    			}else{
    				throw new InstantiationException("method not found :" + methodName);	
    			}
    
    		} catch (ClassNotFoundException e) {
    			e.printStackTrace();
    		} catch (IllegalArgumentException e) {
    			e.printStackTrace();
    		} catch (IllegalAccessException e) {
    			e.printStackTrace();
    		} catch (InvocationTargetException e) {
    			e.printStackTrace();
    		} catch (InstantiationException e) {
    			e.printStackTrace();
    		}
    		return null;
    	}
    
    
    	public static void main(String[] arg) {
    		// StringBuffer buff=new StringBuffer();
    		// buff.append("Gregs init");
    		// Functions.call(java.lang.Class, T, java.lang.String, java.lang.String, java.lang.Object...)
    		/*
    		 * Functions.call(StringBuffer.class, buff, "java.lang.StringBuffer","append"," Init ");
    		 * Functions.call(StringBuffer.class, buff, "java.lang.StringBuffer","append"," greg ");
    		 * System.out.println("output="+ buff);
    		 */
    
    		//#{t:call(null, ".util.DateUtil", "normalizeDate", t:parametize(editRiskActionPlan.riskActionPlan.completionDate,",","java.lang.Object"))}
    	//	c(call(null, "util.DateUtil", "normalizeDate", new Date()));
    		
    		//	#{t:parametize(editRiskActionPlan.riskActionPlan.completionDate,",","java.lang.Object")}
    		//parametize((new Date()).toString(),",","java.lang.Object");
    		Date a=new Date();
    		
    		Date b=new Date();
    		
    		String rawString=param((Date)b, Date.class.toString() );					
    		//System.out.println(rawString);
    		
    		//Replaced=#{t:call("Gregs ' car", 'java.lang.String', 'replace', t:params( parameter ))}
    		
    		String paramA=param("\\u0027","");
    		String paramB=param("\\u0022","");
    		String params=paramA+paramB;
    		String in="I need to ' have a replaced single quote with double";
    		String out=(String)call(in, "java.lang.String", "replace", params(params));
    		
    		System.out.println(out);
    		
    		
    		/*
    		Object[] obj=params(rawString);
    		for(Object o:obj){
    			System.out.println(o);
    		}
    		//c(call(null, "@DateUtil", "normalizeDate", obj));
    		
    		*/
    		
    	}
    
    }
    

    I hope this helps, btw this was copied/pasted from my project so not sure if I missed anything.

  • Project quitsomething.com rolled out

    Just started working on a new project quitsomething.com, idea is simple keeps a diary of things that I want to quit hence the name “quitsomething”.

    Technology

    • C#
    • jQuery
    • NHibernate with MySQL
    • Twitter Integration

    Why NHibernate with MySQL? Well I am familiar with Hibernate and MySQL and I don’t want to pay extra for having extra MSSql Database from my hosting provider.

    Update

    Project have officially moved to public beta, I am having a designer taking a look at the site design and making some improvements.

    Official launch is for Jan 01 2010, just in time to create your New Year resolutions.