Recent Post

Categories

Archives

Cow Computing

10 Mar 4

Finding Files with particular extension or Pattern in Java

Often, to find a file with a particular extension or naming pattern within a directory, we might implement as below:

// The directory which search would be conducted
File directoryForSearch = new File("C:\folder");

// This may not be the best way to accomplish the task, please bear me with it
File[] allFile = directoryForSearch.listFiles();
File[] resultFile = new File[allFile.length];
int resultCount = 0;

// loop thru the list of files to find the required files
for(int i=0; i<allFile.length; i++)
{
    if(allFile[i].getName().matches(".*\\.java")
    {
        resultFile[resultCount] = allFile[i];
        resultCount++;
    }
}

Read More / Comment »

10 Jan 16

Some Useful HotKey for Eclipse

If you develop heavily on Java, Eclipse definitely should be your primary programming tool (other than Text Editor).
To be more effective in coding, one must master the tools he/she uses. In terms of Eclipse, hotkey is one of the chapter which should be learnt. After sometimes, the hotkey usage will eventually speed up your coding.

Below are some common ones:

Ctrl + Shift + P // Go to the corresponding ending brace
Ctrl + Q // Go back to last edited location
Alt + Left/Right Arrow // Go to previous or next editor
Ctrl + I // Format code
Ctrl + 1 // Generate try/catch or do/if/while/for
Ctrl + / // Comment/Uncomment
F3 // Find Method
Ctrl + L // Go to line
Ctrl + Space // Toggle code assist
Ctrl + Shift + Space // Toggle arguments hints

10 Jan 11

Using Java Mail API

In order to have the ability of sending email from your java program, you would need Java Mail API. It could be obtained here.

The following code illustrate how to use it. (Comment will guide you thru)

// Obtain the system property and set inside the SMTP server
Properties props = System.getProperties();
props.put("mail.smtp.host", "your isp smtp");

// Obtain the mail session
Session session = Session.getDefaultInstance(props, null);
Message message = new MimeMessage(session);

// Set the address for sender
message.setFrom(new InternetAddress("sender mail address"));

// Set the address for recipient
message.addRecipient(Message.RecipientType.TO, new InternetAddress("recipient mail address"));

// Set the Subject of the mail
message.setSubject("Subject");

// Set the message content of the mail
message.setContent("Message Body", "text/plain");

// Send the mail
Transport.send(message);

10 Jan 5

SLF4J – Simple Logging Facade for Java

The logging tool come with the java.util.logging package is just so horrible to work with, and most people tend to use Log4J, while open source project tend to use common-logging. And here, i would like to introduce a better (IMHO) logging tool — SLF4J. SLF4J is a facade wrapper, while you could choose your own implementation to be run below, and that includes Log4J, Java.util.logging, SimpleLogger and Logback. I personally would recommend the use of Logback as the logging implementation as it’s a better successor of Log4J. So, to use SLF4J, setup the project as follows:

1. Put into your lib folder the following jars:

slf4j-api.jar
logback-core.jar
logback-classic.jar

2. Then create a logback.xml or logback-test.xml in your classpath with the following content:

<?xml version="1.0" encoding="UTF-8" ?>

<configuration>
 <appender name="STDOUT">
   <layout>
     <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{80} - %msg%n</pattern>
   </layout>
 </appender>
 <root level="debug">
   <appender-ref ref="STDOUT" />
 </root>
</configuration>

3. In your class, make use the logger as simple as follows:

// Simply get a logger from factory and start logging
Logger logger = LoggerFactory.getLogger("LogTest");
logger.debug("DEBUG MSG");

There’s one thing i like SLF4J so much is that, it actually supports parameterized logging:

// Parameterized logging reduce the hassle when constructing long log msg
Logger logger = LoggerFactory.getLogger("LogTest");
logger.debug("Error: {}, Reason: {}", error, reason);

And one more tips, sometimes when you want to override the original logging tool used in certain open source framework or codebase (e.g Spring Framework), you could simply add the jcl-over-slf4j.jar to the lib/, this will automatically hook into the common-logging of spring and replace it with SLF4J.

Hope this is useful! Enjoy!

09 Sep 23

Java – Cloning an InputStream

There’s a moment when you have been given an InputStream, with its markSupported returned “False”. This means you could only read the stream one and only once, as you can’t call “reset” on it. So, what to do if you want to read the stream for more than one time and be able to re-read the previously read data. The answer is “CLONE”. My very own approach would be to use Apache Commons to turn the stream into string in which it acts as a base. Whenever i need that InputStream, i turns the string back into an stream without affecting the read position and data lost. OK, here’s the steps.

Suppose you got a request object with InputStream.

// request is the Request Object
// Turns InputStream into string
String base = IOUtils.toString(request.getInputStream());

// Whenever you need the InputStream
// Turn the string back to InputStream this way
InputStream in = new ByteArrayInputStream(base.getBytes());