Saturday, August 9, 2014

How to debug android app installation failures

Install "catlog" and "terminal emulator" apps from android market.

Run catlog app and begin recording log messages.

Start installation of the app to be debugged from android market.

On installation failure,  stop recording the log messages.  Open the recorded log.  Set log level filter to error.  This directly displays error messages.

If error message points to any file system permission or duplicate file issues,  use terminal emulator. It takes unix shell commands.  Use su command so that any command can be executed. To use su command the device should be rooted.

Wednesday, July 9, 2014

mysql

If disk space has run low, you will observe:

1. Application query response time increases.
2. Few application queries will randomly fail with lock wait timeout.
3. /mnt/eprint/mysql/mysqld.err error log will display the message: /usr/libexec/mysqld: Disk is full writing '/mnt/eprint/mysql/replication/mysql-bin.000033' (Errcode: 28). Waiting for someone to free space... (Expect up to 60 secs delay for server to continue after freeing disk space)


sudo su
mysql -u root -popelin
show databases;
use cpgDB;
show tables;
show create table tablename;
drop table tablename;
set foreign_key_checks=0;
select database();
drop database testdb;
create database testdb;
describe tablename;
SHOW TABLE STATUS FROM db_name LIKE 'tbl_name';
SET GLOBAL TRANSACTION ISOLATION LEVEL SERIALIZABLE;
SET tx_isolation = 'READ-COMMITTED';
exit;
tx_isolation system variable. Has both global and session scope.
The default transaction isolation level. Defaults to REPEATABLE-READ.
You can refer to the values of specific global or sesson system variables in expressions by using one of the @@-modifiers. For example,
you can retrieve values in a SELECT statement like this:
SELECT @@global.sql_mode, @@session.sql_mode, @@sql_mode;
For SHOW VARIABLES, if you specify neither GLOBAL nor SESSION, MySQL returns SESSION values.
autocommit is a session variable and must be set for each session.
use \G for displaying columns linearly
You can also use scripts from the mysql prompt by using the source command or \. command:
mysql> source C:\srini\IPG\code\CloudPrint\database-main\src\main\sql\cpgdb\00289.DE11469.dmapi.cpgDB.insert.reserved.email.addresses.into.BlockedEmailAddress.table.sql
mysql> \. filename
SHOW INDEX FROM tbl_name
mysql -uroot -popelin -e 'show engine innodb status\G' >> /home/cp_user/srini/out.txt
mysql> tee /tmp/out.txt    //this commands makes mysql to write its output to the given file along with console
mysql> notee                //this command disables the effect of tee command
mysqld --defaults-file="C:\ProgramData\MySQL\MySQL Server 5.5\my2.ini"
mysqladmin -u root –p shutdown
mysqldump --no-data -u root -p cpgDB > /tmp/cpgDB.sql    //This option exports only database and table schema, not data.
--no-create-info, -t     //This option instructs the utility not to add CREATE TABLE statements to the export file.
--no-data, -d            //This option exports only database and table schema, not data.
mysqldump -u russell -p workrequests work_req clients > /tmp/workreq_clients_tables.sql   //Here the database is workrequests and the tables to be backed up are
work_req and clients. Their table structures and data will be copied into the text file workreq_clients_tables.sql.

mysqldump --no-create-info --insert-ignore --where="service_name='storage'" -u root -p appconfig appconfig > /tmp/appconfig.sql
mysqldump -u root -p puma_db > /tmp/puma_db.sql
mysql -u root -p < /tmp/puma_db.sql
mysql -h host -u user -p
alter table deviceemailaddressalias add unique key (deviceId,creationTimeInMilliSec); to add unique key constraint
alter table deviceemailaddressalias add index index_name (deviceId,creationTimeInMilliSec); to drop unique key constraint
alter table deviceemailaddressalias drop index deviceId; to drop unique key constraint
show procedure status
show function status
CREATE INDEX idx_actor_first_name ON actor (first_name); The simplest CREATE INDEX statement adds a non-unique index to a table.
du -sk * | sort -nr | more
----------------------------
use cpgDB;
CREATE TABLE innodb_lock_monitor(a int) ENGINE=INNODB;//this statement starts writing (more than thrice per minute) enhanced output of 'show engine innodb status\G' to error log which in our case is /opt/apps/ms/mysql/mysqld.err. This is usfull for continuous monitoring.
drop table innodb_lock_monitor; //to disable lock monitoring, the table should be dropped.
-----------------------------
CREATE TABLE innodb_monitor (a INT) ENGINE=INNODB;
DROP TABLE innodb_monitor;
----------------------------------
select Token from AccessToken where expiryTime<=1414728000000 order by expiryTime asc into outfile 'c:\\srini\\testmail\\prodissues\\renew tokens\\finalTokens.txt';
LOAD DATA INFILE 'c:\\srini\\oauth1_clients.txt' INTO TABLE ConsumerDetails;
select Token from AccessToken where expiryTime<=1414728000000 into outfile 'c:\\srini\\testmail\\prodissues\\renew tokens\\latest tokens\\googleTokens.txt';
mysql> show variables like '%general%';
mysql> set global general_log=ON;
mysql> show open tables in testdb; //shows table locks on all the tables
mysql> analyze table SessionToken; //allows query optimizer to choose  better indexes
mysql> optimize table SessionToken; //reorganizes data on the disk.

cat > /opt/apps/ms/mysql/mysqld.err
csplit -k -f finalTokens -n 3 finalTokens.txt 50000 {*}



enabling general log for mysql 5.0.x versions:

1. log variable value should be set to ON.
2. Mysql should be started with command line option --log=/mnt/eprint/mysql/genlog.log as below
/bin/sh /usr/bin/mysqld_safe --defaults-file=/mnt/eprint/mysql/my.cnf --datadir=/mnt/eprint/mysql/data --socket=/mnt/eprint/mysql/mysql.sock --log-error=/mnt/eprint/mysql/mysqld.err --pid-file=/mnt/eprint/mysql/mysqld.pid --log=/mnt/eprint/mysql/genlog.log --user=mysql



 

Tuesday, July 8, 2014

tomcat remote debugging using netbeans

Tomcat:

tomcat/bin/catalina.sh checks for jpda argument. If jpda argument is passed then if other required variables are not available, it automatically sets defaults values for those variables. Below is the snippet of /mnt/eprint/tomcat/bin/catalina.sh file:

if [ "$1" = "jpda" ] ; then
  if [ -z "$JPDA_TRANSPORT" ]; then
    JPDA_TRANSPORT="dt_socket"
  fi
  if [ -z "$JPDA_ADDRESS" ]; then
    JPDA_ADDRESS="8000"
  fi
  if [ -z "$JPDA_SUSPEND" ]; then
    JPDA_SUSPEND="n"
  fi
  if [ -z "$JPDA_OPTS" ]; then
    JPDA_OPTS="-agentlib:jdwp=transport=$JPDA_TRANSPORT,address=$JPDA_ADDRESS,server=y,suspend=$JPDA_SUSPEND"
  fi
  CATALINA_OPTS="$CATALINA_OPTS $JPDA_OPTS"
  shift
fi


 /mnt/eprint/tomcat/bin/startup.sh run the command "catalina.sh start $@". $@ represents all the argument passed to startup.sh. /mnt/eprint/tomcat/bin/startup.sh has the below snippet:

PRGDIR=`dirname "$PRG"`
EXECUTABLE=catalina.sh

.
.
.
exec "$PRGDIR"/"$EXECUTABLE" start "$@" 


To start tomcat in remote debug mode the command run by /mnt/eprint/tomcat/bin/startup.sh should look like "catalina.sh jpda start $@". After doing the changes /mnt/eprint/tomcat/bin/startup.sh looks like below:

PRGDIR=`dirname "$PRG"`
EXECUTABLE=catalina.sh

.
.
.
exec "$PRGDIR"/"$EXECUTABLE" jpda start "$@"


If you don't want catalina.sh to set default values for jpda parameters then you can even declare them in the /mnt/eprint/tomcat/bin/startup.sh as below:

export JPDA_ADDRESS=8000
export JPDA_TRANSPORT=dt_socket


Netbeans:

To debug an externally started application call Debug . Attach Debugger. Select the Java Debugger
(JPDA) and use SocketAttach as connector. Additionally, you indicate the host’s name on which the
application runs, the port number on which the application accepts requests, as well as a timeout.
Press OK after doing the settings.
























Saturday, July 5, 2014

useful linux commands


Shell:

The shell is an interactive command interpreter environment within which commands may be typed at a prompt or entered into a file in the form of a script and executed.

A variety of shell environments have been developed over the years (Bourne shell, C shell, Korn shell, Bash shell). The default shell on CentOS 6 is the Bash shell (shorthand for Bourne again shell) and is based on features provided by both the Bourne Shell and the C Shell.

Bash provides a wide range of command line editing options as outlined in the following table:

Ctrl-b //Move cursor back one position
Ctrl-f  //Move cursor forward on position
Delete  //Delete character currently beneath the cursor
Backspace //Delete character to the left of the cursor
Ctrl-_  //Undo previous change (can be repeated to undo all previous changes)
Ctrl-a //Move cursor to the start of the line
Ctrl-e  //Move cursor to the end of the line
Esc then f  //Move cursor forward one word
Esc then b //Move cursor back on word
Ctrl-l  //Clear the screen of everything except current command
Ctrl-k  //Delete to end of line from current cursor position
Esc then d  //Delete to end of current word
Esc then DEL  //Delete beginning to current word
Ctrl-w  //Delete from current cursor position to previous white space 

File Name and Path Completion 

press the Esc key twice //complete the filename for you with the first file or path name in the directory that matches the characters you entered.

press Esc =  //Displays a list of possible matches 

Shell commands:

history //Displays a list of previously executed commands. In addition, Ctrl-p (or up arrow) and Ctrl-n (or down arrow) may be used to scroll back and forth through previously entered commands. Another option is to enter the ‘!’ character followed by the first few characters of the command to be repeated followed by the Enter key.

which ls //The available shell commands are either built into the shell itself, or reside on the physical file system. The location on the file system of a command may be identified using the which command.

cat list?.txt //Single character matches may be specified using the ‘?’ character. ‘*’ wildcard character to can be used to represent any number of characters.

ls *.txt > files.txt //redirect the output from an ls command to a file named files.txt 

wc –l < files.txt //The contents of a file may be fed into a command in place of stdin. This displays the number of lines contained in files.txt file.

df -h //Displays available partitions with their free space. -h allows human readable format

dd if=/home/srinivas/downloads/CentOS-6.5-x86_64-bin-DVD1.iso of=/dev/sdb //we can create bootable linux image usb device

sudo [options] [command]  //If you are allowed, execute command as the superuser. Authorized users of sudo and the commands they are permitted to execute are listed in the sudo configuration file, /etc/sudoers. If an unauthorized
user attempts to run a command, sudo informs an administrator via email. By default, it sends the message to the root account. Users attempting to run commands are prompted for their password. Once authenticated, sudo sets a timestamp for the user. For five minutes from the timestamp, the user may execute further commands without being prompted for her password. This grace period may be overridden by settings in the /etc/sudoers file. Also see /etc/sudoers for configuration examples. The sudoedit form of sudo is equivalent to running sudo -e.

su [option] [user] [shell_args]  //Create a shell with the effective user ID user. If no user is specified, create a shell for a privileged user (i.e., become a superuser). Enter EOF to terminate. You can run the shell with particular options by passing them as shell_args (e.g., if the shell runs bash, you can specify -c command to execute command via bash, or -r to create a restricted shell).

env //Shell environment variables provide temporary storage of data and configuration settings. Displays list of currently defined environment variables

echo $PATH //Displays the value of PATH environment variable. PATH defines the directories in which the shell will search for commands entered at the command prompt prompt, and the order in which it will do so.

export PATH=$PATH:$HOME/scripts //you wanted the shell to also look for commands in the scripts directory located in your home directory, you would modify the PATH variable like this.

export DATAPATH=/data/files //You can create your own environment variables using the export command. If there are environment variable or alias settings that you need to be configured each time you enter the shell environment, they may be added to a file in your home directory named .bashrc.

export NOW=`date` //Assign the output from a command to an environment variable involves the use of back quotes (`) around the command.

vmstat

top

rpm -Uvh package_file //updates existing installation

rpm -i package_file //installs package  

rpm -e package_name --noscripts //if normal erase didn't work because of any installation problems, the --noscripts option forcefully erases the package.

rpm -qa | grep java   //finds all the installed java rpm's on the machine

rpm -qf /user/bin/vim //displays which package is responsible for the file installation

rpm -ql package-name //list all files installed by that package


yum search package_file // * can be used at either end of the package file name

yum install package_file   //yum searches the repositories listed under /etc/yum.repos.d/ for specified package file. yum does dependency resolution also.

yum localinstall jdk-7u60-linux-i586.rpm  //package-file is on the local machine. This takes the help of yum for installation along with dependency resolution.

yum erase package_name //uninstall the package 

 yum update //apply any available updates to the installed packages

yum info package_name //displays information about the package 

yum repolist //display your current yum repositories

yum repolist all //to display all the repositories (both enabled and disabled) 

yum --enablerepo=fedora-source install vim-X11.x86_64 //install from a disabled repositories

yum list | less //list all the packages available in the yum database
yum list installed | less //view all the packages that are installed on your system
yum provides /etc/sysconfig/nfs //know which package a particular file belongs to

chmod +x filename.bin //well bin files you typicallly have to change the file permissions to be able to execute it by typing

./filename.bin //and then run. If instead you want to only extract the RPM file but not install it, you can run the .bin file with the -x argument.

ls /bin /usr/bin /usr/sbin | sort | uniq | grep -i Postfix //this command returned no entries. This means Postfix binaries are not installed on this machine.

groupadd groupname  //adds a new group. The /etc/group file contains all the grops
usermod -a -G groupname username //Add an Existing User to a Group
usermod -g groupname username //Change a User’s Primary Group
id username  //to see what groups the user is assigned to
groups username  //to see what groups the user is assigned to
groups //To view all the groups on the system

service mysqld start //runs mysqld available under /etc/rc.d/init.d. To automatically start and stop a service create symbolic links for /etc/rc.d/init.d/mysqld under /etc/rc.d/rc3.d/S99mysqld and /etc/rc.d/rc0.d/K01mysqld

service mysqld stop //runs mysqld available under /etc/rc.d/init.d

chkconfig --list //displays whether a service is enabled at various run levels.

nautilus . //opens the current directory in the file browser




Shell scripting:

Shell scripts are essentially text files containing sequences of statements that can be executed within the shell environment to perform tasks. In addition to the ability to execute commands, the shell provides many of the programming constructs such as for and do loops and if statements that you might reasonably expect to find in a scripting language.

The first step in creating a shell script is to create a file (for the purposes of this example we name it simple.sh) and add the following as the first line:

#!/bin/sh

The #! is called the shebang and is a special sequence of characters indicating that the path to the interpreter needed to execute the script is the next item on the line (in this case the sh executable located in /bin). This could equally be, for example, /bin/csh or /bin/ksh if either were the interpreter you wanted to use.

The next step is to write a simple script:

#!/bin/sh
for i in *
do
echo $i
done

All this script does is iterate through all the files in the current directory and display the name of each file. This may be executed by passing the name of the script through as an argument to sh:

sh simple.sh

In order to make the file executable (thereby negating the need to pass through to the sh command) the chmod command can be used:

chmod +x simple.sh

Once the execute bit has been set on the file’s permissions, it may be executed directly. For example:

./simple.sh




Filesystem layout (http://www.centos.org/docs/5/html/Deployment_Guide-en-US/s1-filesystem-fhs.html):

File systems break files down into two logical categories:
  • Shareable vs. unsharable files
  • Variable vs. static files
Shareable files are those that can be accessed locally and by remote hosts; unsharable files are only available locally. Variable files, such as documents, can be changed at any time; static files, such as binaries, do not change without an action from the system administrator.

/boot/ directory contains static files required to boot the system, such as the Linux kernel.

/dev/ directory contains device nodes that either represent devices that are attached to the system or virtual devices that are provided by the kernel. The udev demon takes care of creating and removing all these device nodes in /dev/.
Devices in the /dev directory and subdirectories are either character (providing only a serial stream of input/output) or block (accessible randomly). Character devices include mouse, keyboard, modem while block devices include hard disk, floppy drive etc.

The /etc/ directory is reserved for configuration files that are local to the machine. No binaries are to be placed in /etc/. Any binaries that were once located in /etc/ should be placed into /sbin/ or /bin/.

/lib/ directory should contain only those libraries needed to execute the binaries in /bin/ and /sbin/. These shared library images are particularly important for booting the system and executing commands within the root file system.

/media/ directory contains subdirectories used as mount points for removeable media such as usb storage media, DVDs, CD-ROMs, and Zip disks. 

/mnt/ directory is reserved for temporarily mounted file systems, such as NFS file system mounts. For all removeable media, please use the /media/ directory. Automatically detected removeable media will be mounted in the /media directory.

/opt/ directory provides storage for most application software packages.
A package placing files in the /opt/ directory creates a directory bearing the same name as the package. This directory, in turn, holds files that otherwise would be scattered throughout the file system, giving the system administrator an easy way to determine the role of each file within a particular package.
For example, if sample is the name of a particular software package located within the /opt/ directory, then all of its files are placed in directories inside the /opt/sample/ directory, such as /opt/sample/bin/ for binaries and /opt/sample/man/ for manual pages.
Packages that encompass many different sub-packages, data files, extra fonts, clipart etc are also located in the /opt/ directory, giving that large package a way to organize itself. In this way, our sample package may have different tools that each go in their own sub-directories, such as /opt/sample/tool1/ and /opt/sample/tool2/, each of which can have their own bin/, man/, and other similar directories.

/proc/ directory contains special files that either extract information from or send information to the kernel. Examples include system memory, cpu information, hardware configuration etc.

/sbin/ directory stores executables used by the root user. The executables in /sbin/ are used at boot time, for system administration and to perform system recovery operations. Of this directory, the FHS says:
/sbin contains binaries essential for booting, restoring, recovering, and/or repairing the system in addition to the binaries in /bin. Programs executed after /usr/ is known to be mounted (when there are no problems) are generally placed into /usr/sbin. Locally-installed system administration programs should be placed into /usr/local/sbin.

/usr/ directory is for files that can be shared across multiple machines. The /usr/ directory is often on its own partition and is mounted read-only. At a minimum, the following directories should be subdirectories of /usr/:

/usr
   |- bin/
   |- etc/
   |- games/   
   |- include/   
   |- kerberos/   
   |- lib/   
   |- libexec/        
   |- local/   
   |- sbin/   
   |- share/   
   |- src/   
   |- tmp -> ../var/tmp/ 


/usr/local hierarchy is for use by the system administrator when installing software locally. It needs to be safe from being overwritten when the system software is updated. It may be used for programs and data that are shareable among a group of hosts, but not found in /usr.

/var/. Since the FHS requires Linux to mount /usr/ as read-only, any programs that write log files or need spool/ or lock/ directories should write them to the /var/ directory. The FHS states /var/ is for:
...variable data files. This includes spool directories and files, administrative and logging data, and transient and temporary files.

Below are some of the directories found within the /var/ directory:

/var
   |- account/   
   |- arpwatch/   
   |- cache/   
   |- crash/   
   |- db/   
   |- empty/   
   |- ftp/   
   |- gdm/   
   |- kerberos/   
   |- lib/   
   |- local/   
   |- lock/   
   |- log/   
   |- mail -> spool/mail/   
   |- mailman/   
   |- named/   
   |- nis/   
   |- opt/   
   |- preserve/   
   |- run/   
   +- spool/
       |- at/        
       |- clientmqueue/        
       |- cron/        
       |- cups/        
       |- exim/               
       |- lpd/        
       |- mail/        
       |- mailman/        
       |- mqueue/        
       |- news/        
       |- postfix/         
       |- repackage/        
       |- rwho/        
       |- samba/         
       |- squid/        
       |- squirrelmail/        
       |- up2date/        
       |- uucp         
       |- uucppublic/        
       |- vbox/   
|- tmp/   
|- tux/   
|- www/   
|- yp/
 System log files, such as messages and lastlog, go in the /var/log/ directory. The /var/lib/rpm/ directory contains RPM system databases. Lock files go in the /var/lock/ directory, usually in directories for the program using the file. The /var/spool/ directory has subdirectories for programs in which data files are stored.


Friday, May 16, 2014

why url encoding

What characters need to be encoded and why?

ASCII Control characters
     Why: These characters are not printable.
Characters: Includes the ISO-8859-1 (ISO-Latin) character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal.)
Non-ASCII characters
     Why: These are by definition not legal in URLs since they are not in the ASCII set.
Characters: Includes the entire "top half" of the ISO-Latin set 80-FF hex (128-255 decimal.)
"Reserved characters"
     Why: URLs use some characters for special use in defining their syntax. When these characters are not used in their special role inside a URL, they need to be encoded.
Characters:
CharacterCode
Points
(Hex)
Code
Points
(Dec)
 Dollar ("$")
 Ampersand ("&")
 Plus ("+")
 Comma (",")
 Forward slash/Virgule ("/")
 Colon (":")
 Semi-colon (";")
 Equals ("=")
 Question mark ("?")
 'At' symbol ("@")
24
26
2B
2C
2F
3A
3B
3D
3F
40
36
38
43
44
47
58
59
61
63
64
"Unsafe characters"
     Why: Some characters present the possibility of being misunderstood within URLs for various reasons. These characters should also always be encoded.
Characters:
CharacterCode
Points
(Hex)
Code
Points
(Dec)
Why encode?
Space2032 Significant sequences of spaces may be lost in some uses (especially multiple spaces)
Quotation marks
'Less Than' symbol ("<")
'Greater Than' symbol (">")
22
3C
3E
34
60
62
These characters are often used to delimit URLs in plain text.
'Pound' character ("#") 2335 This is used in URLs to indicate where a fragment identifier (bookmarks/anchors in HTML) begins.
Percent character ("%") 2537 This is used to URL encode/escape other characters, so it should itself also be encoded.
Misc. characters:
   Left Curly Brace ("{")
   Right Curly Brace ("}")
   Vertical Bar/Pipe ("|")
   Backslash ("\")
   Caret ("^")
   Tilde ("~")
   Left Square Bracket ("[")
   Right Square Bracket ("]")
   Grave Accent ("`")

7B
7D
7C
5C
5E
7E
5B
5D
60

123
125
124
92
94
126
91
93
96
Some systems can possibly modify these characters.


How are characters URL encoded?
URL encoding of a character consists of a "%" symbol, followed by the two-digit hexadecimal representation (case-insensitive) of the ISO-Latin code point for the character.
Example
  • Space = decimal code point 32 in the ISO-Latin set.
  • 32 decimal = 20 in hexadecimal
  • The URL encoded representation will be "%20" 
 
Reference: http://www.blooberry.com/indexdot/html/topics/urlencoding.htm

Wednesday, April 16, 2014

How to handle Hibernate StaleStateException

Hibernate StaleStateException happens when two threads read a record from database and simutaneously try to delete the same record, one of them deletes first and the second one throws StaleStateException as the record is not found. In this case the only alternative is to either ask the end user to retry the operation or handle the exception and retry the operation for few number of times.

 for(int i=0;i<3 br="" i="">                try{
                    //Creating a session token
                    tokenEntity = securityManager.createSessionToken(printer, consumerKey);
                    break;
                }catch(CpFaultException e){
                    Throwable t = e.getCause();
                    if(t!=null && (t instanceof OptimisticLockException || t instanceof EntityNotFoundException)){
                        continue;
                    }else{
                        throw e;
                    }
                }
            }


ERROR | 2014-04-15 23:42:08,876 | http-443-164 |  [com.api.resources.device.SessionTokenRsource::handlePost_aroundBody0::107] An exception occurred. Please look at the stack trace: | 
com.faultbarrier.CpFaultException: javax.persistence.OptimisticLockException: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at com.faultbarrier.AbstractExceptionHandling.ajc$afterThrowing$com_hp_cloudprint_faultbarrier_AbstractExceptionHandling$1$5c51846b(AbstractExceptionHandling.aj:203) ~[util-3.13.7.29.jar:3.13.7.29]
    at com.entities.dao.impl.SecurityDAOImpl.deleteObject(SecurityDAOImpl.java:86) ~[entities-3.13.7.29.jar:3.13.7.29]
    at com.entities.dao.impl.SecurityDAOImpl.deleteSessionToken(SecurityDAOImpl.java:137) ~[entities-3.13.7.29.jar:3.13.7.29]
    at sun.reflect.GeneratedMethodAccessor309.invoke(Unknown Source) ~[na:na]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_17]
    at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_17]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307) ~[spring-2.5.6.jar:2.5.6]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:198) ~[spring-2.5.6.jar:2.5.6]
    at $Proxy152.deleteSessionToken(Unknown Source) ~[na:na]
    at com.security.impl.SecurityManagerImpl.createSessionToken(SecurityManagerImpl.java:172) ~[printer-3.13.7.29.jar:3.13.7.29]
    at sun.reflect.GeneratedMethodAccessor294.invoke(Unknown Source) ~[na:na]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_17]
    at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_17]
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307) ~[spring-2.5.6.jar:2.5.6]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:182) ~[spring-2.5.6.jar:2.5.6]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:149) ~[spring-2.5.6.jar:2.5.6]
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:106) ~[spring-2.5.6.jar:2.5.6]
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171) ~[spring-2.5.6.jar:2.5.6]
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204) ~[spring-2.5.6.jar:2.5.6]
    at $Proxy153.createSessionToken(Unknown Source) ~[na:na]
    at com.api.resources.device.SessionTokenRsource.handlePost_aroundBody0(SessionTokenRsource.java:93) [SessionTokenRsource.class:na]
    at com.api.resources.device.SessionTokenRsource.handlePost_aroundBody1$advice(SessionTokenRsource.java:16) [SessionTokenRsource.class:na]
    at com.api.resources.device.SessionTokenRsource.handlePost(SessionTokenRsource.java:40) [SessionTokenRsource.class:na]
    at org.restlet.Finder.handle(Finder.java:357) [org.restlet-1.1.6.jar:na]
    at org.restlet.Filter.doHandle(Filter.java:150) [org.restlet-1.1.6.jar:na]
    at org.restlet.Filter.handle(Filter.java:195) [org.restlet-1.1.6.jar:na]
    at org.restlet.Router.handle(Router.java:504) [org.restlet-1.1.6.jar:na]
    at org.restlet.Filter.doHandle(Filter.java:150) [org.restlet-1.1.6.jar:na]
    at org.restlet.Filter.handle(Filter.java:195) [org.restlet-1.1.6.jar:na]
    at org.restlet.Filter.doHandle(Filter.java:150) [org.restlet-1.1.6.jar:na]
    at org.restlet.Filter.handle(Filter.java:195) [org.restlet-1.1.6.jar:na]
    at org.restlet.Filter.doHandle(Filter.java:150) [org.restlet-1.1.6.jar:na]
    at com.noelios.restlet.StatusFilter.doHandle(StatusFilter.java:130) [com.noelios.restlet-1.1.6.jar:na]
    at org.restlet.Filter.handle(Filter.java:195) [org.restlet-1.1.6.jar:na]
    at org.restlet.Filter.doHandle(Filter.java:150) [org.restlet-1.1.6.jar:na]
    at org.restlet.Filter.handle(Filter.java:195) [org.restlet-1.1.6.jar:na]
    at com.noelios.restlet.ChainHelper.handle(ChainHelper.java:124) [com.noelios.restlet-1.1.6.jar:na]
    at com.noelios.restlet.application.ApplicationHelper.handle(ApplicationHelper.java:112) [com.noelios.restlet-1.1.6.jar:na]
    at org.restlet.Application.handle(Application.java:341) [org.restlet-1.1.6.jar:na]
    at com.noelios.restlet.ext.servlet.ServletConverter.service(ServletConverter.java:199) [com.noelios.restlet.ext.servlet-1.1.6.jar:na]
    at com.util.servlet.RestletFrameworkServlet.doService(RestletFrameworkServlet.java:44) [util-3.13.7.29.jar:3.13.7.29]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571) [spring-webmvc-2.5.6.jar:2.5.6]
    at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:511) [spring-webmvc-2.5.6.jar:2.5.6]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:637) [servlet-api.jar:na]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:717) [servlet-api.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:na]
    at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:378) [spring-security-core-2.0.4.jar:2.0.4]
    at org.springframework.security.intercept.web.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109) [spring-security-core-2.0.4.jar:2.0.4]
    at org.springframework.security.intercept.web.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) [spring-security-core-2.0.4.jar:2.0.4]
    at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) [spring-security-core-2.0.4.jar:2.0.4]
    at com.api.security.ConsumerKeyProtectedResourceProcessingFilter.onValidSignature(ConsumerKeyProtectedResourceProcessingFilter.java:51) [ConsumerKeyProtectedResourceProcessingFilter.class:na]
    at org.springframework.security.oauth.provider.OAuthProviderProcessingFilter.doFilter(OAuthProviderProcessingFilter.java:159) [spring-security-oauth-3.9.jar:na]
    at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) [spring-security-core-2.0.4.jar:2.0.4]
    at org.springframework.security.context.HttpSessionContextIntegrationFilter.doFilterHttp(HttpSessionContextIntegrationFilter.java:235) [spring-security-core-2.0.4.jar:2.0.4]
    at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53) [spring-security-core-2.0.4.jar:2.0.4]
    at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) [spring-security-core-2.0.4.jar:2.0.4]
    at org.springframework.security.securechannel.ChannelProcessingFilter.doFilterHttp(ChannelProcessingFilter.java:116) [spring-security-core-2.0.4.jar:2.0.4]
    at org.springframework.security.ui.SpringSecurityFilter.doFilter(SpringSecurityFilter.java:53) [spring-security-core-2.0.4.jar:2.0.4]
    at org.springframework.security.util.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:390) [spring-security-core-2.0.4.jar:2.0.4]
    at org.springframework.security.util.FilterChainProxy.doFilter(FilterChainProxy.java:175) [spring-security-core-2.0.4.jar:2.0.4]
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:236) [spring-2.5.6.jar:2.5.6]
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) [spring-2.5.6.jar:2.5.6]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:na]
    at com.eprintdirectory.util.ShardCleanupFilter.doFilter(ShardCleanupFilter.java:30) [eprintDirectory-3.13.7.29.jar:3.13.7.29]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:na]
    at com.metrics.MetricsUpdationFilter.doFilter(MetricsUpdationFilter.java:34) [metrics-3.13.7.29.jar:3.13.7.29]
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235) [catalina.jar:na]
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206) [catalina.jar:na]
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233) [catalina.jar:na]
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191) [catalina.jar:na]
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127) [catalina.jar:na]
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [catalina.jar:na]
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:555) [catalina.jar:na]
    at org.apache.catalina.valves.RemoteIpValve.invoke(RemoteIpValve.java:600) [catalina.jar:na]
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [catalina.jar:na]
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:298) [catalina.jar:na]
    at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:852) [tomcat-coyote.jar:na]
    at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:588) [tomcat-coyote.jar:na]
    at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489) [tomcat-coyote.jar:na]
    at java.lang.Thread.run(Thread.java:619) [na:1.6.0_17]
Caused by: javax.persistence.OptimisticLockException: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at org.hibernate.ejb.AbstractEntityManagerImpl.wrapStaleStateException(AbstractEntityManagerImpl.java:654) ~[hibernate-entitymanager-3.3.1.ga.jar:na]
    at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:600) ~[hibernate-entitymanager-3.3.1.ga.jar:na]
    at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:300) ~[hibernate-entitymanager-3.3.1.ga.jar:na]
    at sun.reflect.GeneratedMethodAccessor237.invoke(Unknown Source) ~[na:na]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) ~[na:1.6.0_17]
    at java.lang.reflect.Method.invoke(Method.java:597) ~[na:1.6.0_17]
    at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:198) ~[spring-2.5.6.jar:2.5.6]
    at $Proxy114.flush(Unknown Source) ~[na:na]
    at com.entities.dao.impl.SecurityDAOImpl.deleteObject(SecurityDAOImpl.java:85) ~[entities-3.13.7.29.jar:3.13.7.29]
    .. 81 common frames omitted
Caused by: org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1
    at org.hibernate.jdbc.Expectations$BasicExpectation.checkBatched(Expectations.java:61) ~[hibernate-3.2.2.ga.jar:3.2.2.ga]
    at org.hibernate.jdbc.Expectations$BasicExpectation.verifyOutcome(Expectations.java:46) ~[hibernate-3.2.2.ga.jar:3.2.2.ga]
    at org.hibernate.jdbc.BatchingBatcher.checkRowCounts(BatchingBatcher.java:68) ~[hibernate-3.2.2.ga.jar:3.2.2.ga]
    at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48) ~[hibernate-3.2.2.ga.jar:3.2.2.ga]
    at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:242) ~[hibernate-3.2.2.ga.jar:3.2.2.ga]
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:235) ~[hibernate-3.2.2.ga.jar:3.2.2.ga]
    at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:144) ~[hibernate-3.2.2.ga.jar:3.2.2.ga]
    at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298) ~[hibernate-3.2.2.ga.jar:3.2.2.ga]
    at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27) ~[hibernate-3.2.2.ga.jar:3.2.2.ga]
    at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1000) ~[hibernate-3.2.2.ga.jar:3.2.2.ga]
    at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:297) ~[hibernate-entitymanager-3.3.1.ga.jar:na]
    .. 87 common frames omitted

Sunday, April 13, 2014

Netbeans Scala plugin

1. Go to the url http://sourceforge.net/projects/erlybird/files/nb-scala/ (reference http://wiki.netbeans.org/Scala )
2. Download the Zip file. Extract it on the local filesystem.
3. Open Netbeans IDE. Go to Tools -> Plugins. In the "Plugins" window, "Downloaded" tab, click "Add Plugins" button and select the extracted zip file.

Sunday, March 16, 2014

How to configure D'link pocket router dir-506l with Reliance netconnect+ dongle

Yesterday I bought D'link pocket router dir-506l. I bought it to use with my Reliance netconnect+ dongle (Huwei EC1262).

D'link pocket router dir-506l comes with battery backup so it allows me to connnect to my Reliance netconnect+ from virtually anywhere.

I could configure dir-506l easily from my mobile web browser.  But I found there is no option to configure 3g/4g networks. Similar to traditional routers this router has options to configure with dhcp/pppop/static/.... networks only.  I've searched internet about the device support for Reliance Netconnect+. I found many others are in the same situation as mine and there is no solution.
Then I had a thought about upgrading to latest firmware.  I've searched for latest firmwares for this product.  My device has come with a firmware dated back to 2012 and 2.13 is the exact version.
While searching internet I found a website http://www.dlink.com.au/tech/download/download.aspx?product=DIR-506L which has latest firmwares released Upto 08/july/2013 and the latest is 2.15 version. There also I found compatible device list.  In compatible devices I found Huwei EC1261. This is not exactly my device.  But I thought to go with 2.15 version.  I've downloaded it and upgraded it by connecting to the device through Wi-Fi even though recommended  for firmware upgrade is through wired connection. Once upgrade is completed I've reset the device to factory settings by pressing reset button for 10 seconds.  After that I connected from my Mobile phone to the device through Wi-Fi. Now I am able to see 3g/4g mode in the internet settings menu.  I've selected this mode and selected manual configuration. There I configured my Reliance netconnect+ details. Once these settings are saved the router rebooted and connected to the internet.


Saturday, March 15, 2014

fedora 19 64 bit android development

To develop Android apps on Fedora 19 64 bit environment follow the below steps:

  1. Download Android bundle from http://developer.android.com. This downloads /home/jay/Downloads/adt-bundle-linux-x86_64-20131030.zip. This bundle contains "Eclipse IDE" and "Android SDK with 4.4 kitkat framework".
  2. Extract the downloaded zip file to your home directory. For me I've extracted it to /home/jay resulting in /home/jay/adt-bundle-linux-x86_64-20131030. After extracting the folder structure should look like below:

    [root@localhost jay]# ls -l ./adt-bundle-linux-x86_64-20131030
    total 8
    drwxrwxrwx.  9 jay jay 4096 Mar 16 08:37 eclipse
    drwxrwxrwx. 11 jay jay 4096 Mar 16 00:24 sdk
     
  3.  Give read/write/execute permissions:

    [root@localhost jay]# chmod -R 777 ./
  4. Run /home/jay/adt-bundle-linux-x86_64-20131030/sdk/tools/android to install few more frameworks (default the dowloaded SDK comes with 4.4 kitkat) 4.0.x IceCreamSandwitch. Having lower version frameworks allows you to check backward compatibility of the newly developed apps.
  5. Run /home/jay/adt-bundle-linux-x86_64-20131030/eclipse/eclipse. Create new eclipse workspace for android projects /home/jay/android-workspace
  6. In Eclipse Go to "Windows->Preferences". Expand list of Options under "Android" item in the left menu. When you select each option Eclipse shouldn't display any kind of "no such file or directory" dialog box. We've already given 777 permission to read/write/execute for all the files under "/home/jay/" so that both "Eclipse" and "Android SDK" have enough permissions and you won't be facing any kind of error.
  7. In Eclipse Go to "File->new->AndroidApplicationProject". Fill the Dialogs properly. This creates new project. Remember even 777 permissions helps in creating a project without errors.
  8. In Eclipse Go to "Window->Android Virtual Device Manager". Create new AVD. While creating new AVD I faced a problem "[2014-03-16 08:40:03 - SDK Manager] Failed to create sdcard in the AVD folder." To resolve this you need to install few 32bit libraries. While installing those 32 bit libraries I found a conflicting alsa-lib-1.0.27.1-2.fc19.x86_64 64 bit library. Then I removed this library without removing any other dependent libraries on alsa-lib-1.0.27.1-2.fc19.x86_64. Run the below commands. (Reference http://www.if-not-true-then-false.com/2010/android-sdk-and-eclipse-adt-on-fedora-centos-red-hat-rhel/)

    [root@localhost jay]# rpm -e --nodeps alsa-lib-1.0.27.1-2.fc19.x86_64
    [root@localhost jay]# yum install libX11.i686 libXext.i686 libao.i686 alsa-lib.i686 libX11-devel.i686

    Now I am able to create new AVD.
  9. Try to build the application. If you see the error "aapt: error while loading shared libraries: libz.so.1: cannot open shared object file: No such file or directory", run the command:
    [root@localhost jay]# yum install zlib.i686
  10. if you see the error "error libGL.so: cannot open shared object file: No such file or directory" (reference http://stackoverflow.com/questions/18507812/which-libgl-to-use-for-android-emulator-in-fedora-64-bit)

    [root@localhost jay]# yum install glibc.i686 glibc-devel.i686 libstdc++.i686 zlib-devel.i686 ncurses-devel.i686 libX11-devel.i686 libXrender.i686 libXrandr.i686
    [root@localhost jay]# rpm -e --nodeps mesa-libGL-9.2-0.12.20130610.fc19.x86_64
    [root@localhost jay]# yum install mesa-libGL.i686

Tuesday, March 4, 2014

how to increase internal storage of Android device

I've been using Karbon A25 with internal storage of 135mb. Because of this lower storage capacity I couldn't install more than a couple of apps (10 apps). Following the below steps l could successfully add some part of the external SD card (5gb of 30 gb sd card) to existing internal storage.

1. First root the device. For rooting follow The steps at http://forum.xda-developers.com/showthread.php?t=2421802
2. Verify whether the device is rooted by installing "root checker" app.
3. Follow the steps at http://rootmyandroid.org/increase-internal-memory-phone.html

Monday, February 10, 2014

how to release a port in windows 7

ref: http://stackoverflow.com/questions/788348/how-do-i-free-my-port-80-on-localhost-windows

netstat -ano
That will show you the PID of the process that is listening on port 80. After that, open the Task Manager -> Processes tab. From the View -> Select Columns menu, enable the "PID" column, and you will see the name of the process listening on port 80.

apache-tomcat-6.0.35 SEVERE: Failed to initialize connector [Connector[HTTP/1.1-443]] LifecycleException: Protocol handler initialization failed: java.lang.Exception: No Certificate file specified or invalid file format

reference: http://tomcat.10.x6.nabble.com/SSL-No-Certificate-file-specified-or-invalid-file-format-td2087714.html

Feb 10, 2014 2:38:32 PM org.apache.catalina.core.AprLifecycleListener init
INFO: Loaded APR based Apache Tomcat Native library 1.1.22.
Feb 10, 2014 2:38:32 PM org.apache.catalina.core.AprLifecycleListener init
Feb 10, 2014 2:38:33 PM org.apache.coyote.http11.Http11AprProtocol init

As mentioned in the docs, there are two SSL implementations that can
be used by Tomcat:
- one provided by Java runtime,
- another provided by OpenSSL library (called through APR/Tomcat-Native).

Their configurations are very different.

The above log fragment shows that you are using the APR one.

To configure it correctly: 

I disabled APR by following these steps:
 a) remove bin\tcnative-1.dll
 b) remove  className="org.apache.catalina.core.AprLifecycleListener"
SSLEngine="on" /> line from server.xml.

c) remove 'protocol="http11.Http11AprProtocol"' from server.xml's Connector
,
   changed as follow:
                    maxThreads="150" scheme="https" secure="true"
               clientAuth="false" sslProtocol="TLS"
               keystoreFile="conf/server.keystore" keystorePass="test"
     truststoreFile ="conf/client.keystore" truststorePass="test"/>

Saturday, February 1, 2014

How to install VLC on Fedora 20

http://sayaksarkar.wordpress.com/2013/06/04/installing-vlc-player-on-fedora-19-schrodingers-cat/

  1. Login as Super User:
    • $su
  2. Setup rpmfusion:
  3. Install vlc using the default yum package manager:
    • #yum install vlc mozilla-vlc

How to install skype 4.2 on Fedora 20

http://www.if-not-true-then-false.com/2012/install-skype-on-fedora-centos-red-hat-rhel-scientific-linux-sl/

http://sayaksarkar.wordpress.com/2013/11/18/installing-skype-on-fedora-19/

First I've followed instructions from the above two websites and have run the below commands.

  1. su
  2. yum install alsa-lib.i686 fontconfig.i686 freetype.i686 glib2.i686 libSM.i686 libXScrnSaver.i686 libXi.i686 libXrandr.i686 libXrender.i686 libXv.i686 libstdc++.i686 pulseaudio-libs.i686 qt.i686 qt-x11.i686 qtwebkit.i686 zlib.i686

Next I found another website https://ask.fedoraproject.org/en/question/8738/how-to-install-skype/ and did the below steps:

  1. Download the skype package from its official website, downloads section. Choose Fedora as your distribution. Fedora 16 32 bit is fine for Fedora 18 installs or later.
  2. Double-click on the downloaded package.
  3. The system will ask if you'd like to install the package. Confirm.
 I could find skype icon in the Activities menu bar and is running well.

Wednesday, January 22, 2014

How to inject dependencies into an Aspectj class using Spring

I've an aspect written using Aspectj at the location onramp\src\main\aspects\metrics\com\hp\cloudprint\api\onramp\reliability\metrics\MonitoringAspect.aj

When compiled, Aspectj genereates onramp\target\classes\com\hp\cloudprint\api\onramp\metrics\MonitoringAspect.class (For details about how to compile, look at the post "Compiling aspectj files declared under maven java project").

I've made my aspectj compilation optional during build time by using Maven profile to override the default aspectj plugin configuration in the onramp\pom.xml. Default plugin configuration doesn't compile aspects at the location src/main/aspects/metrics.
To compile aspects at the location src/main/aspects/metrics enter onramp>mvn clean install -Donramp.metrics=true command, which generates compiled file at the location onramp\target\classes\com\hp\cloudprint\api\onramp\metrics\MonitoringAspect.class.  

I want to inject metricsManager dependency into the MonitoringAspect.aj through Spring dependency injection.

If the MonitoringAspect.aj gets compiled always the I could have declared the below definition in the onramp\src\main\resources\applicationContext-onramp.xml


       

 
As the MonitoringAspect.aj is optionally compiled, in the default build
MonitoringAspect.class would be missing and Spring container start up fails with BeanClassNotFoundException. The alternative is to use Spring auto detection feature. This feature is available from Spring2.5. 

To enable Spring auto detection feature add to the
onramp\src\main\resources\applicationContext-onramp.xml. Add @Component annotation to
MonitoringAspect.aj. Add @Autowired annotation to each dependency to be injected in the
MonitoringAspect.aj. These annotations allow Spring to auto detect classes with the @Component annotation and register those as Spring beans and dependency inject those attributes with
@Autowired annotation. For more details about @Component refer http://www.mkyong.com/spring/spring-auto-scanning-components/

As Aspectj instantiates the MonitoringAspect.class, Spring won't get a chance to inject the dependencies. To make Spring aware of when the
MonitoringAspect.class gets instantiated, we also need to add
to the
onramp\src\main\resources\applicationContext-onramp.xml,  and @Configurable("monitoringAspect") annotation to
MonitoringAspect.aj.




pom.xml
-----------


<build>
    <finalName>onramp</finalName>
    <plugins>
        <plugin>
            <groupId>org.codehaus.mojo</groupId>
            <artifactId>aspectj-maven-plugin</artifactId>
            <version>1.2</version>
            <configuration>
                <!-- <outxml>true</outxml>
                <showWeaveInfo>true</showWeaveInfo>
                <Xlint>warning</Xlint>
                <verbose>true</verbose> -->
            </configuration>
            <executions>
                <execution>
                    <phase>process-sources</phase>
                    <goals>
                        <goal>compile</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>
<dependencies>
    <dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.6.5</version>
        <scope>runtime</scope>
    </dependency>
</dependencies>

<profiles>
   
<profile>
       
<id>metrics</id>
       
<activation>
           
<property>
               
<name>onramp.metrics</name>
               
<value>true</value>
           
</property>
       
</activation
>
       
<build>
           
<plugins>
               
<plugin>
                   
<groupId>org.codehaus.mojo</groupId>
                   
<artifactId>aspectj-maven-plugin</artifactId>
                   
<version>1.2</version>
                   
<configuration>
                       
<aspectDirectory>src/main/aspects/metrics
>
                       
<source>1.6</source>
                       
<target>1.6</target>
                       
<!-- <outxml>true</outxml>
                       
<showWeaveInfo>true</showWeaveInfo>
                       
<Xlint>warning</Xlint>
                       
<verbose>true</verbose> -->
                   
</configuration>
                   
<executions>
                       
<execution>
                           
<phase>process-sources</phase>
                           
<goals>
                               
<goal>compile</goal>
                           
</goals>
                       
</execution>
                   
</executions>
               
</plugin>
           
</plugins>
       
</build>
   
</profile></profiles>

 applicationContext-onramp.xml
----------------------------------------

<?xml version="1.0" encoding="UTF-8"?> 
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="
       http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"
       default-autowire="byName">   
               
   
<context:annotation-config />     
  <context:component-scan base-package="com.hp.cloudprint" />
   
<context:spring-configured/>
</beans>             
   
   

   




 MonitoringAspect.aj
----------------------------
package com.hp.cloudprint.api.onramp.reliability.metrics;

import org.springframework.beans.factory.annotation.Configurable;
import com.hp.cloudprint.util.logging.EPrintLoggerFactory;
import com.hp.cloudprint.util.logging.EPrintLogger;
import com.hp.cloudprint.metrics.MetricsManager;
import com.hp.cloudprint.metrics.MetricsManagerException;
import org.springframework.security.AccessDecisionManager;
import org.springframework.security.AccessDeniedException;
import org.springframework.security.AuthenticationManager;
import org.springframework.security.AuthenticationException;
import org.springframework.security.oauth.provider.OAuthProviderProcessingFilter;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Autowired;

@Component
@Configurable("monitoringAspect")
public aspect MonitoringAspect {
    protected static final EPrintLogger LOG = EPrintLoggerFactory.getLogger();
   
    @Autowired
    private MetricsManager metricsManager;
   
    pointcut accessDeniedException() : execution(* AccessDecisionManager.decide(..));
    pointcut authenticationException() : execution(* AuthenticationManager.authenticate(..)) || execution(* OAuthProviderProcessingFilter.validateSignature(..));
   
   
    after() throwing(AccessDeniedException ex):accessDeniedException() {
       
            LOG.debug("------------------------------------#######################authorization begin############################----------------------------------");
            try{
                metricsManager.incrementIntegerAttribute("authorizationFailures");
            }catch(MetricsManagerException x){
                LOG.debug("MonitoringMetricsException", null);
            }
            LOG.debug("------------------------------------#######################authorization end############################----------------------------------");
          
    }
   
   public void setMetricsManager(MetricsManager metricsManager){
        this.metricsManager = metricsManager;
    }
}

Followers