Eclipse Unlimited Console

Hello Readers,

Not being able to see entire console of your program can be annoying. Eclipse by default allows 80K characters in console. It will show last 80K characters. While redirecting the logs to a file is a viable option, you can even change the setting to remove console limit.

Navigate to:

Window –> Preferences –> Run/Debug –> Console

Uncheck limit console output. You are all set

Eclipse Unlimited Console

Eclipse Unlimited Console

Advertisements
Posted in Core Java, Eclipse | Tagged , , | Leave a comment

Eclipse Display Workspace name

Hello Readers,

In Eclipse you can have the workspace name displayed on window title at top left. It is helpful when you have multiple workspaces open on your workstation. So that you don’t write right code in wrong workspace 🙂

It can be added by navigating to:

Window –> Preferences –> General –> Workspace

Enter Workspace Title

Enter Workspace Title

After hitting Apply –> OK, you will see the title on top left of your window.

Posted in Core Java, Eclipse | Tagged , , | Leave a comment

Line count of file

We all have been there waiting for a huge file to load in our fav editor. Knowing the number of lines in the file does not hurt. Check out below commands:

Windows:

find /c /v “hffhsdfsdlkfjsdlfj” <file_path>

/c – Displays only the count of lines containing the string “hffhsdfsdlkfjsdlfj”

/v – Displays all lines not containing “hffhsdfsdlkfjsdlfj”

PS: make sure you don’t expect “hffhsdfsdlkfjsdlfj” string in the file

Unix:

wc -l <file_path>

Posted in Unix, Windows | Tagged , , , , , | Leave a comment

When Sachin switches on, I switch off

Posted in Cricket | Tagged , | Leave a comment

Java XPath Evaluation Example

Hello Readers,

It’s been a while since my last post. This one will show an example of reading element/attribute content from XML file using XPath utility that comes with Java API.

Below is the XML I used to demo:

<?xml version="1.0" encoding="UTF-8"?>
<note>
 <from>Google</from>
 <to>Apple</to>
 <subject>Friendly Advice</subject>
 <body language="English">Get a life!</body>
</note>

Let’s not focus so much on the content ;).

The XML could have different elements and attributes. So long as you know the hierarchy of the element, you can read the content within. We use XPath expressions to read the content. It’s pretty powerful, you can read more about it here.

Java source does 3 things:

1. Define the XPath expression of elements to be read

2. Create a DOM from XML file

3. Executes evaluate method in XPath class by passing DOM and XPath expression

package com.badalchowdhary.xml;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.w3c.dom.Document;
import org.xml.sax.SAXException;

public class XPathEval {

 private static final String FROM = "/note/from"; // read element
 private static final String TO = "/note/to";
 private static final String SUBJECT = "/note/subject";
 private static final String BODY = "/note/body";
 private static final String LANGUAGE = "/note/body/@language"; // read an attribute

public static void main(String[] args) throws ParserConfigurationException,
 SAXException, IOException, XPathExpressionException {

// create a dom from xml file
 DocumentBuilderFactory docFactory = DocumentBuilderFactory
 .newInstance();
 DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
 Document document = docBuilder.parse(new File(
 "./src/com/badalchowdhary/xml/sample.xml"));

// create xpath instance
 XPathFactory xPathFactory = XPathFactory.newInstance();
 XPath xPath = xPathFactory.newXPath();

 String from = xPath.evaluate(FROM, document);
 String to = xPath.evaluate(TO, document);
 String subject = xPath.evaluate(SUBJECT, document);
 String body = xPath.evaluate(BODY, document);
 String language = xPath.evaluate(LANGUAGE, document);

 System.out.println("from: " + from + "\nto: " + to + "\nsubject: "
 + subject + "\nbody: " + body + "\nlanguage: " + language);

}

}

One common use of XPath expressions is when asserting XML data using JUnit.

Looking forward for your feedback.

Your’s Truly

Posted in Core Java, XML | Tagged , , , , , | Leave a comment

Java Executor Framework Example

Hello Readers,

This post will show an example of writing multi-threaded program using Executor framework introduced in Java 1.5.

Before making  your program multi-threaded, you should define task boundaries. If you are doing n independent tasks sequentially, then using multiple threads can go a long way in speeding up processing by utilizing CPU power.

Executor framework takes care of thread life cycle management and you can focus on the tasks to be done. It is based on Producer-Consumer pattern. Activities that submit tasks are producers and activities that perform tasks are consumers. Producer and Consumer are decoupled from each other by using the BlockingQueue interface. A BlockingQueue holds all tasks (work items). Producer keeps adding tasks to BlockingQueue and Consumers keep consuming them from BlockingQueue. So you don’t have to manage conditions when either Producer or Consumer is working at a faster rate. There are many implementations of BlockingQueue available to use based on your requirements.

Let’s see some action. Consider you want to read data from 2 files and these are independent operations. So instead of reading them sequentially, you could have 2 threads read them in parallel. Let even.txt contain even numbers between 0 and 99 and odd.txt contain odd numbers.

First, we write a ThreadWorker that will do the task of reading a file.

package com.badalchowdhary.threads;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * ThreadWorker represents the tasks to be done. It consumes work items from
 * Blocking Queue and invokes the run method on each task submitted by producer.
 *
 * @author badal
 *
 */
public class ThreadWorker implements Runnable {

public ThreadWorker(File file) {
 super();
 this.file = file;
 }

public void run() {
 try {
 BufferedReader br = new BufferedReader(new FileReader(getFile()));
 String line = null;
 while ((line = br.readLine()) != null) {
 System.out.println(getFile().getName() + " - " + line);
 }
 } catch (FileNotFoundException e) {
 e.printStackTrace();
 } catch (IOException e) {
 e.printStackTrace();
 }
 }

File file;

public File getFile() {
 return file;
 }

public void setFile(File file) {
 this.file = file;
 }

}

Next and last, we will write a program to:
1. Instantiate a BlockingQueue to hold work items.

2. Instantiate an Executor to specify number of threads, timeout and BlockingQueue to be used.

3. Create 2 tasks.

4. Submit tasks to Executor created in Step 2.

5. Shutdown the executor. It basically says, run the submitted the tasks and no more tasks will be submitted.

6. Wait for executor to finish all tasks before continuing ahead.

package com.badalchowdhary.threads;

import java.io.File;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ThreadExample {

public static void main(String[] args) {
 // Create a blocking queue to hold work items (runnables). Decouples
 // producers and consumers.
 BlockingQueue workQueue = new LinkedBlockingQueue();

// Create a thread pool executor with core size and maximum size as 2,
 // specify a time out and pass the blocking queue
 ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 2, Long.MAX_VALUE, TimeUnit.SECONDS, workQueue);

ThreadWorker worker1 = new ThreadWorker(new File("even.txt"));
 ThreadWorker worker2 = new ThreadWorker(new File("odd.txt"));

// Submit runnable to thread pool executor
 executor.submit(worker1);
 executor.submit(worker2);

// Gracefully shutdown thread pool executor. All submitted tasks will
 // run to completion, no new tasks will be accepted.
 executor.shutdown();

// Wait for all submitted tasks to complete. Handle InterruptedException
 // if thread pool executor is interrupted.
 try {
 executor.awaitTermination(Long.MAX_VALUE, TimeUnit.SECONDS);
 } catch (InterruptedException e) {
 System.out.println("ThreadPoolExecutor was interrupted. Do appropriate handling.");
 e.printStackTrace();
 }

}

}

The output on console will toggle as both even.txt and odd.txt are being processed by 2 processors simultaneously. Below is a snapshot:


 even.txt - 0
 even.txt - 2
 odd.txt - 1
 odd.txt - 3
 odd.txt - 5
 odd.txt - 7
 odd.txt - 9
 odd.txt - 11

Hope this post was useful. Always looking for feedback from readers.

Your’s Truly

Posted in Core Java | Tagged , , , , , | 8 Comments