/*
i-net software provides programming examples for illustration only, without warranty
either expressed or implied, including, but not limited to, the implied warranties
of merchantability and/or fitness for a particular purpose. This programming example
assumes that you are familiar with the programming language being demonstrated and
the tools used to create and debug procedures. i-net software support professionals
can help explain the functionality of a particular procedure, but they will not modify
these examples to provide added functionality or construct procedures to meet your
specific needs.
© i-net software 1998-2010
*/
package samples.sign;


import java.io.FileOutputStream;

import com.inet.report.Engine;
import com.inet.report.Field;
import com.inet.report.Fields;
import com.inet.report.PromptField;
import com.inet.report.RDC;
import com.inet.report.ReportException;


/**
 *  This sample shows how to create a custom certificate info factory
 *  and to make it active through RDC methods; so it is possible to choose
 *  the certificate that will be used to sign the pdf document.
 *    
 *  For using this sample some settings must be adjusted: they are listed below as
 *  'Parameters to adjust'.
 */
public class SignatureSample {
	// Parameters to adjust:
    private String reportName	= "E:/sign/reports/EmptyReport.rpt";
    private String keyStoreType	= "JKS";
    private String keyStorePath = "E:/sign/stores/store.jks";
    private String keyPassword	= "storejkspass";
    private String exportPath 	= "E:/sign/export/test.pdf";
    
    
    /**
     * main entry method for class, writes an invisible signature to a sample report
     * @param args not used
     */
    public static void main( String[] args ) {
    	new SignatureSample().writeInvisibleSignature();
    }
    
    /**
     * Defines custom certificate factory;
     * Creates engine with the security information saved in prompt fields;
     * Executes pdf export and writes the invisible signature into the pdf file.
     */
    private void writeInvisibleSignature() {
    	setCustomFactory();
    	try {
    		Engine eng = createSampleReport( reportName, keyStoreType, keyStorePath, keyPassword );
    		doPdfExport( eng, exportPath );
    	} catch ( Exception e ) {
    		e.printStackTrace();
    	}
    }
    
    /** 
     * Sets custom certificate factory to be used for signing the document.
     * This factory is initialized with engine prompt values.
     * If initialized, the custom factory has a higher priority than the default certificate
     * factory defined through configuration.
     */
    private void setCustomFactory() {
        CustomCertificateInfoFactory customFactory = new CustomCertificateInfoFactory();
        RDC.setCertificateInfoFactory( customFactory );
    }
    
    /**
     * Creates engine with some prompt fields describing security settings.
     * @param reportName absolute path (e.g. "C:/reports/empty.rpt")
     * @param keyStoreType type of the key store
     * @param keyStorePath path to the key store
     * @param keyPassword password of the key store
     * @return test engine
     * @throws ReportException if creating engine or setting report file fails.
     */
    private Engine createSampleReport( String reportName, String keyStoreType, String keyStorePath, String keyPassword ) throws ReportException {
        Engine eng = new Engine( Engine.EXPORT_PDF );
        
        eng.setReportFile( reportName );
        
        // pack security information in prompt fields (FOR TEST ONLY!) 
        Fields fields = eng.getFields();
        PromptField pField = null;
        
        // adding some prompt fields to the fields list:
        pField = fields.addPromptField("keystoretype", "Type of the key store", Field.STRING);
        pField.setPromptValue( keyStoreType );

        pField = fields.addPromptField("keystorepath", "path to key store", Field.STRING);
        pField.setPromptValue( keyStorePath );
        
        pField = fields.addPromptField("keystorepassword", "store password", Field.STRING);
        pField.setPromptValue( keyPassword );
        
        return eng;
    }
   
   /**
    * Runs pdf export and saves the result in a pdf file.
    * @param eng   active engine.
    * @param exportPath    path of the pdf file.
    */
   private void doPdfExport( Engine eng, String exportPath ) {
       FileOutputStream fos = null;
       try {
           eng.execute();
           fos = new FileOutputStream( exportPath );
           for( int i = 1; i <= eng.getPageCount(); i++ ) {
               fos.write( eng.getPageData( i ) );
           }
       } catch( Throwable th ) {
           th.printStackTrace();
       } finally{
           if( fos != null ) {
               try {
                   fos.close();
               }catch( Exception e ) {/*empty*/}
           }    
       }
   }
}
