Friday, February 20, 2015

Struts: Tricky s:if tag syntax

tag is very useful for me especially when I want to manipulate display of data in JSP. I use it often. But then, one day I encountered an odd bug that i can't seem to find solution in a few days. Syntax of tag is
<s:if test="%{memberCd == 'OVERSEAS WORKER'}"> 
Code:

 <s:if test="%{memberCd == 'OVERSEAS WORKER'}">     
  <tr>  
       <td colspan="1" id="labels"><label>Country:</label></td>  
       <td colspan="3" class="labelVal"><s:label cssClass="labelVal" id="ofwCountry" value="%{ofwCountry}"/></td>           
  </tr>       
  <tr>  
       <td colspan="1" id="labels"><label>Monthly Earnings:</label></td>  
       <td colspan="3" class="labelVal"><label class="label">(Php)</label>&nbsp;<s:label cssClass="labelVal" id="salary" value="%{salary}"/> </td>  
  </tr>     
  <s:if test="%{memberSubCd=='A'}">  
  <tr>  
       <td colspan="1" id="labels"><label>Flexi Fund Member:</label></td>  
       <td colspan="3" class="labelVal"><label>YES</label></td>  
  </tr>   
  </s:if>  
 </s:if>  

But inner <s:if> (highlighted)is not showing even though the statement is true. 

Solution:
1. Change the order of single quote and double quote. Take note that in the original syntax, the double quote is used to quote the outer part, while the single quote is used for the inner part. To solve the problem, use single quote for the outer and the double quote for the inner. 
From this  
 <s:if test="%{memberSubCd=='A'}">   
to this:
 <s:if test='%{memberSubCd=="A"}'>   

2. Use equalsIgnoreCase comparison statement of Java
From this  
 <s:if test="%{memberSubCd=='A'}">   
to this:
 <s:if test='%{memberSubCd.equalsIngnoreCase("A")}'>   

Hope this helps. If there is another way, then feel free to comment. Thanks!

Load Properties file that resides inside WEB-INF

Intention: Load the rcs.properties values in your application that is located insideWEB-INF folder.

I used the following code but it gave me error.
 Properties properties = new Properties();  
 properties.load(getClass().getClassLoader().getResourceAsStream("rcs.properties"));  

Error:
 java.lang.NullPointerException  
      at java.util.Properties$LineReader.readLine(Properties.java:418)  
      at java.util.Properties.load0(Properties.java:337)  
      at java.util.Properties.load(Properties.java:325)  
      at com.project.rcs.controller.CommonTransaction.home(CommonTransaction.java:244)  
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)  
      at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)  
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)  
      at java.lang.reflect.Method.invoke(Method.java:597)  

Solution
 Properties properties = new Properties();        
 properties.load(servletContext.getResourceAsStream("/WEB-INF/rcs.properties"));  
 /*load the property that is inside your file*/  
 properties.getProperty("urls")  

Also if still doesn't work, you need to add a configuration in your weblogic. Include the following script in your weblogic.xml
  <container-descriptor>  
   <show-archived-real-path-enabled>true</show-archived-real-path-enabled>  
  </container-descriptor>  

Sunday, February 15, 2015

Change Text of Button or Link in Jquery

In your script file or section, put the following code:

 //to change text of button  
 $('#btnId').attr('value', 'New button text);
  
 //to change text of link  
 $('a#btnId').text('New button text');  

Remove HTML Fieldset border in CSS

In you CSS code, put the following:

 fieldset {  
   border: 0;  
 }  

Thursday, February 12, 2015

Java Struts2 Spring: Create PDF in ByteStream and Attach in Email

   private void ssNumIssuedEmail(String applNm, String memNum, String dobth, String email, String purpose) throws Exception {  
     try {  
         String from = "";  
         String to = email;  
         String userid = "userid";  
         String password = "pass";  
         tranNo = (String)request.getSession().getAttribute("tranNo");  
         Date systemDate = registrationFacade.getRcsFacade().getLibrariesDao().getSystemDate();          
         SimpleDateFormat sdf = new SimpleDateFormat("dd MMMM yyyy hh:mm:ss a");  
         String formatedDate = sdf.format(systemDate);  
         Properties properties = new Properties();  
         properties.load(getClass().getClassLoader().getResourceAsStream("email.properties"));  
         Session mailSession = null;  
         try{  
         final String emailUserNm = properties.getProperty("mail.user");  
         final String emailPassword = properties.getProperty("mail.password");  
         mailSession = Session.getInstance(properties,  
           new javax.mail.Authenticator() {  
             protected PasswordAuthentication getPasswordAuthentication() {  
             return new PasswordAuthentication(emailUserNm, emailPassword);  
           }  
         });  
         }catch(Exception e){  
           e.printStackTrace();  
         }  
         from = properties.getProperty("mail.user");            
         MimeMessage message = new MimeMessage(mailSession);  
         message.setFrom(new InternetAddress(from, "Application Confirmation"));  
         message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(to));  
         message.setSubject("SSS Number Application Confirmation");  
         message.setSentDate(systemDate);  
         BodyPart messageBodyPart = new MimeBodyPart();  
         messageBodyPart.setContent("<div style=\"font-family:Tahoma, Arial, Helvetica, sans-serif;font-size:12px\">Good day <b>" + applNm + "</b>!<br/>" +  
                       "<p>Please be informed that you have successfully applied for GOCC Membership number online. Below is your SS number with your application details:</p><br/>" +  
                       "<p>SS Number: <b>" + memNum + "</b></p>" +  
                       "<p>Date and Time of Application: <b>" + formatedDate + "</b></p>" +  
                       "<p>Transaction No: <b>" + tranNo +"</b></p>" +                                             
                       "<p>Purpose of Application: <b>" + purpose + "</b></p><br/>" +  
             "<p>Kindly go to the nearest Branch for submission of the required supporting documents and issuance of the Personal Record Form. </p>" +  
             "<p>We would like to inform you also of user id and password to our Website Account, as follows:</p>" +  
             "<p>user id: <b>" + userid + "</b></p>" +  
             "<p>password: <b>" + password + "</b></p><br/><br/>" +  
             "<p>Thank you for using the GOCC Website!</p>" +  
             "<p><i>This is a system generated email. Please do not reply.</i></p>",  
             "text/html");  
         Multipart multipart = new MimeMultipart();  
         ByteArrayInputStream bais = createSlip();  
         String fileNameOfSource = "Membership Confirmation Slip";  
         multipart.addBodyPart(messageBodyPart);  
         messageBodyPart = new MimeBodyPart();  
         DataSource attachment = new ByteArrayDataSource(bais, "application/pdf");  
         messageBodyPart.setDataHandler(new DataHandler(attachment));  
         messageBodyPart.setFileName(fileNameOfSource);  
         multipart.addBodyPart(messageBodyPart);  
         message.setContent(multipart);  
         Transport.send(message);  
       }  
     } catch (Exception e) {  
       e.printStackTrace();  
     }  
   }  

   public ByteArrayInputStream createSlip(){  
     try{  
       ssNum = "3427898025";  
       rcsUtils = new RCSUtils();        
       memberStaticBean = registrationFacade.getRcsFacade().getRcStaticDao().getInfoSummary(ssNum);  
       ssNum = rcsUtils.formatSsNumber(ssNum);  
       applNm = memberStaticBean.getMemberName();  
       dobth = memberStaticBean.getDobth();  
       ByteArrayOutputStream baos = new ByteArrayOutputStream();  
       Document document = new Document(PageSize.A6);  
       document.addAuthor("GOCC Author");  
       document.addCreationDate();  
       document.addCreator("GOCC Author");  
       document.addTitle("SSS Number Slip");  
       PdfWriter writer = PdfWriter.getInstance(document, baos);  
       document.open();  
       /*set rectangle border*/  
       PdfContentByte under = writer.getDirectContent();  
       under.rectangle(5, 180, 285, 210);  
       Image imgLogo = Image.getInstance(new URL("http://" + request.getLocalAddr() +  
                      ":" + request.getLocalPort() +  
                      request.getContextPath() +  
                      "/images/sss_logo.gif"));  
       imgLogo.scalePercent(25.0f);  
       imgLogo.setAbsolutePosition(9f, 340f);  
       Font fontNormal = new Font(Font.FontFamily.TIMES_ROMAN, 11, Font.NORMAL);  
       Font fontBold = new Font(Font.FontFamily.TIMES_ROMAN, 11, Font.BOLD);  
       Paragraph par10 = new Paragraph();  
       par10.add(imgLogo);  
       par10.setAlignment(Element.ALIGN_LEFT);  
       Paragraph par11 =  
         new Paragraph("Republic of the Philippines", fontNormal);  
       par11.setAlignment(Element.ALIGN_CENTER);  
       Paragraph par12 =  
         new Paragraph("GOCC", fontBold);  
       par12.setAlignment(Element.ALIGN_CENTER);  
       Paragraph par13 =  
         new Paragraph("GOCC NUMBER SLIP" + "\n", fontNormal);  
       par13.setAlignment(Element.ALIGN_CENTER);  
       Paragraph par0 =  
         new Paragraph("\n Membership Number: " + ssNum, fontNormal);  
       par0.setAlignment(Element.ALIGN_CENTER);  
       Paragraph par1 = new Paragraph(applNm, fontNormal);  
       par1.setAlignment(Element.ALIGN_CENTER);  
       Paragraph par2 =  
         new Paragraph("Birthdate: " + dobth, fontNormal);  
       par2.setAlignment(Element.ALIGN_CENTER);  
       Paragraph par3 = new Paragraph(" ", fontNormal);  
       par3.setAlignment(Element.ALIGN_CENTER);  
       document.add(par10);  
       document.add(par11);  
       document.add(par12);  
       document.add(par13);  
       document.add(par0);  
       document.add(par1);  
       document.add(par2);  
       document.add(par3);  
       Image barcode = Image.getInstance(new URL(request.getRequestURL().substring(0, request.getRequestURL().indexOf(request.getContextPath()) +  
                                       request.getContextPath().length()) +  
                      "/barcode.html?barcode=" + ssNum +" " + applNm));  
       PdfPTable table = new PdfPTable(1);  
       table.setHorizontalAlignment(Element.ALIGN_CENTER);  
       table.addCell(barcode);  
       document.add(table);  
       document.close();  
       fileName = "Membership_Slip.pdf";  
       pdfReport = new ByteArrayInputStream(baos.toByteArray());  
       baos.close();  
       return pdfReport;  
     }catch(Exception e){  
       e.printStackTrace();  
       return null;  
     }      
   }  

Java Struts Spring: Create PDF and View on Page

   public String viewE1PDF() {  
     try {  
       portalRole = (String)request.getSession().getAttribute("Portal_Role");  
 //      portalRole = "RCS_WBREG";  
       if (portalRole != null) {  
         ByteArrayInputStream bais;  
         bais = createApprovalSlip();  
         ByteArrayOutputStream baos = new ByteArrayOutputStream();  
         PdfReader pdfReader = new PdfReader(bais);  
         PdfStamper stamper = new PdfStamper(pdfReader, baos);  
         stamper.close();  
         pdfReader.close();  
         pdfReport = new ByteArrayInputStream(baos.toByteArray());  
         pdflength = baos.toByteArray().length;  
         baos.close();  
         return SUCCESS;  
       } else {  
         return "notLogin";  
       }  
     } catch (Exception e) {  
       e.printStackTrace();  
       return ERROR;  
     }  
   }  

   public ByteArrayInputStream createApprovalSlip(){  
     try{  
       ByteArrayOutputStream baos = new ByteArrayOutputStream();  
       Document document = new Document(PageSize.A4);  
       document.addAuthor("Social Security System");  
       document.addCreationDate();  
       document.addCreator("Social Security System");  
       document.addTitle("Approval Slip");  
       PdfWriter writer = PdfWriter.getInstance(document, baos);  
       document.open();  
       ssNum = (String)request.getSession().getAttribute("ssNum");  
       memberStaticBean = registrationFacade.getRcsFacade().getRcStaticDao().searchBySsNum(ssNum);  
       memberName = memberStaticBean.getMemberName();  
       dobth = memberStaticBean.getDobth();  
       purpose = memberStaticBean.getMemberCd();  
       rcsUtils = new RCSUtils();  
       Font fontNormal = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.NORMAL);  
       Font fontBold = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.BOLD);  
       Font fontItalic = new Font(Font.FontFamily.TIMES_ROMAN, 10, Font.ITALIC);  
       Format formatter;  
       Date date = new Date();  
       DateFormat df = new SimpleDateFormat("MM/dd/yyyy");  
       String dateToday = df.format(date);  
       formatter = new SimpleDateFormat("hh:mm:ss a");  
       String timeToday = formatter.format(date);  
       Image img = Image.getInstance(new URL("http://" + request.getLocalAddr() +  
                ":" + request.getLocalPort() +  
                request.getContextPath() +  
                "/images/sss_logo.gif"));  
       img.scalePercent(35.0f);  
       img.setAbsolutePosition(35f, 750f);        
       Paragraph par10 = new Paragraph();  
       par10.add(img);  
       par10.setAlignment(Element.ALIGN_LEFT);  
       branchCd = (String)request.getSession().getAttribute("branchCd");  
       String branchDesc = registrationFacade.getRcsFacade().getLibrariesDao().getBrachDescByCode(branchCd);  
       Paragraph par11 = new Paragraph("Republic of the Philippines", fontNormal);  
       par11.setAlignment(Element.ALIGN_CENTER);  
       Paragraph par12 = new Paragraph("GOVERNMENT CONTROLLED CORPORATION", fontBold);  
       par12.setAlignment(Element.ALIGN_CENTER);  
       Paragraph par13 = new Paragraph(branchDesc + " BRANCH", fontNormal);  
       par13.setAlignment(Element.ALIGN_CENTER);  
       Paragraph par14 = new Paragraph("\nDate: " + dateToday, fontNormal);  
       par14.setAlignment(Element.ALIGN_RIGHT);  
       memberStaticBean = registrationFacade.getRcsFacade().getRcStaticDao().getInfoSummary(ssNum);  
       memberName = memberStaticBean.getMemberName();  
       address = memberStaticBean.getAddress();  
       dobth = memberStaticBean.getDobth();  
       purpose = memberStaticBean.getMemberCd();  
       surNm = memberStaticBean.getSurNm();  
       memberCd = memberStaticBean.getMemberCd();  
       salary = memberStaticBean.getSalary();  
       ssNum = rcsUtils.formatSsNumber(ssNum);  
       Paragraph par = new Paragraph("\nMr./Mrs. " + memberName + "\n" + address +  "\nSS Number: " + ssNum + "\n", fontNormal);  
       par.setAlignment(Element.ALIGN_LEFT);  
       Paragraph par1 = new Paragraph("\nDear Mr./Mrs. " + surNm+":\n", fontNormal);  
       par1.setAlignment(Element.ALIGN_LEFT);  
       Paragraph par2 = new Paragraph("\n    We are pleased to inform you that your application has been approved and your assigned Membership number is ", fontNormal);  
       Chunk ch1 = new Chunk(ssNum, fontBold);  
       Chunk ch2 = new Chunk(". This is your lifetime Membership number, which you should use in all your transactions with the GOCC.\n\n", fontNormal);  
       par2.add(ch1);  
       par2.add(ch2);  
       par2.setAlignment(Element.ALIGN_JUSTIFIED);  
       document.add(par10);  
       document.add(par11);  
       document.add(par12);  
       document.add(par13);  
       document.add(par14);  
       document.add(par);  
       document.add(par1);  
       document.add(par2);        
       document.close();  
       pdfReport = new ByteArrayInputStream(baos.toByteArray());  
       baos.close();  
       return pdfReport;  
     }catch(Exception e){  
       e.printStackTrace();  
       return null;  
     }  
   }  

Tuesday, February 10, 2015

Jquery: Get table row count

 var rowCount = $('#myTable tr').length;   
or
 
 var rowCount = $('#myTable >tbody >tr').length;  

Thursday, February 5, 2015

Send Email thru Office 365: Client does not support from this sender

com.sun.mail.smtp.SMTPSendFailedException: 550 5.7.60 SMTP; Client does not have permissions to send as this sender at com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2110) at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1889) at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1120) at javax.mail.Transport.send0(Transport.java:189) at javax.mail.Transport.send(Transport.java:118)..

This site has a very good explanation with the error.

How to Send email from Office 365 in your application

Cause:
The Mail Address set as the SMTP server does not have the permission to send email on behalf of other mail addresses.
Resolution:
  1. Make sure that the 
  2. Do not send test email with any other mail address except for the SMTP server mail address in the From field

Your set up of email properties should be like this
  mail.smtp.host=smtp.office365.com   
  mail.smtp.port=587   
  mail.smtp.starttls.enable=true   
  mail.smtp.auth=true   
  mail.smtp.ssl.trust=smtp.office365.com   
  mail.user=noreply@mycompany.com  //your From address should be the same of the username set here  
  mail.password=Password123$   

How to Send Email using Office 365 from your application

//email.properties
 mail.smtp.host=smtp.office365.com  
 mail.smtp.port=587  
 mail.smtp.starttls.enable=true  
 mail.smtp.auth=true  
 mail.smtp.ssl.trust=smtp.office365.com  
 mail.user=noreply@mycompany.com  
 mail.password=Password123$  

//Your Java Controller
 Properties properties = new Properties();  
 properties.load(getClass().getClassLoader().getResourceAsStream("email.properties"));  
 Session mailSession = null;  
 try{  
 final String emailUserNm = properties.getProperty("mail.user");  
 final String emailPassword = properties.getProperty("mail.password");  
 mailSession = Session.getInstance(properties,  
      new javax.mail.Authenticator() {  
           protected PasswordAuthentication getPasswordAuthentication() {  
           return new PasswordAuthentication(emailUserNm, emailPassword);  
      }  
 });  
 }catch(Exception e){  
      System.out.println("hello");  
 }  
 String from = properties.getProperty("mail.user");   

Some Notes:

  • Username and From field of the email should be the same email. 
  • Office 365 is using TLS authentication.