Tuesday, June 5, 2012

Atlapp and secure atl !!

After upgrading to VS2008, I started getting errors for lstrlenA, size_t, and lstrcpynA. My "include directories" settings are exactly the same as my old VS2005, and if I open the project in VS2005, everything compiles just fine. So what is the fix for this problem??

And the fix is really simple, before including atlapp.h, just define:
 
#define _SECURE_ATL 1 


Tuesday, May 1, 2012

SWT - Capturing Control Screen-Shot

SWT code for capturing control screen-shot.

public class ScreenCaptureTest 
{
 public static void main(String[] args) 
 {
  String[] names  = {"Harry", "Sally", "Jhon", "Tim", "Scott"};
  String[] msg = {"Hello World!", "Today is a nice day to walk", "I am bored", "This is how you take widget capture", "Ha Ha Ha!! That's funny !"}; 
  
  final Display display = new Display();
  final Shell shell = new Shell(display);
  shell.setText("Screen Capture");
  shell.setLayout(new GridLayout(1, true));
  
  final Composite composite = new Composite(shell, SWT.BORDER);
  composite.setLayout(new GridLayout(2, true));
  composite.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
  
  Table table = new Table(composite, SWT.BORDER|SWT.V_SCROLL|SWT.H_SCROLL|SWT.FULL_SELECTION);
  
  table.setLinesVisible(true);
  table.setHeaderVisible(true);
  
  table.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
  
  TableColumn columnName = new TableColumn(table, SWT.LEFT);
  columnName.setText("Name");
  columnName.setWidth(100);
  
  TableColumn columnMsg = new TableColumn(table, SWT.LEFT);
  columnMsg.setText("Message");
  columnMsg.setWidth(200);
  
  for (int i = 0; i < 5; i++) 
  {
   TableItem item = new TableItem(table, SWT.NONE, 0);
   item.setText(0, names[i]);
   item.setText(1, msg[i]);   
  }
  
  StyledText text = new StyledText (composite, SWT.BORDER);
  text.setText("0123456789 ABCDEFGHIJKLM NOPQRSTUVWXYZ");
  text.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
  
  StyleRange style1 = new StyleRange();
  style1.start = 0;
  style1.length = 10;
  style1.fontStyle = SWT.BOLD;
  text.setStyleRange(style1);
  
  StyleRange style2 = new StyleRange();
  style2.start = 11;
  style2.length = 13;
  style2.foreground = display.getSystemColor(SWT.COLOR_RED);
  text.setStyleRange(style2);
  
  StyleRange style3 = new StyleRange();
  style3.start = 25;
  style3.length = 13;
  style3.background = display.getSystemColor(SWT.COLOR_BLUE);
  text.setStyleRange(style3);
  
  Button button = new Button(shell, SWT.PUSH);
  button.setText("Capture");
  button.pack();

  button.addListener(SWT.Selection, new Listener()
  {
   public void handleEvent(Event event) 
   {
    GC gc = new GC(display);
    final Image image = new Image(display, shell.getBounds());
    gc.copyArea(image, shell.getBounds().x, shell.getBounds().y);
    gc.dispose();

    Shell popup = new Shell(shell);
    popup.setText("Captured Image");
    popup.addListener(SWT.Close, new Listener() {
     public void handleEvent(Event e) {
      image.dispose();
     }
    });

    Canvas canvas = new Canvas(popup, SWT.NONE);
    canvas.setBounds(0,0,image.getImageData().width, image.getImageData().height);
    canvas.addPaintListener(new PaintListener() {
     public void paintControl(PaintEvent e) {
      e.gc.drawImage(image, 0, 0);
     }
    });
    popup.pack();
    popup.open();
   }
  });
  
  shell.pack();
  shell.open();
  
  while (!shell.isDisposed()) {
   if (!display.readAndDispatch())
    display.sleep();
  }
  
  display.dispose();
 }
}

Original Composite:


Captured Image:

Wednesday, April 18, 2012

Programmatically create eclipse Java project

Following is a brief code snippet for creating an eclipse Java project using core JDT API.

private IJavaProject createProject() throws Exception
{
    IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
    String projName = getProjectName();

    if(projName == null || projName.trim().length() == 0)
        return null;

    //create eclipse project
    IProject project = root.getProject(projName);
    if(project.exists())
        project.delete(true, null);

    project.create(null);
    project.open(null);

    //set the java project nature
    IProjectDescription description = project.getDescription();
    description.setNatureIds(new String[] { JavaCore.NATURE_ID});
    project.setDescription(description, null);

    //create java project
    IJavaProject javaProject = JavaCore.create(project);

    //add bin/ouput folder
    IFolder binFolder = project.getFolder("bin");
    binFolder.create(false, true, null);
    javaProject.setOutputLocation(binFolder.getFullPath(), null);

    //add libs to project class path
    List<IClasspathEntry> entries = new ArrayList<IClasspathEntry>();
    IVMInstall vmInstall = JavaRuntime.getDefaultVMInstall();
    LibraryLocation[] locations = JavaRuntime.getLibraryLocations(vmInstall);
    for (LibraryLocation element : locations) {
        entries.add(JavaCore.newLibraryEntry(element.getSystemLibraryPath(), null, null));
    }
    
    javaProject.setRawClasspath(entries.toArray(new IClasspathEntry[entries.size()]), null);

    //create source folder
    IFolder sourceFolder = project.getFolder("src");
    sourceFolder.create(false, true, null);

    IPackageFragmentRoot srcRoot = project.getPackageFragmentRoot(sourceFolder);
    IClasspathEntry[] oldEntries = project.getRawClasspath();
    IClasspathEntry[] newEntries = new IClasspathEntry[oldEntries.length + 1];
    System.arraycopy(oldEntries, 0, newEntries, 0, oldEntries.length);
    newEntries[oldEntries.length] = JavaCore.newSourceEntry(srcRoot.getPath());
    project.setRawClasspath(newEntries, null);

    return javaProject;
}

private String getProjectName()
{
    String init_value = "project_" + System.currentTimeMillis();
    InputDialog dialog = new InputDialog(getShell(), "Java Project", "Provide project name ..", init_value, new IInputValidator() {
        public String isValid(String newText)
        {
            char[] array = newText.toCharArray();
            for (int i = 0; i < array.length; i++)
            {
                if(!Character.isJavaIdentifierPart(array[i]))
                    return "Cannot contain special characters !!";
            }

            IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
            IProject[] projs = root.getProjects();
            for (int i = 0; i < projs.length; i++) {
                if(projs[i].getName().equalsIgnoreCase(newText))
                    return "Project already exist !!";
            }

            /*
                Not checking for special Win32 names like con etc.
            */
            return null;
        }
    });

    if(dialog.open() == Dialog.CANCEL)
        return null;

    return dialog.getValue();
}

Friday, November 25, 2011

Running PostgreSQL From Command Line

This October I enrolled for the online database course offered by Stanford university. I started out with SQLite as the RDBMS of my choice because it is easy to use, needs no installation and one can use it out of the box. But, in case of SQLite simplicity was the main problem too. So, I downloaded the PostgreSQL for windows. Now, as my workstation is normally overloaded (so I can’t afford background services) and also I just wanted to have a no-install distribution; so I downloaded the Zip Archive.

The first problem I faced was that when I started to run my postgres server then it gave me this long error message:
“Execution of PostgreSQL by a user with administrative permissions is not permitted.The server must be started under an unprivileged user ID to prevent possible system security compromises.  See the documentation for more information on how to properly start the server.”

Forums were of no use and mostly people were suggesting to create a non-admin user and use it. But the problem is I can’t do that as I am working a system which doesn’t allow me to do that. So, I read the documentation and found pg_ctl which is a utility to initialize, start, stop, or control a PostgreSQL server. Here are the steps:
  1. CD C:\pgsql\bin (or where ever your postgres bin folder is)
  2. set PGDATA=c:/temp/test
  3. pg_ctl.exe init
    The files belonging to this database system will be owned by user "ABCDXYZ". This user must also own the server process….
  4. Although after the step# 2 it instructs to start your postgres server as "C:/pgsql/bin\postgres" -D "c:/temp/test"; but it is of no use. Instead do this, pg_ctl.exe start
  5. That it, the server is running and the process is owned by the logged in user.
  6. Now for the admin tool, run the ‘pgAdmin3.exe’ (its inside the C:\pgsql\bin)
  7. Now select ‘Add a connection to server’ toolbar button. This will show an image like this and fill in the values as suggested:

  8. Finally this page will come:

Wednesday, September 14, 2011

ANTLR: Global member function in ‘C’ parser & custom error printing

Technorati Tags: ,,

Writing a Java parser using ANTLR is a breeze. And why not ! It is written in Java, the default IDE which comes with it is in Java and etc. But recently I needed a tool for writing C/C++ parsers. My first choice was to go ahead with YACC or BISON. But management of the generated parser is hard (at least to people who are new to them), so I started with ANTLR.
After few rounds of testing the ANTLR seemed ok to me. But the actual problem came when I have to provide my own custom handler for error processing. After some rounds of googling and diving through the documentation I found the solution.

First create a generic handler: exceptionhandler.h
#pragma once  
#include "R2SParser.h"  
#ifdef __cplusplus
extern "C" {
#endif  
void myDisplayRecognitionError (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_UINT8 * tokenNames);  
#ifdef __cplusplus
}
#endif  
Its sample implementation: exceptionhandler.cpp (taken from antlr3baserecognizer.c)
#include "exceptionhandler.h"
#include <string>  
 
void myDisplayRecognitionError (pANTLR3_BASE_RECOGNIZER recognizer, pANTLR3_UINT8 * tokenNames) 
{
    //====================================  
    pANTLR3_PARSER            parser;
    pANTLR3_TREE_PARSER        tparser;
    pANTLR3_INT_STREAM        is;
    pANTLR3_STRING            ttext;
    pANTLR3_STRING            ftext;
    pANTLR3_EXCEPTION        ex;
    pANTLR3_COMMON_TOKEN    theToken;
    pANTLR3_BASE_TREE        theBaseTree;
    pANTLR3_COMMON_TREE        theCommonTree;  
    // Retrieve some info for easy reading.
    //
    ex        =        recognizer->state->exception;
    ttext   =        NULL;  
    std::string error;  
    // See if there is a 'filename' we can use
    //
    /*if    (ex->streamName == NULL)
    {
        if    (((pANTLR3_COMMON_TOKEN)(ex->token))->type == ANTLR3_TOKEN_EOF)
        {
            ANTLR3_FPRINTF(stderr, "-end of input-(");
        }
        else
        {
            ANTLR3_FPRINTF(stderr, "-unknown source-(");
        }
    }
    else
    {
        ftext = ex->streamName->to8(ex->streamName);
        ANTLR3_FPRINTF(stderr, "%s(", ftext->chars);
    }*/  
    // Next comes the line number
    //  
    ANTLR3_FPRINTF(stderr, "%d) ", recognizer->state->exception->line);
    ANTLR3_FPRINTF(stderr, " : error %d : %s", 
        recognizer->state->exception->type,
        (pANTLR3_UINT8)       (recognizer->state->exception->message));  
    // How we determine the next piece is dependent on which thing raised the
    // error.
    //
    switch    (recognizer->type)
    {
    case    ANTLR3_TYPE_PARSER:  
        // Prepare the knowledge we know we have
        //
        parser        = (pANTLR3_PARSER) (recognizer->super);
        if(parser->super == NULL)
        {
            fprintf(stdout, "I think i can use it");
        }else
        {
            fprintf(stdout, "BAD LUCK");
        }  
        tparser        = NULL;
        is            = parser->tstream->istream;
        theToken    = (pANTLR3_COMMON_TOKEN)(recognizer->state->exception->token);
        ttext        = theToken->toString(theToken);  
        ANTLR3_FPRINTF(stderr, ", at offset %d", recognizer->state->exception->charPositionInLine);
        if  (theToken != NULL)
        {
            if (theToken->type == ANTLR3_TOKEN_EOF)
            {
                ANTLR3_FPRINTF(stderr, ", at <EOF>");
            }
            else
            {
                // Guard against null text in a token
                //
                ANTLR3_FPRINTF(stderr, "\n    near %s\n    ", ttext == NULL ? (pANTLR3_UINT8)"<no text for the token>" : ttext->chars);
            }
        }
        break;  
    case    ANTLR3_TYPE_TREE_PARSER:  
        tparser        = (pANTLR3_TREE_PARSER) (recognizer->super);
        parser        = NULL;
        is            = tparser->ctnstream->tnstream->istream;
        theBaseTree    = (pANTLR3_BASE_TREE)(recognizer->state->exception->token);
        ttext        = theBaseTree->toStringTree(theBaseTree);  
        if  (theBaseTree != NULL)
        {
            theCommonTree    = (pANTLR3_COMMON_TREE)        theBaseTree->super;  
            if    (theCommonTree != NULL)
            {
                theToken    = (pANTLR3_COMMON_TOKEN)    theBaseTree->getToken(theBaseTree);
            }
            ANTLR3_FPRINTF(stderr, ", at offset %d", theBaseTree->getCharPositionInLine(theBaseTree));
            ANTLR3_FPRINTF(stderr, ", near %s", ttext->chars);
        }
        break;  
    default:  
        ANTLR3_FPRINTF(stderr, "Base recognizer function displayRecognitionError called by unknown parser type - provide override for this function\n");
        return;
        break;
    }  
     switch  (ex->type)
    {
    case    ANTLR3_UNWANTED_TOKEN_EXCEPTION:  
        if    (tokenNames == NULL)
        {
            ANTLR3_FPRINTF(stderr, " : Extraneous input...");
        }
        else
        {
            if    (ex->expecting == ANTLR3_TOKEN_EOF)
            {
                ANTLR3_FPRINTF(stderr, " : Extraneous input - expected <EOF>\n");
            }
            else
            {
                ANTLR3_FPRINTF(stderr, " : Extraneous input - expected %s ...\n", tokenNames[ex->expecting]);
            }
        }
        break;  
    case    ANTLR3_MISSING_TOKEN_EXCEPTION:  
        if    (tokenNames == NULL)
        {
            ANTLR3_FPRINTF(stderr, " : Missing token (%d)...\n", ex->expecting);
        }
        else
        {
            if    (ex->expecting == ANTLR3_TOKEN_EOF)
            {
                ANTLR3_FPRINTF(stderr, " : Missing <EOF>\n");
            }
            else
            {
                ANTLR3_FPRINTF(stderr, " : Missing %s \n", tokenNames[ex->expecting]);
            }
        }
        break;  
    case    ANTLR3_RECOGNITION_EXCEPTION:  
        ANTLR3_FPRINTF(stderr, " : syntax error...\n");    
        break;  
    case    ANTLR3_MISMATCHED_TOKEN_EXCEPTION:  
        if    (tokenNames == NULL)
        {
            ANTLR3_FPRINTF(stderr, " : syntax error...\n");
        }
        else
        {
            if    (ex->expecting == ANTLR3_TOKEN_EOF)
            {
                ANTLR3_FPRINTF(stderr, " : expected <EOF>\n");
            }
            else
            {
                ANTLR3_FPRINTF(stderr, " : expected %s ...\n", tokenNames[ex->expecting]);
            }
        }
        break;  
    case    ANTLR3_NO_VIABLE_ALT_EXCEPTION:  
        ANTLR3_FPRINTF(stderr, " : cannot match to any predicted input...\n");  
        break;  
    case    ANTLR3_MISMATCHED_SET_EXCEPTION:  
        {
            ANTLR3_UINT32      count;
            ANTLR3_UINT32      bit;
            ANTLR3_UINT32      size;
            ANTLR3_UINT32      numbits;
            pANTLR3_BITSET      errBits;  
            ANTLR3_FPRINTF(stderr, " : unexpected input...\n  expected one of : ");  
            count   = 0;
            errBits = antlr3BitsetLoad        (ex->expectingSet);
            numbits = errBits->numBits        (errBits);
            size    = errBits->size            (errBits);  
            if  (size > 0)
            {
                for    (bit = 1; bit < numbits && count < 8 && count < size; bit++)
                {
                    // TODO: This doesn;t look right - should be asking if the bit is set!!
                    //
                    if  (tokenNames[bit])
                    {
                        ANTLR3_FPRINTF(stderr, "%s%s", count > 0 ? ", " : "", tokenNames[bit]); 
                        count++;
                    }
                }
                ANTLR3_FPRINTF(stderr, "\n");
            }
            else
            {
                ANTLR3_FPRINTF(stderr, "Actually dude, we didn't seem to be expecting anything here, or at least\n");
                ANTLR3_FPRINTF(stderr, "I could not work out what I was expecting, like so many of us these days!\n");
            }
        }
        break;  
    case    ANTLR3_EARLY_EXIT_EXCEPTION:  
        ANTLR3_FPRINTF(stderr, " : missing elements...\n");
        break;  
    default:  
        ANTLR3_FPRINTF(stderr, " : syntax not recognized...\n");
        break;
    }  
    //====================================
}  
Then create a place holder for error message (this is a trimmed down version): errorstruct.h
#pragma once  
#ifndef __ERRORSTRUCT__
#define __ERRORSTRUCT__  
struct errormessage_struct
{
    char* message;
};  
typedef struct errormessage_struct ErrorMessage;
typedef ErrorMessage* pErrorMessage;  
#endif  
Now at this point your ANTLR grammar should have this:
@parser::header {
   #include "errorstruct.h"
   #include "exceptionhandler.h" 
   #define ERRORMESSAGE CTX->errorMessage  
}  
@parser::context
{
    ErrorMessage errorMessage;
}  
@parser::apifuncs {
    RECOGNIZER->displayRecognitionError = myDisplayRecognitionError;
    ERRORMESSAGE.message = NULL;
}
And that’s it. Now you can access your error message any where like this parser->errorMessage.message. Similarly, you can add some member function to the structure (in the above example it is errormessage_struct) and then can use it anywhere.
One point worth noting is that with the above approach you get the free threading, which is built into the code generation and the runtime. Here you get one errorMessage per thread.

References:
  1. http://www.antlr.org/pipermail/antlr-interest/2009-May/034567.html
  2. http://groups.google.com/group/il-antlr-interest/browse_thread/thread/80ec25032e9af7a8?pli=1