com.instantbank.lettertemplate.editor.web
Class TemplateTransformer

java.lang.Object
  |
  +--com.instantbank.lettertemplate.editor.web.TemplateTransformer

public class TemplateTransformer
extends java.lang.Object

Transforms a Template --first-- to FO format and --after-- either to PDF format --if the template has "laser" print type-- or to TXT format --if the template has "typewriter" print type--.

Author:
InstantBank (Rodrigo Lopez)

Field Summary
private  java.util.Hashtable calendars
          Company's Calendars.
private static org.apache.log4j.Category cat
          The rtf2fo logger
static char CHARIMGMARK
          Auxiliary mark indicating the occurrence of an image in a fo file.
static java.lang.String closeRtfVarTag
          Closing text for a true Rtf variable occurrence.
private static java.text.SimpleDateFormat dateFormater
          Parser for dates comming from the data base
private static Debug debug
          Debugger objet for this class.
static java.lang.String FO_EXT
          Extension for the temporary file that contains a fo template just before variables are substituted by values.
private  java.lang.String foFileName
          Base name shared by the foTemplate file and the directory of images.
(package private)  org.apache.log.Logger foplog
          The Fop logger.
(package private)  java.lang.String foTemplate
          Fo template which is the base of the transformations.
private  java.util.Hashtable hashFields
          Full information about company fields
static java.lang.String IMAGES_DIR
          Extension for the directory that contains the images files referenced by a fo template.
static java.lang.String IMGMARK
          Rtf auxiliary mark indicating the occurrence of an image.
private  LetterTemplate letejb
          Private reference to the letter template ejb.
static java.lang.String openRtfVarTag
          Opening rtf text for a true Rtf variable occurrence.
private  org.xml.sax.XMLReader reader
          Sax parser for the construction of the (xsl)templates and for the actual substitution of variables in the (letter)template.
static int RENDER_PDF
          Rendering mode for laser templates.
static int RENDER_TXT
          Rendering mode for typewritter templates.
private  int renderMode
          Rendering mode for the final document.
private static java.lang.String rtf2foconfdir
          Path for rtf2fo's configuration dir.
private  javax.xml.transform.sax.SAXTransformerFactory saxFactory
          Sax factory required for xsl transformer building.
private  java.util.ArrayList[] theImages
          The sequence of images in ascending order of position <pos,varCode,formatCode>
private  java.util.ArrayList[] theVars
          The set of vars as {[varCode,[format1, format2, ..]]}
private  VariablesFormat varFormatter
          Formatter for values of variables as taken from the data base.
static java.lang.String VARMARK
          Rtf "auxiliary" mark indicating the occurrence of a variable.
private  java.lang.String[] varsOffsetType
          Offset type and name for variables in theVars
protected  java.lang.String workDir
          working directory where temporary files are generated.
private  javax.xml.transform.Templates xslTemplates
          Common Xsl templates constructed from LetterTemplateGlobals.fillSheet.
 
Constructor Summary
TemplateTransformer(java.util.ArrayList[] theVars, java.util.Hashtable hashFields)
          Light version of a TemplateTransformer.
TemplateTransformer(java.lang.String tmpDir, java.lang.String foTemplate, java.util.ArrayList[] theImages, java.util.ArrayList[] theVars, java.lang.String foFileName, LetterTemplate letejb)
          TemplateTransformer constructor.
 
Method Summary
(package private) static void ()
           
static java.lang.String actualFamily(java.lang.String fontName)
          Delivers actual font family and family name for a font name managed by template editor.
static java.lang.String actualFontTable(java.lang.String fontTable)
          Delivers a font table in rtf notation with actual family names and font names.
 java.lang.String applyDelta(java.lang.String strDate, java.lang.Long delta, java.lang.String offType)
          Applies a days offset to a date.
private static java.lang.String buildVarName(java.util.ArrayList var)
           
private static java.lang.String buildVarName(java.lang.Long varCode, java.lang.Long fmtCode, java.lang.Long delta)
           
 java.lang.String buildXmlData(java.util.ArrayList[] setOfVars, java.lang.String[] varsOffType, java.lang.String[] varValues)
          Builds the xml format of "variables' values" expected by "rtf2fo" in order to fill the fo template produced by toFoFile().
 void cleanfiles()
          Erases the fo-template file and image files.
 java.lang.String fillVarValues(java.lang.String baseUri, java.lang.String foName, java.lang.String xmlVarData)
          Fills a fo template with variable values.
 java.util.Hashtable getHashFields()
          Getter method for hashFields
private  java.lang.String imageReference(java.lang.String imageDir, java.lang.String imageFile)
          Constructs a fo:inline reference to an image file
private  void initfiller()
          Inits the parser(reader) and the (xsl)templates.
private  void initFopLogger()
          Inits the logger for the FOP api
private  void initOffsetType(java.util.ArrayList[] theVars, java.util.Hashtable hashFields)
          Calculates --in varsOffsetType--the offset types and names of a list of variables.
private static boolean nonullOffset(java.util.ArrayList fmtDelta)
          Test if there is a non zero date offset in a list of [varFormat, dateOffset]
 java.util.Set offsetConsistency()
          Checks if date offsets in theVars are consistent with the type of offset precalculated in varsOffsetType by initOffsetType(ArrayList[], Hashtable).
static void printAllVars(java.util.ArrayList allVars)
          Debug method that allows to print variables' information as extracted from the data base.
static void printRawVars(java.lang.Long[] varCodes, java.lang.String[] varValues)
          Debug method that allows to print raw variable values as extracted from the data base.
static void printSetOfVars(java.util.ArrayList[] set)
          Debug method that allows to "see" the set generated by setOfVariables.
static java.lang.String rtftoFoTemplate(java.lang.String data)
          Creates a String containing the FO version of a rtf text using the "rtf2fo" api.
private static java.lang.String rtfVariableTag(java.lang.String varName)
          Delivers a rtf variable tag after the name of the variable.
static java.util.ArrayList[] setOfVariables(java.util.ArrayList allVars)
          Calculates the set --without repetitions-- of codes of variables mentioned in an ArrayList with information of variables.
 void setRenderMode(int mode)
          Sets the renderMode attribute.
 java.lang.String substituteImages(java.lang.String basePath, java.lang.String unfilledFo)
          Substitutes images marks in a Fo template by an actual fo-reference to images files.
static java.lang.String substituteVariableTags(java.lang.String rtf, java.util.ArrayList[] theVariables)
          Substitutes every occurrence of a VARMARK --in the rtf text of this template-- by the "\docvar" rtf convention (see rtfVariableTag(String)).
 void toFile(java.lang.String fileName, java.lang.String data)
          Debug method allowing to write a string of characters in a file.
 java.lang.String toFoFile()
          Transform a LetterTemplate in a "fo-template" file with external references to image files.
 java.io.ByteArrayOutputStream toLetter(java.lang.String filledTemplate)
          Constructs the final version of the document.
 java.io.ByteArrayOutputStream transform(java.lang.String[] varValues)
          Produces an actual letter
static java.lang.Long[] varCodesFromSet(java.util.ArrayList[] set)
          Extracts the codes of variables from a set of variables as calculated by setOfVariables(ArrayList).
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, registerNatives, toString, wait, wait, wait
 

Field Detail

IMGMARK

public static final java.lang.String IMGMARK
Rtf auxiliary mark indicating the occurrence of an image.

VARMARK

public static final java.lang.String VARMARK
Rtf "auxiliary" mark indicating the occurrence of a variable. This text must be replaced by a "true" rtf variable occurrence. See openRtfVarTag, closeRtfVarTag.

CHARIMGMARK

public static final char CHARIMGMARK
Auxiliary mark indicating the occurrence of an image in a fo file.

openRtfVarTag

public static final java.lang.String openRtfVarTag
Opening rtf text for a true Rtf variable occurrence.

closeRtfVarTag

public static final java.lang.String closeRtfVarTag
Closing text for a true Rtf variable occurrence.

FO_EXT

public static final java.lang.String FO_EXT
Extension for the temporary file that contains a fo template just before variables are substituted by values.

IMAGES_DIR

public static final java.lang.String IMAGES_DIR
Extension for the directory that contains the images files referenced by a fo template.

RENDER_PDF

public static final int RENDER_PDF
Rendering mode for laser templates.

RENDER_TXT

public static final int RENDER_TXT
Rendering mode for typewritter templates.

foTemplate

java.lang.String foTemplate
Fo template which is the base of the transformations.

foFileName

private java.lang.String foFileName
Base name shared by the foTemplate file and the directory of images.

workDir

protected java.lang.String workDir
working directory where temporary files are generated.

renderMode

private int renderMode
Rendering mode for the final document. Default value is RENDER_PDF.

debug

private static Debug debug
Debugger objet for this class.

reader

private org.xml.sax.XMLReader reader
Sax parser for the construction of the (xsl)templates and for the actual substitution of variables in the (letter)template.

xslTemplates

private javax.xml.transform.Templates xslTemplates
Common Xsl templates constructed from LetterTemplateGlobals.fillSheet. The actual Xsl transformer is built starting from these templates.

saxFactory

private javax.xml.transform.sax.SAXTransformerFactory saxFactory
Sax factory required for xsl transformer building.

varFormatter

private VariablesFormat varFormatter
Formatter for values of variables as taken from the data base.

theImages

private java.util.ArrayList[] theImages
The sequence of images in ascending order of position <pos,varCode,formatCode>

theVars

private java.util.ArrayList[] theVars
The set of vars as {[varCode,[format1, format2, ..]]}

varsOffsetType

private java.lang.String[] varsOffsetType
Offset type and name for variables in theVars

hashFields

private java.util.Hashtable hashFields
Full information about company fields

calendars

private java.util.Hashtable calendars
Company's Calendars.

letejb

private LetterTemplate letejb
Private reference to the letter template ejb.

rtf2foconfdir

private static java.lang.String rtf2foconfdir
Path for rtf2fo's configuration dir.

cat

private static org.apache.log4j.Category cat
The rtf2fo logger

dateFormater

private static java.text.SimpleDateFormat dateFormater
Parser for dates comming from the data base

foplog

org.apache.log.Logger foplog
The Fop logger.
Constructor Detail

TemplateTransformer

public TemplateTransformer(java.lang.String tmpDir,
                           java.lang.String foTemplate,
                           java.util.ArrayList[] theImages,
                           java.util.ArrayList[] theVars,
                           java.lang.String foFileName,
                           LetterTemplate letejb)
                    throws LetterTemplateEventException
TemplateTransformer constructor.
Parameters:
tmpDir - Directory where the foTemplate will be created.
foTemplate - The foTemplate --without images references-- as a String.
theImages - Images in ascending order --by position--.
theVars - Variables' information (unordered). Each variable is paired with all formats and date offsets applied to it in the template.
foFileName - Chosen name for the fo template file.
letejb - Session ejb providing letter template services.
Throws:
LetterTemplateEventException - Description of the Exception

TemplateTransformer

public TemplateTransformer(java.util.ArrayList[] theVars,
                           java.util.Hashtable hashFields)
                    throws LetterTemplateEventException
Light version of a TemplateTransformer. When instantiated through this constructor, it behaves correctly only for checking date offset inconsistencies.
Parameters:
theVars - Variables' information (unordered). Each variable is paired with all formats and date offsets applied to it in the template.
hashFields - Table with company field's information.
Throws:
LetterTemplateEventException - Description of the Exception
Method Detail

static void ()

initFopLogger

private void initFopLogger()
Inits the logger for the FOP api

initOffsetType

private void initOffsetType(java.util.ArrayList[] theVars,
                            java.util.Hashtable hashFields)
Calculates --in varsOffsetType--the offset types and names of a list of variables.
Parameters:
theVars - The list of variables with the format: [varCode, [(fmt1, offset1), (fmt2, offset2), ...]]
Side effects:
Sets the varsOffsetType attribute.
hashFields - Description of the Parameter

offsetConsistency

public java.util.Set offsetConsistency()
Checks if date offsets in theVars are consistent with the type of offset precalculated in varsOffsetType by initOffsetType(ArrayList[], Hashtable).
Returns:
A set with codes of the inconsistent variables (if there are inconsistencies).

nonullOffset

private static boolean nonullOffset(java.util.ArrayList fmtDelta)
Test if there is a non zero date offset in a list of [varFormat, dateOffset]
Parameters:
fmtDelta - A list of [varFormat, dateOffset]
Returns:
True if there is, at least, one non zero offset. False otherwise

getHashFields

public java.util.Hashtable getHashFields()
Getter method for hashFields
Returns:
The hashFields value

initfiller

private void initfiller()
Inits the parser(reader) and the (xsl)templates.

rtftoFoTemplate

public static java.lang.String rtftoFoTemplate(java.lang.String data)
Creates a String containing the FO version of a rtf text using the "rtf2fo" api. The resulting text includes "fo variable tags" that must be filled afterwards in order to obtain an actual letter. Based on the rtf2fo API.
Parameters:
data - Rtf text to be transformed. Includes "rtf variable tags" and "rtf image marks".
Returns:
The resulting fo template (as a String) or "null" if any trouble arises.

substituteVariableTags

public static java.lang.String substituteVariableTags(java.lang.String rtf,
                                                      java.util.ArrayList[] theVariables)
                                               throws LetterTemplateEventException
Substitutes every occurrence of a VARMARK --in the rtf text of this template-- by the "\docvar" rtf convention (see rtfVariableTag(String)). All the processing is made in "reverse order" in order to ease the String searches. The names of the generated tags are constructed by buildVarName.
Parameters:
rtf - Description of the Parameter
theVariables - Description of the Parameter
Returns:
The resulting rtf with the substituted text.
Throws:
LetterTemplateEventException -  

buildVarName

private static java.lang.String buildVarName(java.util.ArrayList var)

buildVarName

private static java.lang.String buildVarName(java.lang.Long varCode,
                                             java.lang.Long fmtCode,
                                             java.lang.Long delta)

rtfVariableTag

private static java.lang.String rtfVariableTag(java.lang.String varName)
Delivers a rtf variable tag after the name of the variable.
Parameters:
varName - Variable's name.
Returns:
The rtf variable tag "in reverse order". See substituteVariableTags(String,ArrayList[]).

actualFontTable

public static java.lang.String actualFontTable(java.lang.String fontTable)
Delivers a font table in rtf notation with actual family names and font names.
Parameters:
fontTable - Font Table with \fnil family names and font names as presented by the template editor.
Returns:
The corrected font table or the original one if anything goes wrong.

actualFamily

public static java.lang.String actualFamily(java.lang.String fontName)
Delivers actual font family and family name for a font name managed by template editor.
Parameters:
fontName - Font name managed by the editor.
Returns:
Actual font family and family name for "fontName"

setOfVariables

public static java.util.ArrayList[] setOfVariables(java.util.ArrayList allVars)
Calculates the set --without repetitions-- of codes of variables mentioned in an ArrayList with information of variables. Each variable will be paired with a list of formats and date offsets. The resulting array is in ascending order by varCode.
Parameters:
allVars - The new ofVariables value
Returns:
Array of [varCode, [(format1, delta1), (format2, delta) ..]]. If there is no variables, returns an array with 0 entries. The array is in ascending order by varCode.

printSetOfVars

public static void printSetOfVars(java.util.ArrayList[] set)
Debug method that allows to "see" the set generated by setOfVariables.
Parameters:
set - Vars in format [(code, {[fmt1,offset],[fmt2,offset]})]

printAllVars

public static void printAllVars(java.util.ArrayList allVars)
Debug method that allows to print variables' information as extracted from the data base.
Parameters:
allVars - Description of the Parameter

printRawVars

public static void printRawVars(java.lang.Long[] varCodes,
                                java.lang.String[] varValues)
Debug method that allows to print raw variable values as extracted from the data base.
Parameters:
varCodes - Description of the Parameter
varValues - Description of the Parameter

varCodesFromSet

public static java.lang.Long[] varCodesFromSet(java.util.ArrayList[] set)
Extracts the codes of variables from a set of variables as calculated by setOfVariables(ArrayList).
Parameters:
set - The original set.
Returns:
An array of codes of variables in ascending order.

toFoFile

public java.lang.String toFoFile()
                          throws LetterTemplateEventException
Transform a LetterTemplate in a "fo-template" file with external references to image files. The fo-template is stored in a file and the images are stored in a subdirectory.
Returns:
Name of the file containing the fo-template.
Throws:
LetterTemplateEventException -  

substituteImages

public java.lang.String substituteImages(java.lang.String basePath,
                                         java.lang.String unfilledFo)
                                  throws LetterTemplateEventException
Substitutes images marks in a Fo template by an actual fo-reference to images files. The images files are constructed after the raw image bytes stored for each image in the theImages array. They are created in a subdirectory whose name is composed from the basePath parameter, the foFileName and the ".images" extension. The files themselves are named pict1.jpeg, pict2.jpeg, etc.
Parameters:
basePath - Directory where the images subdirectory should be located.
unfilledFo - Name of the fo template file.
Returns:
The fo template (as a String) with external images references or null if the images subdirectory can not be created or any other trouble arises.
Throws:
LetterTemplateEventException -  

imageReference

private java.lang.String imageReference(java.lang.String imageDir,
                                        java.lang.String imageFile)
Constructs a fo:inline reference to an image file
Parameters:
imageDir - Directory where the image file is located.
imageFile - Name of the image file.
Returns:
A reference of the form
   <fo:inline><fo:external-graphic src="file:///..."/>
      

toFile

public void toFile(java.lang.String fileName,
                   java.lang.String data)
Debug method allowing to write a string of characters in a file. The file is created in the workDir directory.
Parameters:
fileName - File's name.
data - The string to be written.

transform

public java.io.ByteArrayOutputStream transform(java.lang.String[] varValues)
                                        throws LetterTemplateEventException
Produces an actual letter
Parameters:
varValues - The values of variables in the template.
Returns:
the letter.
Throws:
LetterTemplateEventException - Description of the Exception

buildXmlData

public java.lang.String buildXmlData(java.util.ArrayList[] setOfVars,
                                     java.lang.String[] varsOffType,
                                     java.lang.String[] varValues)
Builds the xml format of "variables' values" expected by "rtf2fo" in order to fill the fo template produced by toFoFile(). The names of the variables are generated with buildVarName.
Parameters:
setOfVars - Set of variables in the template.
varsOffType - Date Offset type for variables in setOfVars
varValues - Array containing the values of the variables in the same order as in setOfVars.
Returns:
A xml string with the syntax:
   <varvalues>
     <var-name-1> value-of-this-var </var-name-1>
     <var-name-2> value-of-this-var </var-name-2>
                            ::::
     <var-name-n> value-of-this-var </var-name-n>
   </varvalues>
 

fillVarValues

public java.lang.String fillVarValues(java.lang.String baseUri,
                                      java.lang.String foName,
                                      java.lang.String xmlVarData)
Fills a fo template with variable values.
Parameters:
baseUri - Base of the Uri address of the file containing the fo template.
foName - Name of the fo template file.
xmlVarData - Xml structure containing the variables values. It has the syntax:
   <varvalues>
     <var-name-1> value-of-this-var </var-name-1>
     <var-name-2> value-of-this-var </var-name-2>
                            ::::
     <var-name-n> value-of-this-var </var-name-n>
   </varvalues>
 
Returns:
A String containing a FO document with variables substituted by actual values.

cleanfiles

public void cleanfiles()
Erases the fo-template file and image files.

setRenderMode

public void setRenderMode(int mode)
Sets the renderMode attribute. Valid values: RENDER_PDF, RENDER_TXT. Default value is RENDER_PDF.
Parameters:
mode - The new renderMode value

toLetter

public java.io.ByteArrayOutputStream toLetter(java.lang.String filledTemplate)
Constructs the final version of the document. Before using it, renderMode must be set in order to produce a TXT or a PDF document.
Parameters:
filledTemplate - The fo template (as a String) filled with variable values and external references to images.
Returns:
The final version of the document.

applyDelta

public java.lang.String applyDelta(java.lang.String strDate,
                                   java.lang.Long delta,
                                   java.lang.String offType)
Applies a days offset to a date.
Parameters:
strDate - The date as a string in the format specified by LetterTemplateGlobals.DATE_PARSING_PATTERN
delta - the offset. Can be positive, negative or zero.
offType - Description of the Parameter
Returns:
The fixed date, again as a String in the same format as the original date.