PermGen space Exception in Eclipse

April 25, 2014

Well a quick post. Sometimes Eclipse really go nuts and starts throwing this exception for each and every action :

————————–
Unhandled event loop exception
PermGen space
————————–

You can solve this by editing the eclipse.ini file which is residing in the same directory as the eclipse.exe. Towards the end of the file add this line :

-XX:MaxPermSize=128M

You can give whatever space you like such as 256M or 512M. After this restart your eclipse and forget about the PermGen Space Exception. (I Hope So. :P)

For those who are more interested in permGen, The permanent generation (or permgen) was used for class definitions and associated metadata prior to Java 8. Permanent generation was not part of the heap. The permanent generation was removed from Java 8. Originally there was no permanent generation, and objects and classes were stored together in the same area. But as class unloading occurs much more rarely than objects are collected, moving class structures to a specific area allowed significant performance improvements. In short, PermGen is used by the JVM to hold loaded classes.

For More information on Eclipse permGen space Exception read this : More

Happy Coding Guys…

Selectable Text in Flex DataGridColumn

May 24, 2013

Last day my junior asked me a question “How do I make text selectable in a DataGridColumn? I want the user to copy the text from the datagrid.”. Well I had really didn’t thought about that feature till then. Important thing, by default you cannot copy the text shown in the datagrid if you are using the default ItemRenderer. But this turned out to be very very easy one. Couple of options.

1.  The most simple one. Make the ItemRenderer of the datagrid column as mx.controls.Text.

<mx:DataGridColumn dataField="name" headerText="Name" itemRenderer="mx.controls.Text"/>

2. By default the item renderer of a datagrid column is DataGridItemRenderer which is based on TextField. And the selectable property is set to false. So extend another class from DataGridItemRenderer and set the selectable property to true.

package com.renderers
{
    import mx.controls.dataGridClasses.DataGridItemRenderer;

    public class SelectableDataGridItemRenderer extends DataGridItemRenderer
    {
        public function SelectableDataGridItemRenderer()
        {
            super();
            this.selectable = true;
        }
    }
}
<mx:DataGridColumn dataField="name" headerText="Name" itemRenderer="com.renderers.SelectableDataGridItemRenderer"/>

3. Create a custom component with a selectable label and assign it as the ItemRenderer.

SelectableDataGridItemRenderer.mxml

<mx:Label xmlns:mx="http://www.adobe.com/2006/mxml" selectable="true">
</mx:Label>

 

<mx:DataGridColumn dataField="name" headerText="Name" itemRenderer="SelectableDataGridItemRenderer"/>

The last two options are just said, in case the first simple one doesn’t work. If you are using a custom Item Renderer, then you are on your own. :-)

Happy Coding Guys… :)

Train Wreck Pattern

May 20, 2013

Well, this might not be a good pattern, and will definitely have pitfalls, but the first look was very much interesting for me. :)

public class TrainWreckPattern {
  public static void main(String[] args) {
    new Mailer()
    .to("to@example.com")
    .from("from@exmaple.com")
    .subject("Some subject")
    .body("Some content")
    .send();

  }
}

class Mailer{
  public Mailer to(String address){
    System.out.println("To: "+address);
    return this;
  }
  public Mailer from(String address){
    System.out.println("From: "+address);
    return this;
  }
  public Mailer subject(String sub){
    System.out.println("Subject: "+sub);
    return this;
  }
  public Mailer body(String body){
    System.out.println("Body: "+body);
    return this;
  }
  public void send(){
    System.out.println("Sending ...");
  }
}

This code effectively removes the unnecessary setter methods. Though all the methods are set methods, it in turn returns the current object after setting the attribute. A single line, and all setter methods are called. And in fact in the above example the main operation of sending is also done on the same line of code. Interesting, isn’t it. Well I do not know whether this is an officially recognized pattern, but for me, who want to minimize the coding, this pattern seems to be too much interesting.

That’t it guys. Happy Coding… :)

Apache POI Lost Document Summary Information

April 24, 2013

Being working on Intranet projects, lot of my work runs around exporting records into excel and pdf files. For excel exporting mostly we use Apache POI, the awesome tool to deal with Office files. Recently I came around a problem, where after generating the excel file, while trying to open it , it gave error and the log file states : “Lost document summary information.”.

On inspecting my code, I came across these lines :

byte[] b = report.getBytes();

I was using this byte array to flush to the output. In fact this was causing the problem. On detail research I found out that getBytes() method will not give the complete bytes and some of the bytes are lost. Unfortunately those lost bytes are of the summary information, which was causing Excel to throw error. As a workaround, you can do like this, which solved my problem :

ByteArrayOutputStream bos = new ByteArrayOutputStream();
report.write(bos);
byte[] b = bos.toByteArray();

That’s all for now. Happy Coding. :-)

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? :P 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. :)

Java Optimization Tips

July 27, 2012

When writing Java code it can be easy to make simple mistakes that seem harmless on the surface but, as our applications grow larger, they can show themselves to be slow, resource intensive processes that could use a tune-up. Luckily there are some easy ways to optimize your Java code that you can begin using today. Here, we will introduce you to five of them.

1. Avoid unnecessary casting

Casting, for the new developer, is a way of converting between reference data types. Most casting is done to allow a more generic form of programming where your code will be able to work with all types of objects and classes that are descended from some type of base class.

However, new programmers do not always write these casting statements correctly and are creating a situation where they are improperly casting and creating more overhead for their application in the VM than necessary. An example:

class MyCastingClass {
    public Object myMethod() {
        String myString = "Some data";
        Object myObj = (Object) myString;
        return myObj;
    }
}

Ok, let’s examine the statement Object myObj = (Object) myString; which is violating the unnecessary casting rule. There would be no reason to explicitly cast the string to an Object type since the string class already inherits from Object. Casting also bypasses the safety checks of the Java compiler and can end up causing errors at execution. The proper way to write this code would be:

class MyCastingClass {
    public Object myMethod() {
        return "Some data";
    }
}

Clean, easy to read and maintainable while preserving the rules of the compiler and creating less memory overhead. A very simple fix.

2. Eliminating Common Sub Expressions

A common mistake is the use of the same common sub-expression repeatedly in your code, yet you continue to type it out for each calculation. An Example:

int someNumber = (someValue * number1 / number2) + otherValue;
int someNumber2 = (someValue * number1 / number2) + otherValue2;

You may not realize it but you do this all the time. Performing a calculation that has a portion repeated over and over for each calculation. Because part of the calculation changes each time, you didn’t think to loop it and save yourself some trouble. Instead you are being redundant and slowing down the speed of your calculations. Here is a fix:

final int constantCalculation = (someValue * number1 / number2);
int someNumber = (constantCalculation) + otherValue;
int someNumber2 = (constantCalculation) + otherValue2;

Bingo! By placing the repeated portion of the sub-expression into a constant we can reuse it for multiple calculations without being redundant. A deceptively simple optimization.

3. Use StringBuffer (or StringBuilder) instead of String for non-constant strings.

Since strings are immutable objects and cannot change it creates a lot of overhead when you perform actions with string objects that the compiler must transform in order to interpret. Operations that appear to change string objects are actually creating new ones behind the scenes in order to perform your operation. The overhead on this becomes higher when you use String instead of StringBuffer (or StringBuilder). For Example:

class MyStringClass {
    public void myMethod() {
        String myString = "Some data";
        for (int i = 0; i < 20; i++) {
            myString += getMoreChars();
        }
    }
}  

This is the reason that the StringBuffer class exists, to provide assistance when concatenating strings since a new object would need to be created to transform the string. The new object the compiler will create is of type StringBuffer. A new string object would then be created to copy the finished string at the end of the transformation, thus creating two new objects to perform this simple step.

The difference between StringBuffer and StringBuilder is that the former is thread-safe, which is great in some cases, and an overhead in others. All StringBuffer‘s methods are synchronized. StringBuilder isn’t thread-safe and its methods aren’t synchronized, which is much more performant when you just need to use it as a local variable.

The solution would be to cut out the StringBuffer middle-man and make our own StringBuffer object so the compiler doesn’t have to:

class MyCastingClass {
    public Object myMethod() {
        String myString = "Some data";
        StringBuffer myBuffer = new StringBuffer();
        for (int i = 0; i < 20; i++) {
            myBuffer.append(getMoreChars());
        }
        myString = myBuffer.toString();
    }
}

Voila! By creating our own StringBuffer class the compiler no longer has to create one for us to do the transformation. This means there is now only one new string object being created during this process when we call the toString() method of the buffer to transfer that data to myString.

4. Use Short Circuit Boolean Operators

When making logical checks or tests in your code, the use of short-circuit evaluation will almost always speed up the time it takes to make the evaluation because the compiler does not have to check the second condition. When two expressions are joined by an OR (||) as long as the first one is true the compiler will not check the second condition, it will assume the whole statement to be true. This also works with AND (&&) where the compiler will evaluate the first state and if false, will evaluate the whole statement to false. However, the logical OR (|) does not use the short circuit evaluation.

Using || saves the compiler time by not having to check both conditions because it wouldn’t change the outcome of the statement. Here is an example of what usually happens:

class MyShortCircuitClass {
    public void myMethod() {
        if (someValue.equals("true") | someValue.equals("false")) {
            System.out.println("valid boolean");
        }
    }
}

What ends up happening in the above example is that the compiler has to check both conditions and evaluate a true or false for each even through the OR logic would have made it true if the first condition evaluated to true. Here is a better way to write these kinds of statements:

class MyCastingClass {
    public void myMethod() {
        if ("true".equals(someValue) || "false".equals(someValue)) {
            System.out.println("valid boolean");
        }
    }
}

By using short-circuit evaluation you will speed up the time it takes for the compiler to make boolean logical decisions and thus the overall processing time of your application.

Here’s a table describing four of Java’s boolean operators:

Meaning Short circuit?
&& and yes
& and no
|| or yes
| or no

The && and || operators are short circuit operators. A short circuit operator is one that doesn’t evaluate all of its operands.

5. Use length() instead of equals() to find the length of a string

It seems to be common practice among developers that when testing for an empty string to use the equals() method, like so:

class MyStringClass {
    public boolean myTestMethod() {
        return myString.equals("");
    }
}

The problem here is the sheer overkill taking place by using equals() due to the higher overhead. The issue comes from the implementation of equals() which is designed to test if two objects reference back to the same object class. The alternative, length() (or isEmpty()), just tests to see if the references point to the same underlying object type. This is a much more efficient way if you are just testing for an empty string. You don’t care about object types or if they reference back to the same class, so quit using a sledgehammer to pound the nail. Here is how you should be testing for empty strings:

class MyCastingClass {
    public void myMethod() {
        public boolean myTestMethod() {
            // which really does myString.length() == 0 behind the schenes
            return myString.isEmpty();
        }
    }
}

Using length() provides a much more efficient method for testing for empty strings that does not require object reference overhead from the compiler.

Remember that code optimization doesn’t require fancy tricks and unreadable code. These are often simple changes that you can start making today that will speed up your processing time and make your code better. A lot of optimization is getting into the underlying processing of the compiler and understanding what is taking place in the code that you write. By learning these tips now you can begin to implement them into your solutions every time, thus making you a better developer in the process.

Courtsey : 5 Easy Java Optimization Tips/

The Ten Commandments of Egoless Programming

July 11, 2012

The Ten Commandments of Egoless Programming:

  1. Understand and accept that you will make mistakes. The point is to find them early, before they make it into production. Fortunately, except for the few of us developing rocket guidance software at JPL, mistakes are rarely fatal in our industry. We can, and should, learn, laugh, and move on.

  2. You are not your code. Remember that the entire point of a review is to find problems, and problems will be found. Don’t take it personally when one is uncovered.

  3. No matter how much “karate” you know, someone else will always know more. Such an individual can teach you some new moves if you ask. Seek and accept input from others, especially when you think it’s not needed.

  4. Don’t rewrite code without consultation. There’s a fine line between “fixing code” and “rewriting code.” Know the difference, and pursue stylistic changes within the framework of a code review, not as a lone enforcer.

  5. Treat people who know less than you with respect, deference, and patience. Non-technical people who deal with developers on a regular basis almost universally hold the opinion that we are prima donnas at best and crybabies at worst. Don’t reinforce this stereotype with anger and impatience.

  6. The only constant in the world is change. Be open to it and accept it with a smile. Look at each change to your requirements, platform, or tool as a new challenge, rather than some serious inconvenience to be fought.

  7. The only true authority stems from knowledge, not from position. Knowledge engenders authority, and authority engenders respect – so if you want respect in an egoless environment, cultivate knowledge.

  8. Fight for what you believe, but gracefully accept defeat. Understand that sometimes your ideas will be overruled. Even if you are right, don’t take revenge or say “I told you so.” Never make your dearly departed idea a martyr or rallying cry.

  9. Don’t be “the coder in the corner.” Don’t be the person in the dark office emerging only for soda. The coder in the corner is out of sight, out of touch, and out of control. This person has no voice in an open, collaborative environment. Get involved in conversations, and be a participant in your office community.

  10. Critique code instead of people – be kind to the coder, not to the code. As much as possible, make all of your comments positive and oriented to improving the code. Relate comments to local standards, program specs, increased performance, etc.

Courtsey : http://blog.stephenwyattbush.com/2012/04/07/dad-and-the-ten-commandments-of-egoless-programming

Show a default prompt in Flex Combobox

May 8, 2012

At times, you may need to show a combobox, where none of the items should be selected by default and it should show something like ‘Please Select’. One way is to add this object also to the dataprovider, as the first item. But if you think that is a burden for your dataprovider, then Flex SDK provides you a built in option. To be frank, after working in Flex for more than 4 years, I am finding out this now only. :) You can use the prompt property of the combobox to show a default value. This will go away once you select one option, and you cannot bring it back. (I think so, but there are high chances that this is not true).

eg :

<mx:ComboBox id=”comboBox”  dataProvider=”{dataprovider}”
labelField=”name” prompt=”Please select an entry” />

That’s all guys. Flex Your Life. Cheers. :)


Follow

Get every new post delivered to your Inbox.

Join 95 other followers

%d bloggers like this: