Blog

  • Invoking Webservice Methods from Java

    This is my helper method for invoking webservices from java. One bonus perk is that this handles the exception when we are using self signed certificates by providing our own HostnameVerifier. This could be more generalized but all I needed was to invoke this one server.

    	/**
    	 * Invoke webservice to retrive data
    	 * 
    	 * @param 
    	 *            Return type the service will return
    	 * @param T
    	 * @param methodName
    	 *            name of method to execute
    	 * @param methodArgument
    	 *            need to match the methods in the webservice
    	 * @return
    	 */
    	public  T invokeWebserviceService(Class T, String methodName,
    			Object... methodArgument) {
    		T result = null;
    		try {
    			HttpServletRequest req = getRequest();
    			String host = req.getServerName();
    			String schema = "http";
    			if ("https".equals(req.getScheme())) {
    				schema = "https";
    				// Need to overide HostnameVerifier otherwise it throws a
    				// exception when we are using selfsigned certificates
    				HostnameVerifier hv = new HostnameVerifier() {
    					public boolean verify(String urlHostName, SSLSession session) {
    						return true;
    					}
    				};
    				HttpsURLConnection.setDefaultHostnameVerifier(hv);
    			}
    
    			String wsdlURL = schema + "://" + host
    					+ "/webservices/RiskBean"
    					+ schema.toUpperCase() + "?wsdl";
    			URL url = new URL(wsdlURL);
    
    			String ns = "http://reporting.ws.com/";
    			QName qname = new QName(ns, "RiskService"
    					+ schema.toUpperCase());
    			QName port = new QName(ns, "RiskBean"
    					+ schema.toUpperCase() + "Port");
    			QName operation = new QName(ns, methodName);
    
    			ServiceFactory riskServiceFactory = ServiceFactory.newInstance();
    			Service riskService = riskServiceFactory.createService(url, qname);
    
    			Call call = riskService.createCall(port, operation);
    			result = (T) call.invoke(methodArgument);
    		} catch (Exception e) {
    			e.printStackTrace();
    		}
    		return result;
    	}
    

    Hopefully someone finds this helpful.

  • Detaching managed entity from entitymanager.

    This code will detach a entity from hibernate Entitymanger making it thus unmanaged entity.

    // Prepare workbook object to be used for cloning.
     Session session = (Session) entityManager.getDelegate();
     session.evict(workbook); // same as detached
     workbook.setId(null);
    
  • Ant BuildException Cannot run program “..\src\protoc”

    Error that I am getting when trying to run mvn test on google protobuf library.

    [INFO] Executing tasks
    [INFO] ------------------------------------------------------------------------
    [ERROR] BUILD ERROR
    [INFO] ------------------------------------------------------------------------
    [INFO] An Ant BuildException has occured: Execute failed: java.io.IOException: Cannot run program "..\src\protoc": CreateProcess error=2, The system c
    annot find the file specified
    
    [INFO] ------------------------------------------------------------------------
    [INFO] For more information, run Maven with the -e switch
    

    I did place protoc.exe in the src directory. As a side note this is running on windows machine.

    Quick solution that I found was to edit the pom.xml file and modify the Ant tast into

          
                    
    
  • Ant BuildException Cannot run program “..\src\protoc”

    Error that I am getting when trying to run mvn test on google protobuf library.

    [INFO] Executing tasks
    [INFO] ------------------------------------------------------------------------
    [ERROR] BUILD ERROR
    [INFO] ------------------------------------------------------------------------
    [INFO] An Ant BuildException has occured: Execute failed: java.io.IOException: Cannot run program "..\src\protoc": CreateProcess error=2, The system c
    annot find the file specified
    
    [INFO] ------------------------------------------------------------------------
    [INFO] For more information, run Maven with the -e switch
    

    I did place protoc.exe in the src directory. As a side note this is running on windows machine.

    Quick solution that I found was to edit the pom.xml file and modify the Ant tast into

          
                    
    
  • SQL Injection Presentation for ISSA

    This is a PowerPoint of presentation I gave for ISSA group in Oklahoma City, OK

    Here is listing of assets used during the presentation

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