Saturday, September 24, 2011

Unicode character appear as Question Mark or JSP not Support Language Translation

Nowadays most of the application are supposed to support foreign Language for that we need to create properties file.
In the properties file we translate each and every word and save them using key value pair.
Example file:
languageTranslation_ru.properties
name = имя
password = пароль
submit = представлять
signIn = Войти приложений

Either use Unicode converter or directly place the translated value in your properties file. You set it up correctly and running your application,

Surprisingly you are getting question mark "???" in unicode converted place like below screen shot.
Everything you did correctly, but why its not working. In your jsp page please check whether you included below attribute.
<%@ page contentType="text/html; charset=UTF-8"%>
If not include it and you will get expected output. Check below screen shot for actual result

Saturday, August 6, 2011

How to Run Multiple IE Version in One Machine

As a Developer, We need to test our application in all IE version. In some IE version scroll bar will appear in some others it wont appear. Sadly it behave strange in IE6 version. Its not possible to install all IE version in one machine. If you uninstall your higher IE version, you can get default version i.e IE6 version, but its not possible to install and uninstall all the time.

Don't scratch your head ???

Here is the possible way to get all IE version in one machine.
Most of you may heard about IE Tester, some of them may not come across this tool.
If you guys fall in second category just go to their IE Tester Home page and download the software.
For those who falls under first category just share your views here.
And you can see the screen shot of IE tester home page in this post.






I can able to hear your mind voice.
Hey man who want IETester or out dated version say IE5.5 and IE6. I am running higher version of IE for example IE9, I want to test my application in IE7 or IE8 version.
Do you have any idea??

If you have above mentioned query in your mind, Yes its possible is my answer.
No need to install any other software or tool to run  all IE version except IE6 in one machine.

Open your IE browser, press F12 or follow the below instruction
Go to tools--> click Developer tools














It will open one window, in that window you can choose your preferred version by following this step click browser mode-->in the list select your preferred version.
For example currently I am running IE9 version in my machine, but I want to test my application in IE7 or IE8.I will choose my preferred version as IE7 or IE8 in the list.
So it will change the opened tab to selected version.
Check below screen shot.







Try it and share your comments...

Thursday, April 21, 2011

Get client width to fix 800x 600 resolution problem in IE and Mozilla using Javascript

              For last couple of weeks, one bug killing me. i.e., the page is not rendering properly in 800x600 resolution.
             Well,while assigning the defect I thought it will be so easy to fix and I thought nowadays who cares about that 800x600 resolution problem, but still some freaks are living with that 800x600 resolution.
              Let me share the experience/information to fix the defect using javascript. Though I found solution using css, but it not helped me to fix the defect.
Later I decided to fix the defect using javascript and the code as follows,
function windowWrapper() {
var cliRes = screen.width;
var cliHeight = document.documentElement.clientHeight;
if(cliRes<=800) {
 var newHeight = cliHeight-60;     
 document.getElementById("wrapping").style.height = newHeight+"px";
 document.getElementById("wrapping").style.overflow ="auto";
  } 
}
         Have you noticed, I have used wrapping inside getElementById. place the id wherever you want to reduce size of the screen in 800x600 resolution.
  //used to reduce the body screen size.
//reduce div container size.
Let me know how it was worked for you and waiting for your comments.

Friday, March 11, 2011

Remove dot infront of actionerror and actionmessage in Struts2

You can see the dot symbol infront of actionError and actionMessages while displaying your result in jsp page.

This is because of placing <s:actionerror />  and <s:actionmessages />  directly into your jsp page.
Actionerror and Actionmessage displays result in un-ordered list format.
Your Error or Message in the following format

1) . Action Error
2) . Action Message

Inorder to remove the dot symbol place the <s:actionerror> and <s:actionmessage> inside <s:if> condition


   


   
div class="errors" and div class="messages" are not mandatory.
Both are css classes.
Dot symbol will get removed and you will get the expected result.

For more java programming click this Link.
Do post your comments

Tuesday, February 15, 2011

Send Mail in specific time Interval using Java

The following jar files required to send mail using java program.
1)Activation.jar
2)Mail.jar
Click this Link to download the jar file.
Okay you have downloaded the jar files and placed the same in classpath.

Lets discuss the program step by step.
There are two options mentioned in this program.Single and multiple
While running program it will ask input from the user single or multiple.
If the user gives single as input the mail will send only once.The program get executes after the timedelay specified in the program.Here we specified as 1000milliseconds.

If the user pass multiple as input then the program send the mail multiple times with time interval as 10000milliseconds
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

public class sendMailUsingTimeInterval{
 public static void main(String[] args) throws IOException{
     int delayInMilliSec= 1000; //in milli seconds.
     int delayBetweenExec = 10000;//in milli seconds
     Timer timer = new Timer();
     System.out.println("Please enter \'Single\' or \'Multiple\')?");
     BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
     String ans = in.readLine();
     if (ans.equalsIgnoreCase("Single")){
       timer.schedule(new TimerTask(){     
         public void run(){
          SendMailUsingAuthentication send = new SendMailUsingAuthentication();
          try {
     send.sendingDetails();
    } catch (Exception e) {
     System.out.println("in catch block:::");
     e.printStackTrace();
    }
          System.out.println("Single time selected ***");
         }
       },delayInMilliSec);
     }
     else if(ans.equalsIgnoreCase("Multiple")){
       timer.schedule(new TimerTask(){
         public void run(){
          SendMailUsingAuthentication send = new SendMailUsingAuthentication();
          try {
     send.sendingDetails();
    } catch (Exception e) {
     System.out.println("in catch block:::");
     e.printStackTrace();
    }
           System.out.println("Multiple time selected ****");
         }
       },delayInMilliSec,delayBetweenExec);
     }
     else{
      System.out.println("Pass single or multiple as input ***");
      System.exit(0);
     }
   }
}
In above program you can see the method sendingDetails get called.
The sendingDetails method contain the information about the host,port,from user,to user and content.Make sure your local machine machine has internet facility then give host as localhost else give the ip address of the machine.
Generally the port number is 25.
Then you know the from address,to mail address and the mail content also.
pass all the information.
sendingDetails method now invoke the mailSending() method in the same program.
In mailSending method set all valuse to message.
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendMailUsingAuthentication {
  
    public void mailSending(String smtpHost, int smtp_Port,
                            String from, String to,
                            String subject, String content)
                throws AddressException, MessagingException {

        // Create a mail session
     java.util.Properties props = new java.util.Properties();
     
     String smtpPort = Integer.toString(smtp_Port);
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", smtpPort);
        props.put("mail.smtp.auth", "true");
        
        Session session = Session.getDefaultInstance(props, null);
        Message msg = new MimeMessage(session);
        msg.setFrom(new InternetAddress(from));//set from mailId here.
        msg.setRecipient(Message.RecipientType.TO, new InternetAddress(to));//set to mailId here.
        msg.setRecipient(Message.RecipientType.CC,new InternetAddress(to));//set cc mailId here.
        msg.setSubject(subject);//mail Subject
        msg.setContent(content,"text/plain");//mail content in plain format
        /*
         * To send mail in HTML format disable the 
         * above content and enable the below one
         */

//      msg.setContent("

HTML TYPE MESSAGE

","text/html");//mail Type.It may be plain or html whatever. /* * In below I have set the mail sent date as previous date. * Default it set present date as sent date. * you can change this as your wish. * If you want to enable for previous date.just uncomment the below code */ /*Calendar origDay = Calendar.getInstance(); System.out.println ("Original Date: " + origDay.getTime()); Calendar prevDay = (Calendar) origDay.clone(); prevDay.add (Calendar.DAY_OF_YEAR, -1); DateFormat df = new SimpleDateFormat("MM/dd/yyyy"); msg.setSentDate(prevDay.getTime());*/ String mailHost= "urmail.host.com";//mailHost for your mail provider.For gmail smtp.gmail.com String userName = "from";//userName for an E-mail provider. String password = "password";//password for the same. Transport tr = session.getTransport("smtp"); tr.connect(mailHost,userName,password); System.out.println("whether connection established***"+tr.isConnected()); msg.saveChanges(); tr.sendMessage(msg, msg.getAllRecipients()); tr.close(); System.out.println("Message sent OK."); } public void sendingDetails() throws Exception { mailSending("localhost", 25, "from@gmail.com", "to@gmail.com", "Sriram", "Test mail."+"\n"+"\n"+"Cheers,"+"\n"+"Sriram.V"); } }
Read the comments in the program for more clarification.
Here we send the mail by using Transport.
Transport opens the connection and it connects to mail host.
After the Connection open we are going to send mail using tr.sendMessage()
Once the mail has been successfully send the connection is get closed by calling tr.close()

Possible execptions
AuthenticationFailedException:
Check the user name and password given in the program to connect to the Transport.
javax.mail.AuthenticationFailedException
at javax.mail.Service.connect(Service.java:306)
at javax.mail.Service.connect(Service.java:156)
at sriram.tutorial.javapgm.SendMailUsingAuthentication.mailSending(SendMailUsingAuthentication.java:61)
at sriram.tutorial.javapgm.SendMailUsingAuthentication.sendingDetails(SendMailUsingAuthentication.java:70)
at sriram.tutorial.javapgm.sendMailUsingTimeInterval$1.run(example.java:25)
at java.util.TimerThread.mainLoop(Timer.java:432)
at java.util.TimerThread.run(Timer.java:382)
MessagingException:
Check the mailHost.It attempt to connect to the given host but failed to connet.
javax.mail.MessagingException: Exception reading response;
  nested exception is:
 java.net.SocketException: Connection reset
 at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1462)
 at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1260)
 at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:370)
 at javax.mail.Service.connect(Service.java:275)
 at javax.mail.Service.connect(Service.java:156)
 at sriram.tutorial.javapgm.SendMailUsingAuthentication.mailSending(SendMailUsingAuthentication.java:61)
 at sriram.tutorial.javapgm.SendMailUsingAuthentication.sendingDetails(SendMailUsingAuthentication.java:70)
 at sriram.tutorial.javapgm.sendMailUsingTimeInterval$1.run(example.java:25)
 at java.util.TimerThread.mainLoop(Timer.java:432)
 at java.util.TimerThread.run(Timer.java:382)
Caused by: java.net.SocketException: Connection reset
 at java.net.SocketInputStream.read(SocketInputStream.java:168)
 at com.sun.mail.util.TraceInputStream.read(TraceInputStream.java:97)
 at java.io.BufferedInputStream.fill(BufferedInputStream.java:183)
 at java.io.BufferedInputStream.read(BufferedInputStream.java:201)
 at com.sun.mail.util.LineInputStream.readLine(LineInputStream.java:75)
 at com.sun.mail.smtp.SMTPTransport.readServerResponse(SMTPTransport.java:1440)
 ... 9 more
Want to Send SMS Using java program then click this Link and for more java program click this Link..
Do post your comments.

Wednesday, February 2, 2011

Search String in a file

This program will help you to search the string from the file.Just go through the program you can easily understand.
Here i used command line argument to search string in the file.You can replace the args[i] in the program to meet your requirement.
import java.io.*;
public class stringSearcher {
 public static void main(String args[]) {
  try {
   //Give your file path here.
    File file = new File("C:\\Documents and Settings\\" +
                          "sriram\\Desktop\\workspace.txt");
    BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
    int linecount = 0;
    String line;
    while((line=bufferedReader.readLine())!= null) {
     /*
      * Here Searching word is passed using command line argument.
      * Replace the args[i] in stringFound to the actual string you are looking for.
      * you can pass the value from properties file also.
      * According to your requirement you change it.
      */
      int length = args.length;
      for(int i=0;i -1) {
        System.out.println("At "+stringFound+" Searching word...."+args[i]+"...found in fileName***"+file.getName());
       } else {
        System.out.println("Searching word..."+args[i]+"...not found in fileName***"+file.getName());
       }
      }
     }
    bufferedReader.close();
   }
  catch (IOException excep) {
   System.out.println("Exception occured***"+ excep.toString());
   }
  }
 }
For more java programming click this Link.

Sunday, January 30, 2011

Send SMS using Java

In most of the forums i found this question.How to send SMS Using java.
For answering this question i spent few hours for you guys.


For sending SMS you need to have the following files
1) javax.comm.properties
2) comm.jar
3) win32com.dll
In this Link you can download the files.Let me know if the given link is broken.So that i will upload the files and change the link here.

Check the java_home twice before copy and paste the files.Because most of the problems occurred by pasting the files in wrong folder. 
javax.comm.properties:
Should falls under
   %JAVA_HOME%/lib
   %JAVA_HOME%/jre/lib
win32com.dll:
Should falls under
    %JAVA_HOME%/bin
    %JAVA_HOME%/jre/bin
    %windir%System32
comm.jar:
 Should falls under
     %JAVA_HOME%/lib
     %JAVA_HOME%/jre/lib/ext

Okay i believe you placed all files in respective folder correctly.
Wait guys i heard your mind voice,you are asking where is the java program.
How i will forget,here you go for java programs

import java.io.IOException;
import java.util.Enumeration;
import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.UnsupportedCommOperationException;
public class SriramSMS {
public void sendsms()   
{  
 static Enumeration portList;
 static CommPortIdentifier portId;
 static SerialPort serialPort;
 static OutputStream outputStream;
 String messageString = "";
 String userName="";
 String phoneNumber="";
 Thread thread;

  try
  {
     userName = "periodicUpdates.blogspot.com";
     phoneNumber = "9876543210";
     messageString = " Hi." +userName+"welcome to this blog" ;

            String line1 = "AT+CMGF=1\r\n";
     String line2 = "AT+CMGS=" + phoneNumber + "\r\n"+messageString+ "\r\n";
     String line3 = "\u001A";

    // Here initialize the driver class
                  String driverName = "com.sun.comm.Win32Driver";
    CommDriver commdriver = (CommDriver)Class.forName(driverName).newInstance();
    commdriver.initialize();

    portList = CommPortIdentifier.getPortIdentifiers();
    while (portList.hasMoreElements())
     {       
      portId = (CommPortIdentifier) portList.nextElement();
      if(portId.getPortType() == CommPortIdentifier.PORT_SERIAL)   {
      System.out.println("SMS Sending........" + portId.getName());
      if((portId.getName().equals("COM1"))) {
       try
        {
         serialPort = (SerialPort) portId.open("SimpleWriteApp",10000);
         System.out.println("sms sending port--->"+serialPort);
         outputStream = serialPort.getOutputStream();
         serialPort.setSerialPortParams(230400,SerialPort.DATABITS_8,SerialPort.STOPBITS_1,SerialPort.PARITY_NONE);
         outputStream.write(line1.getBytes());
         outputStream.write(line2.getBytes());
         outputStream.write(line3.getBytes());
         outputStream.flush();
         thread.sleep(5000);
         serialPort.close();
        } catch (PortInUseException portUse) {
         System.out.println("Port In Use " + portUse.toString());
        } catch (UnsupportedCommOperationException unsuppComOperExcep) {
         System.out.println("UnsupportedCommOperationException occured:::"+unsuppComOperExcep.toString());
        }  catch (IOException ioExcep) {
         System.out.println("Error occured while writing to output stream IOException" + ioExcep.toString());
        } catch(Exception excep) {
         System.out.println("Error writing message  with exception while closing " +excep.toString());
        }
     }
    }
   }
  } catch(Exception excep) {
   System.out.println("EXCEPTION raised while writing message@@" +excep.toString());
  }
 }
}
You got the program for sending sms through java program.

Want to Send Mail Using java program then click this Link and for more java program click this Link.
Do post your comments.

Saturday, January 29, 2011

Interview Questions

Like you guys i also surfed and prepared for the interview.Few months before got selected in one MNC Company.I can help you guys by providing set of interview questions.

By clicking this Link you can download the interview questions in rar file format.

why you are waiting just download the files and rock the interview.

All the best guys...

Thursday, January 27, 2011

Struts2 Select Box Error.

I believe you faced this error thats why you are here for the solution.
Instead of wasting our time straightly we will go to the solution.

struts.xml

  /jsp/selectBox.jsp  


SelectList.java
package com.demo.actions;
import com.opensymphony.xwork2.ActionSupport;
import java.util.*;
public class SelectList extends ActionSupport{
private ArrayList dayList;
public String execute() throws Exception {
//instantiate the Arraylist here
dayList = new ArrayList();
dayList.add("monday");
dayList.add("tuesday");
...
dayList.add("sunday");
return SUCCESS;
}
//Make sure you have created the getter and setter method for ArrayList
public ArrayList getDayList() {
  return dayList;
 }
public void setDayList(ArrayList dayList) {
  this.dayList= dayList;
 }
}
selectBox.jsp
Thats it your code will work like a charm.
Do post your comments and for more java programming click this Link.

Wednesday, January 26, 2011

Maintain Image Aspect Ratio Using Java

In Internet i have searched more about maintaining the aspect ratio of the image using java program.After a long struggle found one example and i changed according to met my requirement.Here you go for the complete solution.
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;

class imageAspectRatio {
  public static void main(String args[]) {
  File file = new File("path");//Specify the input image source file location.
    
  try {
   FileInputStream fis = new FileInputStream(file);
   InputStream bis = new BufferedInputStream(fis);
   FileOutputStream fos = null;
   
   Image image = (Image)ImageIO.read(bis);
   
   int thumbWidth = 100;//Specify image width in px
   int thumbHeight = 100;//Specify image height in px
   
   int imageWidth = image.getWidth(null);//get image Widht
   int imageHeight = image.getHeight(null);//get image Height 
   
   double thumbRatio = (double)thumbWidth/(double)thumbHeight;
   double imageRatio = (double)imageWidth/(double)imageHeight;
   
//This calculation is used to convert the image size according to the pixels mentioned above
   if(thumbRatio<imageRatio) {
    thumbHeight = (int) (thumbWidth/imageRatio);
   } else {
    thumbWidth = (int) (thumbHeight*imageRatio);
   }
   
   BufferedImage thumbImage = 
       new BufferedImage(thumbWidth,thumbHeight,BufferedImage.TYPE_INT_RGB);
   
   Graphics2D graphics = thumbImage.createGraphics();
   graphics.setRenderingHint(RenderingHints.KEY_INTERPOLATION,RenderingHints.VALUE_INTERPOLATION_BILINEAR);
   graphics.drawImage(image,0, 0, thumbWidth, thumbHeight,null);
   
   ByteArrayOutputStream out = new ByteArrayOutputStream();
   
   JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
   JPEGEncodeParam param  = encoder.getDefaultJPEGEncodeParam(thumbImage);
   
   int quality = 100;
   quality = Math.max(0,Math.min(quality,100));
   param.setQuality((float)quality/100.0f,false);
   
//output image type.
   String format = "jpg";
   
   encoder.setJPEGEncodeParam(param);
   encoder.encode(thumbImage);
   ImageIO.write(thumbImage,format, new File("path"));//Specify the location for output image .
    } catch(IOException ioExcep) {
   ioExcep.printStackTrace();
  }catch(Exception excep) {
   excep.printStackTrace();
  }
  }
}

Run this program you will get the expected result.
Do post your comments and for more java programming click this Link.