Monday, December 24, 2007

IP address locator in java

If u want to locate and integrate IP Address Locator i.e. for provided IPAddress it will give Coutry,City,etc.. useful infromation regards where it is located.

This is the following script

<script language="JavaScript"src="http://www.geoiptool.com/webjs.php?xl=en&xt=1&xw=200&xh=275"></script&gt;<noscript><a target="_blank" href="http://www.geoiptool.com/">Geo Web Tool</a></noscript>

For more information   http://www.maxmind.com/app/ip-location

Sunday, December 23, 2007

File upload/download and save it into Database

Following struts source code is to store & retrive uploaded file in database to overcome file permissions, file writing/reading etc.

sample code in action class:

import java.io.InputStream;
import java.util.ArrayList;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.DispatchAction;
import org.apache.struts.upload.FormFile;
import org.hibernate.Hibernate;
import com.jiva.commons.StringUtil;
import com.jiva.pojos.PatientAttachments;
import com.jiva.pojos.PatientAttachmentsDAO;
import com.jiva.pojos.PatientInformation;
import com.jiva.pojos.PatientServiceInfo;

public class UploadAttachementsAction extends DispatchAction {

public ActionForward setUpForDisplay(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
{
DynaActionForm df = (DynaActionForm) form;
String patientId = StringUtil.checkNull(request.getParameter("patientId"));
String patientServiceInfoId = StringUtil.checkNull(request.getParameter("patientServiceInfoId"));
df.set("patientId", patientId);
df.set("patientServiceInfoId", patientServiceInfoId);
PatientAttachmentsDAO patientAttachmentsDAO=new PatientAttachmentsDAO();
PatientAttachments patientAttachments=new PatientAttachments();
String queryString = "from " + PatientAttachments.class.getName() + " as model where model.patientInformation.patientId=" + patientId + " and model.patientServiceInfo.patientServiceInfoId =" + patientServiceInfoId;
ArrayList arrayList = (ArrayList)patientAttachmentsDAO.executeQuery(queryString);
request.setAttribute("attachmentList", arrayList);
return (mapping.findForward("success"));
}

public ActionForward uploadAttacment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
{
if ( form != null ) {
PatientAttachments patientAttachments=new PatientAttachments();
DynaActionForm df = (DynaActionForm) form;
FormFile myFile = (FormFile) df.get("myFile");
PatientInformation patientInformation=new PatientInformation();
PatientServiceInfo patientServiceInfo=new PatientServiceInfo();
patientInformation.setPatientId(Integer.valueOf(""+df.get("patientId")));
patientServiceInfo.setPatientServiceInfoId(Integer.valueOf(""+df.get("patientServiceInfoId")));
patientAttachments.setPatientInformation(patientInformation);
patientAttachments.setPatientServiceInfo(patientServiceInfo);
patientAttachments.setAttachmentName(myFile.getFileName() );
patientAttachments.setAttachmentSize(String.valueOf(myFile.getFileSize()) );
patientAttachments.setAttachmentType(myFile.getContentType() );
patientAttachments.setAttachmentSource(Hibernate.createBlob (myFile.getInputStream()) );
PatientAttachmentsDAO patientAttachmentsDAO = new PatientAttachmentsDAO();
patientAttachmentsDAO.create(patientAttachments);
}

return (mapping.findForward("success"));
}
public ActionForward downloadAttacment(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception
{
String attachmentId=request.getParameter("attachmentId");
PatientAttachmentsDAO patientAttachmentsDAO=new PatientAttachmentsDAO();
PatientAttachments patientAttachments= patientAttachmentsDAO.find(Integer.valueOf(attachmentId));
response.setContentLength ( Integer.parseInt(patientAttachments.getAttachmentSize() ) );
response.setContentType ( patientAttachments.getAttachmentType());
response.setHeader ("Content-disposition", "attachment; filename=" + patientAttachments.getAttachmentName());
response.setHeader ("Cache-Control", "max-age=600");
ServletOutputStream outStream = response.getOutputStream();
InputStream in = patientAttachments.getAttachmentSource().getBinaryStream();
byte[] buffer = new byte[32768];
int n = 0;
while ( ( n = in.read(buffer)) != -1) {
outStream.write(buffer, 0, n);
}
in.close();
outStream.flush();
return (null);
}
}

code in struts-config.xml file is:

<form-beans>
<form-bean name="tabUploadAttachementsForm" type="org.apache.struts.action.DynaActionForm" >
<form-property name="myFile" type="org.apache.struts.upload.FormFile" />
<form-property name="patientId" type="java.lang.String"/>
<form-property name="patientServiceInfoId" type="java.lang.String"/>
</form-bean>
</form-beans>

<action-mapping>
<action
attribute="tabUploadAttachementsForm"
input="/tabUploadAttachements.jsp"
name="tabUploadAttachementsForm"
parameter="method"
path="/uploadAttachments"
scope="request"
type="com.jiva.struts.action.UploadAttachementsAction" >
<forward name="success" path=".showUploadForm"></forward>
</action>

</action-mappings>

code in jsp file
<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<jsp:directive.page import="com.jiva.commons.MenuTemplate"/>
<%@ taglib uri="WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="http://displaytag.sf.net" prefix="display" %>
<html:html>
<head>
</head>
<%
MenuTemplate menuTemplate=new MenuTemplate();
out.println(menuTemplate.getMenuBar(request.getParameter("headerMenu"),request.getParameter("subMenu"),request.getParameter("patientId"),request.getParameter("patientServiceInfoId")));
%>
<body>
<html:form action="/uploadAttachments" method="post" enctype="multipart/form-data">
<input type="hidden" name="headerMenu" id="headerMenu" value="<%=request.getParameter("headerMenu") %>"/>
<input type="hidden" name="subMenu" id="subMenu" value="<%=request.getParameter("subMenu") %>"/>
<display:table name="attachmentList" id="attachment" export="true" sort="list" class="display_tag">
<display:column title="File Id" sortable="true" headerClass="sortable">
<a href="./uploadAttachments.do?method=downloadAttacment&attachmentId=<bean:write name="attachment" property="patientAttachmentId"/>" /><bean:write name="attachment" property="patientAttachmentId" /> </a>
</display:column>
<display:column title="File Name" sortable="true" headerClass="sortable">
<a href="./uploadAttachments.do?method=downloadAttacment&attachmentId=<bean:write name="attachment" property="patientAttachmentId"/>" /><bean:write name="attachment" property="attachmentName" /> </a>
</display:column>
<display:column title="File Type" property="attachmentType" />
<display:column title="File Size" property="attachmentSize" />
</display:table>
<table>
<tr><td><html:file property="myFile"></html:file></td></tr>
<tr><td>
<html:hidden property="method" value="uploadAttacment"/>
<html:hidden property="patientId"/>
<html:hidden property="patientServiceInfoId"/>
<html:submit><bean:message key="uploadattachements.submit.name"/></html:submit>
</td></tr>
</table>
</html:form>
</body>
</html:html>

Saturday, December 22, 2007

Important stept to be taken for H1b Interview

 

Chennai Process - Part 1

Hi Guys,

 

This is as of 9th Aug.
Walk up to the entrance 15 - 30 minutes before your appt.

Pre-requisites...
Keep all your docs in a plastic bag. No other bags are allowed. Do not take your cellphones, lip balms, vicks etc. You may have to throw them out on the street. There is no facility to safe keep them.

Dress sharp. Presentation matters.. since they will judge you in the first 20 seconds.

Preferrably organize ur docs in 3 folders/envelopes.. makes life easy... I have seen people search for the documents when the VO asks for it.. and that is a -ve point for them when they decide to issue a Visa or not.

1. Contains passport, hdfc receipt, invitation letter, DS 156, DS 157, 1797, 1-129 and related suppliment docs, DOL application, Letter from the employer to the Consulate General in Chennai (or where ever).
2. All your certificates, appt letters, experience letters, conduct certificates, accolades, etc.. in original... properly organized for speedy presentation
3. copies (xerox) all the contents of 2nd folder + copy of your passport.. properly organized for speedy presentation

Keep all the 3 folders in a plastic bag.

 

Chennai Process - Part 2

Here is the process
1. Show your passport, receipt & interview letter at the gate (for all applicants)
2. Step inside
3. Show your plastic bag containing the docs to the security. He will ask you if you are carrying any sealed envelopes. If yes, he will ask you to open them in front of him (anthrax threat).
4. Metal detector
5. You enter a room with 10 counters. People sitting in chairs all over.
6. Walk up to any counter that is empty and has a person sitting on the other side.
7. Give him the folder 1 mnentioned above.
8. He will arrange all the docs, scan them for mistakes and put them all in one of their plastic folders and give them to you.
9. You go and then sit in an empty chair.
10 There will be VFS employees who periodically call out the appt. time. Note that the people sitting with you in the lobby may be form previous appt slots.
11. when its turn for your appt time, he will call out the time...
12. All of you in that slot are guided to the next building, where you wait outside.
13. Then when the Visa Interview lobby empties out.. you are called in.
14. The VFS guys will guide you thru the fingerprint and then you go and sit in the chair again.
15 People who have appt thru' lunch, will have chance to buy refreshments. The refreshments guy will close shop at 2:00PM.
16. Another vfs employee will call out your appt time again. Now you go and stand in line in front of the counters. You may end up standing for around 30 -60 minutes depending on the complexity of the cases in front of you.

If you are a family with a small kid, you do not have to wait in line anywhere. You skip steps 9-13. Once your fingerprinting is over, you will be inserted into the beginning of a existing queue. If there are a few more families with kids, then a new ewindow is opened.

 

 

Chennai Process - Part 3

Here are some tips and suggestions based on the guyys standing in front of me. Also the chief VO will come out once in 2 hours & spell some advice to the applicants

1. Be confident, but dont be arrogant.
2. Listen carefully, the speakers & microphones may distort their voice,. Also, there are multiple windows and you tend to hear what's happening in the next window instead of yours. For first timers, their accent might be hard to catch. Ask the VO to repeat a question, if you dont understand. Do not give wrong answer.
3. Do not contradict yourself... like for example.. you cannot be a SAP consultant working on an inhouse project.. a consultant means you will be hired out to clients for solving their problems.
4. Answer to the point. Do not volunteer any extra information.
5. If they ask for information, they are trying to understand and assess you. Do not think that asking questions is a -ve & you may be rejected. you will only end up getting tensed.
6. Be properly organized with your documents (foplder 2 mentioned above). Then you will not start sweating when you do not find that small certificate..
7. When you approach the window, a simpe "hello" or "Good Morning" should be enough. they will not have time for any more pleasentries. Its all about statictics. 6 - 10 VOs' interview about 1000 candidates a day. The average time per candidate is 3 minutes. they claim to start making their judgement in the first 20 seconds.
8. Make sure that the picture you have taken resembles you, not the picture on the passport. What I mean to say is that the picture for Visa should be as recent as possible. There will be touts standing outside saying that your picture is wrong and they will take the correct picture for you. Ignore them. VFS will give you 1 hour time to take a correct picture, if yours is wrong.
9. If you have made some mistake (like some typing mistake or something like hat) talk to the VFS employee standing there. he will help you make the required changes. Don't panic.

 

Friday, December 21, 2007

Mail component source code

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

public class HtmlJavaMail {
public static void main(String[] args) {
HtmlJavaMail mjm = new HtmlJavaMail();
//mjm.sendMail();
}

public HtmlJavaMail() {}

public void sendMail(String to, String subject, String msgKey, HashMap hmMsgValues) {
Properties props = new Properties();
props.put("mail.smtp.host", MailSettings.smtpHost);
props.put("mail.debug","true");
Session session = Session.getDefaultInstance(props, new ForcedAuthenticator());
Message message = new MimeMessage(session);
try {
message.setFrom(new InternetAddress(MailSettings.fromAddress,MailSettings.fromName));
message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
message.setSubject(subject);
MimeMultipart multipart = new MimeMultipart();
BodyPart msgBodyPart = new MimeBodyPart();
String body = buildMessage(MailSettings.getMessageBody(msgKey), hmMsgValues);
msgBodyPart.setContent(body,"text/html");
/*
BodyPart embedImage=new MimeBodyPart();
DataSource ds=new URLDataSource(new URL(MailSettings.inlineImage));
embedImage.setDataHandler(new DataHandler(ds));
embedImage.setHeader("Content-ID","");
*/
multipart.addBodyPart(msgBodyPart);
//multipart.addBodyPart(embedImage);
message.setContent(multipart);
message.setSentDate(new Date());
Transport.send(message);
} catch (AddressException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (MessagingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} /* catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}

class ForcedAuthenticator extends Authenticator {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(MailSettings.smtpUsername,
MailSettings.smtpPassword);
}
}

public String buildMessage(String body, HashMap hmMsgValues)
{
String strTempBody = body;
try
{
String strKey = null;
String strValue = null;
Iterator itrMsgValues = hmMsgValues.keySet().iterator();
while(itrMsgValues.hasNext())
{
strKey = itrMsgValues.next().toString();
strValue = hmMsgValues.get(strKey).toString();
strKey = "<<" + strKey + ">>";
while(strTempBody.indexOf(strKey) != -1)
{
strTempBody = strTempBody.substring(0, strTempBody.indexOf(strKey)) + strValue + strTempBody.substring(strTempBody.indexOf(strKey) + strKey.length());
}
}
}
catch(Exception exp)
{
exp.printStackTrace();
}
return strTempBody;
}
}



import java.util.HashMap;

public class MailSettings {

// Set smtpHost to the hostname for your mail server
public static String smtpHost="ipaddress";
// For SMTP authentication, set the next two lines to your username and password for the mail server
public static String smtpUsername="username";
public static String smtpPassword="password";
// Set toAddress to the address you want the email to go to
public static String toAddress="toaddress";
public static String[] ccAddresses=new String[] { "ccaddress1", "ccaddress2" };
public static String fromAddress="fromaddress";
public static String fromName="Mail Example App";
public static String messageSubject="This is a test mail";
public static String messageBody1="This is a test mail sent by a mail example";
public static String inlineImage="file:uk-builder-com.gif";
public static HashMap hashMap = new HashMap();
static {
hashMap.put("FORGOT_PASSWORD",
""<html>"" +
""<body>"" +
"Your User Name is "<"<USERNAME>">"" + "\n" +
"Password is "<"<PASSWORD>">"" + "\n" +
""</body>"" +
""</html>"");
}
public static String getMessageBody(String msgKey)
{
return hashMap.get(msgKey).toString();
}
}

Wednesday, November 7, 2007

Compilation of all java files together including subfolders

javac -classpath %CLASSPATH%;"<Path of required jar files>" *.java

Monday, November 5, 2007

Mysql: Retriving Field Names of a Table

 In order to retrive field name from the table that matches the search criteria, just do run the following query.

 

 

SELECT *, MATCH(Field name 1) AGAINST ('*searchable value*' in boolean mode) as label1,
MATCH(Field name 2) AGAINST ('*searchable value*') as label2, ... FROM table_name
WHERE MATCH(Field name 1, Field name 2, ...) AGAINST ('*searchable value*')

Ex:

SELECT *, MATCH(customers_firstname) AGAINST ('*suresh*') as firstname,
MATCH(customers_lastname) AGAINST ('*suresh*') as lastname,
MATCH(customers_email_address) AGAINST ('*suresh*') as email_address
FROM customers
WHERE MATCH(customers_firstname, customers_lastname,
customers_email_address) AGAINST ('*suresh*').

if you dont want to include in boolean mode then alter the table with index type of "full text". and do the same thing excluding in boolean mode

 

How to open a hyper link outside of Iframe?

How to open a hyper link outside of Iframe?

If we use target as "_top" in hyperlink tag then the destination url will
open in that same window.

If you don't use target, then the link will be opened within IFrame.

If we use target as "_blank" then the link will be opened in new browser
window.

 

Jar files missing.

MymeTypesFileTypeMap cannot be resolved -------------- activation.jar

mailSession error --------------------------------------------------- mail.jar,mailplugin.jar

org.apache.struts.taglib.html.BaseHandlerTag error ----- jboss-j2ee.jar                       

 

Printing word document using java

Following link will help you….

http://www.ibm.com/developerworks/java/library/j-mer0322/

 

Real time Difference between Interface and Abstract Class

In real time how the abstraction and interface uses when we go for those concept in real time.

Both abstract classes and interfaces are used when there is a difference in behaviour among the sub-types extending the abstract class or implementing the interface.

When the sub-types behaviour is totally different then you use an interface, when the sub-types behaviour is partially common and different with respect to the supertype an abstract class is used. In an abstract class the partially common behaviour is given a concrete implementation. Since there is no common behaviour between an interface and a sub-type an interface does not have an implementation for any of its behaviour.

Lets assume you are developing a framework for a 'killer' competition where the people who participate have to demonstrate their killing skills. Members participating in the competetion have their own ways of killing.

It could be as different as 'using a gun to kill', 'throwing the victim up in the air and kicking his balls when he victim comes down,  'slitting his throat or behaeding the victim'

The expected behaviour here is to 'KILL', though all the members do have that behaviour 'KILL" each member manifests the behaviour in a different way. Since the behaviour manifestation varies from member to member this scenario calls for an interface.

Interface KilingCompetition{
  Corpse kill();
}

Each member will implement this interface and give an implementation in his/her own way.

Now, lets consider a karate competition(is it called sparring?). Here each member has to follow certain things as laid out by the organizers or the karate protocol. It may include things like bowing to the opponent before and after the fight starts, taking a stand etc. Now these behaviours are common and has to manifested in the same way by every paticipating member. But the behaviour 'fight' will differ from member to member. So now we have a set of common behaviour and also a behaviour which manifests differently from member to member. this calls for an abstract class where you give implementation to the common behaviour and make the differeing behaviour abstract and hence the class abstract.

public abstract class KarateFight{
      public void bowOpponent(){
         //implementation for bowing which is common
         // for every participant
      }

      public void takeStand(){
         //implementation which is common
         // for every participant
      }

      public abstract boolean fight(Opponent op);
      //this is abstract because it differs from
      // person to person
}