Posts

Showing posts with the label java

Singleton Design Pattern for Utility Clases

public class DateUtility {   private static DateUtility instance;         public static DateUtility getInstance() {    synchronized (DateUtility.class) {      if (instance == null) {        instance = new DateUtility();      } } return instance; }  public String convertDateToString(Date date) { ....................................... } } Usage : DateUtility.getInstance().convertDateToString();

Add PMD rules into your project

pom.xml <properties>              <pmd.failOnViolation>true</pmd.failOnViolation> </properties> <plugin>             <groupId>org.apache.maven.plugins</groupId>             <artifactId>maven-pmd-plugin</artifactId>             <version>3.1</version>             <executions>               <execution>                 <id>pmd</id>                 <phase>verify</phase>               ...

Convert XSD element choice with "maxOccurs=unbounded" into individual list of objects

Problem defined here: http://archive.oreilly.com/pub/a/onjava/2003/12/10/jaxb.html?page=2 Plugins used: https://github.com/highsource/jaxb2-basics/wiki/JAXB2-Simplify-Plugin XSD Sample <xs:schema xmlns:tns="http://www.omnicogroup.com/FPF/namespace" attributeFormDefault="unqualified" elementFormDefault="qualified" targetNamespace="http://www.omnicogroup.com/FPF/namespace" xmlns:xs="http://www.w3.org/2001/XMLSchema">   <xs:element  name="transaction">     <xs:complexType>       <xs:sequence>         <xs:choice maxOccurs="unbounded">           <xs:element  name="TransactionDetails">             <xs:complexType>               <xs:sequence>        ...

JDBC Data Types Equivalent in Java

SQL JDBC/Java setXXX getXXX VARCHAR java.lang.String setString getString CHAR java.lang.String setString getString LONGVARCHAR java.lang.String setString getString BIT boolean setBoolean getBoolean NUMERIC java.math.BigDecimal setBigDecimal getBigDecimal TINYINT byte setByte getByte SMALLINT short setShort getShort INTEGER int setInt getInt BIGINT long setLong getLong REAL float setFloat getFloat FLOAT float setFloat getFloat DOUBLE double setDouble getDouble VARBINARY byte[ ] setBytes getBytes BINARY byte[ ] setBytes getBytes DATE java.sql.Date setDate getDate TIME java.sql.Time setTime getTime TIMESTAMP java.sql.Timestamp setTimestamp getTimestamp CLOB java.sql.Clob setClob getClob BLOB java.sql.Blob setBlob getBlob ARRAY java.sql.Array setARRAY getARRAY REF java.sql.Ref SetRef getRef STRUCT java.sql.Struct SetStruct getStruct

Maven + Oracle XE + Sample App

<dependency>     <groupid>com.oracle</groupid>     <artifactid>ojdbc6</artifactid>     <version>11.2.0.3</version> </dependency> ... <repositories>     <repository>       <id>codelds</id>       <url>https://code.lds.org/nexus/content/groups/main-repo</url>     </repository>   </repositories> public class OracleSample {     public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:XE";     public static final String DBUSER = "rtpmodern";     public static final String DBPASS = "P@ssw0rd";     public static void main(String[] args) throws SQLException {         // Load Oracle JDBC Driver         DriverManager.registerDriver(new oracle.jd...

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;        ...

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...

JBoss Application Server 7

View more presentations from Raymond Ploski

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 Fil...

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);   ...

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 {   ...

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 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.add(paragraph); document.clo...

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

Installing Java on Ubuntu Manually

Steps to follow: 1. Download jdk. I downloaded java7 from oracle's website. 2. Unzip and copy the folder into /usr/lib/jvm      Make directory jvm if it doesn't exist. I renamed the folder to java-7-oracle 3. Open /etc/environment and add this line      JAVA_HOME=/usr/lib/jvm/java-7-oracle      PATH=$PATH:$JAVA_HOME/bin 4. Then execute this command      source /etc/environment 5. On terminal type java -version to check if it shows the right version