Posts Tagged ‘java’

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.

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. 🙂

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 🙂

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/

Why MVC? Simply Explained

March 29, 2012

Disclaimer : I collected this from one support forum. Its not my original post.

MVC (Model – View – Controller) is one of those concepts that only starts to make sense when you’re dealing with larger applications and/or when working on the same application with several developers.

Compare it with tasks, if you’ve got 3 tasks that need to be done on a certain date, you won’t feel the need to have some kind of task organization, but if you have to deal with dozens of different tasks, with various due dates you’ll start using todo-lists. Then when you start working with a team of people and you need to prioritize and sequence tasks, you realize simple todo-lists won’t suffice and you’ll end up with applying SCRUM for instance (it obviously deals with more than task management, but it is one of the core parts of the methodology)

The same applies to MVC. It’s benefits are absolutely not restricted to large-scale, team-based development, but they become most obvious in such situations.

Let’s say you need to make a web application that loads some data in a xml file, lets the user do some operations on that data and saves the users edits in a SharedObject.
Fine. It’s a small application, you can develop it pretty fast and there’s no need to start thinking about using MVC or other patterns for structuring your components (not talking about UI components here, just cogs in the machine).
The application is a huge success and your client is extremely satisfied, they ask you to change the application because they’ll be setting up a back end with which the xml file can be manipulated by them, in fact no, they want to use a database instead of the file. And since it’s 2012 they definitely need an iphone app as well.
You’ll start working on the web application and since the deadline’s not just tight, but completely insane chances are you’ll be modifying it to reflect the use case changes, make a copy of the entire project to create the iphone app and again simply making the iOS required changes in that project directly.
Now repeat this five times. The client keeps on asking modifications. expansions etc. These can be UI related changes, but even complete backend architecture swaps, going from REST to SOAP for instance.
If you didn’t structure your project using MVC, you’ll be in a world of pain. No, you’ll be in a world of pain anyway, but had you used MVC from the start you’d notice that some things would’ve been less painful:

  • 95% of the code for the web application and the iphone app will be the same, but instead of saving the user data to a Shared Object or through a web service, you’d be using a local DB for instance. Due to the separation of concerns as promoted with MVC (and even more specifically with RL) you’d notice that the only thing different in the web app and the iphone app would’ve been a single service class. Without MVC chances are pretty high you’ll be making modifications in a bunch of classes.
  • The same applies to the UI for instance. Again, the heart of the application is the same, only the way it’s presented to the user is different. Due to separation of your app into the various tiers you’ll notice that changing the UI for the iphone app, will only have an impact on view classes and you’ll spent a tremendous amount of time less of searching through your code and finding out where to change what.
  • w/o MVC 95% of both apps would still be the same, but the differences would’ve been scattered in various files, here and there some lines, with MVC the differences will be in using different classes, ie the changes are more compact and overseeable.

All in all using MVC makes your code more structured and far more flexible to accomodate change in size, platform etc. etc.

Courtsey : creynders of Robotlegs Support

Inserting / Updating NULL values in iBatis

March 1, 2012

Inserting or Updating nulls in iBatis should be done in a crewked way. One obvious fix is to put the isNotNull tag before the fields which can be null. But this will make the sqlmap file cumbersome or hard to read. For eg:, the below insert query will throw error, if you are trying to insert a null value for, say, infoId.

<insert id=”insertInformation” parameterClass=”Information”>
insert into info (Key, Name, InfoId)
values (#key#, #name#, #infoId#)
</insert>

We can put isNotNull tage like this :

<insert id=”insertInformation” parameterClass=”Information”>
insert into info (Key, Name, InfoId)
values (#key#, #name#
<isNotNull property=”infoId”>
, #infoId#
</isNotNull>
)
</insert>

Now doesn’t that became too much. So here comes the ultimate fix. You just need to put the Oracle datatype of the column separated by a colon in the statment like this :

#infoId:VARCHAR#

The complete sql tag will become like this :

<insert id=”insertInformation” parameterClass=”Information”>
insert into info (Key, Name, InfoId)
values (#key#, #name#, #infoId:VARCHAR#)
</insert>

Similarly the update statement also can be modified like this :

<update id=”updateInformation” parameterClass=”Information”>
update Info set
Key = #key#,
Name = #name#,
infoId = #infoId:VARCHAR#
where
id = #id#
</update>

Debug using Apache Tomcat and Eclipse

May 16, 2011

It is always useful to debug the code in a line by line fashion to track where the code went wrong. Since I am using Apache Tomcat server for development purpose this article deals with enabling debugging on Apache Tomcat with Eclipe IDE.

First we need to set up the Tomcat server to enable debugging. Usually the debugging port used for tomcat is 8000, but you can set to any free port.

1. Open the startup.bat file from Tomcat directory (<Tomcat Installation Directory>/bin/)

2. After the script initializes the command line arguements, most probably towards end of file, add these two lines :

set JPDA_ADDRESS=8000
set JPDA_TRANSPORT=dt_socket

3. Change the line where it calls the EXECUTABLES to :

call “%EXECUTABLE%” jpda start %CMD_LINE_ARGS% (add jdpa start).

Save the file and start the tomcat. Now the first line of the tomcat startup console will show :

Listening for transport dt_socket at address: 8000

At this point your Tomcat server is ready to be run in debug mode. Now do the following steps at Eclipse IDE for debugging in Eclipse.

1. Open one class where you want to put breakpoint and add one breakpoint. (This can be done by clicking on the left margin on the corresponding line.

2. From Run menu, select Debug Configurations

3. From the left side, right click on Remote Java Application and click new

4. Fill out the form appearing. Only thing to take care is the server name should be localhost and port number 8000. This can be changed if you are debugging on a remote server.

5. Click on debug and now the eclipse is running in debug mode.

Now you can run the application and whenever the thread reaches the line, where you have put the breakpoint, it will pause execution. Then you can see the current values of the variables, you can step by step execute the line and so on.

That’s it guys. Happy Coding 🙂

Pausing Execution of Java Program

March 31, 2011

Sometimes, we may need to wait for in between the execution of our java program. Thread.sleep() is the best way to do so. A sample code taken directly from Oracle Site :

public static void main(String args[]) throws InterruptedException {
String importantInfo[] = {
“Mares eat oats”,
“Does eat oats”,
“Little lambs eat ivy”,
“A kid will eat ivy too”
};

for (int i = 0; i < importantInfo.length; i++) {
Thread.sleep(4000);
System.out.println(importantInfo[i]);
}
}

Happy Coding 😉

 


%d bloggers like this: