Search This Blog

Monday, August 30, 2010

How to remove HTML tags from a Java String?

Some times we need to remove HTML tags from a java string before publishing it to the page. We can achieve this by using a regular express. Sample code is given below for your reference.

public class RemoveTags{
    public static void main(String a[]){
        String text = "<b>I dont want this to be bold<\b>";
        text = text.replaceAll("\\<.*?\\>", "");
        System.out.println(text);
    }
}

Output:

I dont want this to be bold

How to remove non-ASCII characters from a Java String?

We can remove non-ASCII characters from a Java String by using below regular expression.

String.replaceAll("[^\\p{ASCII}]", ""))

Tuesday, April 6, 2010

How to formate date into user defined patterns?

SimpleDateFormat allows you to start by choosing any user-defined patterns for date-time formatting. All that you need to do is provide the date format string along with the constructor. You can find the format letters in SimpleDateFormat javadocs. For example we have given few formats below:

Date and Time PatternResult
"yyyy.MM.dd G 'at' HH:mm:ss z"

2001.07.04 AD at 12:08:56 PDT
"EEE, MMM d, ''yy"Wed, Jul 4, '01
"h:mm a"12:08 PM

"hh 'o''clock' a, zzzz"12 o'clock PM, Pacific Daylight Time
"K:mm a, z"0:08 PM, PDT


The sample code also given below for your reference.

Sample Code:

import java.text.SimpleDateFormat;
import java.util.Date;

public class DateFormatter {
   
    public static void main(String a[]){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
        System.out.println("yyyy.MM.dd G 'at' HH:mm:ss z  ---> "+sdf.format(new Date()));
        sdf = new SimpleDateFormat("hh 'o''clock' a, zzzz");
        System.out.println("hh 'o''clock' a, zzzz  ---> "+sdf.format(new Date()));
    }
}


Output:

yyyy.MM.dd G 'at' HH:mm:ss z  ---> 2010.04.06 AD at 19:30:50 IST
hh 'o''clock' a, zzzz  ---> 07 o'clock PM, India Standard Time

Monday, April 5, 2010

How to get different country currency formats in java?

Java provides NumberFormat class to support currency formats based on local. All you need to do is get currency instance for NumberFormat class and calling format() method on top of the instance. An example is given below for your reference.


Sample Code:


import java.text.NumberFormat;
import java.util.Locale;


public class Currency {


    public static void main(String a[]){
        NumberFormat nf = NumberFormat.getCurrencyInstance(Locale.US);
        double currency = 52.12;
        System.out.println("In Dollars: "+nf.format(currency));
        nf = NumberFormat.getCurrencyInstance(Locale.UK);
        System.out.println("In British Pound: "+nf.format(currency));
    }
}


Output:


In Dollars: $52.12
In British Pound: £52.12

Saturday, March 27, 2010

How to display special characters in HTML using Java?

To make special characters and accented letters show up on your web pages, use special set of codes called character entities, which you insert into your HTML code and which your browser will display as the corresponding symbols or characters you want. You can achieve this in java using apachie's String Escape Utils function. It provides functions to encode the special characters from java. The method is given below for your reference:


StringEscapeUtils.escapeHtml(text);


Include commons-lang-2.4.jar jar file in your classpath.


Sometimes we need to display special characters in encoded format itself, you can use this class either way, it provides unescape functions for special characters to display its code in your web page itself.


This class provides escape util functions for XML, Javascript, CSV also.

Friday, February 12, 2010

oncontextmenu Event

How to disable right mouse click on a browser window?

It can be resolved by the useage of oncontextmenu event in your html body tag, the usage is shown given below.

<body oncontextmenu="return false;">

AllowEncodedSlashes Directive

Sometimes our web application fails to process request when the URL contains encoded slashes (it can be forward slash or backword slash). To avoid such kind of situations we should modify configurations in Http Apache server. Add below directive to httpd.conf file.

AllowEncodedSlashes On|Off

It determines whether encoded path separators in URLs are allowed to be passed through.
The default value will be Off. Turn it On.
The AllowEncodedSlashes directive allows URLs which contain encoded path separators (%2F for /  and additionally %5C for \ on according systems) to be used. Normally such URLs are refused with a 404 (Not found) error.

Thursday, February 11, 2010

Should white spaces in template text between actions or directives be trimmed?

Sometimes when we generate response text from a JSP page, we will get white spaces/lines in the response text. To avoid that we have to configure our tomcat web.xml file. Follow below steps to avoid the white spaces.


Goto Tomcat Directory/conf folder
Open web.xml file to edit.
Search for a  <servlet> tag, where you can find <servlet-name>jsp</servlet-name> .
Add <init-param> tag as like below:


<init-param>
<param-name>trimSpaces</param-name>
<param-value>true</param-value>
</init-param>


Save the web.xml file and restart the tomcat.


It will remove white spaces from your response text.

Friday, February 5, 2010

How to get auto-generated keys from database using jdbc in java


There are cases that our database insert statements can generate auto-increment ids when we perform executeUpdate() method on our PreparedStatement object. The example given below gives an idea how to get those auto increment ids. After perfoming executeUpdate() method on PreparedStatement, call getGeneratedKeys() method on PreparedStatement. It will return you ResultSet, from which you can get auto increment column values.

Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rset = null;
String query = "insert into emps (name, dept, salary) values (?,?,?)";
try{
//get connection object here
conn = Get Connection Object Here;
pstmt = conn.prepareStatement(query,Statement.RETURN_GENERATED_KEYS);
pstmt.setString(1, "Junk Fellow");
pstmt.setString(2, "Junk Dept");
pstmt.setFloat(3, 10000.00);
pstmt.executeUpdate();
rset = pstmt.getGeneratedKeys();
if(rset != null && rset.next()){
System.out.println("Generated Emp Id: "+rset.getInt(1));
}
} catch (SQLException exx) {
exx.printStackTrace();
} finally {
try{
if(conn != null) conn.close();
if(rset != null) rset.close();
if(pstmt != null) pstmt.close();
} catch(Exception ex){
ex.printStackTrace();
}
}

Thursday, February 4, 2010

Java Servlet API - ServletContextListener Usage Example Code

Whenever the web application got instantiated, it initializes the class which implements ServletContextListener, and calls contextDestroyed() method. Also the application context calls contextDestroyed() method when the application getting shutting down. We can use this type of classes to initialize application sepecific processes.The example for ServletContextListener is given below.

package com.test.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public final class ApplicationListenerContext implements ServletContextListener {

public void contextInitialized(ServletContextEvent scEvent) {
/*
* This method will get called when the application instance got created.
* Initialiaze required process here.
*/
}
public void contextDestroyed(ServletContextEvent arg0) {
/*
* This method will get called when the application instance is shutting down.
* Shutdown initialined processes here.
*/
}
}

Also add below entry to web.xml to register context listener.

<listener>
<listener-class>com.test.listener.ApplicationListenerContext</listener-class>
</listener>

Wednesday, February 3, 2010

Working with Java Memcached API


Memcached is a memory object caching system. It is used to improve the performance of web applications which is dynamic in nature.  Memcached server is an in-memory key value store for small amount of data like strings, objects from results of database calls, API calls, or page rendering.  It is very simple. Server (daemon) process written in C, providing an in-memory hashmap. Clients can be written in any language.

The below example gives very basic example to understand memcached server. 

Set memcached clinet jar file (memcached-client-2.3.jar) in your classpath.

General Usage:

Use below code to connect with memcache and push object to memcache and retrive object from memcache.

MemcachedClient c = null;
try{
c = new MemcachedClient(new InetSocketAddress("memcached_host_IP", PORT));
c.set("MyTest", 60*60*24, new Integer(20));
int fromMC = (Integer)c.get("MyTest");
System.out.println(fromMC);
} catch (Exception ex){
out.println("Exception raised when getting object from memcached; "+ex.getMessage());
} finally{
if(c != null) c.shutdown();
}

In the above code below line creates MemcachedClient with memcached ip, and port. It establishes connection to the memcache.

c = new MemcachedClient(new InetSocketAddress("memcached_host_IP", PORT));

The below line is storing Integer object into the memcache with a key "MyTest". You can get the object using this key. The object will be available in memcache for 24 hours.

c.set("MyTest", 60*60*24, new Integer(20));

The below line gets the stored object from memcache by passing key. You need to do proper typecast.

int fromMC = (Integer)c.get("MyTest");

The finally block below closes the memcache client connection.

finally{
if(c != null) c.shutdown();
}


Advaned Usage:

MemcachedClient may be processing a great deal of asynchronous messages or possibly dealing with an unreachable memcached, which may delay processing. If a memcached is disabled, for example, MemcachedConnection will continue to attempt to reconnect and replay pending operations until it comes back up. To prevent this from causing your application to hang, you can use one of the asynchronous mechanisms to time out a request and cancel the operation to the server.

Get a memcached client connected to several servers, over the binary protocol.

MemcachedClient c = new MemcachedClient(new BinaryConnectionFactory(), AddrUtil.getAddresses("server1:11211 server2:11211"));

Wednesday, January 20, 2010

How to create XML file using JDOM in java

This example creates xml file using JDOM apis .

import java.io.FileOutputStream;
import java.io.OutputStream;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;

public class CreateXML {
public static void main(String a[]){
OutputStream fos = null;
Document doc = new Document();
Element root = new Element("emps");
doc.setRootElement(root);
// create emp element
Element emp = new Element("emp");
emp.setAttribute("id", "1016");
Element name = new Element("name");
name.setText("Nataraj");
emp.addContent(name);
Element dep = new Element("dep");
dep.setText("development");
emp.addContent(dep);
//Add emp element to root element
root.addContent(emp);
Element emp1 = new Element("emp");
emp1.setAttribute("id", "1015");
Element name1 = new Element("name");
name1.setText("Nagesh");
emp1.addContent(name1);
Element dep1 = new Element("dep");
dep1.setText("accounts");
emp1.addContent(dep1);
//Add emp element to root element
root.addContent(emp1);
try{
fos = new FileOutputStream("c://test.xml");
new XMLOutputter().output(doc, fos);
} catch(Exception ex){
ex.printStackTrace();
} finally {
try{
if(fos != null) fos.close();
} catch(Exception ex){
ex.printStackTrace();
}
}
}
}

OUTPUT:

<emps><emp id="1016"><name>Nataraj</name><dep>development</dep></emp><emp id="1015"><name>Nagesh</name><dep>accounts</dep></emp></emps>

Tuesday, January 19, 2010

How to read XML file using JDOM in java

This article gives you an example to read xml file using JDOM api. We will read xml file and print the values on to the console:

Save below xml into emp.xml file.

<emps>
<emp id="1016">
<name>Nataraj</name>
<dep>Accounts</dep>
</emp>
<emp id="1015">
<name>Nagesh</name>
<dep>Marketing</dep>
</emp>
</emps>


Java code to read xml file:

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class ParseXml {

public static void main(String a[]){

Document xmlDoc = null;
SAXBuilder builder = new SAXBuilder();
InputStream is = null;
Element root = null;
try {
is = new FileInputStream(new File("C:\\emp.xml"));
xmlDoc = builder.build(is);
if(xmlDoc != null){
root = xmlDoc.getRootElement();
System.out.println("Root element name: "+root.getName());
List
empList = root.getChildren("emp");
System.out.println("Emp Size: "+empList.size());
for(Element emp:empList){
System.out.println("Id: "+emp.getAttributeValue("id"));
Element name = emp.getChild("name");
System.out.println("Name: "+name.getText());
Element dep = emp.getChild("dep");
System.out.println("Deportment: "+dep.getText());
System.out.println("<--------------------------------------->");
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}


OUTPUT:
-----------
Root element name: emps
Emp Size: 2
Id: 1016
Name: Nataraj
Deportment: Accounts
<--------------------------------------->
Id: 1015
Name: Nagesh
Deportment: Marketing
<--------------------------------------->

Monday, January 18, 2010

How to get ClassLoader or Resource in a java static method?

Follow the below steps to load property file in a java static method.

Properties prop = new Properties();

prop.load(YourClassName.class.getResourceAsStream("File path"));