Tuesday, July 28, 2015

Java: Trigger is Mutating

Error:
 org.apache.ibatis.exceptions.PersistenceException:   
 ### Error committing transaction. Cause: org.apache.ibatis.executor.BatchExecutorException: 
 DEPENDENT.insertDependentToStaging (batch index #1) failed. Cause: java.sql.BatchUpdateException:   
 ORA-04091: table MO0RCO00_UAT.RCMBENSTAGWF is mutating, trigger/function may not see it  
 ORA-06512: at "MO0RCO00_UAT.TRIG_DEPENDENTNO", line 4  
 ORA-04088: error during execution of trigger 'MO0RCO00_UAT.TRIG_DEPENDENTNO'  


I have a DAO

   public void saveBeneficiariesToStaging(List<DependentBean> dependents){  
     SqlSession session = getSqlSessionFactory().openSession(ExecutorType.BATCH);  
     int len = dependents.size();  
     try {  
      for(int i = 0; i < len; i++) {        
       session.update("insertDependentToStaging", dependents.get(i));       
      }  
     } catch(Exception e) {  
      logger.error("saveBeneficiariesToStaging", e);  
      e.printStackTrace();  
      session.close();  
     }finally{   
       session.close();    
     }  
   }  

Solution
 public void saveBeneficiariesToStaging(List<DependentBean> dependents){  
      SqlSession session = getSqlSessionFactory().openSession(ExecutorType.BATCH);  
      int len = dependents.size();  
      try {  
       for(int i = 0; i < len; i++) {        
           session.update("insertDependentToStaging", dependents.get(i));  
           session.commit();      
       }  
      } catch(Exception e) {  
       logger.error("saveBeneficiariesToStaging", e);  
       e.printStackTrace();  
       session.close();  
      }finally{  
           session.close();   
      }  
 }    
Explanation: The trigger is selecting from the latest inserted rows in the batch update. But Trigger is mutating because it selects something that is not yet on the table because I am using batch update. Program should commit each row it inserts so that the trigger can select the recently inserted row.

Radio Button Erratic Behavior in Firefox Only

I have this HTML below. Where there are two radio buttons.
  <label class="full-width label-indented">Are you applying for membership in the Flexi Fund Program?       
      <p><input type="radio" id="flexi" name="flexi" value="A" autocomplete="off" />&nbsp;<span class="label">Yes</span></p>  
      <p><input type="radio" id="flexi1" name="flexi" value="0" autocomplete="off" checked/>&nbsp;<span class="label">No</span></p>  
 </label>  

Problem:
On first try, When I select No radio button, it automatically selects to Yes. And the Yes button is always clicked no matter how I try to select the No button.

Solution: Remove radio buttons inside label tag.
 <label class="full-width label-indented">Are you applying for membership in the Flexi Fund Program?</label>  
 <p><input type="radio" id="flexi" name="flexi" value="A" autocomplete="off" />&nbsp;<span class="label">Yes</span></p>  
 <p><input type="radio" id="flexi1" name="flexi" value="0" autocomplete="off" checked/>&nbsp;<span class="label">No</span></p>  

Tuesday, June 16, 2015

Invalid Namespace Value ORACLE TRIGGER

Error:

FAILURE ORA-28267: Invalid NameSpace Value
ORA-02063: preceding line from SYS00_DEVSCS00
ORA-06512: at "SYS00_UAT.CONTACTINFOMF_TX_TRG", line 4
ORA-04088: error during execution of trigger 'SYS00_UAT.CONTACTINFOMF_TX_TRG'

Trigger Code

 create or replace trigger SYS00_UAT.CONTACTINFOMF_TX_TRG  
 AFTER INSERT OR UPDATE of CONTACT_CD, CONTACT_INFO on SYS00_UAT.CONTACTINFOMF  
 REFERENCING NEW AS New OLD AS Old  
 FOR EACH ROW  
 BEGIN  
 -- test if contact code is Mobile  
  if :New.CONTACT_CD = 'M' then  
  insert into SYS00_UAT.MOBILENOTF (CUSTID, CEL_NO, SYSTEM_CODE, TRAN_CODE, MESSAGE)  
  VALUES(:New.SSNUM, :New.CONTACT_INFO, 'REG', 'REG','Sample Message');  
  end if;  
 END;  

Background:

Table CONTACTINFOMF is in Oracle 11g. MOBILENOTF is in Oracle 10g. Though Dblink and other configs are seem okay, the error above is still encountered. Based on forums the error needs a database patch to fix this, but of course this will take time and may affect the stable configuration of the table.

I am using Java and running on WebLogic Server.

Quick Fix:

I downloaded a ojdbc6.jar on the oracle site, loaded it in my application library. Then voila, works like magic!

Hope this helps you!



Wednesday, June 3, 2015

Java Log4j - Log Errors in Text File Then Download

//java

 import java.io.File;  
 import java.io.FileInputStream;  
 import java.io.InputStream;  
 import com.opensymphony.xwork2.ActionSupport;  
 public class DownloadLogsAction extends ActionSupport {  
   private InputStream fileInputStream;  
   public InputStream getFileInputStream() {  
       return fileInputStream;  
   }  
   public String execute() throws Exception {      
     fileInputStream = new FileInputStream(new File("/u01/app/logs/systemerr.log"));  
     return SUCCESS;  
   }  
 }  

//struts action
   <action name="download" class="com.project.system.utilities.DownloadLogsAction">  
     <result name="success" type="stream">  
       <param name="contentType">application/octet-stream</param>  
       <param name="inputName">fileInputStream</param>  
       <param name="contentDisposition">attachment;filename="systemerr.log"</param>  
       <param name="bufferSize">1024</param>  
     </result>  
   </action>  

//html
 <%@ taglib prefix="s" uri="/struts-tags" %>  
 <html>  
 <body>  
 <h1>Struts 2 download RCS Redesigned logs</h1>  
 <s:url id="fileDownload" namespace="/" action="download" ></s:url>  
 <h4>Download file - <s:a href="%{fileDownload}">rcsv3.log</s:a>  
 </h4>  
 </body>  
 </html>  

Jquery - Validate Email Format

 function validateEmail(email) {  
   var filter=/^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i  
   if (filter.test(v)) return true;      
   else return false;  
 }  

Call Jquery function
 var email = $('#txtEmail).val();        
 if(validateEmail(email) == false){  
   alert('Invalid Email');            
 }else{  
   alert('Valid Email);  
 }  

Java - Check If Email is Valid by Checking the HostName

//java
   public String checkHostName(){  
     try{  
       String email = request.getParameter("email");       
       Integer index = email.indexOf('@');  
       String domain = email.substring(index + 1, email.length());  
       /*check if domain exists in dns*/  
       try{  
         InetAddress inetAddress = InetAddress.getLocalHost();  
         inetAddress = InetAddress.getByName(domain);  
         host = inetAddress.getHostName().toString();          
       }catch(UnknownHostException e){  
         host = "unknown";  
       }  
       return SUCCESS;  
     }catch(Exception e){  
       e.printStackTrace();  
       return ERROR;  
     }  
   }  

//jquery
 function checkHostName(callback){  
   var host = null;  
   var email = $('#email').val();          
   $.ajax({  
    type: "POST",  
    url: "checkhostname.html",     
    async:false,  
    data: {  
       email: email  
    },  
    success: callback  
   });  
   return host;  
 }  
//call jquery using jquery callback
 checkHostName(function(host){          
           $('#hostName').val(host);   
           if(host == 'unknown'){               
             $('#erremail').text('Invalid email address');              
           }  
           else{ $('#erremail').text('');  
           }  
         });   

Sunday, May 31, 2015

Add Code Short Cut on NetBeans IDE

For a long time, I have been using JDeveloper to develop Java Web Applications. One convenient thing i like about JDeveloper is a short cut code for typing syntax. For instance, when I do debug, I simply type "sop" (with no double quote) then press Ctrl + Enter simultaneously, and the code automatically spell "System.out.println();" (with no double quote again). For my latest project, I used NetBeans IDE 8.0.1 since it is very convenient for creating GUI Desktop APIs. But then, the shortcoding of System.out.println is "sout". I always unconsciously type "sop" for SysOut short cut and it somehow annoys me that the Netbeans did not spell it out. So though, I made a custom short code short cut to make "sop"  spell out after I pressed Enter. So here is what I did:

1. Open your NetBeans. I am using version 8.0.1.
2. Go to your Tools menu then click Options.


3. Options menu will appear. Check on the templates if the abbreviations you will use already exists in the list. If not, click New button. 

4. New Code Template window will appear. Type your abbreviation on the text box. Click OK to continue.

5. The abbreviation added will be seen on the templates list. Click the row of your abbreviation. On the tabs below, type your corresponding code of your abbreviation on the Expanded Text tab (e.g System.out.println();). On the Expand Template on dropdown list, select the key to where your code spelling out will trigger. I chose Enter key. Click Apply button to save.


6. Voila! Try on your short code and press the key/s you designated to on when to expand.

I've read in one Quora forum that a sign that a programmer is abreast to the rest of his colleague when he/she has already mastered how to use the IDE he is working on.

I hope that this helps! Freely share your IDE tricks to make your programming life easier.



Tuesday, May 19, 2015

Open PDF file from your Java application

I have this help button in my application and I want that when the Help button is clicked, the User Manual in PDF format should be opened for the user.

 btnHelp.addActionListener(new ActionListener() {  
      @Override  
      public void actionPerformed(ActionEvent evt) {  
           if (Desktop.isDesktopSupported()) {  
                try {  
                     String userDir= System.getProperty("user.dir");  
                     String fileSeparator = System.getProperty("file.separator");      
                     String pdfPath = userDir + fileSeparator + "usermanual.pdf";    
                     File myFile = new File(pdfPath);  
                     Desktop.getDesktop().open(myFile);  
                } catch (IOException e) {  
                     JOptionPane.showMessage(null, "No PDF viewer installed.");                      
                }  
           }  
      }  
 });  

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.

Wednesday, January 28, 2015

Close PDF Child Window in Parent (works in IE, Mozilla, Firefox)

In my previous post, I tried to open a pdf in another window, and when user clicks Done button in the parent window, the pdf (child) window should close. I have successfully achieved this but it didn't work in Internet explorer. But Thank God! I found an alternate fix that will run both in Internet Explorer, Chrome and Mozilla.

 var child; //initialize as global
$('#printBtn').button().click(function (e) {      
     var link = 'viewtranslip.html'; //link for generating your pPDF 
     var html = "<html><head><title></title>";  
     html += "</head><body style='margin: 0;'>";  
     html += "<iframe height='100%' width='100%' src='" + link +"'></iframe>";  
     html += "</body></html>";  
     child = window.open("", "_blank", "resizable=1,status=0,toolbar=0,menubar=0");  
     child.document.write(html);  
     return win;  
 });     

 //close child button   
   $('#doneBtn').button().click(function (e) {  
     e.preventDefault();  
 //check if child window is already closed  
       if (child && !child.closed){       
         child.close();       
       }        
   });
  

Tuesday, January 27, 2015

Close Child Window from Parent Jquery

Open new window (child) from parent
 var child; //initialize as global  
   
   $('#prinBtn').button().click(function (e) {  
     child = window.open('viewtranslip.html');      
   });       
   
 //close child button   
   $('#doneBtn').button().click(function (e) {  
     e.preventDefault();  
 //check if child window is already closed  
       if (child && !child.closed){       
         child.close();       
       }        
   });       
   

Tested in IE 8, Chrome and Mozilla.
Limitation: If you open a pdf, doc, xls, in child window, this function will return a "Permission Denied" error on the child.close() line. "When Internet Explorer uses an Active Document server, such as Microsoft Word, Microsoft Excel, or Adobe Reader, to display a document in an Internet Explorer window, the page contains only the active document window and not the MSHTML. "
Read more about this limitation at http://support.microsoft.com/kb/934365/

Update: I found a fix that works in Internet Explorer, Mozilla, Chrome