Posts

Showing posts from 2012

Show GIT branch on CLI

Add the following code in  ~/.bashrc alias ls='ls --color=auto' PS1="\[\e[1;32m\][\u@\h \W]\$(parse_git_branch)\[\e[0m\] " function parse_git_branch () {        git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/' } Type the following command to see the GIT branch name. source ~/.bashrc

Parse Bill n Pay Customer Info Json Response

 //{}&&{"biller":{"customerinfo":{"customer":[{"firstname":"S","middlename":"R","lastname":"S","internalid":"502CD927-651E-E67C-A3FD-AABEC48F026B","id":"502CD927-651E-E67C-A3FD-AABEC48F026B"}]}}}                 JSONParser parser = new JSONParser();                 //cut out first 4 characters {}&&         jsonString = jsonString.substring(4);                         Object obj = parser.parse(jsonString);         JSONObject jsonObject = (JSONObject) obj;         JSONObject biller = (JSONObject) jsonObject.get("biller");         JSONObject customerinfo = (JSONObject) biller.get("customerinfo");                   JSONArray customerArray = (JSONArray) customerinfo.get("customer");                 JSONObject customer = (JSONObject) customerArray.get(0);             System.out.println("fullna

Curiosity Cam

Live streaming by Ustream

Auto Increment Oracle Table Id Mapping With JPA Entity

When you create entities file of the mysql table with JPA, auto increment field 'id' is mapped as follows.     @Id        @GeneratedValue(strategy = GenerationType.IDENTITY)     @Basic(optional = false)     @NotNull     @Column(name = "id")     private Long id; However, Oracle doesn't support auto increment. Hence sequence generator is set up for the field id of table. The respective entity mapping for 'id' should be changed as below.     @Id        @GeneratedValue(strategy = GenerationType.IDENTITY)     @Basic(optional = false)     @NotNull     @Column(name = "id")     private Long id;     @SequenceGenerator(initialValue=1, sequenceName="INVOICE_SEQ",allocationSize=1,name="invoice_seq_name")     @GeneratedValue(generator="invoice_seq_name")

Debug JSF lifecycle

Dynamic Image in Jasper Report

jrxml content <image>                 <reportElement x="5" y="5" width="200" height="90"/>                 <imageExpression class=" java.awt.Image "><![CDATA[$P{logo}]]></imageExpression>             </image> Java Code to convert image from URL into BufferedImage        URL url = new URL("http://localhost/image/image.jpg");         // Read the image ...         InputStream inputStream = url.openStream();         ByteArrayOutputStream baos = new ByteArrayOutputStream();         byte[] buffer = new byte[1024];         int n = 0;         while (-1 != (n = inputStream.read(buffer))) {             baos.write(buffer, 0, n);         }                 baos.flush();         byte[] imageInByte = baos.toByteArray();         baos.close();         // convert byte array back to BufferedImage         InputStream in = new ByteArrayInputStream(imageInByte);         BufferedImage

Bill & Pay Web API Call Example

What is Bill & Pay? Businesses of any size can affordably send electronic invoices and receive ACH and credit card payments online from their customers. Bill & Pay is the most comprehensive product of its kind on the market today. It is loaded with features and options, while remaining affordable and easy-to-use . Checkout out Bill & Pay for QuickBooks users or Bill & Pay Easy Invoice for non-QuickBooks users. Benefits of Bill & Pay  Here is sample java code for authentication. String xmlRequestData = "<?xml version=\"1.0\"?><request><response><type>xml</type></response><biller><authenticate><id>1111</id><password>password</password></authenticate></biller></request>"; public String xmlPost(String xmlRequestData) {         String result = "";         OutputStream os = null;         try {             URL url = new URL("ht

Configuring Oracle XE connection pool in Glassfish and Using JPA

To setup an Oracle Datasource in Glassfish, follow these steps: 1. Download and copy the Oracle JDBC driver (ojdbc14.jar ) to /glassfish/domains/domain1/lib/ext directory. 2. Start Glassfish. 3. Login to the admin interface and create a JDBC Connection Pool.     Delete all properties, and add following properties:     * user - set this to Oracle userid     * password - set this to Oracle password     * URL - set this to the URL, example jdbc:oracle:thin:@localhost:1521:xe.     * xa-driver-does-not-support-non-tx-operations - set this to true. Test the connection pool using ping. 4. Create a JDBC DataSource using the Connection Pool. If in case of Oracle major version error : javax.persistence.PersistenceException: org.hibernate.HibernateException: unknown Oracle major version [11] The fix for the error is add <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/> in your persistence.xml

Velocity Templating for Email

Library Requirement : velocity-1.7.jar Make template folder under resources and put following template vm file  invoice_email.vm file content <html>        <head>     <style>             *{margin:0; padding:0; outline:none}     </style>     </head>     <body>     <div style="background:#fcdd8c; padding:30px;">             <div style="background:#FFF; border-radius:15px; width:600px; padding:20px; margin:0 auto; box-shadow:0 1px 5px #000">             <p style="font:bold 14px/30px Tahoma, Geneva, sans-serif">Dear ${vp.salutation} ${vp.lastName},</p>             <p style="font:normal 12px/20px Arial, Helvetica, sans-serif; margin-bottom:5px">Please find the attached invoice dated: ${vp.invoiceDate}. Please let us know if you have any question.</p>             <p style="font:normal 12px/18px Arial, Helvetica, sans-serif; margin-bottom:20px">Thank

JBoss Application Server 7

View more presentations from Raymond Ploski

CASifying your web application

CAS used for Single Sign On Download required jar files for CAS integration. Configuration in web.xml  <!--CAS Integration-->     <filter>         <filter-name>CAS Authentication Filter</filter-name>         <filter-class>org.jasig.cas.client.authentication.AuthenticationFilter</filter-class>         <init-param>             <param-name>casServerLoginUrl</param-name>             <param-value>https://li419-10.members.linode.com:8443/cas/login</param-value>         </init-param>         <init-param>             <param-name>serverName</param-name>                        <param-value>http://li419-101.members.linode.com:8080</param-value>         </init-param>         <init-param>             <param-name>renew</param-name>             <param-value>false</param-value>         </init-param>         <init-param>           

IPCommerce Secure Hosted Payments for Invoicing Web Service Call

public static void main(String[] args) throws RemoteException,ServiceException {                         InvoicingServiceInfoServiceLocator lInfoServiceLocator = new InvoicingServiceInfoServiceLocator();                lInfoServiceLocator.setEndpointAddress("InvoicingServiceInfoService", "https://pay.cert.ipcommerce.com/LS/InvoicingServiceInfo/InvoicingServiceInfoService.svc");                        InvoicingServiceInfoServiceStub infoServiceStub = (InvoicingServiceInfoServiceStub) lInfoServiceLocator.getInvoicingServiceInfoService();                 AuthenticatedUser user = infoServiceStub.logon("username","password","SAK number");         InvoiceCodeRequest invoiceCodeRequest = new InvoiceCodeRequest();         invoiceCodeRequest.setCurrentAmount(new BigDecimal(3000));         invoiceCodeRequest.setInvoiceNo("");         invoiceCodeRequest.setCustomerName("Customer Name");         invoiceCodeRequest.setCustomerID

Display Images From a Non-Project Directory in JSF

<h:graphicImage value="/headerimage/?img=logo.jpg"/> Create Servlet : @WebServlet(name = "DynamicImageServlet", urlPatterns = "/headerimage/*"}) public class DynamicImageServlet extends HttpServlet {     protected void processRequest(HttpServletRequest request, HttpServletResponse response)             throws ServletException, IOException {         response.setContentType("text/html;charset=UTF-8");                 try {             //Get image file             String img = request.getParameter("img");                        BufferedInputStream in = new BufferedInputStream(new FileInputStream("path to absolute location of image/"+img));             //Get image contents                         byte[] bytes = new byte[in.available()];                         in.read(bytes);             in.close();             //Write image contents to response             response.getOutputStream().write(bytes);

Send Email With Attachment in Java

public boolean sendEmailWithAttachment() {         // create some properties and get the default Session         Properties props = System.getProperties();         props.put("mail.smtp.host", "smtp host address");         props.put("mail.smtp.port", "25");         Session session = Session.getInstance(props, new MailAuthenticator());         try {             // create a message             MimeMessage msg = new MimeMessage(session);             msg.setFrom(new InternetAddress(from));             InternetAddress address = new InternetAddress(to);             msg.setRecipient(Message.RecipientType.TO, address);             msg.setSubject("Subject");             // create and fill the first message part             MimeBodyPart mbp1 = new MimeBodyPart();                        mbp1.setContent("Body Text", "text/html");             // create the second message part             MimeBodyPart mbp2 = new MimeBodyPart();   

Nepal Zip Code Lists

Download Zip Code list from here

Reading properties file at glassfish starttime

Goto JVM options (server-config) and add this line -Dproperty.file.path=......filepath/einvoice.properties einvoice.properties: smtp.address = localhost ipcommerce.url = http://someipcommerceurl.com/ email.body = Plese check the attachment for invoice. email.subject = Invoice file.create.location = /home/shakeelstha/Interac\ Liferay\ Repo/invoice file.upload.location = /home/shakeelstha/Interac\ Liferay\ Repo/upload jasper.location = smtp.mail.password = smtp.mail.username = root mail.sender.address = Interac<shakeelshrestha@lftechnology.com> ContextListener.java package com.lftech.interac.listener; import com.lftech.interac.dto.EInvoiceProperty; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; /**  *  * @author shakeelstha  */ public class ContextListener implements ServletContextListener {     @Override     public v

Simple Invoice Creation With Jasper Report

Image
<?xml version="1.0" encoding="UTF-8"?> <jasperReport xmlns="http://jasperreports.sourceforge.net/jasperreports" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd" name="invoicePdf" pageWidth="595" pageHeight="842" columnWidth="535" leftMargin="30" rightMargin="30" topMargin="30" bottomMargin="50">     <property name="ireport.zoom" value="1.5"/>     <property name="ireport.x" value="0"/>     <property name="ireport.y" value="140"/>     <property name="ireport.callouts" value="##Fri Mar 30 16:17:30 NPT 2012"/>     <style name="table">         <box>             <pen li

Export Jasper Report As PDF And Content Disposition

public void createPdfInvoice(String inputFileName, String outputFileName, Collection dataCollection, Map inputParameters) throws Exception { FacesContext fc = FacesContext.getCurrentInstance(); ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse(); ServletOutputStream servletOutputStream = response.getOutputStream(); String jrxmlReportPath = context.getRealPath("/WEB-INF/resources/report/" + inputFileName + ".jrxml"); response.setContentType("application/pdf"); try { JasperCompileManager.compileReportToFile(jrxmlReportPath); } catch (Exception e) { System.out.println("jrxml exception :::: createReportAsPdf"); e.printStackTrace(); } try {

Export Jasper Report As PDF And Save Into FileSystem

public void savePdfInvoice(String inputFileName, String outputFileName, Collection dataCollection, Map inputParameters) throws Exception { ServletContext context = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext(); String jrxmlReportPath = context.getRealPath("/WEB-INF/resources/report/" + inputFileName + ".jrxml"); try { JasperReport jasperReport = JasperCompileManager.compileReport(jrxmlReportPath); JRBeanCollectionDataSource jrbcds = new JRBeanCollectionDataSource(dataCollection); /*if (jrbcds == null) { System.out.println("....JRBCDS is null"); } if (inputParameters == null) { System.out.println("....inputParameters is null"); } */ JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, inputParameters, jrbcds); S

Append hyperlink into PDF file using iText

download iText library filepath = valid path to pdf file url = hyperlink to show at the end of the pdf file public boolean appendUrlPdf() { try { File inputFile = new File(filepath); Document document = new Document(PageSize.A4); PdfReader reader = new PdfReader(new FileInputStream(inputFile)); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(inputFile)); document.open(); PdfContentByte cb = writer.getDirectContent(); for (int i = 1; i < reader.getNumberOfPages() + 1; i++) { PdfImportedPage page = writer.getImportedPage(reader, i); Image instance = Image.getInstance(page); document.add(instance); } Paragraph paragraph = new Paragraph(); Anchor anchor = new Anchor(url); anchor.setReference(url); paragraph.add(anchor); document

Appending hyperlink into Docx file using docx4j library

Download docx4j library. filepath = valid path to .docx file url = hyperlink to append into end of the file public boolean appendUrlDocx() { try { File inputFile = new File(filepath); WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(inputFile); // Create hyperlink P.Hyperlink link = createHyperlink(wordMLPackage, url); // Add it to a paragraph org.docx4j.wml.ObjectFactory wmlFactory = new org.docx4j.wml.ObjectFactory(); org.docx4j.wml.P paragraph = wmlFactory.createP(); paragraph.getParagraphContent().add(link); wordMLPackage.getMainDocumentPart().addObject(paragraph); // Now save it wordMLPackage.save(inputFile); return true; } catch (InvalidFormatException ex) { ex.printStackTrace(); return false; } catch (Exception ex) { ex.printStackTr

Java Enterprise Edition 6 Tutorial

Java Enterprise Edition 6 Tutorial

Adding row data dynamically in datatable in JSF

Image
This code is useful when making order bill dynamically. default.xhtml <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"         xmlns:h="http://java.sun.com/jsf/html"       xmlns:f="http://java.sun.com/jsf/core">     <h:head>         <h:outputStylesheet library="css" name="table-style.css"  />     </h:head>     <h:body>         <h:form>             <h:dataTable value="#{order.orderList}" var="o"                          styleClass="order-table"                          headerClass="order-table-header"                          rowClasses="order-table-odd-row,order-table-even-row">                 <h:column>