Thursday, September 6, 2012

GWT - Cookie provided by RPC doesn't match request cookie

Even after setting the security cookie on client and server-
bindConstant().annotatedWith(SecurityCookie.class).to("mycookie");

I was getting the following exception-

Sep 6, 2012 4:09:40 PM com.gwtplatform.dispatch.server.AbstractDispatchServiceImpl cookieMatch
INFO: No cookie sent by client in RPC. (Did you forget to bind the security cookie client-side? Or it could be an attack.)
Sep 6, 2012 4:09:40 PM com.gwtplatform.dispatch.server.AbstractDispatchServiceImpl execute
SEVERE: Cookie provided by RPC doesn't match request cookie, aborting action, possible XSRF attack. (Maybe you forgot to set the security cookie?) While executing action: com.company.appmodule.client.Login

Solution: Clear cache and cookies from browser.



Sunday, August 26, 2012

GWT Celltable - Add multiple anchors to a cell



I am trying to insert multiple anchors in a single celltable cell. This is how it would look like-
The cars column has multiple cars, each car link can be clicked to perform different actions.
I have extended a MultipleAnchorCell class from AbstractSafeHtmlCell like this-



And then I use this cell in a celltable to create a column. My User class contains comma separated values of cars in a class variable.

      

       

I am still learning GWT and it took me a while to figure this out.

Comments/feedback is welcome.
===============================================================

Saturday, April 7, 2012

GWT dygraph example using visualization datatable

Here is a quick example of how to create a dygraph using GWT and visualization api to get the datatable.

1. Add dygraph-gwt.jar to your build path and these inherits tags in your mysamplegwtproj.gwt.xml file

<inherits name="com.google.gwt.visualization.Visualization"/>
<inherits name="org.danvk.dygraphs"/>

2. Add the following script tag in mysamplegwtproject.html file

<script type="text/javascript" src="dygraph-combined.js">
<script type="text/javascript" src="http://www.google.com/jsapi">
3. Add the following code in your onModuleLoad() function-



        final VerticalPanel vp = new VerticalPanel();
        vp.setWidth("700px");
        vp.setHeight("700px");
        VisualizationUtils.loadVisualizationApi(new Runnable() {
            @Override
            public void run() {
                Query q = Query
                        .create("mysampleproj/getMyDatatable?params=2&id=1");

                q.send(new Callback() {
                    @Override
                    public void onResponse(QueryResponse response) {
                        JavaScriptObject jdygraph = createDygraph(
                                vp.getElement(), response.getDataTable(), 0,
                                100);
                    }
                });
            }
        }, LineChart.PACKAGE);

        RootPanel.get().add(vp);

4. Here is the JSNI function which actually creates the dygraph.


public static native JavaScriptObject createDygraph(Element element,
            DataTable dataTable, double minY, double maxY) /*-{
        var chart = new $wnd.Dygraph.GVizChart(element);
        chart.draw(dataTable, {
            valueRange : [ minY, maxY ],
            displayAnnotations : true,
            showRangeSelector : true,
            legend : 'always',
            labelsDivStyles : {
                'textAlign' : 'right'
            },
            title : 'TITLE',
            titleHeight : 25,            
            axes : {
                x : {
                    pixelsPerLabel : 50
                }
            }            
        });
        return chart;
    }-*/;

Hope this helps. Suggestions/improvements are welcome.

===============================================================
 

Wednesday, April 4, 2012

NoClassDefFoundError: com.google.common.collect.Sets


Error-
NoClassDefFoundError: "com.google.common.collect.Sets"

Solution-
Add guava-11.0.2.jar to WEB-INF/lib and add it to the build path.

Wednesday, March 21, 2012

GWT wrapper for visualization treemap with mouse events

A treemap is a helpful visualization of a data tree. It would be nice if the treemap had features like weighted box sizes for intermediate levels and explicitly setting up colors for non-leaf nodes. I wrote a  quick Google Web Toolkit(GWT) wrapper for Google visualization treemap-

 public class TreeMap extends Visualization<TreeMap.Options>
{
   public static class Options extends AbstractDrawOptions {
       public static Options create() {
           return JavaScriptObject.createObject().cast();
       }

       protected Options() { }
   }

   public static final String PACKAGE = "treemap";

   public TreeMap() {
       super();
   }

   public TreeMap(AbstractDataTable data, Options options) {
       super(data, options);
   }

   @Override
   protected native JavaScriptObject createJso(Element parent) /*-{
       return new $wnd.google.visualization.TreeMap(parent);                
   }-*/;
   
   public final void addOnMouseOverHandler(OnMouseOverHandler handler) {
       Handler.addHandler(this, "onmouseover", handler);
   }
   
   public final void addOnMouseOutHandler(OnMouseOutHandler handler) {
       Handler.addHandler(this, "onmouseout", handler);
   }
}

Tuesday, March 20, 2012

Postgres script - for loop two dimension array using array upper and lower


A basic script to loop over an array in psql-


CREATE OR REPLACE FUNCTION func1(n character varying, v character varying)

  RETURNS integer AS

$BODY$

    DECLARE   

       return_code integer;

    BEGIN

       RAISE NOTICE '(%,%)', n, v;          

       return_code := 1;

    RETURN return_code; 

    EXCEPTION 

        WHEN NO_DATA_FOUND THEN           
           RETURN -1;
    END;

    $BODY$

  LANGUAGE plpgsql;

CREATE OR REPLACE FUNCTION func2()

  RETURNS integer AS

$BODY$

    DECLARE      

       return_code integer;

       pairs varchar[][] := array[['key2','val2'],

                            ['key1','val2']];

    BEGIN

        FOR i IN array_lower(pairs, 1) .. array_upper(pairs, 1)

        LOOP

         --RAISE NOTICE '%,%',pairs[i][1]::varchar, pairs[i][2]::varchar;

           PERFORM func1(pairs[i][1]::varchar, pairs[i][2]::varchar);

        END LOOP;

    return 1;

    END;

    $BODY$

  LANGUAGE plpgsql;

SELECT * from func2();

Saturday, October 15, 2011

Problem - GWT logging not working

When you inherit certain modules in .gwt.xml file, it disables GWT logging. This happened to me when I tried inheriting Requestfactory. Some modules inherit com.google.gwt.logging.LoggingDisabled  internally and thus affect your logging.

To fix this you should explicitly enable logging after you have inherited all your modules. At the end of your list of inherits add the following to your .gwt.xml file-

<set-property name="gwt.logging.enabled" value="TRUE"/>

Executing Postgres crosstab query as a prepared statement


I was executing a crosstab query as a prepared statement in Java(in a GWT app) and getting the following error -

PSQLException - Can't use query methods that take a query string on a PreparedStatement.

With some helpful folks from stackflow, I was able to resolve the error with the following code -

String query = "SELECT * FROM crosstab(
                      'SELECT rowid, a_name, value
                       FROM test WHERE a_name = ''att2''
                                    OR a_name = ''att3''
                      ORDER BY 1,2'
) AS ct(row_name text, cat_1 text, cat_2 text, cat_3 text);";

PreparedStatement stat = conn.prepareStatement(query);
ResultSet rs = stat.getResultSet();

//Note that, it is executeQuery() and not executeQuery(query)
stat.executeQuery();
rs = stat.getResultSet();
while (rs.next()) {
    //TODO
}





Thanks!

PostgreSQL crosstab query - Rotate a table about a pivot

An interesting feature of relational databases(postgres in this case) is the ability to rotate the table about a pivot. So if you have data like this-
 id | rowid | key | value
---+------+----+-------
  1 | test1 | key1      | val1
  2 | test1 | key2      | val2
  3 | test1 | key3      | val3
  4 | test1 | key4      | val4
  5 | test2 | key1      | val5
  6 | test2 | key2      | val6
  7 | test2 | key3      | val7
  8 | test2 | key4      | val8

And want to have a result set like this -

rowid | key1 | key2 | key3 | key4
------+------+-----+-----+------
 test1  | val1  | val2  | val3  | val4
 test2  | val5  | val6  | val7  | val8


It can be achieved by a "crosstab" query in a postgres database -



Update: 02/14/2013
The following can be achieved by a crosstab and also by an interesting SQL which I came across here - http://stackoverflow.com/questions/14863985/postgres-crosstab-maybe


Thursday, September 15, 2011

Virtualbox-Windows 8 developer preview installation error

Downloaded the Windows 8 developers preview yesterday but only to find I could not get it installed on a Oracle Virtualbox. I tried both 32-bit and 64 bit version on a Win 7 64 bit machine(HP EliteBook 8440p). The 32-bit got stuck at the following screen. I need to look for help on this error 0x81B8C63B


EDIT: From "Smiley"'s comments below, after I turned the Virtualization option ON from the BIOS menu at startup, I was able to install windows 8. Thanks.
Surprisingly, I have a Ubuntu virtual machine and it runs fine without turning on the Vitualization option.

Thursday, March 17, 2011

Wxpython snippet - A date time control



Make sure you have installed wxwidgets.



# Create date control
self.dateCtrl = wx.DatePickerCtrl(panel, -1, pos=(130, 70))

#create time control
self.timeCtrl = wx.lib.masked.timectrl.TimeCtrl(panel,display_seconds=False,
                                               fmt24hr=False, id=-1, name='timeCtrl',
                                               style=0,useFixedWidthFont=True,
                                               value=datetime.now().strftime('%X'), pos = (250,70))

To get values -

self.timeCtrl.GetValue()

self.dateCtrl.GetValue())

Monday, March 7, 2011

C++ - Virtual functions

I came across an interesting question in an interview today. It was about virtual functions. I wanted to improve my understanding of virtual functions, so here are some interesting findings, some new and some already known to me.
  • Destructors are called in the order - derived to base(if base destructor is virtual)
  • A virtual function is member function of a class , whose functionality can be overridden by its derived class.
  • The virtual function call is resolved at run time. Unlike non-virtual member functions which are resolved at compile time.(static binding/dynamic binding)
  • If a same 'name' function is implemented in both base class and derived class, the base class function would be called.
  • A class with one or more pure virtual functions becomes an abstract base class. This means that it has to be inherited.
  • An interface class has no members variables, and all of the functions are pure virtual.



Friday, February 4, 2011

Yii web service and php soap client

A web service is a method of communication between two machines. The web methods are exposed for world wide access. Yii has support for implementing web services. It uses SOAP as its foundation layer.

To create a web service-

1. Create a web app using Yii console application.
2. Inside the controllers folder, create a file lets say 'ServiceController.php'.
3. Add the following code, which implements two functions. One adds a session variable and the other returns it back.
<?php
class ServiceController extends CController
{
   public function actions()
    {
       return array(
        'wreader' => array(
          'class' => 'CWebServiceAction',
        ),
      );
    }

    /**
     * @param string username
     * @return float
     * @soap
     */
     public function getauth($uname)
     {
              
            $session = Yii::app()->session;
            $session['u_id'] = 1111;
            return 1;
     }

     /**
     * @param string username
     * @return float
     * @soap
     */
     public function getemp($uname)
     {
        $session = Yii::app()->session;
        return isset($session['u_id'])?$session['u_id']:999;
     }
}

* Remember to mark the web methods with the tag @soap in its doc comment. Yii relies on doc comment to specify the data type of the web method's input parameters and return value.

Create a php file and enter the following code which consumes the web service.
<?php
$client=new SoapClient('http://127.0.0.1/s/index.php/service/wreader');
echo "\n".$client->getauth('harpreet');
echo "\n".$client->getemp('harpreet');

?>

Execute the php script in a terminal to check out your web service.

Open to suggests/improvements.

Read from Magtek card swipe reader in HID mode using libusb-win

This post deals with reading card swipe information from a Magtek USB Swipe Reader when set in HID mode. I used Visual Studio C++ Express Edition for a windows development environment. I installed libusb-win32 from http://www.libusb.org/wiki/libusb-win32
Create a C++ project in Visual studio, include the usb.h file and link the project with libusb.lib. Both of these are included in the libusb package.

The following can be used to read the card information-

// magtekusbhidcardswipe.cpp : Defines the entry point for the console application.
//
#include
#include

#include "stdafx.h"
#include "usb.h"

int _tmain(int argc, _TCHAR* argv[])
{
    struct usb_bus *busses;
    struct usb_bus *bus;
    struct usb_device *dev;
    int c, i, res;
    char data[337];
    char idata[10];

    usb_init();
    usb_find_busses();
    usb_find_devices();
    busses = usb_get_busses();
    for (bus = busses; bus; bus = bus->next) {

        for (dev = bus->devices; dev; dev = dev->next) {           
        if(dev->descriptor.idProduct == 2 && dev->descriptor.idVendor == 0x801) {
        printf("Product id: %04hx" ,dev->descriptor.idProduct);
        printf("Vendor id: %04hx \n" ,dev->descriptor.idVendor);
               
        usb_dev_handle *l_Handle = usb_open( dev);
        if( NULL == l_Handle ){
            printf( "usb_open(): no handle to device\n" );
        }
        res = usb_claim_interface(l_Handle, 0);
        if(res  < -EBUSY) {
            printf("Device interface not available to be claimed! \n");
            exit(0);
        }
        if(res < -ENOMEM) {
            printf("Insufficient Memory! \n");
            exit(0);
        }
        printf( "\nPlease swipe your card\n",res );
       
        res = usb_interrupt_read(l_Handle, 0x81, data, 337, -1);
        printf( "\nusb_interrupt_read %d \n",res ); 
       
        c=-1;
                //I am interested in only 10 characters in this range
        for(i=1;i<10;i++) {
            idata[++c] = data[i];
        }
        c=atoi(idata);
        printf( "\nMy data : %d\n",c);
       
        usb_release_interface(l_Handle, 0);            
        usb_close(l_Handle);
        }
       }
    }
    getchar();
    return 0;
}
 


Suggestions/improvements are welcome as always.



Tuesday, February 1, 2011

Iphone 4 does not mount on Ubuntu after iOS 4.2 upgrade - DBus Error

After I upgraded my iphone to iOS 4.2, I was not longer able to mount it on Ubuntu 10.10. Whenever I got plugged it in, I would get an error message -
DBus error org.freedesktop.DBus.Error.NoReply: Message did not receive a reply (timeout by message bus)


I looked it up and found a workaround, seems like I need to update to a newer version of libimobiledevice.

Here is how I did it-

Unplug the iPhone and execute the following in the terminal window.

sudo add-apt-repository ppa:pmcenery/ppa
sudo apt-get update
sudo apt-get upgrade

sudo apt-get install libimobiledevice-utils


After the above install, plug in the iphone and execute -

idevicepair unpair
idevicepair pair
idevicepair validate



That was it and we are back with Iphone on Ubuntu.

Monday, January 17, 2011

C++ - prime numbers

I was reading about algorithms the other day and came to know of a faster algorithm to find prime numbers. It is called the Sieve of Eratosthenes. When I compared the execution times of this algorithm to the one I coded, the times were remarkably faster. A very simple and impressive algorithm to find prime numbers less than a number n.