Handling non-english characters in .java files

You should save the .java file as “Encode in UTF-8 without BOM” using an editor like Notepad++.
Do not use Notepad. Notepad introduces some special characters because of which the jvm will throw compiling error because of the special characters.

This applies to .properties files also, which will have non-english characters.

Posted in Java | Leave a comment

Handling OutOfMemory problems in Java

I am now dealing with “big data” applications.
I built applications which process large volumes of data and store them in different data stores like Database, Solr etc.

One of the ways to handle OutOfMemory problem would be to specify the min. and max memory that the JVM can use in your program.

By default a jvm of a Java application uses only 64 MB. We can specify the min and max memory that the JVM can use by using following command line options:
1. -Xms specifies the minimum memory
2. -Xmx specifies the maximum memory

You have to specify the memory values in terms of Megabytes as shown in the following Example:

$ java -Xms1024m -Xmx2048m HelloWorld

You can check the total memory available for the JVM in your program by using the following statement:
Runtime.getRuntime().totalMemory()
This will return the total memory in terms of bytes.

You can check the free memory available for the JVM in your program by using the following statement:
Runtime.getRuntime().freeMemory()

Posted in Java | Leave a comment

Couchbase as properties repository

Couchbase is a NOSQL persistent data store. You can store Serializable Java objects in couchbase.
I have used Couchbase extensively to save all the configurations properties. I have saved all the properties as JSON objects. These objects can be created and edited directly using the admin console provided by Couchbase.

You can perform asynchronous get/set operations with couchbase.

I have observed that the get/set operations fail at certain times. Hence, I have also implemented retrying mechanism. In the retry mechanism I add the the failed tasks to a List of pending tasks. I perform the get/set operations of these pending tasks by means of a separate Timer task which is scheduled at a regular interval.

Posted in Java | Leave a comment

Logging to Loggly – Cloud based logging

Loggly is a platform which acts as a store house of log messages. The advantage of using Loggly is that we will be able to view the logs simply by using a browser. There is an ability to filter the log messages based on the time, category etc.

There is a multi-threaded java implementation of logging messages to Loggly which I customized and used in my project.
You can download the java code from the url – https://github.com/webmetrics/loggly-java/tree/master/src/main/java/biz/neustar/loggly

Posted in Java | Leave a comment

Send email using simple-java-mail API

package com.venkat;

import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.SimpleLayout;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.codemonkey.simplejavamail.Email;
import org.codemonkey.simplejavamail.Mailer;
import org.codemonkey.simplejavamail.TransportStrategy;

import java.io.StringWriter;
import java.util.Date;
import java.util.Properties;

import javax.mail.Message.RecipientType;

import javax.mail.Session;

public class SendMailExample {
public static void main(String args[]) throws Exception {
// normally you would do this in the log4j.xml
Logger rootLogger = Logger.getRootLogger();
rootLogger.addAppender(new ConsoleAppender(new SimpleLayout()));

Velocity.init();

VelocityContext context = new VelocityContext();
context.put(“name”, “Mark”);
context.put(“invoiceNumber”, “42123”);
context.put(“dueDate”, “June 6, 2009″);
context.put(“currentdate”, new Date().toString());

String template = “Hello $name. Please find attached invoice” +
” $invoiceNumber which is due on $dueDate. The current date is $currentdate”;
StringWriter writer = new StringWriter();
Velocity.evaluate(context, writer, “TemplateName”, template);

// Send email logic
final Email email = new Email();
email.addHeader(“X-Priority”, 2);
//email.setFromAddress(“Venkat Ram T at marketforce.com”, “venkatramt@marketforce.com”);
email.setFromAddress(“Venkat Ram T at gmail.com”, “tadivenkat@gmail.com”);
email.setSubject(“test mail from venkat”);
//email.addRecipient(“Venkat Ram T at yahoo.com”, “venkatramt@marketforce.com”, RecipientType.TO);
email.addRecipient(“Venkat Ram T at marketforce.com”, “venkatramt@marketforce.com”, RecipientType.TO);
//email.addRecipient(“C. Bo”, “chocobo@candyshop.org”, RecipientType.BCC);
email.setText(“How are you doing?”);
email.setTextHTML(“Hope this mail reaches you!“);

// embed images and include downloadable attachments
//email.addEmbeddedImage(“wink1″, imageByteArray, “image/png”);
//email.addEmbeddedImage(“wink2″, imageDatesource);
//email.addAttachment(“invitation”, pdfByteArray, “application/pdf”);
//email.addAttachment(“dresscode”, odfDatasource);

// Change outgoing server (SMTP) to 587 and use TLS as the encrypted connection.
Properties props = System.getProperties();
props.setProperty(“mail.transport.protocol”, “smtp”);
//props.put(“mail.smtp.host”, “gadc-qarelay1.mfi.marketforceinfo.com”);
props.put(“mail.smtp.host”, “relay.mfi.marketforceinfo.com”);
props.put(“mail.smtp.port”, “25”);
props.put(“mail.smtp.auth”, “false”);
Session session = Session.getDefaultInstance(props, null);
new Mailer(session).sendMail(email);
//new Mailer(“smtp.mail.yahoo.com”, 465, “tadivenkat@yahoo.com”, “tvrsp071104″, TransportStrategy.SMTP_SSL).sendMail(email);
//new Mailer(“ga-mail.marketforce.com”, 25, “venkatramt”, “password-2″, TransportStrategy.SMTP_TLS).sendMail(email);
System.out.println(“email sent successfully!”);
}
}

Notes:

  1. List of jars used for this example:

    • activation.jar
    • log4j-1.2.15.jar
    • mailapi-1.4.4.jar
    • simple-java-mail-v2.1.jar
    • smtp-1.4.4.jar
    • velocity-1.7.jar
  2. I used glossary terms in the email template. I used velocity framework to substitute these glossary terms with the dynamic values.
Posted in Java | 1 Comment

Large String manipulations with java.io.StringWriter

We usually have a tendency to use java.lang.StringBuilder to build a String. StringBuilder is fine if number of manipulations are limited. It is also fine when we are dealing with small strings.

StringBuilder is not the right fit when it comes to building very large Strings. java.io.StringWriter comes to our rescue. To build large strings we can use StringWriter decorated with BufferedWriter. Usage of BufferedWriter ensures that we do not end up with “out of memory” issues when dealing with very large strings.

The following illustrates the usage of StringWriter:

StringWriter stringWriter = new StringWriter();
BufferedWriter bufferedWriter = new BufferedWriter(stringWriter);
// perform write operations
bufferedWriter.write(str1);
bufferedWriter.newLine();
bufferedWriter.write(str2);
bufferedWriter.newLine();
bufferedWriter.write(str3);
………
// Ready to get the huge string that we built with StringWriter
bufferedWriter.close();
String hugeString = stringWriter.toString();

The above code is “out of memory” error proof.

Posted in Java | 3 Comments

How to implement Singleton pattern in actionscript

We know that actionscript does not support private or protected constructors. So to implement Singleton class we can make use of an inline class which can only be accessed within the package.

We should define the constructor with the reference to the object of the inline class as a parameter. As the inline class will not be visible outside the package, the constructor can never be called and hence we can enforce the singleton pattern.

In the following code we see that ModelLocator is implemented as a Singleton class.

package com.venkat {
public class ModelLocator {
private static var INSTANCE : ModelLocator;

public function ModelLocator(singletonEnforcer : SingletonEnforcer) {
if (singletonEnforcer == null) {
throw new Error(“Please use ModelLocator.getInstance() method to get the reference to ModelLocator object”);
}
}

public static function getInstance() : ModelLocator {
if (INSTANCE == null) {
INSTANCE = new ModelLocator(new SingletonEnforcer());
}
return INSTANCE;
}
}
}

class SingletonEnforcer {}

Posted in Flex | Leave a comment