Sunday, November 18, 2018

DIY GPS for Nikon D7000

Hello All,

With this unit plugged in, all pictures will be geo-tagged automatically secondly, camera clock will automatically be synced. Though there are GPS unit available in market for camera but for me it was fun to put it all together and do it as DIY project.

Here is how you can build your own unit.

Tech details before we proceed

Nikon D7000 → GPS input should be plugged into shutter release cable. Shutter release cable uses two wires which triggers Focus and Shutter release. GPS data needs another wire, only input, and data needs to go in TTL input with 4800 baud rate.

Adafruit GPS breakout board →  Works with 3.5V/5V input. Default baud rate of the unit is 9600. To get it to work at 4800, we need to have backup battery (CR1220 coin cell). Arduino / USB to TTL adapter to send GPS command to change baud rate of the unit.

MC-DC2 to USB Mini pin cable → Use multimeter to to figure out which MC-DC2 pin leads to USB pin.



USB Mini B breakout board

  • VCC → this draws power from camera
  • D - → shutter
  • D + → GPS Data in @ 4800 baud rate
  • ID → Focus 
  • "ID" pin is "D-" pin is for Shutter release

Once USB breakout board is connected to camera, it starts drawing power. There is no off switch. You can have GPS data flow in continuously or add a switch. I didn't add switch on purpose as I won't leave cable connected to camera on continuous basis.

If you are planning to use camera with shutter release cable, you will have to extend this circuit to have addition connections/controls for cable release. Have your cable control connected to PIN ID and D-. The way it works is with half shutter button press, Focus pin(ID pin on USB breakout) needs to be active and with full press Shutter pin needs to be active (D- pin on USB breakout). Note that with full press both(ID and D-) pins should be active.

As of now, I have only GPS data flowing in and I will not be using cable release controls.

Circuit

Components
  1. Nikon D7000 camera
  2. Adafruit GPS breakout (https://learn.adafruit.com/adafruit-ultimate-gps)
    • Mount header pins
    • Add coin cell at the back of the unit
  3. USB Mini B breakout board (https://core-electronics.com.au/breakout-board-for-usb-mini-b.html)
  4. MC-DC2 to Mini USB B cable (Search ebay for "Micnova GPS-N-7 Camera GPS cable for Nikon")
  5. A protoyping board
  6. CR1220 coin cell
  7. 9 PIN female header pin (to make GPS breakout board plug-n-play. I intend to use GPS in other applications as well)
  8. USB to TTL Converter (Amazon link) / Arduino Uno
Prototyping
First we need to get GPS unit working at 4800 baud rate. Adafruit GPS unit by default runs at 9600 baud rate. I ended up using Arduino Uno board and modified echo example to set set baud rate of GPS unit to 4800. The command we need to send it to GPS RX terminal is "$PMTK251,4800*14". Alternatively, you can use USB to TTL converter with any program which can communicates over TTL.

Arduino Code for ref.
#include 
// Connect the GPS Power pin to 5V
// Connect the GPS Ground pin to ground
// If using software serial (sketch example default):
//   Connect the GPS TX (transmit) pin to Digital 3
//   Connect the GPS RX (receive) pin to Digital 2

// If using software serial, keep these lines enabled
// (you can change the pin numbers to match your wiring):
#if ARDUINO >= 100
  SoftwareSerial mySerial(3, 2);
#else
  NewSoftSerial mySerial(3, 2);
#endif
Adafruit_GPS GPS(&mySerial);

#define GPSECHO  true

// this keeps track of whether we're using the interrupt
// off by default!
boolean usingInterrupt = false;
void useInterrupt(boolean); // Func prototype keeps Arduino 0023 happy

void setup() {    
  // connect at 115200 so we can read the GPS fast enuf and
  // also spit it out
  Serial.begin(115200);
  Serial.println("Adafruit GPS library basic test!");

  // 9600 NMEA is the default baud rate for MTK - some use 4800
  GPS.begin(9600);
  GPS.sendCommand("$PMTK251,4800*14");
  delay(1000);
  // You can adjust which sentences to have the module emit, below
  
  // uncomment this line to turn on RMC (recommended minimum) and GGA (fix data) including altitude
  GPS.sendCommand(PMTK_SET_NMEA_OUTPUT_RMCGGA);
  GPS.sendCommand(PMTK_SET_NMEA_UPDATE_5HZ);
  GPS.sendCommand(PMTK_API_SET_FIX_CTL_5HZ);
}

void loop() {

}


Please note: changing baud rate is one time activity - until backup battery on GPS unit runs out.

Verify the data that it works at 4800 baud rate. I have used USB to TTL converter.

Assembly
Let's put everything on breadboard to verify all connections work as expected.




Finished Product

Once everything is verified on breadboard, I hardwired the connection on prototyping board. And last is field test. :)




Field test


Monday, June 04, 2018

Tera Khayal...

Long distance relationships ... phew !!!

Aaj tu phir bahut yaad aaya hai,
Aaj phir khud ko bahut bechain humne paya hai

Beech humare -
Samundar ki gahrayi aur meelon ka faasla hai,
Ye soch, dil bechain kuch is kadar hua hai
Jazbaaton ka tufaan, ye dil, maano seene me dabaye baitha hai,
Aaj tera khayal kuch is kadar aaya hai
Wo teri naadaniyan, wo tera bholapan,
Wo tera bin wajah muskuraana,
Baat baat par ruth jaana ,
Chidate-chidate khud ro jaana,
Mujhe manane ki wajaye khud ko manwana,
Tere saath bitaye hua wo lamhe,
Sab ek pal me yaad aaya hai,
Aaj tera khayal kuch is tarah aaya hai


Aaj phir tujhe chedne ka dil kiya,
Gudgunane ka dil kiya,
Meelon ka fasla pal bhar me mitane jee kiya,
Bahon me bhar tujhe
So jaane ko dil kiya,
Khud ko tanha-akela,
Aaj phir humne paya hai,
Aaj tera khayal kuch is kadar aaya hai

Aaj message se tasalli na hogi
Aaj phone call se bhi tasalli na hogi,
Ru-ba-ru na hone ki teri kami kuch is tarah bechain kar rahi hai
Jaise mano, jism ko ruh ki kami khal rahi ho
Aaj tera khayal kuch is kadar aaya hai

Zindagi mano teher si gayi ho,
Saans ruki aur,
Jeene ki wajah kho si gayi ho,
Phir kisi tarah aaj humne khud ko samjhaya hai,
Aaj tera khayal kuch is kadar aaya hai,
...aakhen nam aur dil bhar aaya hai !!!


-Mayank

Friday, October 14, 2016

Volume Control script for Raspberry Pi

Here is a small script to control audio volume. Feel free to modify the script as per need. Make sure pulseaudio is is up and running.

Filename: volchg.sh

Usage: 
volchg.sh [+/-] [x]

volchg.sh --increase volume by 5%
volchg.sh + --increase volume by 5%
volchg.sh + 10 --increase volume by 10%
volchg.sh - --decrease volume by 5%
volchg.sh - 10 --decrease volume by 10%

Script

#!/bin/sh
#############################
### Volume Up/Down Script ###
#############################

# Specify increase or decrease
MODE=$1

# Percentage Change
VAL=$2

#Set defaut change to 5%
if [ -z "$2" ]; then
  VAL=5
fi

#Get MAX Value
MAX_VOL=`amixer cget numid=3 | grep "max=" |  cut -d, -f5 | cut -d= -f 2`

#Get current val
CURRENT_VOL=`amixer cget numid=3 | grep ":" | cut -d, -f2`

#UPDATE VOL

if [ "$MODE" = "+" ]; then
  MUL=1
else
  MUL=-1
fi

NEW_VOL=$(( ($CURRENT_VOL + ($MUL * (( $VAL * $MAX_VOL) / 100 ))) ))
PER_VOL=$(( ($NEW_VOL * 100) / $MAX_VOL ))

amixer cset numid=3 $NEW_VOL > /dev/null
echo "Volume Level: $PER_VOL%"

Have fun !!!

Tuesday, September 13, 2016

Raspberry Pi - Bluetooth Choppy Audio

Raspberry Pi 3, Model B / RASPBIAN OS

BCM43438 is a single chip provide 2.4GHz 802.11n wireless LAN and Bluetooth radio support.

With a lot of google, hit and trial methods solution found to the choppy audio problem. Try turning off WiFi on Raspberry Pi while streaming bluetooth audio.

This worked for me.

Thanks.

Raspberry Pi - A2DP Profile - Bluetooth Audio Streaming via Cellphone

Raspberry Pi 3, Model B / RASPBIAN OS

Recently purchased Raspberry Pi, and I am pretty happy with it. Credit card sized SOC and it's pretty amazing. Love for music is pretty high so first thing I took up is to stream music from from my cellphone connected to Raspberry Pi via bluetooth. And Raspberry Pi will throw audio out to speakers connected to 3.5 mm audio jack.

I won't go deep into configurations settings as you will find plenty of articles to configure settings for A2DP profiles and make Raspberry Pi using audio input stream from cellphone. Though I will highlight few things on which I faced difficulty

  1. First OS I installed was Ubuntu Mate
    • A2DP profile settings worked via Desktop mode. Kick off bluetooth connectivity wizard and you are all set.
    • However when I booted to console only mode, tried bunch of things but couldn't get things to work
  2. Eventually I switched to RASPBIAN and it worked via UI as well as console mode.
Few commands which came in handy
  1. Bluetooth utility
    bluetoothctl
    #show - display basic information
    #scan on - turns scanning on
    #pair xx:xx:xx:xx:xx:xx - start pairing with cellphone
    #trust xx:xx:xx:xx:xx:xx - add it to trust store
    #connect xx:xx:xx:xx:xx:xx - connects to cellphone
    #ctrl + d - exits bluetooth prompt
  2. pulseaudio
    pulseaduio -D - starts pulse audio instance
    pulseaduio -k - kills any pulseaudio running instance
  3. Audio Bus
    pactl list sources short - lists all audio sources
    pactl list sinks short - lists output
  4. Audio Output
    amixer cset numid=3 0 -- Automatic selection
    amixer cset numid=3 1 -- sets output to HDMI
    amixer cset numid=3 2 -- sets output to 3.5mm analogue port
  5. Raspberry Pi Config
    sudo raspi-config - master utility to change various settings for Raspberry Pi


Thanks.

Monday, October 27, 2014

File History - Alternate to Memeo WD Anywhere backup

Hello All,

After windows 8.1 upgrade, just like you, I ran into WD Memeo Backup incompatibility issues. I tried bunch of options to get it to work but failed and got only one message "WD Anywhere Backup cannot be run under this version of windows" and Memeo does not have any plans to extend support for this version of backup software.

Solution

I tried couple of options, like FreeFileSync, Synkronizer etc, to get my backup plan up and running but finally settled down with Windows 8.1 "File History" program. It's bit messy in terms of setting up, unless you know "how it does". But once you get it right you will be happy that you do not have to reply on any third party program and worry about any installation/un-installation.

I am listing out steps which will help you to set your backup.

Few concepts before we proceed.

  1. "File History" program manages backing up files using your "library folders".
  2. By default it will backup all Library Folders(My Documents, My Music, My Videos etc), Desktop, Contacts, and couple of more items including One Drive(only offline files).
  3. You can setup "exclude list" to exclude any folders that you might want to be part of backup.
  4. Setup Network Folder from your WD Network Hard Disk.
  5. Few "Advanced Setting" options to set frequency and version.


Let's get to work !!!

Note: By Default all libraries(Default and Custom) will get selected for backup. So do not set "File History" to ON unless you have all exclude list setup(as in Step 2) to avoid unnecessary files to be part of backup plan.

Step 1 (optional): Setup a new Library Folder and have folders listed in it that you want to be part of backup plan.


  • As shown in below image, open Explorer, Right click on "Documents" -> Include In Library -> "Create new library"
  • Provide a name for your library
  • New Library folder will get listed under Homegroup as shown in picture below.
Create Library Folder

  • Now under manage tab, click on "Manage Library" folder.
  • Add folders that you want to be the part of backup plan.
  • That's it setting up your Library Folder.


Step 2: Press Windows key from your desktop and key in "File History" for search and select "File History" and Setup "Exclude Folders"
Launch File History
File History

Step 3: Network Directory share.

  • Create new share or use already existing share from your WD Network Hard Drive.
  • Open WD Drive in explorer, and you will list of all shared folders.
  • Right Click on desired backup folder and click on "Map Network Drive"


Step 4: From Start Menu, search for "File History" and go to "File History Settings"
Turn On "File History" and Select newly mapped network drive.
File History Settings

And your backup process should commence !!!

Step 5: Configure frequency and version settings
Open the "File History" window as mentioned in step 2, and goto "Advanced  Setting" options and make necessary changes.

Once a cycle of backup completes, you can clear your memeo backup files and un-install memeo backup program.

That's all folks !!! :)

Thanks.

Saturday, April 06, 2013

Apache Lucene - Brief Concept & Code Snippet

Searching ... a simple concept with a complex algorithms. That's how I see it. Always fascinated by the complexity and wanted to implement and use some sort of basic algorithms.
So I end using Apache's Lucene library to for search functionality. In this post I will walk through on some basic terminology/concept of this library along with small code snippets to initialize and make use of this library.

Lucene - it is text based search library. To built up an index source information could be anything a database, file system or web sites. You can feed in info from any source you like to index.

Data is indexed by Lucene using "Inverted Indexing" technique. That means it will "retrieves the pages related to a keyword instead of searching a pages for a keyword".

On Apache's website there are below two things are available for downloads
  • Lucene - It is an engine which can be used by programmers to customize searches.
  • Solr - It's a war file can be used by non-programmers. It can be directly deployed on tomcat, jetty or any web server.
Lucene Concepts
  • Document - It is unit of search/index. Just like a row when we fire sql queries.
  • Fields - A document is consist of one of more fields. Columns in a row.
  • Searching - It is done using "QueryParser" class
  • Queries - It has its own mini language. It does have ability to add weightage to fields, known as boosting.
  • Building Indexes - To build index lucene needs a directory on file system where information can be stored. While indexing records, we need to specify 
    • what all fields needs to be stored and 
    • what all fields needs to be indexed.
  • Directory - FSDirectory is the abstract class which points to the index directory. It has direct sub-classes. I have listed down below.
    • It is recommended to let lucene pick up implementation class based on environment.
    • SimpleFSDirectory - Poor for concurrent performace
    • NIOFSDirectory - Poor choice for windows
    • MMapDirectory - It has some issue with JRE bug.
    • RAMDirectory - It cannot handle huge indexes.
    • There are few more implementation classes provided by lucene which can be easily located in java docs provided by lucene
Coming to to coding part.
  • Index Directory
File idxFile = new File(INDEX_DIR); //e.g. /work/index/
Directory idxDir = FSDirectory.open(idxFile);
  • Prepare Analyzer
Map<String, Analyzer> map = new HashMap<String, Analyzer>(): //key, Analyzer pair
map.put(FILE_NAME, new StandardAnalyzer(Version.LUCENE_36));
Analyzer analyzer = new PerFieldAnalyzerWrapper(new StandardAnalyzer(Version.LUCENE_36), map);
  • Index Writer Configuration
Config = new IndexWriterConfig(Version.LUCENE_36, analyzer);
  • Index Writer
new IndexWriter(idxDir, config);
Before we go further let's take quick peek on Analyzer.
  • It builds up token streams.
  • A policy for extracting index terms from text.
  • Subclasses
    • PerFieldAnalyzerWrapper
    • ReusableAnalyzerBase
      • PatternAnalyzer
      • KeywordAnalyzer
      • PatternAnalyzer
Moving forward with code snippets to 
  • Create documents to be stored in index.
Field fPath = new Field(FULL_PATH, path, Field.Store.YES , Field.Index.toIndex(true, true, false));
document.add(fPath); // Add a field to document. Keep on multiple fields that needs to be stored.
  • Add document to index
indexWriter.addDocument(document);
Fine tune above process to build index. Once indexes ready, lets gear up for searching...
  • Initialize index directory
IndexReader ir = IndexReader.open(idxDir);
IndexSearcher searcher = new IndexSearcher(ir);
  • Prepare fields analyzers
Map map = new HashMap();
map.put(FILE_NAME, new StandardAnalyzer(Version.LUCENE_36));
Analyzer analyzer = new PerFieldAnalyzerWrapper(new StandardAnalyzer(Version.LUCENE_36), map);
  • Query Parser
QueryParser qp = new MultiFieldQueryParser(Version.LUCENE_36, new String[]{FILE_NAME, TITLE, ALBUM, ARTIST}, analyzer);// FILE_NAME, TITLE, ALBUM, ARTIST are the fields of Document used in my example
Query query = qp.parse(srchText); //pass in the search keyword
TopDocs res = searcher.search(query, 10);
  • Iterate through results
for(ScoreDoc sc:res.scoreDocs) {
Document doc = searcher.doc(sc.doc);
sc.doc //Gives Document ID
doc.getFieldable(FILE_NAME).stringValue(); // Read Field Value
}
Hope this helps implementation get rolling quickly. 
Thanks !!!

Tuesday, April 24, 2012

CSV Excel - Double Click Issue

So here I am again, with a fix for another issue which I tried to resolve with my colleague the other day.

Problem Statement:
We used CSVWriter to write CSV file's and on double clicking it; excel was not showing the special characters, to be precise korean characters. However if we were opening the same file in Notepad characters were rendering properly.

Issue:
The CSV file was getting generated without BOM(Byte Order Mark). BOM is nothing but the Unicode character used to signal the byte order of the text file or stream. Its code point is U+FEFF. BOM use is optional, and, if used, should appear at the start of the text stream

I detected this issue when I opened the file in Notepad++ and found "UTF8 without BOM" option was selected under "Format" menu. I then changed the format to "UTF8" and saved a copy of the file. Double click the file and Excel rendered all the korean characters.

Click here to read more on Byte Order Mark.

Fix:
We added below mentioned three statements to have BOM character at the start of the file. That's it.

OutputStream fos = new FileOutputStream("c:/test.csv");
//Write BOM Characters
fos.write(239); //0xEF
fos.write(187); //0xBB
fos.write(191); //0xBF

PrintWriter writer = new PrintWriter(new OutputStreamWriter(fos, "UTF-8"));
//Write all the required contents.

writer.close();
fos.close();

Thanks !!!

Thursday, March 15, 2012

Internet Explorer file downloads issue over SSL

Problem
File download fails in IE over SSL(https) protocol. I am posting another issue which I faced couple of days back. And it consumed approximately 4 hours of my time.

Reason
It happens when server response header contains "Pragma: no-cache" and/or "Cache-Control: no-store" or "Cache-Control: no-cache".

This is a known issue in IE and mentioned by Microsoft at http://support.microsoft.com/kb/323308.

Solution
While sending the response set "Pragma: cache" and/or "Cache-Control: Private" depending on the header you are receiving.

To track the response headers in IE you can use Fiddler tool. Or you can switch to Firefox.

I have been working on Struts-2 based web application. I end up implementing interceptor to modify response headers. I placed this interceptor just before workflow interceptor in my default interceptor stack.

Tip
While going through many forums I read it somewhere that above header setting should be used for only for IE and SSL.

Hope it helps.

Enjoy !!! :)

Tuesday, January 24, 2012

Broken Pipe Issue in Hibernate

Hey guys, here is one of the many key issues which I was facing in one the web based java application on which I am currently working on. Here is the development environment.
  • Java 1.6
  • Struts 2
  • Hibernate with C3p0
  • Postgres
  • Tomcat 6
Assuming database server & tomcat are both up an running and are on different machines. At any point if there is any network issues or for some reason database server goes down for few seconds, the c3p0/hibernate connection pool goes into bad state. And application keeps on throwing "Socket Exception" / "Broken Pipe" issue. And even if the database server comes up, it is not able to re-create the connection pool. The only solution to this issue is to re-start the tomcat server. There are other users who faced this issue with MySQL database.

There is key entry which was missing from my "hibernate.cfg.xml". Adding this entry resolves this issue.
<property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>

Along with the above I do have following properties in my application
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.timeout">1800</property>

I tested this setting and it works fine.
I just fixed my broken pipe !!! :)

Thursday, December 15, 2011

Eclipse Memory Enhancements

Default Eclipse settings are optimal for machines running on 1 GB/low memory. So if you have a machine with high memory, you can use below settings to optimize performance. Add the following settings in eclipse.ini(residing in your eclipse home directory) file and start/restart the eclipse.

-Xmn128m
-Xms1024m
-Xmx1024m
-Xss2m
-XX:PermSize=128m
-XX:MaxPermSize=128m
-XX:+UseParallelGC

Thanks.

Wednesday, October 05, 2011

SQL Restriction In Hibernate Criteria Query

Here is an example to add a SQL Restriction in hibernate Criteria query.
Let's consider we have
  • A Student.java entity
  • A stored procedure in place which returns total marks obtained by a student in each subject.
public Class Student {
    private Integer id;
    private String name;
    .
    .
    //getters & setters methods
}
Assuming get_marks() stored procedure will result records in following format.

id Maths Enlish Science
1 78 75 23
2 74 70 97
I want to list down the Students who has got more than 90 in Maths. Here goes the Hibernate Criteria query.
Criteria c = session.createCriteria(Student.class)
		.addSqlrestriction(" {alias}.id in (SELECT id FROM get_marks() WHERE maths_total > ? ) ", new Double(90.0), Hibernate.Double);

In above statement {alias}.id will refer to the id column of Student table. The above addSqlrestriction example shows the SQL restriction statement with only one parameter.
What if you have to pass multiple arguments?
In such cases you need to pass array of Objects & array of Type as second & third parameter to the addSqlrestriction(String, Object[], Type[]). And in SQL String have ? where ever argument is required, as shown in above example.

I hope this helps.
Thanks.

Sunday, August 28, 2011

GTalk - Show Current Music Track - Bug: Workaround Fix

Hi All,

I have Windows XP, Google Talk 1.0.0.104 and Winamp 5.6.

GTalk is crashing whenever I'm setting my status message to "Show Current Music Track" (Winamp Playing). Here is a simple fix for this issue.

1. Open notepad
2. Click on File --> Save
3. Save file it under Winamp installation directory [ "C:\Program Files\Winamp" - in my case] with file name as "winamp.m3u".

Restart Winamp & GTalk.

This is it !!! :)

Tuesday, August 23, 2011

Khatarkun, Khatarkun, Khatarkun

Last Friday, I got bored of regular work. I was working with a colleague(and a good friend) at work and after a while our discussion turned into gossip. And my wickedly awesome head created what you are about to read...he he he !!! :D

khatarkun, khatarkun, khatarkun
mere dil ki aawaz sun...

tattos hai latest addiction uske,
naam uska lete he, sabke kaan hote hai suuunnnn,
khatarkun, khatarkun, khatarkun
mere dil ki aawaz sun...

log kehte hain, log kehte hain pj ko pyaar hua hai,
kabhi wo bhi to bole, meri ishq ki kisse sun,
khatarkun, khatarkun, khatarkun
mere dil ki aawaz sun...

hairband chode hai usne,
system me ghus coding karti hai wo,
kalyan kar uska bhi,
mere khuda, dua hum sab ki sun
khatarkun, khatarkun, khatarkun
mere dil ki aawaz sun...

naye hai additions, nayi hai value,
internal to internal,
external sources bhi hua hai guum,
khatarkun, khatarkun, khatarkun,
mere dil ki aawaz sun...

bade dino baad aaya koi chera nazar me
aaj pata chala hai naam uska, aaj hai dil me naya junoon
khatarkun, khatarkun, khatarkun
mere "bhi" dil ki aawaz sun...



This is just for fun, no offense !!!! :)

Wednesday, August 10, 2011

Hibernate Interceptors

Are you using hibernate and thinking of using Database Triggers? Then wait....

If most of your database operations are done via stored procedures then having triggers in place is the only choice to intercept any DML calls.

But since we are using hibernate we need a more object oriented way of handling things.
Hibernate interceptors is similar to triggers in database. Monitoring DML operations via triggers is the most efficient way, but it won't be easy to maintain, understand and manipulate business logic when all database operations are done via hibernate.

Coming straight to the point, hibernate provides "org.hibernate.Interceptor" interface to have the business logic to perform pre or post operations around DML hibernate calls. Following methods are required to be implemented against "org.hibernate.Interceptor".

public interface Interceptor {

public void afterTransactionBegin(Transaction arg0) {

}

public void afterTransactionCompletion(Transaction arg0) {

}

public void beforeTransactionCompletion(Transaction arg0) {

}

public int[] findDirty(Object arg0, Serializable arg1, Object[] arg2,
Object[] arg3, String[] arg4, Type[] arg5) {
return null;
}

public Object getEntity(String arg0, Serializable arg1)
throws CallbackException {
return null;
}

public String getEntityName(Object arg0) throws CallbackException {
return null;
}

public Object instantiate(String arg0, EntityMode arg1, Serializable arg2)
throws CallbackException {
return null;
}

public Boolean isTransient(Object arg0) {
return null;
}

public void onDelete(Object arg0, Serializable arg1, Object[] arg2,
String[] arg3, Type[] arg4) throws CallbackException {
}

public boolean onFlushDirty(Object arg0, Serializable arg1, Object[] arg2,
Object[] arg3, String[] arg4, Type[] arg5) throws CallbackException {
return false;
}

public boolean onLoad(Object arg0, Serializable arg1, Object[] arg2,
String[] arg3, Type[] arg4) throws CallbackException {
return false;
}

public boolean onSave(Object arg0, Serializable arg1, Object[] arg2,
String[] arg3, Type[] arg4) throws CallbackException {
return false;
}

public void postFlush(Iterator arg0) throws CallbackException {

}

public void preFlush(Iterator arg0) throws CallbackException {

}
}
Since you won't be interested in implementing all of the methods, hibernate provides "org.hibernate.EmptyInterceptor" class which has empty implementation of the Interceptor interface. Now, as per your need you can override any of the desired method. Below is the sample class which I plugged in hibernate configuration to print out the primary key of any object which is getting saved.

package com.test.interceptor;

import java.io.Serializable;

import org.hibernate.EmptyInterceptor;
import org.hibernate.type.Type;

public class InsertMonitorInterceptor extends EmptyInterceptor{

@Override
public boolean onSave(Object entity, Serializable id, Object[] state,
String[] propertyNames, Type[] types) {
System.out.println("Saving..." + id + ": " entity);
return super.onSave(entity, id, state, propertyNames, types);
}
}
Once you have your Interceptor class implementation ready it can be very easily plugged with any existing hibernate configuration as shown below.


new Configuration().configure(DBUtil.class.getResource("hibernate.cfg.xml"))
.setInterceptor(new InsertMonitorInterceptor())
.buildSessionFactory();
That's it. You can have different interceptor implementation plug it in to start using them.
Hope this article will be helpful. happy Intercepting.

Thanks.

Saturday, September 25, 2010

Blu Ray Player

!!! WOW !!!
That was the first expression when I played a Blu ray disc on my BDP-S370 connected to Bravia LCD.
It’s a feature packed Blu Ray HD player which comes at a decent price. I know the "Sony" and "Price" can't be decent but then it's worth.

Starting with the list of features
  1. Audio/Video formats: It supports a lot of audio and video format including MKV and MT2S which are basically high definition video format files. Apart from this it also supports DivX HD which is pretty common.
  2. USB Connectivity: It has got two USB ports. One can put up all A/V media and stills onto a USB drive and can enjoy them on a big screen.
  3. LAN Connectivity: I connected Blu Ray PLayer and my WB 2 TB disk via switch. And my player detects the Media Server (twonky) running on my WD Disk(DLNA Capability of the player) which hosts all my Audio, Video and Stills.
  4. Wireless LAN: It also supports wireless LAN but then you have to purchase Sony's wireless USB stick separately. It will gonna cost you around Rs. 4500/-. It's a big disappointment. Also it will not support any other wireless USB adapter.
  5. Misc: This player is can access Gracenote server and BD Live enabled. So if your disk player is connected to internet you can definitely make use of this feature. Also it can stream video from popular video sites like www.youtube.com. Well there couple of more sites listed from which videos can be streamed.
  6. Pretty good customer support just in case if you run into any issue (highly unlikely with Sony :) ).
Well those are the good points.
MKV File Problem
I had some issues with playing MKV files larger than 4 GB with Twonky media sever; I complained about this at Sony’s customer support. They kept me informed for two weeks, after that I didn’t heared from them. I guess they were not able to resolve the problem. Well I did some RnD on playing MKV files and here are some of my findings to play those on Sony’s BDP-S370.
Solution
When talking about USB support on BDP-S370, it only supports USB drives with FAT32 file system. It doesn’t support NTFS file system. Now if you have some high definition video files, mostly MKV, whose size mostly exceeds 4GB, you will gonna run into problem as you won't be able to copy those files to FAT 32 USB disk. [ A single file on FAT 32 file system cannot be larger than 4 GB ].
Well, now you can't play the MKV files using USB drive so you can go ahead with one the following options
  • Option 1: You can split those large files into smaller chunks and then copy it to USB disk. That will work. But then the splitting process will gonna take some time.
  • Option 2: Connect the player via LAN to a computer or other device hosting a Media Server. Now the player might not detect MKV files hosted by your media server. In my case it's Twonky. So I tried Serviio and Wild Media Server. Serviio didn’t work out but Wild Media Server works like a Charm. The Blu Ray player played my MKV file, which is of 11 GB is size, very smoothly.
Now, there is couple of things to be taken into consideration when you are going with second approach.
Wild Media Sever is not free. Trail version is available for download and test things out.
Wild media server basically does on-the-fly transcoding. So it will gonna eat a lot of CPU, in my case the CPU usage was 98%. So make sure that you have a decent CPU power. Also, when you are dealing with such large files over the network make sure that you running at least on 100 Mbps LAN.

Purchasing tips for a Blu Ray player.
  1. Check For Region Code: [Very Very important if you plan to buy Blu Ray discs from different regions of the world]

    • Blu Ray Region Encoding The World is divided into 3 regions A, B & C. The Blu Ray discs coming in the market are region encoded. The Blu Ray player sold will support only the region where it is being sold. So a Blu Ray player purchased from Region C will not gonna play a Blu Ray Disc purchased from Region A or B, until and unless it has got Multi-Region support. :)
      Now I'm not really sure if there are Blu Ray player available in market with Multi-Region support.

      Region Code Area
      A/1 The Americas, and their dependencies, Japan, East Asia (except the People's Republic of China and Mongolia), and Southeast Asia.
      B/2 Africa, Middle East, Southwest Asia, Europe (except Belarus, Russia and Ukraine), Australia, New Zealand, and their dependencies.
      C/3 Central Asia, East Asia (China and Mongolia only), South Asia, Eastern Europe, and their dependencies.
    • DVD Region Encoding: Don't get confused "Multi-region Blu Ray" with "Multi-Region DVD". For DVD's we have 7 Region codes.
      Well there are hacks available to make a player play "Multi-Region" DVD's. But these hacks may not work for Blu Ray discs. Google it and try it at your own risk.
      You can find the Region Codes on Blu Ray player manual. In case of Sony's BDP-S370, these code are mentioned at the back side of the player.

      Region Code Area
      0 Informal term meaning "worldwide". Region 0 is not an official setting; discs that bear the region 0 symbol either have no flag set or have region 1–6 flags set.
      1 United States, Canada, Bermuda, U.S. territories
      2 Europe (except Russia, Ukraine, and Belarus), Middle East, Egypt, Japan, South Africa, Swaziland, Lesotho, Greenland
      3 Southeast Asia, South Korea, Republic of China (Taiwan), Hong Kong, Macau
      4Mexico, South America, Australia, New Zealand, Oceania
      5Afghanistan, Ukraine, Belarus, Russia, Africa (except Egypt, South Africa, Swaziland, and Lesotho), Central and South Asia, Mongolia, North Korea
      6People's Republic of China, Hong Kong
      7Reserved for future use (found in use on protected screener copies of MPAA-related DVDs and "media copies" of pre-releases in Asia)
      8International venues such as aircraft, cruise ships, etc.
      ALLRegion ALL discs have all 8 flags set, allowing the disc to be played in any locale on any player.
  2. USB Support: Check for file system that a Blu Ray supports for the USB disks. Also check for the maximum size of the USB disk that will be supported by the player. This will come handy when you want to play high-def video files which are typically very large in size.
  3. Make sure that you get all your accessories comes with your Blu Ray player.
    FYI, Wi-Fi adapter doesn't come with Sony's BDP-S370 Blu Ray player.

That's It !!!
You might get couple of Blu Ray disk free with your purchase. :)
Opps … forgot to mention, I got two disks free. :)

Sunday, May 30, 2010

WD My Book World Edition 2TB

!!! I've got some space !!!

WD My Book World Edition 2TB White Light Edition (WDH1NC20000)
Yippeee!!! I got my disk.

This disk basically a NAS(Network Attached Storage) drive. It comes with a pre-installed Linux. It is a cut down version of Linux. That means Users, file permission groups etc etc basic features of Linux comes into the picture. So you can be pretty sure that only authorized users will be accessing your data. And its pretty good once you have your data on Network.

As I said Linux, no need to worry to all those who don't have knowledge of Linux. It's has got a pretty decent web interface to control & configure the disk properties. Thanks to the httpd service running on it. :)

Apart from that it has got a licensed version of Twonky media server. You can configure Twonky media server to share videos, music and pictures. And the same can be accessed by any PC, cellphone or any other device in the Network. Using web interface you can also enable services like NFS, AFP and FTP.

It has also got iTunes media sharing service running. So iTunes lovers will see this disk under "Sharing" section of iTunes. :)

Cons:
Although this unit Gigabit LAN capable, the data transfer rate is pretty slow over the network. I got max speed of 1350 kB/s while transferring data from my PC/USB Drive to the disk over the 100Mbps LAN card.

Initially I thought I didn't configure the disk properly but after going through blogs & forums I got to know that this disk is powered by ARM9 processor running at 200 MHz. Well I'm still not sure that this is the bottle neck in my case. I google on this a bit more and found that this processor can be over clocked to 500MHz. Probabilily this could improve the data transfer rate. But I didn't tried.

Anyways I got most of data on WD 160 GB USB disk. So I connect my USB disk to the USB port available at the back of the 2TB unit. This basically exposes the USB disk as a network share. To transfer the data logged in to the disk using SSH and fired "cp" command to transfer all my data. And guess what I transferred 50 GB of data in approximately 53 minutes. Pretty impressive...huh !!! ;)

Now since all my data is a one place I really don't need to do a lot of bulk transfer over the LAN. All that data dumping stuff was a one time task and I'm done with that.

To summarize, it's a pretty impressive unit to have your data at one place and share it in home with different PC's/devices(I use my cellphone a lot ;) ). With the Linux in place adds data security. Twonky & iTunes software makes this disk a perfect media server and I'm pretty happy with it after backing up my data.

And special thanks to Mini who brought this for me. :)

Tuesday, February 23, 2010

RSS - Really Simple Syndication

With RSS, it is possible to distribute up-to-date web content from one web site to several other web sites or other applications. RSS has been designed to show selected data.
There are several web sites which provide RSS feeds. A consumer can consume these RSS feeds from multiple web sites and can view a consolidated information in his application. If you are designing your own application and wondering how to consume these RSS feeds, then you are at right spot.
RSS feeds are nothing but XML data, so either you can write your own parser to parse this XML data or you use a third party library to parse it for you.
A RSS feed may look like:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<rss version="2.0">

<channel>
<title>RSS Test</title>
<link>http://www.rsstest.com</link>
<description>RSS sample file</description>
<item>
<title>RSS Introduction</title>
<link>http://www.rsstest.com/rssintro</link>
<description>RSS Introduction</description>
</item>
<item>
<title>RSS Java Code</title>
<link>http://www.rsstest.com/java</link>
<description>How to consume RSS in java</description>
</item>
</channel>
</rss>


In the following example, I have used informa.jar. A third party library, as I don't want to get into details of parsing XML.
I have used a feed from discovery site, which will display the top stories from the discovery site.

public class Client {
public static void main(String[] args) {
Client client = new Client();
client.readRSS();

}

public void readRSS() {
try {
ChannelIF channel = FeedParser.parse(new ChannelBuilder(), new URL("http://dsc.discovery.com/news/subjects/animals/xdb/topstories.xml"));
//Collection feeds = OPMLParser.parse(inpFile);

Collection collection = channel.getItems();
Iterator it = collection.iterator();
ItemIF itemIF;
while(it.hasNext()) {
itemIF = (ItemIF)it.next();

System.out.println("Title: " + itemIF.getTitle());
System.out.println("Link: " + itemIF.getLink());
System.out.println(itemIF.getDate());
System.out.println("Description: " + itemIF.getDescription());
}

System.out.println("Title: " + channel.getTitle());
System.out.println("Copyright: " + channel.getCopyright());



System.out.println("DONE");
}
catch(Exception e){
e.printStackTrace();
}
}
}

That's all.
Enjoy!!! Have Fun !!! :)

Sunday, October 11, 2009

Configure debug port in Tomcat 5.5

I have installed Tomcat 5.5 using setup.exe. After the installation I get following two executable files in my %TOMCAT_HOME%/bin directory:
  • tomcat5.exe - which launches the server.
  • tomcat5w.exe - which allows you to configure tomcat.
Launch tomcat5w.exe and click on Java tab. Under java options add the following line:

-Xrunjdwp:transport=dt_socket,address=8453,server=y,suspend=n

where 8453 is your socket number. Now in eclipse or any other IDE you can easily configure options to debug the application.

I haven't tried this on tomcat's other distribution in which you simple unzip the files for installation. In this case you have to edit catalina.bat file. That's all information I got from various forums.

Smile !!! :)
-- Updated 23rd August, 2011--
In case if you have unzipped tomcat or your are on Linux machine, then "tomcat5w.exe" won't work. In that case, instead of starting tomcat with "startup.sh" script, execute the following command.
catalina.bat jpda start
You can do the same on windows as well. By default your debug port will be 8000.
Thanks.

Monday, September 21, 2009

ERROR 2003: Can't connect to MySQL server (10060)

ERROR 2003: Can't connect to MySQL server (10060)

Well, finally I rectified this error after doing google and research for 3.5 Hours.

I installed mysql database on my machine and I was trying to access it from the remote machine using MySQL query browser. But it was giving the error. If you are also facing the same problem then here are couple of things you can try.

  • If you have antivirus/firewall installed then make sure that it is not blocking traffic for port 3306(default port for mysql).

  • I have installed/configured MySQL to run as a service in windows box. If you have the same configuration, then open the Computer Management by Manage.

    Go to Service under Services And Applicaton.

    Look for mysql service and double click it to check the properties.

    The executable path should be like this: "C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqld-nt" --defaults-file="C:\Program Files\MySQL\MySQL Server 5.0\my.ini" MySQL

    Now it uses "my.ini" file for the configuration. Open this file on text editor. Under [mysqld] section add following line:

    bind-address=0.0.0.0

    You can give any ip address, if you want to listen only to localhost then you can give 127.0.0.1. The above configuration will listen to all ip addresses.

    If you are on linux machine, then you have to edit /etc/mysql/my.cnf file.


Hope this helps !!!
Enjoy !! :)