Friday, June 24, 2011

Script to verify if a date is valid or not


<script type="text/javascript">
function isValidDate(s) {
// format D(D)/M(M)/(YY)YY
var dateFormat = /^\d{1,4}[\.|\/|-]\d{1,2}[\.|\/|-]\d{1,4}$/;
if (dateFormat.test(s)) {

s = s.replace(/0*(\d*)/gi,"$1");
var dateArray = s.split(/[\.|\/|-]/);
// correct month value
dateArray[1] = dateArray[1]-1;
// correct year value
if (dateArray[2].length<4) {
// correct year value
dateArray[2] = (parseInt(dateArray[2]) < 50) ? 2000 + parseInt(dateArray[2]) : 1900 + parseInt(dateArray[2]);
}
var testDate = new Date(dateArray[2], dateArray[1], dateArray[0]);
if (testDate.getDate()!=dateArray[0] || testDate.getMonth()!=dateArray[1] || testDate.getFullYear()!=dateArray[2]) {
                    alert("enter correct date");
return false;
} else {
                     alert("correct date");
return true;
                     
}
} else {
return false;
}
}
   

    </script>

Wednesday, May 25, 2011

code to generate to PDF documents using jasper reports






<html><title>Purchase Reports</title>
<body  bgcolor="#C6ECFF">
<strong>Jasper Report</strong>


<%@ page import="net.sf.jasperreports.engine.*" %>
<%@ page import="net.sf.jasperreports.engine.util.*" %>
<%@ page import="net.sf.jasperreports.engine.export.*" %>
<%@ page import="net.sf.jasperreports.j2ee.servlets.*" %>
<%@ page import="net.sf.jasperreports.engine.util.JRProperties" %>
<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.sql.* , net.sf.jasperreports.engine.base.JRBasePrintImage"%>
<%@ page import="net.sf.jasperreports.engine.base.JRBasePrintLine, net.sf.jasperreports.engine.base.JRBasePrintPage,
net.sf.jasperreports.engine.export.JRPrintServiceExporter,
net.sf.jasperreports.engine.export.JRPrintServiceExporterParameter,
net.sf.jasperreports.engine.util.JRLoader,net.sf.jasperreports.engine.util.JRSaver, javax.print.attribute.HashPrintRequestAttributeSet,
javax.print.attribute.HashPrintServiceAttributeSet,
javax.print.attribute.PrintRequestAttributeSet,
javax.print.attribute.PrintServiceAttributeSet,
javax.print.attribute.standard.MediaSizeName,net.sf.jasperreports.engine.util.JRSaver ,java.text.SimpleDateFormat, java.util.Date"%>
<%@ page import="com.lowagie.text.*"%>
<%@ page import="com.lowagie.text.pdf.PdfWriter"%>
<%@ page import="com.lowagie.text.pdf.BaseFont"%>
<%@ page import="com.lowagie.text.pdf.PdfContentByte"%>
<% Class.forName("com.mysql.jdbc.Driver");
     Connection con= DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename", "username", "password");
JasperCompileManager.compileReportToFile(application.getRealPath("/jrxml/jrxmlfile.jrxml"));
File reportFile = new File(application.getRealPath("/jrxml/jrxmlfile.jasper"));

    if (!reportFile.exists())
throw new JRRuntimeException("File bookreturn.jrxml not found. The report design must be compiled first.");
JasperReport jasperReport = (JasperReport)JRLoader.loadObject(reportFile.getPath());
Map parameters = new HashMap();
parameters.put("ReportTitle", "Address Report");
parameters.put("BaseDir", reportFile.getParentFile());

JasperPrint jasperPrint =JasperFillManager.fillReport(jasperReport,parameters, con);
JRPdfExporter exporter = new JRPdfExporter();
StringBuffer sbuffer = new StringBuffer();
File destFile = new File(reportFile.getParent(), jasperPrint.getName() + ".pdf");
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_FILE, destFile);
exporter.setParameter(JRPdfExporterParameter.IS_ENCRYPTED, Boolean.TRUE);
exporter.setParameter(JRPdfExporterParameter.IS_128_BIT_KEY, Boolean.TRUE);
exporter.setParameter(JRPdfExporterParameter.IS_COMPRESSED , Boolean.TRUE);
//exporter.setParameter(JRPdfExporterParameter.USER_PASSWORD, "jasper");
//exporter.setParameter(JRPdfExporterParameter.OWNER_PASSWORD, "reports");
exporter.setParameter(JRPdfExporterParameter.PERMISSIONS,new Integer(PdfWriter.AllowCopy | PdfWriter.AllowPrinting));

exporter.exportReport();


%>
<jsp:forward page="../../jrxml1/jrxmlfile.pdf"/>
</body>
</html>

Thursday, May 19, 2011

Retrieve Image From Database into Jsp

The Code Snipet shows how to retrieve image from an database. 
First retrieve related data to an ArrayList and get that arrayList use iterator to access elements following code shows how to retrieve and save image  to web folder



<%
ArrayList al=(ArrayList)request.getAttribute("AL");
Iterator it=al.iterator();
while(it.hasNext())
{
    LoginBean lbb=(LoginBean)it.next();
    if (lbb.getPicture()!=null)
{
         Someid = lbb.getid();
//System.out.println("********ID :" + admno);
InputStream sImage = lbb.getPicture();
        System.out.println("sImage==@@" + sImage.available());
        File f = new File(request.getRealPath("/")+"image" + Someid + ".jpg");
        System.out.println("-----"+request.getRealPath("/")+"image" + Someid + ".jpg");
        OutputStream out1 = new FileOutputStream(f);
        byte buf[] = new byte[1024];
        int len;
        while ((len = sImage.read(buf)) > 0)
{
            out1.write(buf, 0, len);
        }
        out1.close();
        sImage.close();
        System.out.println("\nFile is created.................");
}
%>






To show that image :


 <td colspan="2" class="columnname"> <img src ="<%=request.getContextPath()+"/image" + Someid + ".jpg"%>"  alt="" width="90" height="90"  align="right" border="3" /></td>

Wednesday, May 18, 2011

Friday, May 13, 2011

Send a mail to Gmail Using JavaMail

The following programs works fine to send mail to gmail server:


import java.security.Security;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class GoogleTest {

   private static final String SMTP_HOST_NAME = "smtp.gmail.com";
   private static final String SMTP_PORT = "465";
   private static final String emailMsgTxt = "Test Message Contents";
   private static final String emailSubjectTxt = "A test from gmail";
   private static final String emailFromAddress = "XXXX@gmail.com";
   private static final String SSL_FACTORY = "javax.net.ssl.SSLSocketFactory";
   private static final String[] sendTo = { "XXXXX@gmail.com"};
 
 
   public static void main(String args[]) throws Exception {

       Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());

       new GoogleTest().sendSSLMessage(sendTo, emailSubjectTxt,
               emailMsgTxt, emailFromAddress);
       System.out.println("Sucessfully Sent mail to All Users");
   }

   public void sendSSLMessage(String recipients[], String subject,
           String message, String from) throws MessagingException {
       boolean debug = true;

       Properties props = new Properties();
       props.put("mail.smtp.host", SMTP_HOST_NAME);
       props.put("mail.smtp.auth", "true");
       props.put("mail.debug", "true");
       props.put("mail.smtp.port", SMTP_PORT);
       props.put("mail.smtp.socketFactory.port", SMTP_PORT);
       props.put("mail.smtp.socketFactory.class", SSL_FACTORY);
       props.put("mail.smtp.socketFactory.fallback", "false");

       Session session = Session.getDefaultInstance(props,
               new javax.mail.Authenticator() {

                   protected PasswordAuthentication getPasswordAuthentication() {
                       return new PasswordAuthentication("UserName", "Password");
                   }
               });

       session.setDebug(debug);

       Message msg = new MimeMessage(session);
       InternetAddress addressFrom = new InternetAddress(from);
       msg.setFrom(addressFrom);

       InternetAddress[] addressTo = new InternetAddress[recipients.length];
       for (int i = 0; i < recipients.length; i++) {
           addressTo[i] = new InternetAddress(recipients[i]);
       }
       msg.setRecipients(Message.RecipientType.TO, addressTo);

       // Setting the Subject and Content Type
       msg.setSubject(subject);
       msg.setContent(message, "text/plain");
       Transport.send(msg);
   }
}


replace XXXX with From Address and YYYY with To Address and UserName with your gmail Username and That gmail's Password ...





Thursday, April 7, 2011

Login Application with case sensitive data

Hiii friends,

I am using Java and MySql softwares to login into my web application which was developed in jsp and servlets . In login application to check if username is admin and password is Admin. when we enter admin as un and admin as pwd it's logging in .To eliminate this we have to use one keyword as "BINARY" keyword in query like

"SELECT UN,PWD FROM  LOGIN WHERE UN=''"+UN+"' AND BINARY PWD='"+PWD+"';

that's it.

Login Application with case sensitive data

Hiii friends,

I am using Java and MySql softwares to login into my web application which was developed in jsp and servlets . In login application to check if username is admin and password is Admin. when we enter admin as un and admin as pwd it's logging in .To eliminate this we have to use one keyword as "BINARY" keyword in query like

"SELECT UN,PWD FROM  LOGIN WHERE UN=''"+UN+"' AND BINARY PWD='"+PWD+"';

that's it.

Hide Query By Example of PanelCollection on page load

Hi All, If there is a table with filterable is true. If you want to display QueryByExample then surround this table with panelCollection....