Showing posts with label Java Strings. Show all posts
Showing posts with label Java Strings. Show all posts

Saturday, November 19, 2011

Java Source Code : Search for Sub-String in HashMap

import java.util.HashMap;
import java.util.Map;

public class HashMapSearch
{

public static void main(String[] args)
{

String keyValue = null;
String searchStr = "1234"; // Sub-String Search 1
String searchStrs = "1"; // Sub-String Search 2

HashMap<String, String> hmSample = new HashMap<String, String>();
hmSample.put("12", "ram");
hmSample.put("22", "raj");
hmSample.put("32", "koti");


for(Map.Entry<String, String> mapEntry : hmSample.entrySet())
  {
                                            // Sub-String (from starting position) Search 1 Model
if(searchStr.startsWith(mapEntry.getKey()))
{
                 
keyValue = mapEntry.getValue();
break; }
 }

System.out.println("searchStr " + searchStr + "\tkeyValue: " + keyValue);

for(Map.Entry<String, String> mapEntry : hmSample.entrySet())
  {
                                            // Sub-String (from starting position) Search 2 Model
if(mapEntry.getKey().startsWith(searchStrs))
{
                 
keyValue = mapEntry.getValue();
break; }
  }

System.out.println("searchStrs " + searchStrs + "\tkeyValue: " + keyValue);
}
}

Thursday, October 27, 2011

Example for Customized Immutable Class


public final class MyString
{

private final char[] value;

private int length;

public MyString()
{

length=0;
value=new char[length];
}

public MyString(char c[])
{

length=c.length;
value=new char[length];
System.arraycopy(c, 0, value, 0, length);
}

public String toString()
{

return new String(value);
}

public MyString concat(MyString s)
{

char temp[]=new char[length+s.length()];
System.arraycopy(value, 0, temp, 0, length);
System.arraycopy(s.value, 0, temp, length, s.length());
MyString str=new MyString(temp);
return str;
}

public int length()
{

return length;
}
}

i18n : JSP and MySQL Internationalization


I) JSP Character Set Handling

Character handling can be split into two categories: displaying the characters and receiving the ones entered by the user.  For JSP pages, setting the encoding for each category is done separately by using different directives and/or functions.

Displaying International Characters

i. To set the character encoding for JSP page display, use the standard “page” directive with “contentType” parameter as follows:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>

Page directive is used to control the structure of a servlet or a JSP by importing classes, customizing superclasses, and setting the content type, etc.

ii. The following HTML tag can be used for the web browser to load the correct character set:

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

Meta tags with an http-equiv attribute are the same as HTTP headers. In general, they are used to control the action of browsers, and can be used to refine the information provided by the actual headers.

iii. Avoid using Java String functions (or constructors) such as the following to convert character encoding of a string, because it is both inefficient and unnecessary. Once you set all the options mentioned in this article correctly, you will not need to use such a conversion.

str = new String(request.getParameter("value").getBytes("ISO-8859-1"), "UTF-8");

iv. On every request, you have to set the encoding of characters manually; it is best to create a filter that can be called for every action by specifying it in web.xml:

CharacterEncodingFilter.java

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.ServletException;
import javax.servlet.Filter;
import javax.servlet.FilterConfig;
import javax.servlet.FilterChain;

import java.io.IOException;

public class CharacterEncodingFilter implements Filter
{

    private FilterConfig fc;

    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException
    {

        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;

        response.setContentType("text/html; charset=UTF-8");
        request.setCharacterEncoding("UTF8");

        chain.doFilter(request, response);        //do it again, since JSPs will set it to the default

        response.setContentType("text/html; charset=UTF-8");
        request.setCharacterEncoding("UTF8");
    }

    public void init(FilterConfig filterConfig)
    {

        this.fc = filterConfig;
    }

    public void destroy()
    {

        this.fc = null;
    }
}


web.xml


<filter>
  <filter-name>CharacterEncodingFilter</filter-name>
  <filter-class>com.its.struts.action.CharacterEncodingFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <servlet-name>action</servlet-name>
</filter-mapping>

<filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <url-pattern>*.jsp</url-pattern>
</filter-mapping>

<filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <url-pattern>*.html</url-pattern>
</filter-mapping>

ACTION class needs to be specified for the STRUTS application.
Other than STRUTS, we can specify all the servlets to handle all requests.

<filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <url-pattern>/servlets/*</url-pattern>
</filter-mapping>


v. Java Mail : Finally comes the easiest part: sending e-mails with the subject and body in UTF-8.  The only things you have to do here is use MimeMessage, and give additional parameters when setting the subject and text of your message:

(…)
MimeMessage msg = new MimeMessage(session);
msg.setFrom(InternetAddress.parse(from, false)[0]);
msg.setSentDate(new Date());
msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to, false));
msg.setSubject(subject, "UTF-8");
msg.setText(body, "UTF-8");
transport.sendMessage(msg, msg.getAllRecipients());




II) For the data entered into and received from MySQL database server, you can set the default character set and collation at five levels: (i) server, (ii) database, (iii) table, (iv) column, and (v) connection.  More information and example for each follows:

i. When you start the database server: We can add the following lines in my.ini file to initialize the settings on database startup.

default-collation=utf8
collation_server=utf8_unicode_ci
character_set_server=utf8
default-character-set=utf8


ii. When you are creating the database (or with alter statement after creation):

CREATE DATABASE db_name
DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

iii. When you are creating the table (or with alter statement after creation):

CREATE TABLE tbl_name (column_list)
DEFAULT CHARACTER SET utf8 COLLATE utf8_unicode_ci;

iv. When you are describing the columns during table creation:

CREATE TABLE tbl_name
(
clm_name VARCHAR(5) CHARACTER SET utf8 COLLATE utf8_unicode_ci
);

v. When you are creating the connection:

conn.createStatement().execute(" SET NAMES 'utf8' ");


i18n

Saturday, April 23, 2011

Usage of overriding toString method


One of the standard methods defined in java.lang.Object is toString.  This method is used to obtain a string representation of an object.  We can (and normally should) override this method for classes that we write.

Let's first consider some sample code:

class MyPoint
{

       private int x, y;

       public MyPoint(int x, int y)
       {

           this.x = x;
           this.y = y;
       }
}

public class TSDemo1
{

          public static void main(String args[])
          {          // use default Object.toString()

                 MyPoint mp = new MyPoint(37, 47);      
                 System.out.println(mp);

                 // same as previous, showing the
                 // function of the default toString()

                 System.out.println(mp.getClass().getName() + "@" + Integer.toHexString(mp.hashCode()));
          }
}

output:
MyPoint@111f71
MyPoint@111f71


The TSDemo1 program defines a class MyPoint to represent X, Y points.  It does not define a toString method for the class.  The program creates an instance of the class and then prints it.  In fact, the library methods such as System.out.println know nothing about the MyPoint class or its objects.  So, the println calls the java.io.PrintStream.print(Object) method, which then calls the String.valueOf method.  The String.valueOf method is very simple:

public static String valueOf(Object obj)
{

      return (obj == null) ? "null" : obj.toString();
}

When println is called with a MyPoint object reference, the String.valueOf method converts the object to a string.  String.valueOf first checks to make sure that the reference is not null.  It then calls the toString method for the object.  Since the MyPoint class has no toString method, the default one in java.lang.Object is used instead.  The default toString method actually return the name of the class, an "@", and the hex version of the object's hashcode are concatenated into a string and returned.  The default hashCode method in Object is typically implemented by converting the memory address of the object into an integer.  So the results might vary from those shown above.

We can write our own toString method as shown below.

class MyPoint
{

      private int x, y;

      public MyPoint(int x, int y)
     {

          this.x = x;
          this.y = y;
      }

      public String toString()
      {

              return "X=" + x + " " + "Y=" + y;
      }

     public int getX()
    {

                return x;
    }

    public int getY()
    {

            return y;
    }
}

public class TSDemo2
{

       public static void main(String args[])
       {

                          MyPoint mp = new MyPoint(37, 47);
                         // call MyPoint.toString()
                         System.out.println(mp);

                        // get X,Y values via accessor methods
                        int x = mp.getX();
                        int y = mp.getY();
                        System.out.println(x);
                        System.out.println(y);
      }
}

The output is:
X=37 Y=47
37
47


This example adds some descriptive text to the output format, and defines a couple of accessor methods to get at the X, Y values.  In general, when we write a toString method, the format of the string that is returned should cover all of the object contents.  Our toString method should also contain descriptive labels for each field.  And there should be a way to get at the object field values without having to pick apart the string.  Note that using "+" within toString to build up the return value is not necessarily the most efficient approach.  We might want to use StringBuffer instead.

The toString() method was implemented for the following classes to know the content of the object.

HashMap names = new HashMap();
names.put(new Integer(5), "RAM");
names.put(new Integer(1), "KRIS");
names.put(new Integer(4), "BHANU");
names.put(new Integer(8), null);
System.out.println(names);


output: {4=BHANU, 8=null, 1=KRIS, 5=RAM}


ArrayList aNames = new ArrayList();
aNames.add("SWATI");
aNames.add("ANAND");
aNames.add(null);
aNames.add("MAJNU");
System.out.println(aNames);

output: [SWATI, ANAND, null, MAJNU]

For more information about using toString methods, see item 9, Always override toString, in "Effective Java Programming Language Guide" by Joshua Bloch.