Tuesday, January 31, 2012

Tuples in Java

I came across the concept of tuples in C# which is quite interesting and useful. A tuple is a data structure that has a specific number and sequence of elements.  C# introduced this feature since .NET 3.5. It supports upto 8 generic objects. Unfortunately Java haven't got one yet.


In my current project there was a need for a similar Data-structure, where I had to pass back a large amount of data of a particular object. But I was interested only in just two properties of that object. I could have created a proxy class, but that would have ben a sort of over engineering (Which I don't want to do). At that time I thought of a simple attempt to write a Tuple. I wrote one and it's really reusable and clean. You can find the  the code snippet below.

public abstract class Tuple<T1, T2, T3, T4>{


    protected T1 t1;
    protected T2 t2;
    protected T3 t3;
    protected T4 t4;
    
    public static    < T1, T2> Tuple <T1, T2, ?, ?> create(T1 aT1, T2 aT2){
        return new MultipleTuple(aT1, aT2);
    }
    
    public  T1 getFirstItem(){
        return t1;
    }
    
    public T2 getSecondItem(){
        return t2;
    }
    
    public T3 getThirdItem(){
        return t3;
    }
    
    public T4 getFourthItem(){
        return t4;
    }

}

A MultiTuple


final class MultipleTuple<T1, T2> extends Tuple {
    
     MultipleTuple(T1 aT1, T2 aT2) {
        t1 = aT1;
        t2 = aT2;
    }
}


Example


String employee = "Diego Maradona";
double renumeration = 56.5;
        
Tuple  tuple = Tuple.create(employee, renumeration);


System.out.println(tuple.getFirstItem());
System.out.println(tuple.getSecondItem());




You can extend as many classes you want to create. You might need to restrict the visiblilty and make them final so that it's secure. Or you could even extend the MultipleTuple(Hoping it's no longer final) class for the next tuples. Make sure the create method is overloaded with the right parameters.




Happy Hacking.

Wednesday, January 25, 2012

IE Caches Jquery Ajax Request

Do you know what's the time now, while I write this post? It's 2:00 am in the morning. I was asked to fix a Jquery issue happening only in Internet explorer.

There was a piece of code which makes an ajax request to the server periodically. But this code only works  once.  This problem is seen only in Internet explorer. After scratching my head for a while I finally realized that IE caches ajax requests.

The solution is to use the following code:


$.ajaxSetup ({
   cache: false
});

Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]", to the URL. So if you have  long query string as the ajax request this might be a problem. I am  not sure, I but I guess so.

Happy Hacking!


Thursday, January 12, 2012

Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() using Spring JdbcTemplate

My colleague was getting this exception for a Spring JdbcTemplate based code which I had written for some simple Mysql dao functionalities. The funny point was that we were both using the same version of Mysql drivers, but I was using 32bit Mysql 5.5 but my colleague was using the 64bit version.

This quick fix solves the problem:


KeyHolder keyHolder = new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
 public PreparedStatement createPreparedStatement(Connection aConnection) throws SQLException {
                    PreparedStatement preparedStatement = aConnection.prepareStatement(SAVE_USER,
PreparedStatement.RETURN_GENERATED_KEYS);
                    preparedStatement.setString(....);
                    ....
                         preparedStatement.setString(....);
                    return preparedStatement;
                }
            }, keyHolder);
 user.setId(keyHolder.getKey().intValue());

A few other fellow bloggers had given suggestions like switching the Mysql dirvers, but it's didn't help me at all. I had tried all the last 10 Mysql driver releases. I am not sure if its a programming error or a Mysql bug, but the above code does fix the problem!

Happy Hacking :)

Adobe Flash Builder 4.5 Hangs

I recently bought Adobe Flash builder 4.6 Premium. It's pretty good but hangs quite a lot. As it was build on top of eclipse, this simple trick helped me to get rid of the problem.

  • Got Flash Builder Home/eclipse 
  • Open eclipse.ini
  • Change the vmargs( Xms & -Xmx) to  -Xms512m-Xmx1024m ( by default 256 & 512)
  • Save and restart Flash Builder
Note: You could change the Xms and Xmx value to the value suitable to your system. These values are just samples.

Happy hacking :)

Monday, October 17, 2011

OpenSource & RadioShack Myth

I like this quote by Larry (it's a bit old though, but very true)


"One of the myths of open-source is that it's built by a bunch of guys who work at RadioShack (a U.S. electronics store). And when they get home at night, they log on to the Internet and write codes," he said. "The largest investor of Linux with the most number of Linux engineers is from a little RadioShack-related company called IBM."


Read More....





Thursday, October 13, 2011

How to Autowire an argument to a constructor in Spring.

Look into this class:

public class SomeServiceImpl{


    @Autowired
    private AnotherService anotherService;


    public SomeServiceImpl(){
            doThisWithAnotherService();
    }


    private void doThisWithAnotherService(){
            anotherService.doThat();
    }
}


The above code will blowup while initilization with a NullPointerException inside the doThisWithAnotherService().  The reason being the constructor is called before AnotherService bean is injected.

Solution


public class SomeServiceImpl{


    private AnotherService anotherService;


    @Autowired
    public SomeServiceImpl(AnotherService aService){
        this.anotherService = aService;
        doThisWithAnotherService();
    }


    private void doThisWithAnotherService(){
        anotherService.doThat();
    }
}



Fields are injected right after construction of a bean before any config methods are invoked.

Source: http://static.springsource.org/spring/docs/2.5.x


Thursday, June 23, 2011

Error: Unable to transcode assets/xyz.png

I got this error while trying to build a Flex application using Apache ant and Flex 4.5 SDK (Got it even while directly using the MXML command). The strange thing is that, I was able to successfully compile this same project at my office using the very same SDK. I googled and nowhere did I get a satisfactory solution. There were so many threads and links which showed a similar problem:

 Error: unable to resolve 'assets/xyz.png'.

The fact is that, the above error is entirely different from the error I am talking about. The above error is just because the compiler can't resolve the image. A '/' or  '../' before the 'assets' will easily solve the above problem.

But the error:

Error: Unable to transcode assets/xyz.png

is different and frustrating. I happens even though that particular image could be resolved. 

After a few hours of research I finally figured out the problem. The problem was with the underlying JDK.

My Machine is using 64 bit Windows 7, and apparently the JDK  was also a 64 bit. Flex release notes doesn't mention that it supports 64 bit os and now it's clear -It doesn't support. Finally after switching to a 32 bit JDK the project got compiled successfully.

Note- if the above solution doesn't work, you should try downloading the latest 32 bit JDK and try. 


Wednesday, June 22, 2011

org.springframework.beans.FatalBeanException: Could not copy properties from source to target

I came across this irritating issue(While workign on a Spring based project).

org.springframework.beans.FatalBeanException: Could not copy properties from source to target; nested exception is java.lang.IllegalArgumentException: argument type mismatch
at org.springframework.beans.BeanUtils.copyProperties(BeanUtils.java:599)
at org.springframework.beans.BeanUtils.copyProperties(BeanUtils.java:509)

Google took me to this bug which was already logged with SpringSource:

https://jira.springsource.org/browse/SPR-7693 (unfortunately it's still unfixed)

I made a quick fix/workaround for this.

Download/checkout : org.springframework.beans.BeanUtils.java

Add the below line after: writeMethod.invoke(target, value); (Around line 597) if using the 3.1 source.



if(logger.isDebugEnabled()){
logger.debug(MessageFormat.format("Source Property: {0}, Target Property:   {1}, Write method:{2}, Read Method {3} ", sourcePd.getName(),  targetPd.getName(), writeMethod.getName(), readMethod.getName()));
}

Add the file to your project. Now you can happily debug which property in the class is causing  problem.

Monday, June 20, 2011

Flex Builder 3 on Eclipse Ganymede

While this post might be obsolete, I believe its still useful.

I have had a problem this evening configuring Flex builder 3 with Eclipse. On the final step I was getting this annoying error and for that reason the installation fails:

Missing requirement: Flex Debug Plug-in for Eclipse 3.2 3.0.214193 (com.adobe.flexbuilder.debug.e32 3.0.214193) requires 'bundle org.eclipse.debug.ui [3.2.0,3.3.0)' but it could not be found.

The org.eclipse.debug.ui I have is much more higher version, so Flex shouldn't technically complain about this (3.5.x). I saw a lot of google posts asked by various users, but none had a solution. As I finally made it work, I thought it would be worth useful for somebody else out there.

Solution (Well precisely its not a solution, but a workaround)
  • Assuming you have already installed Flex builder.
  • Take a backup of : /com.adobe.flexbuilder.update.site/plugins/com.adobe.flexbuilder.debug.e32_3.0.214193.jar
  • unjar/open: com.adobe.flexbuilder.debug.e32_3.0.214193.jar
  • Edit META-INF/MANIFEST.MF
  • Remove the value : bundle-version="[3.2.0,3.3.0)" (which would be the last Require-Bundle section)
  • Update the Jar with the changes.
  • You might need to replace the modified com.adobe.flexbuilder.debug.e32_3.0.214193.jar into /plugins as well.
  • Restart and continue the flex update from eclipse.
This time the installation should pass. :)



Sunday, March 27, 2011

org.hibernate.util.JDBCExceptionReporter ORA-01407: cannot update (...) to NULL

I faced this issue for a while this afternoon while deleting a row which has a column referenced by a child table.



The cause for this is due to an incorrect JPA mapping:

Solution:
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name = "FK_QUESTION_ID", updatable=false, insertable=false)

updatable=false - column is not included in SQL INSERT statements generated by the persistence provider.
updatable=false - column is not included in SQL UPDATE statements generated by the persistence provider.

Tuesday, October 26, 2010

SOAP Monitor

Came across this brilliant tool for monitoring SOAP inbound/outbound messages:

http://java-source.net/open-source/web-services-tools/membrane-soap-monitor

This is more like a tunneling software, but purely for SOAP monitoring. It formats requests/responses for easiness.

YOu could use the SOAP-UI plugin for eclipse, but its quite heavy. One good thing I liked about SOAPUI eclipse plugin is its ability ot crete Junit test case from WSDL.

Tuesday, June 15, 2010

A very innovative tool...

Steve send a mail to the group about a cool online tool - Dropbox.


If you install DropBox on your desktop, it gives you a 'folder' which you can drop files into. The files are actually stored on the DropBox server.
When you get home, just click on the folder to access all your 'dropped' files. Much easier than emailing files to yourself and more convenient than Google docs.

If you use this link https://www.dropbox.com/referrals/NTgxMjE0NDQ5 (demo video and signup form)


You will get free 250MB of storage. I find it very handy.
No credit card details asked for - its free!

Monday, May 31, 2010

java.lang.IllegalStateException: Error while loading manipulator

While trying to update eclipse plugins, you might get this error:
java.lang.IllegalStateException: Error while loading manipulator

The underlying error in the\workspace\.metadata\.log - would be something similar to:

!ENTRY org.eclipse.equinox.p2.engine 4 4 2010-06-01 00:19:00.483
!MESSAGE An error occurred while unconfiguring the items to uninstall
!SUBENTRY 1 org.eclipse.equinox.p2.engine 4 0 2010-06-01 00:19:00.483
!MESSAGE session context was:(profile=SDKProfile, phase=org.eclipse.equinox.internal.provisional.p2.engine.phases.Unconfigure, operand=[R]org.eclipse.equinox.common 3.5.0.v20090520-1800 --> [R]org.eclipse.equinox.common 3.5.1.R35x_v20090807-1100, action=org.eclipse.equinox.internal.p2.touchpoint.eclipse.actions.SetStartLevelAction).
!SUBENTRY 1 org.eclipse.equinox.p2.engine 4 0 2010-06-01 00:19:00.483
!MESSAGE Error while loading manipulator.
!STACK 0
java.lang.IllegalStateException: Error while loading manipulator.



Reason:
The eclipse has not loaded the equinox.launcher plugin.

What is Equinox and Why should I bother?

Equinox is the Osgi Framework implementation. So what? Alright, Eclipse uses OSGi as the basis for its plug-in system.

http://www.eclipse.org/equinox/

Solution:

We have to force load this plugin during startup by specifying it in the eclipse.ini.
  • Open the Eclipse.ini
  • Add the following line:
-startup
plugins/org.eclipse.equinox.launcher_1.0.201.R35x_v20090715.jar
  • Restart Eclipse
  • Try updating/installing plugins

Wednesday, May 12, 2010

Online XML Formatting.

Most of the times XML generated are not formatted. It is extremely difficult to read/debug.

This cool online tool solves this headache:

http://xmlindent.com/

Monday, April 19, 2010

Browser Emulator

I was recently requested by my client to help fix a bug happening in I.E 6. I can't remember when on earth I last used I.E 6 and why this customer is so skeptical about this old nasty browser. But the truth is I have to fix it. My Windows now is a neat 64 Bit Windows 7 which doesn’t even knew there existed a browser called I.E 6.

I was looking for Emulators online and came across this stuff from Microsoft - Microsoft Expression SuperPreview. I downloaded, installed and played with it while I fixed the bug.

It's a good tool with some features of firebug. The difference being this displays the page layout as it is in a particular browser version, and can open two frames of two different browser versions and show the comparison I tried it and seems very helpful.

On the dark side sessions cannot be configured so for checking UI issues of Session enabled pages – I had to save as webpage complete and then open that file.

Some cool Features:

• Multi browsers Firefox xx , IE (6, 7, 8)
• Compare in two browsers simultaneously
• Dom related checks available
• Can set screen resolutions
• Configure more browsers like chrome/Safari etc.

Drawbacks (I didn’t explore, could be wrong)

• No JavaScript Checks
• Session pages cannot be tested live


Read more:

http://expression.microsoft.com/en-us/dd565874.aspx

Tuesday, January 05, 2010

JSON - Jquery

JSON & Jquery might have stormed well in the AJAX/WS world. But the right documents are missing. I was banging myu head for a few hours, on how to get a json object from a codebehind:

I was building a JSON object:{name:myvalue}

Tried all ways and it never workd in the Ajax method:

$.post("test.aspx?tbg=yu", $("#form1").serialize(),
function(data) {
alert(data.name); ---->Always returned undefined. In firebug it was not showing at all.


The Right solution is {name:'myvalue'}. This ******ing >>>>'<<<<< style="font-style: italic;">-Happy Hacking

Monday, January 04, 2010

String to Stream in C#

There are multiple ways, best two:

Us the System.IO.StringReader.

//Good when you want to preserve the UTL character
byte[] bytesFromString = System.Text.Encoding.UTF8.GetBytes(xml);
System.IO.Stream stream = new System.IO.MemoryStream(xmlBytes);

Tuesday, December 22, 2009

CodeGenerator From XML Schemas using Visual Studion XSD.exe

XSD.exe is a nice tool for .NET Code-Generation from an existing xml Schema. It's very similar like its java counterpart (JAXB- XJC)


Syntax:

Visual Studio 9.0\VC>xsd /c /out:c:\aneesh\classes c:\Aneesh\dataTypes.xsd

/c stands for generating classes
/out specifies the output directory
/namespace can give a specific namespace for the generated class


A bit complex situation, with multiple schema's

Scenario:

You have an XSD, objectrSchema.xsd and you have another XSD dataTypes.xsd. Some of the DataTypes in the dataTypes.xsd are used in the objectSchema.xsd. In this situation if you run the above command, it will give you a straight error:

Warning: Schema could not be validated. Class generation may fail or may produce incorrect results.
Error: Error generating classes for schema 'c:\ Aneesh\objectSchema.xsd '.

We can overcome this situation with a few tweaks. Thought I searched google but didn’t yield any satisfactory results. These are thing steps I did to make it work.

Step 1:

Import the dataTypes.xsd into the objectrSchema.xsd using the More details of XD IMport can be found here.

Note that the “namespace=http://www.aneesh.com/datatypes “should be the same as the one defined in dataTypes.xsd

Step 2:

Finally hit the command:

Visual Studio 9.0\VC>xsd /c /out:c:\aneesh\classes c:\Aneesh\dataTypes.xsd c:\Aneesh\objectSchema.xsd

Here you go. Your code is generated. Happy Hacking!

More Reading


Thursday, July 23, 2009

HTml Files not Being Served By IIS7

For a few days I was wondering when I moved my customers ASP application from DailyRazor to Godaddy, it simply does not server .html, .txt, .pdf, etc files. The only diference (Though a huge difference) is the change of server fomr IIS6 - IIS7). I called their support just to be answered by an Idiot.

Finally I started my classic debugging.

Started from URLRewriter by YAF.net

I noticed one thing, if the web.config just has the default stuff, everything is fine (Except .aspx because it doesn't have any registered dlls)

So I started removing the tags one by one from the web.config. Finally, understood, the problem lied in this particulr entry:



I still don't remember when I added this part to the web.config.

Also I added the following to the web.config for the html files to be served:

<add validate="false" path="*.html" verb="*" type="System.Web.DefaultHttpHandler"></add>


</remove name="StaticFile"/>