Monday, April 20, 2015

Issue with Key Names During DriverManagerDataSource Spring Bean Initialization

So I found a little something while loading a DriverManagerDataSource in Spring.

The DriverManagerDataSource is a class, the objects of which you usually initialize from within the bean configuration (Application Context) XML  file in Spring for configuring a DataSource. And this is how people usually do it:
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="
jdbc:mysql://localhost:3306/mydb" />
<property name="username" value="myuser" />
</bean> 
However, for some reason, I had to do this in code. Now, spring gives you a constructor, which takes a URL and a Properties object as arguments. Signature:
DriverManagerDataSource(String url, Properties conProps)
So I assumed the keys in the conProps object would be the same as the property names in the XML. But turns out I was wrong. The keys that the conProps object must have are actually different. Here's how I did it:
Properties conProps = new Properties();
conProps.put("user", "myuser");
conProps.put("driverClassName", "com.mysql.jdbc.Driver");
DriverManagerDataSource dataSource = new DriverManagerDataSource("
jdbc:mysql://localhost:3306/mydb", conProps);
So the key for the 'username' property is actually 'user' when using the constructor with Properties. Have I found a bug? ;)
Nonetheless, that took a good 15 mins of hair-pulling until I noticed.

Note: I am using Spring 4.1.5.

Monday, March 4, 2013

Microsoft Outlook 'Are you sure?' prompt before sending Email

Often, I have been annoyed when Microsoft Outlook doesn't ask for confirmation before sending an email. Although I haven't faced any unwanted 'oops!-I-sent-the-mail' moments yet, the day is not far (for some of us, the day has already gone by ;) )

For this reason, I did a little search to see how I can add this functionality, and found this incredibly simple way:

1. Open outlook and press ALT+F11.
2. This will open a Microsoft Visual Basic for Applications window. On the left pane, expand the 'Project1' group, and go to 'Microsoft Outlook Objects' > 'ThisOutlookSession' (Double Click).

3. Add the following piece of code in the editor window that shows up:

Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
        If MsgBox("Are you sure you want to send the email?", vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Send Email?") = vbNo Then
                Cancel = True
        End If
End Sub

4. Save the file (CTRL+S) and close.

Try sending a test mail to yourself. If you followed the steps well, the message box should show up the moment you click on 'send'!

Cool, isn't it?

Ref: Original post by Steve here: http://stevesgeekspeak.com/2010/01/howto-are-you-sure-prompt-in-outlook/
Note: I am not a VB expert, if you have questions related to the code. Have just shared this as a cool trick.

Thursday, June 10, 2010

Setting up the Xen-kernel for Virtual Machines

Since many days, I've been trying hard to install xen on various architectures using various methods.. but with a very low success rate. Here are the steps that worked for me (These steps are taken from here, with some modifications):

1. Take a machine with 64 bit architecture. To check the config of a machine:
$uname -a
If the line contains i386 or i686, the machine is 32-bit. If it contains x86_64, the machine is 64-bit.
(Alternatively, you can do:
$egrep -c ' lm ' /proc/cpuinfo
If the result is 1 or higher, it is a 64-bit machine; if it is a 0, it is not a 64-bit machine)


2. Install Ubuntu 8.10.

3.
$sudo su
Configure network, sources, etc.

4.
$apt-get install linux-image-server linux-server
$apt-get install ubuntu-xen-server build-essential libncurses5-dev gawk mercurial

$mkdir -p ~/build/linux-2.6.27-xen
$cd /usr/src/
$hg clone http://xenbits.xensource.com/ext/linux-2.6.27-xen.hg

$cd linux-2.6.27-xen.hg
$make O=~/build/linux-2.6.27-xen/ menuconfig

5.
In the kernel configuration menu, make sure that you select the following options:
General setup ---> Choose SLAB allocator (SLUB (Unqueued Allocator)) ---> (X) SLAB
Processor type and features ---> Subarchitecture Type (PC-compatible) ---> (X) Enable Xen compatible kernel
Bus options (PCI etc.)  ---> [*] PCI support
                             [*]   Xen PCI Frontend
                             [ ]     Xen PCI Frontend Debugging (NEW)
Networking support ---> Networking options ---> <*> 802.1d Ethernet Bridging
Device Drivers ---> [*] Network device support ---> [ ] Ethernet (10000 Mbit) --->
Make the Xen section look as follows (make sure you select Xen version compatibility (3.0.4 and later) instead of Xen version compatibility (3.0.2 and later)):
Device Drivers  ---> XEN  ---> [*] Privileged Guest (domain 0)
                               <*> Backend driver support (NEW)
                               <*>   Block-device backend driver (NEW)
                               <*>   Block-device tap backend driver (NEW)
                               <*>   Network-device backend driver (NEW)
                               (8)     Maximum simultaneous transmit requests (as a power of 2) (NEW)
                               [ ]     Pipelined transmitter (DANGEROUS) (NEW)
                               < >     Network-device loopback driver (NEW)
                               <*>   PCI-device backend driver (NEW)
                                       PCI Backend Mode (Virtual PCI)  --->
                               [ ]     PCI Backend Debugging (NEW)
                               < >   TPM-device backend driver (NEW)
                                  SCSI backend driver (NEW)
                                Block-device frontend driver
                                Network-device frontend driver
                                  Network-device frontend driver acceleration for Solarflare NICs (NEW)
                                SCSI frontend driver (NEW)
                               <*> User-space granted page access driver (NEW)
                               <*> Framebuffer-device frontend driver (NEW)
                               <*>   Keyboard-device frontend driver (NEW)
                               [*] Disable serial port drivers (NEW)
                               <*> Export Xen attributes in sysfs (NEW)
                               (256) Number of guest devices (NEW)
                                   Xen version compatibility (3.0.4 and later)  --->


6. After this, you need to do the following:
Open the file /usr/src/linux-2.6.29.2-xen/arch/x86/kernel/time_32-xen.c

$vim /usr/src/linux-2.6.29.2-xen/arch/x86/kernel/time_32-xen.c

Add the following line (highlighted) to the code at around line 500:
/* System-wide jiffy work. */
 if (delta >= NS_PER_TICK) {
         do_div(delta, NS_PER_TICK);
         processed_system_time += delta * NS_PER_TICK;
         while (delta > HZ) {

         asm("":"+r"(delta));

         do_timer(HZ);
         delta -= HZ;
    }
    do_timer(delta);
 }

(Note: if you don't add this line in the code, then while building the kernel in the next step, you may see too many warnings flashing on the screen and the build process may terminate after throwing an error.
Note2 (imp): The above step applies to the linux-2.6.29.2-xen sources. I have tried it on linux-2.6.27-xen and it worked. It may not apply to later releases. If you have a later release, try skipping this step)


7.
$make O=~/build/linux-2.6.27-xen/
$make O=~/build/linux-2.6.27-xen/ modules_install install

$depmod 2.6.27.5
$update-initramfs -c -k 2.6.27.5

$update-grub


8.
$vim /etc/modules

 and append the line:
loop max_loop=64

9.
$reboot

And after the reboot,
$uname -r
should show the xen kernel version (2.6.27.5).

10. After this you may think it is all done. Thats right, except that networking might have been screwed up!
If that is the case, continue with the following steps:
$apt-get remove network-manager

11.
$vim /etc/network/interfaces
and add the following lines:
auto eth0
iface eth0 inet static
        address         <dom0 IP>
        gateway         <a relevant gateway>
        netmask         <a relevant netmask>
        broadcast       <a relevant broadcast address>
You may get most of this info by doing 'ifconfig' on a similar machine.

12.
$vim /etc/resolv.conf
and add an entry for the DNS server you use:
nameserver <nameserver-IP>
you may add more than one entries.

Further, you may want to try out the following:
1. Create and Start Virtual Machines
     - this is a very good reference for creating image based virtual machines.
2. Migrating Virtual Machines
     - see this.


Other Ref:
http://www.infohit.net/blog/post/running-xen-on-ubuntu-intrepid-and-jaunty.html


Thursday, May 27, 2010

Proxy Authentication from a Java Code

People who are behind company/campus proxies especially those requiring authentication must have faced this problem many times. Say, you are using an API call which does some resource fetching from outside the proxy for you. Now, you need to tell the API that, look, this is the proxy, this is the port and this is the username and password for you to pass through it. Typically, you would try doing this by setting system properties like http.proxyHost, http.proxyPort, http.proxyUser and http.proxyPass respectively. However, turns out that this may not help in some unfortunate cases like mine.. :-)

Some background: I was working on a code which was using an API call to a function (it was actually an application based on the OWLS to UDDI matchmaker client API) which did some ontology accessing using Jena. I needed my code to be able to refer to the ontologies outside seemlessly.

I set all those system properties, changed them to see if it works. But it didn't. It continuously gave me the http 407 response code (proxy authentication reqd).

Now, there are 2 ways in which you can solve such a problem:
1. Creating a proxy authenticator class
2. Setting up a local proxy for the remote proxy.


1. Creating a proxy authenticator class:

I must say this is a rather non-trivial solution. One cannot possibly think of this unless told. Thanks to my friend Nishant who showed me how he had used this in one of his programs and the chap here who has posted this solution.

(a) Create a separate class in the project, say, ProxyAuthenticator:

import java.net.*;

class ProxyAuthenticator extends Authenticator {

private String user, password;

public ProxyAuthenticator(String user, String password) {
this.user = user;
this.password = password;
}

protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(user, password.toCharArray());
}

}

(b) Then, create an object of this class in the code just before the call that accesses outside data:

Authenticator.setDefault(new ProxyAuthenticator("MyUsername", "MyPassword"));

Also set the proxy username and password through system properties:

System.setProperty("http.proxyHost""proxy host");  
System.setProperty("http.proxyPort""port");


2. Setting up a local proxy for the remote proxy:

A local proxy is a program that will basically do all remote proxy authentication for requests going out of your machine.
So, you make calls from your machine as if there was no proxy. These calls pass through the local proxy which does the remote proxy authentication for you.

Squid is one such proxy that you can set up. A very good guide to setting up squid can be found on my friend Prashant Borole's blog here. Don't forget to read the notes of caution given by him at the end.

Happy Coding!
Dhaval

Sunday, May 9, 2010

Connection Pooling in Tomcat for MySQL

Ok, a slight digression from my promise to keep this blog 'simple'... ;-)
But I am sure there must be many first timers in databases and application deployment who will find this useful.

What is Connection Pooling?

Well, connection pooling is a way of creating a pool of database connections on the server.

When you create a single dedicated connection as in:

Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDB", "username", "password");

the driver instance stays dedicated to this thread that has created it. However, the application may require to use this connection for a very short time (few milliseconds) while for the rest of the time, it would be sitting idle but blocking resources.

In such a case, it is beneficial to create a connection pool which just picks a connection from the pool and 'loans' it to the application thread using it.

This gives a very nice overview of connection pooling.


How to perform Connection Pooling?

1. Open the ${CATALINA_HOME}/conf/server.xml file and enter the following inside the <host> </host> tags:

<Context path="/myApp" docbase="myApp" debug="5" reloadable="true" crosscontext="true">

<resource name="jdbc/myDB" auth="Container" type="javax.sql.DataSource" maxactive="100" maxidle="30" maxwait="10000" username="DBusername" password="DBpassword" driverclassname="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/myAppDB">

</resource>
</context>



2. If not already there, add this to WEB-INF/web.xml of your application (which you must have placed under ${CATALINA_HOME}/webapps - so the location will be something like ${CATALINA_HOME}/webapps//WEB-INF/web.xml):


<resource-ref>
<description> My DataSource </description>
<res-ref-name> jdbc/myDB </res-ref-name>
<res-type> javax.sql.DataSource </res-type>
<res-auth> CONTAINER </res-auth>
</resource-ref>


3. Now, your code to access this connection pool should look something like this:

dsname = "java:comp/env/jdbc/myDB";
ctx = new InitialContext();
ds = (DataSource)ctx.lookup(dsname);
conn = ds.getConnection();


..followed by the usual conn.createStatement(), etc. code.


How I got here:

I was trying to set up a jUDDI server on my machine. However, I never found a correspondence between what is written in their user guide and what is available for download. The only consistency I found was when I used the instructions given on the apache wiki for the deployment of this version of jUDDI given on sourceforge.net. So, I will discuss these instructions here.

All the instructions given therein are correct except the stuff suggested to be put under the <host> tag in ${CATALINA_HOME}/conf/server.xml. The following needs to be added instead:


<Context path="/juddi" docbase="juddi" debug="5" reloadable="true" crosscontext="true">

<resource name="jdbc/juddiDB" auth="Container" type="javax.sql.DataSource" maxactive="100" maxidle="30" maxwait="10000" username="juddi" password="123456" driverclassname="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/juddi?autoReconnect=true">

</resource>
</context>

Also, in the WEB-INF/classes/juddi.properties file inside juddi, set the juddi.useConnectionPool property to 'true'.

Now, the http://localhost:8080/juddi/happyjuddi.jsp page should be visible without any red lines - a problem which many people have tried to solve and write blogs about, but seems there is always something that gets missed out. It is possible that I miss out something too. Hence, here are some very good references; if something doesn't work, do try these out too:

Have a good day!
- Dhaval

Fixing your Logitech WebCam on Ubuntu 9.04

Hello guys,

If you are using skype and a Logitech webcam (ID 046d:08af) on Ubuntu 9.04 (Jaunty Jackalope), you must have noticed this.
When you open skype, and go to options > video devices and 'test' your camera, you see some ugly looking green coloured lines all over. When you do a video chat, the other person hears a lot of 'noise' instead of your voice.

Before the solution, how do u check the ID of your webcam?
Just type in:
lsusb | grep QuickCam

And now, here's a quick solution to the problem:
1. Shut Down Skype
2. Make a new file in /usr/local/bin:
sudo vim /usr/local/bin/skype

3. Enter the following lines (INSERT):
#!/bin/sh
LD_PRELOAD=/usr/lib/libv4l/v4l1compat.so /usr/bin/skype

and close the file (ESC :wq).
4. Change file permissions:
sudo chmod a+x /usr/local/bin/skype

5. Start skype and video should work now.. :)

Thanks to the gentleman here who posted this solution!

-Dhaval

Monday, March 15, 2010

Restoring Grub after Reinstalling Windows

Okay, you've had a very nice dual boot system with windows and linux set up, and you had to reinstall windows due to some some virus/upgrade/other issue. Boom! the first thing you see (or rather don't :P) after you restart is the windows boot loader which does not seem to be generous enough to show the ubuntu OS. This is in contrast to the Ubuntu boot loader (GRUB) which accommodates for other installed operating systems too. (For this reason, if you are setting up/reinstalling the whole system, it is generally advisable to first install windows, and then install Ubuntu.. This way, the windows boot loader will get replaced by GRUB which will allow you to boot into both the OSs).
Anyways, coming to our original issue, you have messed up with your boot loaders and now want to be able to boot into both the OSs.. do this:
1. Insert the Ubuntu Live CD and boot into it.
2. Once the CD gets booted, go to the live session and open a terminal.
3. Type 'sudo grub'. You will see a grub prompt like:
grub>
After this, type the following commands:
4. grub> find /boot/grub/stage1
- This will give you something like '(hdx,y)'
6. grub> root (hdx,y)
7. grub> setup (hdx)
8. grub> quit

Now, reboot the system, don't forget to remove the LiveCD and you should see your rocking dual boot system back!

References: check this.