Author Archive

Change Column Separator on CSV in OpenOffice Calc

August 3, 2017

If you want to change the existing column separator or the “delimiter” of a CSV in open office, follow the easy steps :

  • open the csv in openoffice calc
  • go to file-> save as
  • opens the typical save dialog boxUntitled
  • Select the Edit Filter Settings option and click save
  • Opens up a dialog box to change all the default settings.Untitled
  • Change whatever you need and click Ok, and thats all.

Its so easy, but so much hidden with weird settings name. Hope it will be helpful for someone. Enjoy and happy coding!

 

Gradle not finding tools.jar

May 17, 2017

Was struggling with building my project using gradle for some time. Whenever i tried to build it, i get an error message “Could not find tools.jar. Please check that C:\Program Files\Java\jre1.8.0_131 contains a valid JDK installation.”. I made it double sure that my standard JVM is pointing to the JDK installation folder, not the JRE folder. Still getting the error, later I found out that gradle is taking the java.home for the build process. For that you can either start the eclipse through command line parameter for java.home.

Or the easy solution i found is, go to the gradle task you want to run, right click, go to gradle configuration, and in the Java Home tab, point to the JDK installation folder. Voila, it will build the project without crying.

Happy Coding guys!

Viewing complete strings while debugging in Eclipse

February 14, 2017

While debugging Java code, Strings in the views “Variables” and “Expressions” show up only till a certain length, after which Eclipse shows “…”. Even after working with eclipse for 10 years it was a new info for me. There is a way to show the complete string.

In the Variables view you can right click on Details pane (the section where the string content is displayed) and select “Max Length…” popup menu. The same length applies to expression inspector popup and few other places. In the max length give 0 and you will see the whole values in the value box.

untitled

Thats it guys, enjoy coding.

Debug JUnit tests with Eclipse during Maven build

January 4, 2017

If any JUnit test cases are configured to execute along Maven build, Eclipse won’t automatically debug them. That means even if you mark breakpoints it won’t stop the execution there. We can enable such debugging with a simple goals parameter :

-DforkMode=never test

untitled

Untitled.png

If you are using Maven3 Eclipse plugin, go to Debug configurations, Add a new Maven Build configuration, and add the above goal in the Goals input box. By default, Maven runs tests in a separate process. When you set forkMode option to never, maven plugin will not fork the test process. Hence, while connected to the build process you can debug it. The executions will be stalled at the breakpoints as well.

Happy Coding Guys.

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? 😛 That’s it guys, Cheers, Happy Coding 🙂


%d bloggers like this: