Archive for September, 2012

Query for Hash Map using iBatis (MyBatis)

September 27, 2012

An iBatis, oops MyBatis post. Donno why still am tend to call it iBatis only. Anyway just a small post to show how we can query data to fill a hashmap. Directly into code.

<resultMap id="hashMapResult" class="java.util.HashMap">
<result property="key" column="managerName"/>
<result property="value" column="count"/>
</resultMap>

<select id="mCount" resultMap="hashMapResult">
<![CDATA[
select managerName, count(reportees) AS count
from mgr_employee
group by managerName;
]]>
</select>

You can call this from java using the simple command below :

Map<String,Long> mCountMap = getSqlMapClientTemplate().queryForMap("mCount", "", "key", "value");

That’s it guys. I am experimenting this for having objects other than String as Values. I will update the post as soon as that is done. Happy Coding Guys 🙂

Send Image to Flex from Java using HTTPService

September 19, 2012

I was doing some technology upgradation myself nowadays. As part of that I was writing my own twitter client, using Servlets as backend and Flex as Frontend. I used Twitter4J for twitter connectivity from Java, and I deployed the application in Jelastic, the rock solid cloud java server. Twitter connectivity, login process, retrieval, posting and retweeting was done and my app was very well working in beta stage. As my next improvement I tried to show up the user profile images. Twitter4J provides you with the profile image url and my task was to read the image and send the image across the network to the flex client. I could easily give the url of the image to the flex image control, but I felt doing like this.

Since I am using servlets, I use HTTPService to get connect to Java. Hence my main task was to send image through XML! What the heck, that was the first question that came to my mind. So I split my task into different steps :

1. Read the image from the URL in Java
2. Convert this into some sort of textual form
3. Send this across to Flex
4. Convert the textual form Image into something so that Flex Image control can render.

Lets go step-by-step.

1.Read the image from the URL in Java

I am 100% sure that there will be different way to read the image than how I did below. But this also do the trick. It just opens the stream of the url Object of type java.net.URL and reads byte chunks and put into a ByteArrayOutputStream.

URL url = "http://somesite.com/someimage.jpg";
ByteArrayOutputStream bais = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096];
int n;

while ((n = is.read(byteChunk)) > 0 ) {
bais.write(byteChunk, 0, n);
}
}catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
}
finally {
if (is != null) { is.close(); }
}

2. Convert this into some sort of textual form

Our next task is to change this read ByteArrayOutputStream into some textual form so that we can send it through XML. The best and most popular way to do this is to encode it using Base64. There are lots of Base64 encoding and decoding libraries available in the java market, from Oracle, Apache and all. I decided to use the one provided by Oracle themselves. The encoder returns you the binary object in the String format. Hence I wrote an util method for encoding the image from URL and it become like this.


import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

import sun.misc.BASE64Encoder;

/**
* @author Anoop Nair
*
*/
public class UtilClass {

public static String base64Encode(URL url) throws Exception{
ByteArrayOutputStream bais = new ByteArrayOutputStream();
InputStream is = null;
try {
is = url.openStream ();
byte[] byteChunk = new byte[4096];
int n;

while ((n = is.read(byteChunk)) > 0 ) {
bais.write(byteChunk, 0, n);
}
}catch (IOException e) {
System.err.printf ("Failed while reading bytes from %s: %s", url.toExternalForm(), e.getMessage());
e.printStackTrace ();
}
finally {
if (is != null) { is.close(); }
}
BASE64Encoder encoder = new BASE64Encoder();
String encodedImage = encoder.encode(bais.toByteArray());
return encodedImage;
}
}

3. Send this across to Flex

Do I need to say anything about this. Embed this encoded string into an XML and use your HTTPService and its result handler and fault handler to transmit this XML to flex. 🙂 I am becoming lazy here. He He.

4. Render this image in Flex

Thanks to those tons of developers out there who are doing hard-core library development. Bingo, Flex also have a built-in Base64Encoder and Base64Decoder. 🙂  Similar to Java I wrote a Util function in Flex and used the decoder to decode the image and convert it into byte array.


package{

import flash.utils.ByteArray;
import mx.utils.Base64Decoder;

public class UtilClass {
private static var base64Dec:Base64Decoder;

public static function base64Decode(encodedString:String):ByteArray{
var byteArr:ByteArray;

base64Dec = new Base64Decoder();
base64Dec.decode(encodedString);
byteArr = base64Dec.toByteArray();
return byteArr;
}
}
}

This byte array can be loaded and bound into the image control like this, where the ByteArray is stored under the variable userImage :

userImage}"/>

Or this can also be done using actionscript like this :

imgUser.load(userImage)

That’s it guys. It was damn easy, right? But if you wanna be a good developer or programmer, go and read more about Base64 encoding and its algorithm, or try to implement your own encoder. The Apache team is really making us lazy, aren’t they? 😛 That’s it guys, Cheers, Happy Coding 🙂

Set cursor position in the Flex Text Controls

September 19, 2012

You have a text control in flex. At some random event, you need to focus the text control. Simple, right. Just give :

txtInput.setFocus();

All is fine. So what if you need to add some text to the text control? Like the following :

txtInput.text = “@anoop_pk”;
txtInput.setFocus();

This will definitely bring the focus on the control. But hold on. The cursor will be blinking on the beginning of the text and you want it to set to the end of the text. Okay it is quite simple. Flex framework provides with method setSelection for the text controls. Which can be used to select a part of the text in the text controls programatically. The typical usage is like this :

txtInput.setSelection(1,6);

We can use this to achieve our task by giving like this :

txtInput.setSelection(txtInput.text.length, txtInput.text.length);

We are infact selecting nothing, but this will force the cursor to move to the end of the text. Thats it guys, a small tip to keep my writing active. Lots of work. See you. Happy Coding. 🙂