Sunday, September 25, 2011

Start command prompt from context menu in windows

Hi folks,

Again another techie blog.

 This is to solve a simple problem we all face quite often in our daily life. Mainly QA person and developers face this. For getting Command prompt from any opened folder we have to open command prompt then copy the path then paste and ...... long process... Huh..

So here is a simple solution, copy the following text in a .reg file and save that. Now run it once, In some secured system it may ask for admin rights, as it will update the registry. But no worry, just allow it. After that on any right click of any folder will give u an option to open command prompt from there.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\Directory\shell\startCmd]
@="Start Command Prompt From Here"
"@author"="Aniruddha Dutta Chowdhury"

[HKEY_CLASSES_ROOT\Directory\shell\startCmd\command]
@="cmd /k pushd \"%1\""

Saturday, August 27, 2011

Apache log4j queue appender

Hi friends,

Starting another techie post. This is regarding apache log4j appenders. I was using log4j for quite some time. It is excellent one. It has got almost everything required for normal to advanced logging, except if we use it extensively then the application tends to slow down a bit, like if we use the mail and DB appender then the application slows down. Thats not a fault of the system. It will slow down. To solve this we have JMS appender. put every thing in the JMS queue and then read from there and again resend to respective appender. In this we have a small catch. That is, the utility have the JMS appender but it does not have a reader. and to avail this we need to be on J2EE container.

So to solve this I just made one small class which can take care of this situation. This is having a internal JDK5 queue and reader as well. So application does not slows down and all kind of logging we can do.


The Java class:

import java.util.Enumeration;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;

import org.apache.log4j.Appender;
import org.apache.log4j.AppenderSkeleton;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.spi.LoggingEvent;

/**
 * @author: Aniruddha Dutta Chowdhury
 * @since: 11-Aug-2011 : 4:35:01 PM
 */

public class QuedAppender extends AppenderSkeleton {

    private Appender[]            targetAppender        = null;
    private String                adapter                = null;
    private Queue    loggingEventQueue    = null;
    private boolean                isActive            = false;
    private Executor            executor            = null;

    public QuedAppender() {
        loggingEventQueue = new ConcurrentLinkedQueue();
        System.out.println("QuedAppender.QuedAppender()");
        startQueueCheck();
    }

    private void startQueueCheck() {
        Thread l_th = new Thread(new Runnable() {
            @Override
            public void run() {
                callTargetAppender();
            }
        });
        // l_th.setDaemon(true);
        l_th.setName("QuedAppenderChecker");
        l_th.start();
    }

    public void setQueueSize(String a_queueSize) {
        try {
            executor = Executors.newFixedThreadPool(Integer.parseInt(a_queueSize), new ThreadFactory() {

                @Override
                public Thread newThread(Runnable r) {
                    Thread l_th = new Thread(r);
                    l_th.setDaemon(true);
                    return l_th;
                }
            });
        } catch (NumberFormatException a_numberFormatExceptionIgnore) {
        }
    }

    public String getTargetAppender() {
        return adapter;
    }

    public void setTargetAppender(String a_adapter) {
        // System.out.println("QuedAppender.setTargetAppender(" + a_adapter +")");
        if (targetAppender != null) {
            return;
        }

        adapter = a_adapter;
        String[] l_appenders = adapter.split(",");
        targetAppender = new Appender[l_appenders.length];
        int iCounter = 0;
        for (String l_ap : l_appenders) {
            targetAppender[iCounter] = getAppenderById(l_ap.trim());

            if (targetAppender[iCounter] == null) {
                targetAppender = null;
                return;
            }
            iCounter++;
        }
        // targetAppender = getAppenderById(a_adapter);
    }

    public static Appender getAppenderById(String a_strAppenderName) {
        Logger logger = LogManager.getLogger("app.logger.DummyLogger");
        Appender l_targetAppender = logger.getAppender(a_strAppenderName);
        return l_targetAppender;
    }

    private static void printAllAppenders() {
        Enumeration allLoggers = LogManager.getCurrentLoggers();
        while (allLoggers.hasMoreElements()) {
            Logger l = (Logger) allLoggers.nextElement();
            Enumeration appernders = l.getAllAppenders();
            while (appernders.hasMoreElements()) {
                Appender l_ap = (Appender) appernders.nextElement();
                System.out.println("QuedAppender.getAppenderById()" + l_ap.getName());
            }
        }
    }

    @Override
    protected void append(LoggingEvent loggingEvent) {
        if (executor == null) {
            setQueueSize("5");
        }

        if (targetAppender == null) {
            setTargetAppender(adapter);
        }

        if (targetAppender == null || targetAppender.length <= 0) {
            throw new RuntimeException("Target appender is properly not initialised. Please do that first before you start this");
        }

        System.out.println("QuedAppender.append(" + loggingEvent.getLoggerName() + ")");
        loggingEventQueue.offer(loggingEvent);

        try {
            Thread.sleep(100);
        } catch (Throwable a_th) {
        }

        startQueueCheck();
    }

    /**
     * nothing much to do, so just keep it like this
     */
    @Override
    public void close() {
    }

    @Override
    public boolean requiresLayout() {
        return false;
    }

    private void callTargetAppender() {
        LoggingEvent loggingEvent = null;

        /**
         * check is already running then just ignore it
         */
        if (isActive) {
            return;
        }

        /**
         * now mark as this method in action
         */
        isActive = true;

        while ((loggingEvent = loggingEventQueue.poll()) != null) {
            executor.execute(new TargetLogger(loggingEvent, targetAppender));
            try {
                Thread.sleep(100);
            } catch (Throwable a_th) {
            }
        }

        /**
         * lets set it false for others to access
         */
        isActive = false;
    }

    private class TargetLogger implements Runnable {
        private LoggingEvent    loggingEvent    = null;
        private Appender[]        targetAppenders    = null;

        public TargetLogger(LoggingEvent loggingEvent, Appender[] a_targetAppenders) {
            this.loggingEvent = loggingEvent;
            targetAppenders = a_targetAppenders;
        }

        @Override
        public void run() {
            for (Appender targetAppender : targetAppenders) {
                if (((AppenderSkeleton) targetAppender).getThreshold() == null || ((AppenderSkeleton) targetAppender).getThreshold().toInt() <= loggingEvent.getLevel().toInt()) {
                    targetAppender.doAppend(loggingEvent);
                }
            }
        }
    }
}

The Sample Log4j.properties:

log4j.rootLogger=DEBUG,quedAppender

#a dummy logger to initialized, so that all appenders can be loaded
log4j.logger.app.logger.DummyLogger=DEBUG,sendMail,CA,FA

log4j.appender.sendMail=org.apache.log4j.net.SMTPAppender
log4j.appender.sendMail.Threshold=ERROR
log4j.appender.sendMail.To=to@target.com
log4j.appender.sendMail.From=from@source.com
log4j.appender.sendMail.SMTPHost=smtp.source.com
log4j.appender.sendMail.Subject=iSource @ on []
log4j.appender.sendMail.layout=org.apache.log4j.PatternLayout
log4j.appender.sendMail.layout.ConversionPattern=[%d{ISO8601}]%n%n%-5p%n%n%c%n%n%m%n%n
log4j.appender.sendMail.BufferSize=1
#log4j.appender.sendMail.SMTPDebug=true

log4j.appender.quedAppender=QuedAppender
log4j.appender.quedAppender.Threshold=DEBUG
log4j.appender.quedAppender.targetAppender=sendMail, CA, FA

log4j.appender.RquedAppender=QuedAppender
log4j.appender.RquedAppender.Threshold=DEBUG
log4j.appender.RquedAppender.targetAppender=FA

#Console Appender
log4j.appender.CA=org.apache.log4j.ConsoleAppender
log4j.appender.CA.layout=org.apache.log4j.PatternLayout
log4j.appender.CA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
log4j.appender.CA.Threshold=DEBUG

#File Appender
log4j.appender.FA=org.apache.log4j.FileAppender
log4j.appender.FA.File=sample.log
log4j.appender.FA.layout=org.apache.log4j.PatternLayout
log4j.appender.FA.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
log4j.appender.FA.Threshold=INFO

In this sample log4j.properties the dummy logger is required for finding all required appender. I could not come up with any other mechanism.

If any one has any suggestion or modification proposal, please put forward. I would be glad to know that.

Monday, April 26, 2010

Print text in pattern



This program scans pixels and prints accordingly. It will work with any font. For better output please use bigger size
Few examples this would be as font, I just made image to see properly in web.





import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.awt.image.PixelGrabber;
import java.util.ArrayList;
import java.util.List;

public class FontAlgo {
      private static final char           CHAR_TO_PATTERN   = '@';
      private static final int            WIDTH             = 50;
      private static final int            HEIGHT            = 50;
      private static final boolean        isReverse         = true;
      private static final Font           appliedFont       = new Font("Couirer new", Font.BOLD, 20);

      private static TextualChar getTextualChar(char a_char) throws Throwable {
            BufferedImage bImg = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            Graphics g = bImg.getGraphics();
            g.setColor(Color.green);
            g.fillRect(0, 0, WIDTH, HEIGHT);

            g.setFont(appliedFont);
            g.setColor(Color.black);
            g.drawString(new String(new char[] { a_char }), 10, g.getFontMetrics().getHeight());
            PixelGrabber p = new PixelGrabber(bImg, 0, 0, WIDTH, HEIGHT, true);

            if (p.grabPixels()) {
                  char[][] pattern = new char[WIDTH][HEIGHT];
                  int baseColourPixel = 0, contrastColourPixel = 0, x1 = 0, x2 = 0, y1 = 0, y2 = 0;
                  int[] pixels = (int[]) p.getPixels();
                  baseColourPixel = pixels[0];
                  // System.out.println("base: " + base);
                  int xCounter = 0, yCounter = 0;
                  for (int iPixel : pixels) {
                        // System.out.println(iX + " - " + iY);
                        if (isReverse) {
                              pattern[xCounter][yCounter] = iPixel == baseColourPixel ? CHAR_TO_PATTERN : ' ';
                        } else {
                              pattern[xCounter][yCounter] = iPixel != baseColourPixel ? CHAR_TO_PATTERN : ' ';
                        }

                        yCounter++;
                        if (yCounter > 49) {
                              xCounter++;
                              yCounter = 0;
                        }

                        if (contrastColourPixel == 0 && iPixel != baseColourPixel) {
                              contrastColourPixel = iPixel;
                              x1 = xCounter - 2;
                              y1 = yCounter - 3;
                              y2 = yCounter + 3;
                        }

                        if (contrastColourPixel == iPixel) {
                              x2 = xCounter + 3;

                              if (y1 > (yCounter - 3)) {
                                    y1 = yCounter - 3;
                              }

                              if (y2 < (yCounter + 3)) {
                                    y2 = yCounter + 3;
                              }
                        }
                  }
                  return new TextualChar(x1, x2, y1, y2, pattern);
            }
            return null;
      }

      private static List getTexualChars(String strText) throws Throwable {
            List returnList = new ArrayList();
            for (byte lbyte : strText.getBytes()) {
                  TextualChar tChar = getTextualChar((char) lbyte);
                  returnList.add(tChar);
            }
            return returnList;
      }

      public static void main(String[] args) throws Throwable {
            List textualCharList = getTexualChars("Ayantika");

            TextualChar tChar1 = textualCharList.get(0);
            int endPos = tChar1.getxPos2();
            for (int iCounter = tChar1.getxPos1(); iCounter < endPos; iCounter++) {

                  for (TextualChar tChar : textualCharList) {
                        if (endPos < tChar.getxPos2()) {
                              endPos = tChar.getxPos2();
                        }
                        for (int iInnerCounter = tChar.getyPos1(); iInnerCounter < tChar.getyPos2(); iInnerCounter++) {
                              System.out.print(tChar.getPixelPattern()[iCounter][iInnerCounter]);
                        }
                  }
                  System.out.println();
            }
      }

      static class TextualChar {
            private int             xPos1             = 0;
            private int             xPos2             = 0;

            private int             yPos1             = 0;
            private int             yPos2             = 0;

            private char[][]  pixelPattern      = new char[WIDTH][HEIGHT];

            public TextualChar(int xPos1, int xPos2, int yPos1, int yPos2, char[][] a_pattern) {
                  this.xPos1 = xPos1;
                  this.xPos2 = xPos2;
                  this.yPos1 = yPos1;
                  this.yPos2 = yPos2;
                  this.pixelPattern = a_pattern;
            }

            public char[][] getPixelPattern() {
                  return pixelPattern;
            }

            public int getxPos1() {
                  return xPos1;
            }

            public int getxPos2() {
                  return xPos2;
            }

            public int getyPos1() {
                  return yPos1;
            }

            public int getyPos2() {
                  return yPos2;
            }
      }
}

Wednesday, February 17, 2010

My fatherhood (আমার বাবা হওয়া)

Hi,
This is my first blog, so please excuse me in case of mistakes. And it says that only human being makes mistake. Better not to be deviate from original topic and get into my fatherhood.
Well this is one hell of feeling of lifetime. Nothing can be compared with this. Girls may say many things but I know my feelings. No one or nothing can make me forget that. The first time my wife told me that her period is delayed I was very much happy. And I guess my wife was also happy and was wishing for the same. This time we were in Mumbai and after few days she had go back to Calcutta. She contacted with doctor & doctor said that doctor will met my wife on Sunday. Then we were waiting for that Sunday. And finally that Sunday came and my wife and my mother-in-law went to doctor. At around 9:00 am my wife given the best news every men waits for. YESSSSSSS it was positive, she was carrying our baby. The moment was really very exciting and at that time I was feeling like, ohhhh yeah we did something (or rather I did something). Come on I will speak about myself na, this is my fatherhood, not my wife’s motherhood. I know it wouldn’t have been possible without her, in India(in other countries may be guys can carry, give birth baby without a girl). Anyway after that doctor has given my wife whole things of do’s and don’ts.  And another part of life started. Planning of baby’s future, career, society, education and many more things we started talking about. Many people might find it idiotic, childish, immature but folks this was my (our too) first time and I was too happy. I forgot about ground zero and started thinking about many things. Even which school will it be? LOL this is funny, I know my baby will laugh and become angry but since I couldn’t study as much as I wanted, so I was thinking that if my baby should not miss this, if he/she wants. Before 11th june 2009 many thing happened, I went home couple of times to meet my wife and this was surprise. Finally I went before that day. My wife also teases me by saying I got readymade baby. BTW: me and my wife only thought of baby girls name. :P we expected girl. Names are Alankrita (অলঙ্কৃতা) and Olivia (অলিভিয়া). Next day morning we went to the nursing-home. My wife was very scared, she was thinking about many things like, what if I will not come back, take care of m baby and all these. I was not thinking about all these because of two things, fitst I didn’t ever thought of the danger. Come on this is 20th century and when you are going for sizer. And secondly I could not ever believe my life without her. This is bull-shit, ridicules. But she was a bit upset because of this, as I was not serious on this front. But slowly things started happening, she was on the stretcher and we all were at height of excitement. She was then taken into the “Operation Theater”, the “RED LIGHT” lighted  up and all started waiting for the moment. It was mixed, my “Brother in Law” was tensed, His son Guddu & I was very much excited and eagerly waiting for the new “GUEST”. All of a sudden at around 2.05 pm we heard a baby crying sound and next moment it was loud as if was telling me, বাবা (dady) I have come. We all then started dancing, we didn’t knew baby boy or girl. This is the moment which one can’t describe neither experience. You yourself need to experience it like sex, like death, like food. It does not matter really as long as baby and mother both are safe and healthy. Then two trainee nurses were coming out of the OT & we all asked about gender, they initially denied to say, as they are not supposed to say, but I (we all) guess that since baby boy they can say. So they told us. After 5 minutes our Doctor gave a cell phone to my wife to call us and let us know about gender of the baby. When my wife called us and we said that we already know she was and Doctor was also shocked, but it was fun. Doctor knew who it might be. Then “ধাই মা” (first one who takes the baby on lap) came out from the OT with Arkoprovo / Rhick (ঋক) / Gundo / Panko / Bhutu… And our son made me father, gave birth of one father and one mother. Me and my wife felt the same that we gave birth to him but at the same time he gave birth to us as well.
The day when he was to come back home I decorated our house with balloons. Not great but did. Another new member joined our family and the new charm began.