idx
int64
0
41.2k
question
stringlengths
73
5.81k
target
stringlengths
5
918
5,300
public void reset ( ) { gsStack . removeAllElements ( ) ; gsStack . add ( new GraphicsState ( ) ) ; textMatrix = null ; textLineMatrix = null ; resources = new DictionaryStack ( ) ; }
Resets the graphics state stack matrices and resources .
5,301
public void invokeOperator ( PdfLiteral operator , ArrayList operands ) { ContentOperator op = operators . get ( operator . toString ( ) ) ; if ( op == null ) { return ; } op . invoke ( this , operator , operands ) ; }
Invokes an operator .
5,302
public float getStringWidth ( String string , float tj ) { DocumentFont font = gs ( ) . font ; char [ ] chars = string . toCharArray ( ) ; float totalWidth = 0 ; for ( int i = 0 ; i < chars . length ; i ++ ) { float w = font . getWidth ( chars [ i ] ) / 1000.0f ; float wordSpacing = chars [ i ] == 32 ? gs ( ) . wordSpacing : 0f ; totalWidth += ( ( w - tj / 1000f ) * gs ( ) . fontSize + gs ( ) . characterSpacing + wordSpacing ) * gs ( ) . horizontalScaling ; } return totalWidth ; }
Gets the width of a String .
5,303
public void displayPdfString ( PdfString string , float tj ) { String unicode = decode ( string ) ; float width = getStringWidth ( unicode , tj ) ; Matrix nextTextMatrix = new Matrix ( width , 0 ) . multiply ( textMatrix ) ; displayText ( unicode , nextTextMatrix ) ; textMatrix = nextTextMatrix ; }
Displays text .
5,304
public void processContent ( byte [ ] contentBytes , PdfDictionary resources ) { this . resources . push ( resources ) ; try { PdfContentParser ps = new PdfContentParser ( new PRTokeniser ( contentBytes ) ) ; ArrayList operands = new ArrayList ( ) ; while ( ps . parse ( operands ) . size ( ) > 0 ) { PdfLiteral operator = ( PdfLiteral ) operands . get ( operands . size ( ) - 1 ) ; invokeOperator ( operator , operands ) ; } } catch ( Exception e ) { throw new ExceptionConverter ( e ) ; } this . resources . pop ( ) ; }
Processes PDF syntax
5,305
public static boolean isSpecialTag ( String tag ) { return isHtml ( tag ) || isHead ( tag ) || isMeta ( tag ) || isLink ( tag ) || isBody ( tag ) ; }
Checks if this is a special tag .
5,306
public static Color getRGBColor ( String name ) throws IllegalArgumentException { int [ ] c = { 0 , 0 , 0 , 0 } ; if ( name . startsWith ( "#" ) ) { if ( name . length ( ) == 4 ) { c [ 0 ] = Integer . parseInt ( name . substring ( 1 , 2 ) , 16 ) * 16 ; c [ 1 ] = Integer . parseInt ( name . substring ( 2 , 3 ) , 16 ) * 16 ; c [ 2 ] = Integer . parseInt ( name . substring ( 3 ) , 16 ) * 16 ; return new Color ( c [ 0 ] , c [ 1 ] , c [ 2 ] , c [ 3 ] ) ; } if ( name . length ( ) == 7 ) { c [ 0 ] = Integer . parseInt ( name . substring ( 1 , 3 ) , 16 ) ; c [ 1 ] = Integer . parseInt ( name . substring ( 3 , 5 ) , 16 ) ; c [ 2 ] = Integer . parseInt ( name . substring ( 5 ) , 16 ) ; return new Color ( c [ 0 ] , c [ 1 ] , c [ 2 ] , c [ 3 ] ) ; } throw new IllegalArgumentException ( "Unknown color format. Must be #RGB or #RRGGBB" ) ; } else if ( name . startsWith ( "rgb(" ) ) { StringTokenizer tok = new StringTokenizer ( name , "rgb(), \t\r\n\f" ) ; for ( int k = 0 ; k < 3 ; ++ k ) { String v = tok . nextToken ( ) ; if ( v . endsWith ( "%" ) ) c [ k ] = Integer . parseInt ( v . substring ( 0 , v . length ( ) - 1 ) ) * 255 / 100 ; else c [ k ] = Integer . parseInt ( v ) ; if ( c [ k ] < 0 ) c [ k ] = 0 ; else if ( c [ k ] > 255 ) c [ k ] = 255 ; } return new Color ( c [ 0 ] , c [ 1 ] , c [ 2 ] , c [ 3 ] ) ; } name = name . toLowerCase ( ) ; if ( ! NAMES . containsKey ( name ) ) throw new IllegalArgumentException ( "Color '" + name + "' not found." ) ; c = ( int [ ] ) NAMES . get ( name ) ; return new Color ( c [ 0 ] , c [ 1 ] , c [ 2 ] , c [ 3 ] ) ; }
Gives you a Color based on a name .
5,307
private static Process action ( final String fileName , String parameters , boolean waitForTermination ) throws IOException { Process process = null ; if ( parameters . trim ( ) . length ( ) > 0 ) { parameters = " " + parameters . trim ( ) ; } else { parameters = "" ; } if ( acroread != null ) { process = Runtime . getRuntime ( ) . exec ( acroread + parameters + " \"" + fileName + "\"" ) ; } else if ( isWindows ( ) ) { if ( isWindows9X ( ) ) { process = Runtime . getRuntime ( ) . exec ( "command.com /C start acrord32" + parameters + " \"" + fileName + "\"" ) ; } else { process = Runtime . getRuntime ( ) . exec ( "cmd /c start acrord32" + parameters + " \"" + fileName + "\"" ) ; } } else if ( isMac ( ) ) { if ( parameters . trim ( ) . length ( ) == 0 ) { process = Runtime . getRuntime ( ) . exec ( new String [ ] { "/usr/bin/open" , fileName } ) ; } else { process = Runtime . getRuntime ( ) . exec ( new String [ ] { "/usr/bin/open" , parameters . trim ( ) , fileName } ) ; } } try { if ( process != null && waitForTermination ) process . waitFor ( ) ; } catch ( InterruptedException ie ) { } return process ; }
Performs an action on a PDF document .
5,308
public static final Process openDocument ( File file , boolean waitForTermination ) throws IOException { return openDocument ( file . getAbsolutePath ( ) , waitForTermination ) ; }
Opens a PDF document .
5,309
public static final Process printDocument ( File file , boolean waitForTermination ) throws IOException { return printDocument ( file . getAbsolutePath ( ) , waitForTermination ) ; }
Prints a PDF document .
5,310
public static final Process printDocumentSilent ( File file , boolean waitForTermination ) throws IOException { return printDocumentSilent ( file . getAbsolutePath ( ) , waitForTermination ) ; }
Prints a PDF document without opening a Dialog box .
5,311
public static final void launchBrowser ( String url ) throws IOException { try { if ( isMac ( ) ) { Class macUtils = Class . forName ( "com.apple.mrj.MRJFileUtils" ) ; Method openURL = macUtils . getDeclaredMethod ( "openURL" , new Class [ ] { String . class } ) ; openURL . invoke ( null , new Object [ ] { url } ) ; } else if ( isWindows ( ) ) Runtime . getRuntime ( ) . exec ( "rundll32 url.dll,FileProtocolHandler " + url ) ; else { String [ ] browsers = { "firefox" , "opera" , "konqueror" , "mozilla" , "netscape" } ; String browser = null ; for ( int count = 0 ; count < browsers . length && browser == null ; count ++ ) if ( Runtime . getRuntime ( ) . exec ( new String [ ] { "which" , browsers [ count ] } ) . waitFor ( ) == 0 ) browser = browsers [ count ] ; if ( browser == null ) throw new Exception ( "Could not find web browser." ) ; else Runtime . getRuntime ( ) . exec ( new String [ ] { browser , url } ) ; } } catch ( Exception e ) { throw new IOException ( "Error attempting to launch web browser" ) ; } }
Launches a browser opening an URL .
5,312
public void setCrypto ( PrivateKey privKey , Certificate [ ] certChain , CRL [ ] crlList , PdfName filter ) { this . privKey = privKey ; this . certChain = certChain ; this . crlList = crlList ; this . filter = filter ; }
Sets the cryptographic parameters .
5,313
public void setVisibleSignature ( Rectangle pageRect , int page , String fieldName ) { if ( fieldName != null ) { if ( fieldName . indexOf ( '.' ) >= 0 ) throw new IllegalArgumentException ( "Field names cannot contain a dot." ) ; AcroFields af = writer . getAcroFields ( ) ; AcroFields . Item item = af . getFieldItem ( fieldName ) ; if ( item != null ) throw new IllegalArgumentException ( "The field " + fieldName + " already exists." ) ; this . fieldName = fieldName ; } if ( page < 1 || page > writer . reader . getNumberOfPages ( ) ) throw new IllegalArgumentException ( "Invalid page number: " + page ) ; this . pageRect = new Rectangle ( pageRect ) ; this . pageRect . normalize ( ) ; rect = new Rectangle ( this . pageRect . getWidth ( ) , this . pageRect . getHeight ( ) ) ; this . page = page ; newField = true ; }
Sets the signature to be visible . It creates a new visible signature field .
5,314
public void setVisibleSignature ( String fieldName ) { AcroFields af = writer . getAcroFields ( ) ; AcroFields . Item item = af . getFieldItem ( fieldName ) ; if ( item == null ) throw new IllegalArgumentException ( "The field " + fieldName + " does not exist." ) ; PdfDictionary merged = item . getMerged ( 0 ) ; if ( ! PdfName . SIG . equals ( PdfReader . getPdfObject ( merged . get ( PdfName . FT ) ) ) ) throw new IllegalArgumentException ( "The field " + fieldName + " is not a signature field." ) ; this . fieldName = fieldName ; PdfArray r = merged . getAsArray ( PdfName . RECT ) ; float llx = r . getAsNumber ( 0 ) . floatValue ( ) ; float lly = r . getAsNumber ( 1 ) . floatValue ( ) ; float urx = r . getAsNumber ( 2 ) . floatValue ( ) ; float ury = r . getAsNumber ( 3 ) . floatValue ( ) ; pageRect = new Rectangle ( llx , lly , urx , ury ) ; pageRect . normalize ( ) ; page = item . getPage ( 0 ) . intValue ( ) ; int rotation = writer . reader . getPageRotation ( page ) ; Rectangle pageSize = writer . reader . getPageSizeWithRotation ( page ) ; switch ( rotation ) { case 90 : pageRect = new Rectangle ( pageRect . getBottom ( ) , pageSize . getTop ( ) - pageRect . getLeft ( ) , pageRect . getTop ( ) , pageSize . getTop ( ) - pageRect . getRight ( ) ) ; break ; case 180 : pageRect = new Rectangle ( pageSize . getRight ( ) - pageRect . getLeft ( ) , pageSize . getTop ( ) - pageRect . getBottom ( ) , pageSize . getRight ( ) - pageRect . getRight ( ) , pageSize . getTop ( ) - pageRect . getTop ( ) ) ; break ; case 270 : pageRect = new Rectangle ( pageSize . getRight ( ) - pageRect . getBottom ( ) , pageRect . getLeft ( ) , pageSize . getRight ( ) - pageRect . getTop ( ) , pageRect . getRight ( ) ) ; break ; } if ( rotation != 0 ) pageRect . normalize ( ) ; rect = new Rectangle ( this . pageRect . getWidth ( ) , this . pageRect . getHeight ( ) ) ; }
Sets the signature to be visible . An empty signature field with the same name must already exist .
5,315
public static float fitText ( Font font , String text , Rectangle rect , float maxFontSize , int runDirection ) { try { ColumnText ct = null ; int status = 0 ; if ( maxFontSize <= 0 ) { int cr = 0 ; int lf = 0 ; char t [ ] = text . toCharArray ( ) ; for ( int k = 0 ; k < t . length ; ++ k ) { if ( t [ k ] == '\n' ) ++ lf ; else if ( t [ k ] == '\r' ) ++ cr ; } int minLines = Math . max ( cr , lf ) + 1 ; maxFontSize = Math . abs ( rect . getHeight ( ) ) / minLines - 0.001f ; } font . setSize ( maxFontSize ) ; Phrase ph = new Phrase ( text , font ) ; ct = new ColumnText ( null ) ; ct . setSimpleColumn ( ph , rect . getLeft ( ) , rect . getBottom ( ) , rect . getRight ( ) , rect . getTop ( ) , maxFontSize , Element . ALIGN_LEFT ) ; ct . setRunDirection ( runDirection ) ; status = ct . go ( true ) ; if ( ( status & ColumnText . NO_MORE_TEXT ) != 0 ) return maxFontSize ; float precision = 0.1f ; float min = 0 ; float max = maxFontSize ; float size = maxFontSize ; for ( int k = 0 ; k < 50 ; ++ k ) { size = ( min + max ) / 2 ; ct = new ColumnText ( null ) ; font . setSize ( size ) ; ct . setSimpleColumn ( new Phrase ( text , font ) , rect . getLeft ( ) , rect . getBottom ( ) , rect . getRight ( ) , rect . getTop ( ) , size , Element . ALIGN_LEFT ) ; ct . setRunDirection ( runDirection ) ; status = ct . go ( true ) ; if ( ( status & ColumnText . NO_MORE_TEXT ) != 0 ) { if ( max - min < size * precision ) return size ; min = size ; } else max = size ; } return size ; } catch ( Exception e ) { throw new ExceptionConverter ( e ) ; } }
Fits the text to some rectangle adjusting the font size as needed .
5,316
public String getNewSigName ( ) { AcroFields af = writer . getAcroFields ( ) ; String name = "Signature" ; int step = 0 ; boolean found = false ; while ( ! found ) { ++ step ; String n1 = name + step ; if ( af . getFieldItem ( n1 ) != null ) { continue ; } n1 += "." ; found = true ; for ( Iterator it = af . getFields ( ) . keySet ( ) . iterator ( ) ; it . hasNext ( ) ; ) { String fn = ( String ) it . next ( ) ; if ( fn . startsWith ( n1 ) ) { found = false ; break ; } } } name += step ; return name ; }
Gets a new signature fied name that doesn t clash with any existing name .
5,317
public static void main ( String args [ ] ) { if ( args . length != 4 ) { System . err . println ( "arguments: srcfile destfile1 destfile2 pagenumber" ) ; } else { try { int pagenumber = Integer . parseInt ( args [ 3 ] ) ; PdfReader reader = new PdfReader ( args [ 0 ] ) ; int n = reader . getNumberOfPages ( ) ; System . out . println ( "There are " + n + " pages in the original file." ) ; if ( pagenumber < 2 || pagenumber > n ) { throw new DocumentException ( "You can't split this document at page " + pagenumber + "; there is no such page." ) ; } Document document1 = new Document ( reader . getPageSizeWithRotation ( 1 ) ) ; Document document2 = new Document ( reader . getPageSizeWithRotation ( pagenumber ) ) ; PdfWriter writer1 = PdfWriter . getInstance ( document1 , new FileOutputStream ( args [ 1 ] ) ) ; PdfWriter writer2 = PdfWriter . getInstance ( document2 , new FileOutputStream ( args [ 2 ] ) ) ; document1 . open ( ) ; PdfContentByte cb1 = writer1 . getDirectContent ( ) ; document2 . open ( ) ; PdfContentByte cb2 = writer2 . getDirectContent ( ) ; PdfImportedPage page ; int rotation ; int i = 0 ; while ( i < pagenumber - 1 ) { i ++ ; document1 . setPageSize ( reader . getPageSizeWithRotation ( i ) ) ; document1 . newPage ( ) ; page = writer1 . getImportedPage ( reader , i ) ; rotation = reader . getPageRotation ( i ) ; if ( rotation == 90 || rotation == 270 ) { cb1 . addTemplate ( page , 0 , - 1f , 1f , 0 , 0 , reader . getPageSizeWithRotation ( i ) . getHeight ( ) ) ; } else { cb1 . addTemplate ( page , 1f , 0 , 0 , 1f , 0 , 0 ) ; } } while ( i < n ) { i ++ ; document2 . setPageSize ( reader . getPageSizeWithRotation ( i ) ) ; document2 . newPage ( ) ; page = writer2 . getImportedPage ( reader , i ) ; rotation = reader . getPageRotation ( i ) ; if ( rotation == 90 || rotation == 270 ) { cb2 . addTemplate ( page , 0 , - 1f , 1f , 0 , 0 , reader . getPageSizeWithRotation ( i ) . getHeight ( ) ) ; } else { cb2 . addTemplate ( page , 1f , 0 , 0 , 1f , 0 , 0 ) ; } System . out . println ( "Processed page " + i ) ; } document1 . close ( ) ; document2 . close ( ) ; } catch ( Exception e ) { e . printStackTrace ( ) ; } } }
This class can be used to split an existing PDF file .
5,318
public void writeContent ( final OutputStream result ) throws IOException { if ( ! inHeader ) { if ( this . offset != - 1 ) { result . write ( RtfFont . FONT_SIZE ) ; result . write ( intToByteArray ( this . offset ) ) ; } result . write ( RtfParagraph . PARAGRAPH ) ; } for ( int i = 0 ; i < this . rows . size ( ) ; i ++ ) { RtfElement re = ( RtfElement ) this . rows . get ( i ) ; re . writeContent ( result ) ; } result . write ( RtfParagraph . PARAGRAPH_DEFAULTS ) ; }
Writes the content of this RtfTable
5,319
public void writeContent ( final OutputStream result ) throws IOException { if ( this . document . getLastElementWritten ( ) != null && ! ( this . document . getLastElementWritten ( ) instanceof RtfChapter ) ) { result . write ( DocWriter . getISOBytes ( "\\page" ) ) ; } result . write ( DocWriter . getISOBytes ( "\\sectd" ) ) ; document . getDocumentHeader ( ) . writeSectionDefinition ( result ) ; if ( this . title != null ) { this . title . writeContent ( result ) ; } for ( int i = 0 ; i < items . size ( ) ; i ++ ) { RtfBasicElement rbe = ( RtfBasicElement ) items . get ( i ) ; rbe . writeContent ( result ) ; } result . write ( DocWriter . getISOBytes ( "\\sect" ) ) ; }
Writes the RtfChapter and its contents
5,320
public int generate ( byte [ ] text , int textOffset , int textSize ) { int extCount , e , k , full ; DmParams dm , last ; byte [ ] data = new byte [ 2500 ] ; extOut = 0 ; extCount = processExtensions ( text , textOffset , textSize , data ) ; if ( extCount < 0 ) { return DM_ERROR_EXTENSION ; } e = - 1 ; if ( height == 0 || width == 0 ) { last = dmSizes [ dmSizes . length - 1 ] ; e = getEncodation ( text , textOffset + extOut , textSize - extOut , data , extCount , last . dataSize - extCount , options , false ) ; if ( e < 0 ) { return DM_ERROR_TEXT_TOO_BIG ; } e += extCount ; for ( k = 0 ; k < dmSizes . length ; ++ k ) { if ( dmSizes [ k ] . dataSize >= e ) break ; } dm = dmSizes [ k ] ; height = dm . height ; width = dm . width ; } else { for ( k = 0 ; k < dmSizes . length ; ++ k ) { if ( height == dmSizes [ k ] . height && width == dmSizes [ k ] . width ) break ; } if ( k == dmSizes . length ) { return DM_ERROR_INVALID_SQUARE ; } dm = dmSizes [ k ] ; e = getEncodation ( text , textOffset + extOut , textSize - extOut , data , extCount , dm . dataSize - extCount , options , true ) ; if ( e < 0 ) { return DM_ERROR_TEXT_TOO_BIG ; } e += extCount ; } if ( ( options & DM_TEST ) != 0 ) { return DM_NO_ERROR ; } image = new byte [ ( ( ( dm . width + 2 * ws ) + 7 ) / 8 ) * ( dm . height + 2 * ws ) ] ; makePadding ( data , e , dm . dataSize - e ) ; place = Placement . doPlacement ( dm . height - ( dm . height / dm . heightSection * 2 ) , dm . width - ( dm . width / dm . widthSection * 2 ) ) ; full = dm . dataSize + ( ( dm . dataSize + 2 ) / dm . dataBlock ) * dm . errorBlock ; ReedSolomon . generateECC ( data , dm . dataSize , dm . dataBlock , dm . errorBlock ) ; draw ( data , full , dm ) ; return DM_NO_ERROR ; }
Creates a barcode .
5,321
public void normalize ( ) { if ( llx > urx ) { float a = llx ; llx = urx ; urx = a ; } if ( lly > ury ) { float a = lly ; lly = ury ; ury = a ; } }
Normalizes the rectangle . Switches lower left with upper right if necessary .
5,322
public Rectangle rotate ( ) { Rectangle rect = new Rectangle ( lly , llx , ury , urx ) ; rect . rotation = rotation + 90 ; rect . rotation %= 360 ; return rect ; }
Rotates the rectangle . Swaps the values of llx and lly and of urx and ury .
5,323
public boolean hasBorders ( ) { switch ( border ) { case UNDEFINED : case NO_BORDER : return false ; default : return borderWidth > 0 || borderWidthLeft > 0 || borderWidthRight > 0 || borderWidthTop > 0 || borderWidthBottom > 0 ; } }
Indicates whether some type of border is set .
5,324
private void updateBorderBasedOnWidth ( float width , int side ) { useVariableBorders = true ; if ( width > 0 ) enableBorderSide ( side ) ; else disableBorderSide ( side ) ; }
Helper function updating the border flag for a side based on the specified width . A width of 0 will disable the border on that side . Any other width enables it .
5,325
float width ( int character ) { if ( image == null ) return font . getWidthPoint ( character , size ) * hScale ; else return image . getScaledWidth ( ) ; }
Returns the width of a certain character of this font .
5,326
void writeTo ( OutputStream os ) throws IOException { os . write ( DocWriter . getISOBytes ( String . valueOf ( number ) ) ) ; os . write ( ' ' ) ; os . write ( DocWriter . getISOBytes ( String . valueOf ( generation ) ) ) ; os . write ( STARTOBJ ) ; object . toPdf ( writer , os ) ; os . write ( ENDOBJ ) ; }
Writes efficiently to a stream
5,327
public void addColumns ( int aColumns ) { ArrayList < Row > newRows = new ArrayList < Row > ( rows . size ( ) ) ; int newColumns = columns + aColumns ; Row row ; for ( int i = 0 ; i < rows . size ( ) ; i ++ ) { row = new Row ( newColumns ) ; for ( int j = 0 ; j < columns ; j ++ ) { row . setElement ( ( ( Row ) rows . get ( i ) ) . getCell ( j ) , j ) ; } for ( int j = columns ; j < newColumns && i < curPosition . x ; j ++ ) { row . setElement ( null , j ) ; } newRows . add ( row ) ; } float [ ] newWidths = new float [ newColumns ] ; System . arraycopy ( widths , 0 , newWidths , 0 , columns ) ; for ( int j = columns ; j < newColumns ; j ++ ) { newWidths [ j ] = 0 ; } columns = newColumns ; widths = newWidths ; rows = newRows ; }
Gives you the possibility to add columns .
5,328
public void deleteColumn ( int column ) throws BadElementException { float newWidths [ ] = new float [ -- columns ] ; System . arraycopy ( widths , 0 , newWidths , 0 , column ) ; System . arraycopy ( widths , column + 1 , newWidths , column , columns - column ) ; setWidths ( newWidths ) ; System . arraycopy ( widths , 0 , newWidths , 0 , columns ) ; widths = newWidths ; Row row ; int size = rows . size ( ) ; for ( int i = 0 ; i < size ; i ++ ) { row = ( Row ) rows . get ( i ) ; row . deleteColumn ( column ) ; rows . set ( i , row ) ; } if ( column == columns ) { curPosition . setLocation ( curPosition . x + 1 , 0 ) ; } }
Deletes a column in this table .
5,329
public boolean deleteRow ( int row ) { if ( row < 0 || row >= rows . size ( ) ) { return false ; } rows . remove ( row ) ; curPosition . setLocation ( curPosition . x - 1 , curPosition . y ) ; return true ; }
Deletes a row .
5,330
public void deleteAllRows ( ) { rows . clear ( ) ; rows . add ( new Row ( columns ) ) ; curPosition . setLocation ( 0 , 0 ) ; lastHeaderRow = - 1 ; }
Deletes all rows in this table . ( contributed by dperezcar
5,331
private void assumeTableDefaults ( Cell aCell ) { if ( aCell . getBorder ( ) == Rectangle . UNDEFINED ) { aCell . setBorder ( defaultCell . getBorder ( ) ) ; } if ( aCell . getBorderWidth ( ) == Rectangle . UNDEFINED ) { aCell . setBorderWidth ( defaultCell . getBorderWidth ( ) ) ; } if ( aCell . getBorderColor ( ) == null ) { aCell . setBorderColor ( defaultCell . getBorderColor ( ) ) ; } if ( aCell . getBackgroundColor ( ) == null ) { aCell . setBackgroundColor ( defaultCell . getBackgroundColor ( ) ) ; } if ( aCell . getHorizontalAlignment ( ) == Element . ALIGN_UNDEFINED ) { aCell . setHorizontalAlignment ( defaultCell . getHorizontalAlignment ( ) ) ; } if ( aCell . getVerticalAlignment ( ) == Element . ALIGN_UNDEFINED ) { aCell . setVerticalAlignment ( defaultCell . getVerticalAlignment ( ) ) ; } }
Sets the unset cell properties to be the table defaults .
5,332
public PdfPTable createPdfPTable ( ) throws BadElementException { if ( ! convert2pdfptable ) { throw new BadElementException ( "No error, just an old style table" ) ; } setAutoFillEmptyCells ( true ) ; complete ( ) ; PdfPTable pdfptable = new PdfPTable ( widths ) ; pdfptable . setComplete ( complete ) ; if ( isNotAddedYet ( ) ) pdfptable . setSkipFirstHeader ( true ) ; SimpleTable t_evt = new SimpleTable ( ) ; t_evt . cloneNonPositionParameters ( this ) ; t_evt . setCellspacing ( cellspacing ) ; pdfptable . setTableEvent ( t_evt ) ; pdfptable . setHeaderRows ( lastHeaderRow + 1 ) ; pdfptable . setSplitLate ( cellsFitPage ) ; pdfptable . setKeepTogether ( tableFitsPage ) ; if ( ! Float . isNaN ( offset ) ) { pdfptable . setSpacingBefore ( offset ) ; } pdfptable . setHorizontalAlignment ( alignment ) ; if ( locked ) { pdfptable . setTotalWidth ( width ) ; pdfptable . setLockedWidth ( true ) ; } else { pdfptable . setWidthPercentage ( width ) ; } for ( Row row : this . rows ) { Element cell ; PdfPCell pcell ; for ( int i = 0 ; i < row . getColumns ( ) ; i ++ ) { if ( ( cell = ( Element ) row . getCell ( i ) ) != null ) { if ( cell instanceof Table ) { pcell = new PdfPCell ( ( ( Table ) cell ) . createPdfPTable ( ) ) ; } else if ( cell instanceof Cell ) { pcell = ( ( Cell ) cell ) . createPdfPCell ( ) ; pcell . setPadding ( cellpadding + cellspacing / 2f ) ; SimpleCell c_evt = new SimpleCell ( SimpleCell . CELL ) ; c_evt . cloneNonPositionParameters ( ( Cell ) cell ) ; c_evt . setSpacing ( cellspacing * 2f ) ; pcell . setCellEvent ( c_evt ) ; } else { pcell = new PdfPCell ( ) ; } pdfptable . addCell ( pcell ) ; } } } return pdfptable ; }
Create a PdfPTable based on this Table object .
5,333
public void close ( ) throws IOException { writer . write ( "</rdf:RDF>" ) ; writer . write ( "</x:xmpmeta>\n" ) ; for ( int i = 0 ; i < extraSpace ; i ++ ) { writer . write ( EXTRASPACE ) ; } writer . write ( end == 'r' ? XPACKET_PI_END_R : XPACKET_PI_END_W ) ; writer . flush ( ) ; writer . close ( ) ; }
Flushes and closes the XmpWriter .
5,334
public void onOpenDocument ( PdfWriter writer , Document document ) { PdfPageEvent event ; for ( Iterator i = events . iterator ( ) ; i . hasNext ( ) ; ) { event = ( PdfPageEvent ) i . next ( ) ; event . onOpenDocument ( writer , document ) ; } }
Called when the document is opened .
5,335
public void writeTo ( OutputStream target ) throws IOException { this . data . close ( ) ; BufferedInputStream tempIn = new BufferedInputStream ( new FileInputStream ( this . tempFile ) ) ; byte [ ] buffer = new byte [ 8192 ] ; int bytesRead = - 1 ; while ( ( bytesRead = tempIn . read ( buffer ) ) >= 0 ) { target . write ( buffer , 0 , bytesRead ) ; } tempIn . close ( ) ; this . tempFile . delete ( ) ; }
Writes the content of the temporary file into the OutputStream .
5,336
protected void newLine ( ) throws DocumentException { lastElementType = - 1 ; carriageReturn ( ) ; if ( lines != null && ! lines . isEmpty ( ) ) { lines . add ( line ) ; currentHeight += line . height ( ) ; } line = new PdfLine ( indentLeft ( ) , indentRight ( ) , alignment , leading ) ; }
Adds the current line to the list of lines and also adds an empty line .
5,337
protected void carriageReturn ( ) { if ( lines == null ) { lines = new ArrayList ( ) ; } if ( line != null ) { if ( currentHeight + line . height ( ) + leading < indentTop ( ) - indentBottom ( ) ) { if ( line . size ( ) > 0 ) { currentHeight += line . height ( ) ; lines . add ( line ) ; pageEmpty = false ; } } else { newPage ( ) ; } } if ( imageEnd > - 1 && currentHeight > imageEnd ) { imageEnd = - 1 ; indentation . imageIndentRight = 0 ; indentation . imageIndentLeft = 0 ; } line = new PdfLine ( indentLeft ( ) , indentRight ( ) , alignment , leading ) ; }
If the current line is not empty or null it is added to the arraylist of lines and a new empty line is added .
5,338
protected void ensureNewLine ( ) { try { if ( ( lastElementType == Element . PHRASE ) || ( lastElementType == Element . CHUNK ) ) { newLine ( ) ; flushLines ( ) ; } } catch ( DocumentException ex ) { throw new ExceptionConverter ( ex ) ; } }
Ensures that a new line has been started .
5,339
protected float flushLines ( ) throws DocumentException { if ( lines == null ) { return 0 ; } if ( line != null && line . size ( ) > 0 ) { lines . add ( line ) ; line = new PdfLine ( indentLeft ( ) , indentRight ( ) , alignment , leading ) ; } if ( lines . isEmpty ( ) ) { return 0 ; } Object currentValues [ ] = new Object [ 2 ] ; PdfFont currentFont = null ; float displacement = 0 ; PdfLine l ; Float lastBaseFactor = new Float ( 0 ) ; currentValues [ 1 ] = lastBaseFactor ; for ( Iterator i = lines . iterator ( ) ; i . hasNext ( ) ; ) { l = ( PdfLine ) i . next ( ) ; float moveTextX = l . indentLeft ( ) - indentLeft ( ) + indentation . indentLeft + indentation . listIndentLeft + indentation . sectionIndentLeft ; text . moveText ( moveTextX , - l . height ( ) ) ; if ( l . listSymbol ( ) != null ) { ColumnText . showTextAligned ( graphics , Element . ALIGN_LEFT , new Phrase ( l . listSymbol ( ) ) , text . getXTLM ( ) - l . listIndent ( ) , text . getYTLM ( ) , 0 ) ; } currentValues [ 0 ] = currentFont ; writeLineToContent ( l , text , graphics , currentValues , writer . getSpaceCharRatio ( ) ) ; currentFont = ( PdfFont ) currentValues [ 0 ] ; displacement += l . height ( ) ; text . moveText ( - moveTextX , 0 ) ; } lines = new ArrayList ( ) ; return displacement ; }
Writes all the lines to the text - object .
5,340
protected float indentLeft ( ) { return left ( indentation . indentLeft + indentation . listIndentLeft + indentation . imageIndentLeft + indentation . sectionIndentLeft ) ; }
Gets the indentation on the left side .
5,341
protected void addSpacing ( float extraspace , float oldleading , Font f ) { if ( extraspace == 0 ) return ; if ( pageEmpty ) return ; if ( currentHeight + line . height ( ) + leading > indentTop ( ) - indentBottom ( ) ) return ; leading = extraspace ; carriageReturn ( ) ; if ( f . isUnderlined ( ) || f . isStrikethru ( ) ) { f = new Font ( f ) ; int style = f . getStyle ( ) ; style &= ~ Font . UNDERLINE ; style &= ~ Font . STRIKETHRU ; f . setStyle ( style ) ; } Chunk space = new Chunk ( " " , f ) ; space . process ( this ) ; carriageReturn ( ) ; leading = oldleading ; }
Adds extra space . This method should probably be rewritten .
5,342
void traverseOutlineCount ( PdfOutline outline ) { ArrayList kids = outline . getKids ( ) ; PdfOutline parent = outline . parent ( ) ; if ( kids . isEmpty ( ) ) { if ( parent != null ) { parent . setCount ( parent . getCount ( ) + 1 ) ; } } else { for ( int k = 0 ; k < kids . size ( ) ; ++ k ) { traverseOutlineCount ( ( PdfOutline ) kids . get ( k ) ) ; } if ( parent != null ) { if ( outline . isOpen ( ) ) { parent . setCount ( outline . getCount ( ) + parent . getCount ( ) + 1 ) ; } else { parent . setCount ( parent . getCount ( ) + 1 ) ; outline . setCount ( - outline . getCount ( ) ) ; } } } }
Recursive method to update the count in the outlines .
5,343
void writeOutlines ( ) throws IOException { if ( rootOutline . getKids ( ) . size ( ) == 0 ) return ; outlineTree ( rootOutline ) ; writer . addToBody ( rootOutline , rootOutline . indirectReference ( ) ) ; }
Writes the outline tree to the body of the PDF document .
5,344
void outlineTree ( PdfOutline outline ) throws IOException { outline . setIndirectReference ( writer . getPdfIndirectReference ( ) ) ; if ( outline . parent ( ) != null ) outline . put ( PdfName . PARENT , outline . parent ( ) . indirectReference ( ) ) ; ArrayList kids = outline . getKids ( ) ; int size = kids . size ( ) ; for ( int k = 0 ; k < size ; ++ k ) outlineTree ( ( PdfOutline ) kids . get ( k ) ) ; for ( int k = 0 ; k < size ; ++ k ) { if ( k > 0 ) ( ( PdfOutline ) kids . get ( k ) ) . put ( PdfName . PREV , ( ( PdfOutline ) kids . get ( k - 1 ) ) . indirectReference ( ) ) ; if ( k < size - 1 ) ( ( PdfOutline ) kids . get ( k ) ) . put ( PdfName . NEXT , ( ( PdfOutline ) kids . get ( k + 1 ) ) . indirectReference ( ) ) ; } if ( size > 0 ) { outline . put ( PdfName . FIRST , ( ( PdfOutline ) kids . get ( 0 ) ) . indirectReference ( ) ) ; outline . put ( PdfName . LAST , ( ( PdfOutline ) kids . get ( size - 1 ) ) . indirectReference ( ) ) ; } for ( int k = 0 ; k < size ; ++ k ) { PdfOutline kid = ( PdfOutline ) kids . get ( k ) ; writer . addToBody ( kid , kid . indirectReference ( ) ) ; } }
Recursive method used to write outlines .
5,345
boolean localDestination ( String name , PdfDestination destination ) { Object obj [ ] = ( Object [ ] ) localDestinations . get ( name ) ; if ( obj == null ) obj = new Object [ 3 ] ; if ( obj [ 2 ] != null ) return false ; obj [ 2 ] = destination ; localDestinations . put ( name , obj ) ; destination . addPage ( writer . getCurrentPage ( ) ) ; return true ; }
The local destination to where a local goto with the same name will jump to .
5,346
Rectangle getBoxSize ( String boxName ) { PdfRectangle r = ( PdfRectangle ) thisBoxSize . get ( boxName ) ; if ( r != null ) return r . getRectangle ( ) ; return null ; }
Gives the size of a trim art crop or bleed box or null if not defined .
5,347
public void clearTextWrap ( ) { float tmpHeight = imageEnd - currentHeight ; if ( line != null ) { tmpHeight += line . height ( ) ; } if ( ( imageEnd > - 1 ) && ( tmpHeight > 0 ) ) { carriageReturn ( ) ; currentHeight += tmpHeight ; } }
Method added by Pelikan Stephan
5,348
private void processParameters ( ) throws BadElementException , IOException { type = IMGTEMPLATE ; originalType = ORIGINAL_WMF ; InputStream is = null ; try { String errorID ; if ( rawData == null ) { is = url . openStream ( ) ; errorID = url . toString ( ) ; } else { is = new java . io . ByteArrayInputStream ( rawData ) ; errorID = "Byte array" ; } InputMeta in = new InputMeta ( is ) ; if ( in . readInt ( ) != 0x9AC6CDD7 ) { throw new BadElementException ( errorID + " is not a valid placeable windows metafile." ) ; } in . readWord ( ) ; int left = in . readShort ( ) ; int top = in . readShort ( ) ; int right = in . readShort ( ) ; int bottom = in . readShort ( ) ; int inch = in . readWord ( ) ; dpiX = 72 ; dpiY = 72 ; scaledHeight = ( float ) ( bottom - top ) / inch * 72f ; setTop ( scaledHeight ) ; scaledWidth = ( float ) ( right - left ) / inch * 72f ; setRight ( scaledWidth ) ; } finally { if ( is != null ) { is . close ( ) ; } plainWidth = getWidth ( ) ; plainHeight = getHeight ( ) ; } }
This method checks if the image is a valid WMF and processes some parameters .
5,349
public void readWMF ( PdfTemplate template ) throws IOException , DocumentException { setTemplateData ( template ) ; template . setWidth ( getWidth ( ) ) ; template . setHeight ( getHeight ( ) ) ; InputStream is = null ; try { if ( rawData == null ) { is = url . openStream ( ) ; } else { is = new java . io . ByteArrayInputStream ( rawData ) ; } MetaDo meta = new MetaDo ( is , template ) ; meta . readAll ( ) ; } finally { if ( is != null ) { is . close ( ) ; } } }
Reads the WMF into a template .
5,350
private void setBorder ( int borderPosition , int borderStyle , float borderWidth , Color borderColor ) { RtfBorder border = new RtfBorder ( this . document , this . borderType , borderPosition , borderStyle , borderWidth , borderColor ) ; this . borders . put ( Integer . valueOf ( borderPosition ) , border ) ; }
Sets a border in the Hashtable of borders
5,351
public void addBorder ( int bordersToAdd , int borderStyle , float borderWidth , Color borderColor ) { if ( ( bordersToAdd & Rectangle . LEFT ) == Rectangle . LEFT ) { setBorder ( RtfBorder . LEFT_BORDER , borderStyle , borderWidth , borderColor ) ; } if ( ( bordersToAdd & Rectangle . TOP ) == Rectangle . TOP ) { setBorder ( RtfBorder . TOP_BORDER , borderStyle , borderWidth , borderColor ) ; } if ( ( bordersToAdd & Rectangle . RIGHT ) == Rectangle . RIGHT ) { setBorder ( RtfBorder . RIGHT_BORDER , borderStyle , borderWidth , borderColor ) ; } if ( ( bordersToAdd & Rectangle . BOTTOM ) == Rectangle . BOTTOM ) { setBorder ( RtfBorder . BOTTOM_BORDER , borderStyle , borderWidth , borderColor ) ; } if ( ( bordersToAdd & Rectangle . BOX ) == Rectangle . BOX && this . borderType == RtfBorder . ROW_BORDER ) { setBorder ( RtfBorder . VERTICAL_BORDER , borderStyle , borderWidth , borderColor ) ; setBorder ( RtfBorder . HORIZONTAL_BORDER , borderStyle , borderWidth , borderColor ) ; } }
Adds borders to the RtfBorderGroup
5,352
public void removeBorder ( int bordersToRemove ) { if ( ( bordersToRemove & Rectangle . LEFT ) == Rectangle . LEFT ) { this . borders . remove ( Integer . valueOf ( RtfBorder . LEFT_BORDER ) ) ; } if ( ( bordersToRemove & Rectangle . TOP ) == Rectangle . TOP ) { this . borders . remove ( Integer . valueOf ( RtfBorder . TOP_BORDER ) ) ; } if ( ( bordersToRemove & Rectangle . RIGHT ) == Rectangle . RIGHT ) { this . borders . remove ( Integer . valueOf ( RtfBorder . RIGHT_BORDER ) ) ; } if ( ( bordersToRemove & Rectangle . BOTTOM ) == Rectangle . BOTTOM ) { this . borders . remove ( Integer . valueOf ( RtfBorder . BOTTOM_BORDER ) ) ; } if ( ( bordersToRemove & Rectangle . BOX ) == Rectangle . BOX && this . borderType == RtfBorder . ROW_BORDER ) { this . borders . remove ( Integer . valueOf ( RtfBorder . VERTICAL_BORDER ) ) ; this . borders . remove ( Integer . valueOf ( RtfBorder . HORIZONTAL_BORDER ) ) ; } }
Removes borders from the list of borders
5,353
public void writeContent ( final OutputStream result ) throws IOException { Iterator it = this . borders . values ( ) . iterator ( ) ; while ( it . hasNext ( ) ) { ( ( RtfBorder ) it . next ( ) ) . writeContent ( result ) ; } }
Writes the borders of this RtfBorderGroup
5,354
public static int getNumberOfPages ( RandomAccessFileOrArray s ) { try { return TIFFDirectory . getNumDirectories ( s ) ; } catch ( Exception e ) { throw new ExceptionConverter ( e ) ; } }
Gets the number of pages the TIFF document has .
5,355
public static void decodePackbits ( byte data [ ] , byte [ ] dst ) { int srcCount = 0 , dstCount = 0 ; byte repeat , b ; try { while ( dstCount < dst . length ) { b = data [ srcCount ++ ] ; if ( b >= 0 && b <= 127 ) { for ( int i = 0 ; i < ( b + 1 ) ; i ++ ) { dst [ dstCount ++ ] = data [ srcCount ++ ] ; } } else if ( b <= - 1 && b >= - 127 ) { repeat = data [ srcCount ++ ] ; for ( int i = 0 ; i < ( - b + 1 ) ; i ++ ) { dst [ dstCount ++ ] = repeat ; } } else { srcCount ++ ; } } } catch ( Exception e ) { } }
Uncompress packbits compressed image data .
5,356
public void copyDocumentFields ( PdfReader reader ) throws DocumentException { if ( ! reader . isOpenedWithFullPermissions ( ) ) throw new IllegalArgumentException ( "PdfReader not opened with owner password" ) ; if ( readers2intrefs . containsKey ( reader ) ) { reader = new PdfReader ( reader ) ; } else { if ( reader . isTampered ( ) ) throw new DocumentException ( "The document was reused." ) ; reader . consolidateNamedDestinations ( ) ; reader . setTampered ( true ) ; } reader . shuffleSubsetNames ( ) ; readers2intrefs . put ( reader , new IntHashtable ( ) ) ; fields . add ( reader . getAcroFields ( ) ) ; updateCalculationOrder ( reader ) ; }
This method feeds in the source document
5,357
void mergeFields ( ) { for ( int k = 0 ; k < fields . size ( ) ; ++ k ) { HashMap fd = ( ( AcroFields ) fields . get ( k ) ) . getFields ( ) ; mergeWithMaster ( fd ) ; } }
This merge fields is slightly different from the mergeFields method of PdfCopyFields .
5,358
public float getWidth ( int startIdx , int lastIdx ) { char c = 0 ; PdfChunk ck = null ; float width = 0 ; for ( ; startIdx <= lastIdx ; ++ startIdx ) { boolean surrogate = Utilities . isSurrogatePair ( text , startIdx ) ; if ( surrogate ) { width += detailChunks [ startIdx ] . getCharWidth ( Utilities . convertToUtf32 ( text , startIdx ) ) ; ++ startIdx ; } else { c = text [ startIdx ] ; ck = detailChunks [ startIdx ] ; if ( PdfChunk . noPrint ( ck . getUnicodeEquivalent ( c ) ) ) continue ; width += detailChunks [ startIdx ] . getCharWidth ( c ) ; } } return width ; }
Gets the width of a range of characters .
5,359
public static PdfLayer createTitle ( String title , PdfWriter writer ) { if ( title == null ) throw new NullPointerException ( "Title cannot be null." ) ; PdfLayer layer = new PdfLayer ( title ) ; writer . registerLayer ( layer ) ; return layer ; }
Creates a title layer . A title layer is not really a layer but a collection of layers under the same title heading .
5,360
public void addChild ( PdfLayer child ) { if ( child . parent != null ) throw new IllegalArgumentException ( "The layer '" + ( ( PdfString ) child . get ( PdfName . NAME ) ) . toUnicodeString ( ) + "' already has a parent." ) ; child . parent = this ; if ( children == null ) children = new ArrayList ( ) ; children . add ( child ) ; }
Adds a child layer . Nested layers can only have one parent .
5,361
public void setName ( String name ) { put ( PdfName . NAME , new PdfString ( name , PdfObject . TEXT_UNICODE ) ) ; }
Sets the name of this layer .
5,362
public void setCreatorInfo ( String creator , String subtype ) { PdfDictionary usage = getUsage ( ) ; PdfDictionary dic = new PdfDictionary ( ) ; dic . put ( PdfName . CREATOR , new PdfString ( creator , PdfObject . TEXT_UNICODE ) ) ; dic . put ( PdfName . SUBTYPE , new PdfName ( subtype ) ) ; usage . put ( PdfName . CREATORINFO , dic ) ; }
Used by the creating application to store application - specific data associated with this optional content group .
5,363
public void setLanguage ( String lang , boolean preferred ) { PdfDictionary usage = getUsage ( ) ; PdfDictionary dic = new PdfDictionary ( ) ; dic . put ( PdfName . LANG , new PdfString ( lang , PdfObject . TEXT_UNICODE ) ) ; if ( preferred ) dic . put ( PdfName . PREFERRED , PdfName . ON ) ; usage . put ( PdfName . LANGUAGE , dic ) ; }
Specifies the language of the content controlled by this optional content group
5,364
public void setZoom ( float min , float max ) { if ( min <= 0 && max < 0 ) return ; PdfDictionary usage = getUsage ( ) ; PdfDictionary dic = new PdfDictionary ( ) ; if ( min > 0 ) dic . put ( PdfName . MIN_LOWER_CASE , new PdfNumber ( min ) ) ; if ( max >= 0 ) dic . put ( PdfName . MAX_LOWER_CASE , new PdfNumber ( max ) ) ; usage . put ( PdfName . ZOOM , dic ) ; }
Specifies a range of magnifications at which the content in this optional content group is best viewed .
5,365
public void setPrint ( String subtype , boolean printstate ) { PdfDictionary usage = getUsage ( ) ; PdfDictionary dic = new PdfDictionary ( ) ; dic . put ( PdfName . SUBTYPE , new PdfName ( subtype ) ) ; dic . put ( PdfName . PRINTSTATE , printstate ? PdfName . ON : PdfName . OFF ) ; usage . put ( PdfName . PRINT , dic ) ; }
Specifies that the content in this group is intended for use in printing
5,366
public void setView ( boolean view ) { PdfDictionary usage = getUsage ( ) ; PdfDictionary dic = new PdfDictionary ( ) ; dic . put ( PdfName . VIEWSTATE , view ? PdfName . ON : PdfName . OFF ) ; usage . put ( PdfName . VIEW , dic ) ; }
Indicates that the group should be set to that state when the document is opened in a viewer application .
5,367
public boolean addPage ( PdfIndirectReference page ) { if ( ! status ) { addFirst ( page ) ; status = true ; return true ; } return false ; }
Adds the indirect reference of the destination page .
5,368
public void writeContent ( final OutputStream result ) throws IOException { result . write ( OPEN_GROUP ) ; result . write ( ANNOTATION_ID ) ; result . write ( DELIMITER ) ; result . write ( intToByteArray ( document . getRandomInt ( ) ) ) ; result . write ( CLOSE_GROUP ) ; result . write ( OPEN_GROUP ) ; result . write ( ANNOTATION_AUTHOR ) ; result . write ( DELIMITER ) ; result . write ( DocWriter . getISOBytes ( title ) ) ; result . write ( CLOSE_GROUP ) ; result . write ( OPEN_GROUP ) ; result . write ( ANNOTATION ) ; result . write ( RtfParagraph . PARAGRAPH_DEFAULTS ) ; result . write ( DELIMITER ) ; result . write ( DocWriter . getISOBytes ( content ) ) ; result . write ( CLOSE_GROUP ) ; }
Writes the content of the RtfAnnotation
5,369
public static void main ( String [ ] args ) { if ( args . length == 4 ) { File srcdir = new File ( args [ 0 ] ) ; File destdir = new File ( args [ 1 ] ) ; File xsl_examples = new File ( srcdir , args [ 2 ] ) ; File xsl_site = new File ( srcdir , args [ 3 ] ) ; try { System . out . print ( "Building tutorial: " ) ; root = new File ( args [ 1 ] , srcdir . getName ( ) ) . getCanonicalPath ( ) ; System . out . println ( root ) ; build = new FileWriter ( new File ( root , "build.xml" ) ) ; build . write ( "<project name=\"tutorial\" default=\"all\" basedir=\".\">\n" ) ; build . write ( "<target name=\"all\">\n" ) ; action ( srcdir , destdir , xsl_examples , xsl_site ) ; build . write ( "</target>\n</project>" ) ; build . flush ( ) ; build . close ( ) ; } catch ( IOException ioe ) { ioe . printStackTrace ( ) ; } } else { System . err . println ( "Wrong number of parameters.\nUsage: BuildSite srcdr destdir xsl_examples xsl_site" ) ; } }
Main method so you can call the convert method from the command line .
5,370
private Script load ( String name ) throws JellyException { Script script = scripts . get ( name ) ; if ( script != null && ! MetaClass . NO_CACHE ) return script ; script = null ; if ( MetaClassLoader . debugLoader != null ) script = load ( name , MetaClassLoader . debugLoader . loader ) ; if ( script == null ) script = load ( name , classLoader ) ; return script ; }
Obtains the script for the given tag name . Loads if necessary .
5,371
protected void setApplicationObject ( ) { try { Object app = createApplication ( ) ; context . setAttribute ( APP , app ) ; initializer . set ( app ) ; } catch ( Error e ) { LOGGER . log ( Level . SEVERE , "Failed to initialize " + getApplicationName ( ) , e ) ; initializer . setException ( e ) ; throw e ; } catch ( RuntimeException e ) { LOGGER . log ( Level . SEVERE , "Failed to initialize " + getApplicationName ( ) , e ) ; initializer . setException ( e ) ; throw e ; } catch ( Exception e ) { LOGGER . log ( Level . SEVERE , "Failed to initialize " + getApplicationName ( ) , e ) ; initializer . setException ( e ) ; throw new Error ( e ) ; } finally { if ( ! initializer . isDone ( ) ) initializer . cancel ( true ) ; } }
Sets the root application object .
5,372
protected boolean checkEnvironment ( ) { home = getHomeDir ( ) . getAbsoluteFile ( ) ; home . mkdirs ( ) ; LOGGER . info ( getApplicationName ( ) + " home directory: " + home ) ; if ( ! home . exists ( ) ) { context . setAttribute ( APP , new NoHomeDirError ( home ) ) ; return false ; } return true ; }
Performs pre start - up environment check .
5,373
protected File getHomeDir ( ) { String varName = getApplicationName ( ) . toUpperCase ( ) + "_HOME" ; try { InitialContext iniCtxt = new InitialContext ( ) ; Context env = ( Context ) iniCtxt . lookup ( "java:comp/env" ) ; String value = ( String ) env . lookup ( varName ) ; if ( value != null && value . trim ( ) . length ( ) > 0 ) return new File ( value . trim ( ) ) ; value = ( String ) iniCtxt . lookup ( varName ) ; if ( value != null && value . trim ( ) . length ( ) > 0 ) return new File ( value . trim ( ) ) ; } catch ( NamingException e ) { } String sysProp = System . getProperty ( varName ) ; if ( sysProp != null ) return new File ( sysProp . trim ( ) ) ; String env = System . getenv ( varName ) ; if ( env != null ) return new File ( env . trim ( ) ) . getAbsoluteFile ( ) ; return getDefaultHomeDir ( ) ; }
Determines the home directory for the application .
5,374
public void releaseMe ( ) { Ancestor eot = Stapler . getCurrentRequest ( ) . findAncestor ( BoundObjectTable . class ) ; if ( eot == null ) throw new IllegalStateException ( "The thread is not handling a request to a abound object" ) ; String id = eot . getNextToken ( 0 ) ; resolve ( false ) . release ( id ) ; }
Called from within the request handling of a bound object to release the object explicitly .
5,375
public List < FieldRef > getFields ( ) { Map < String , FieldRef > fields = new LinkedHashMap < String , FieldRef > ( ) ; for ( Klass < ? > k = this ; k != null ; k = k . getSuperClass ( ) ) { for ( FieldRef f : k . getDeclaredFields ( ) ) { String name = f . getName ( ) ; if ( ! fields . containsKey ( name ) && f . isRoutable ( ) ) { fields . put ( name , f ) ; } } } return new ArrayList < FieldRef > ( fields . values ( ) ) ; }
Gets all the public fields defined in this type including super types .
5,376
public S findScript ( String name ) throws E { if ( MetaClass . NO_CACHE ) return loadScript ( name ) ; else return scripts . getUnchecked ( name ) . get ( ) ; }
Locates the view script of the given name .
5,377
public < T extends Facet > T getFacet ( Class < T > type ) { for ( Facet f : facets ) if ( type == f . getClass ( ) ) return type . cast ( f ) ; return null ; }
If the facet of the given type exists return it . Otherwise null .
5,378
public void clearScripts ( Class < ? extends AbstractTearOff > clazz ) { synchronized ( classMap ) { for ( MetaClass v : classMap . values ( ) ) { AbstractTearOff t = v . getTearOff ( clazz ) ; if ( t != null ) t . clearScripts ( ) ; } } }
Convenience maintenance method to clear all the cached scripts for the given tearoff type .
5,379
private boolean parseOne ( ClassLoader classLoader , String resName ) throws IOException { InputStream is = classLoader . getResourceAsStream ( resName ) ; if ( is == null ) return false ; BufferedReader in = new BufferedReader ( new InputStreamReader ( is , UTF8 ) ) ; String line ; while ( ( line = in . readLine ( ) ) != null ) { Matcher m = INCLUDE . matcher ( line ) ; if ( m . lookingAt ( ) ) required . add ( m . group ( 1 ) ) ; } in . close ( ) ; return true ; }
Parses CSS or JavaScript files and extract dependencies .
5,380
private String parseHtml ( ClassLoader classLoader , String resName ) throws IOException { InputStream is = classLoader . getResourceAsStream ( resName ) ; if ( is == null ) return null ; BufferedReader in = new BufferedReader ( new InputStreamReader ( is , UTF8 ) ) ; String line ; StringBuilder buf = new StringBuilder ( ) ; while ( ( line = in . readLine ( ) ) != null ) { Matcher m = HTML_INCLUDE . matcher ( line ) ; if ( m . lookingAt ( ) ) required . add ( m . group ( 1 ) ) ; else buf . append ( line ) . append ( '\n' ) ; } in . close ( ) ; return buf . toString ( ) ; }
Parses HTML files and extract dependencies .
5,381
public < T > T as ( Class < T > type ) { return type . cast ( Proxy . newProxyInstance ( type . getClassLoader ( ) , new Class [ ] { type } , new InvocationHandler ( ) { public Object invoke ( Object proxy , Method method , Object [ ] args ) throws Throwable { if ( method . getDeclaringClass ( ) == Object . class ) return method . invoke ( this , args ) ; Configuration cn = method . getAnnotation ( Configuration . class ) ; Class < ? > r = method . getReturnType ( ) ; String key = getKey ( method , cn ) ; String v = source . apply ( key ) ; if ( v == null && cn != null && ! cn . defaultValue ( ) . equals ( UNSPECIFIED ) ) v = cn . defaultValue ( ) ; if ( v == null ) return null ; return ConvertUtils . convert ( v , r ) ; } private String getKey ( Method method , Configuration c ) { if ( c != null && ! c . name ( ) . equals ( UNSPECIFIED ) ) return c . name ( ) ; String n = method . getName ( ) ; for ( String p : GETTER_PREFIX ) { if ( n . startsWith ( p ) ) return Introspector . decapitalize ( n . substring ( p . length ( ) ) ) ; } return n ; } } ) ) ; }
Creates a type - safe proxy that reads from the source specified by one of the fromXyz methods .
5,382
public String [ ] loadConstructorParamNames ( ) { Constructor < ? > [ ] ctrs = clazz . getConstructors ( ) ; Constructor < ? > dbc = null ; for ( Constructor < ? > c : ctrs ) { if ( c . getAnnotation ( DataBoundConstructor . class ) != null ) { dbc = c ; break ; } } if ( dbc == null ) throw new NoStaplerConstructorException ( "There's no @DataBoundConstructor on any constructor of " + clazz ) ; String [ ] names = ClassDescriptor . loadParameterNames ( dbc ) ; if ( names . length == dbc . getParameterTypes ( ) . length ) return names ; String resourceName = clazz . getName ( ) . replace ( '.' , '/' ) . replace ( '$' , '/' ) + ".stapler" ; ClassLoader cl = clazz . getClassLoader ( ) ; if ( cl == null ) throw new NoStaplerConstructorException ( clazz + " is a built-in type" ) ; InputStream s = cl . getResourceAsStream ( resourceName ) ; if ( s != null ) { try { Properties p = new Properties ( ) ; p . load ( s ) ; s . close ( ) ; String v = p . getProperty ( "constructor" ) ; if ( v . length ( ) == 0 ) return new String [ 0 ] ; return v . split ( "," ) ; } catch ( IOException e ) { throw new IllegalArgumentException ( "Unable to load " + resourceName , e ) ; } } throw new NoStaplerConstructorException ( "Unable to find " + resourceName + ". " + "Run 'mvn clean compile' once to run the annotation processor." ) ; }
Determines the constructor parameter names .
5,383
public Adjunct get ( String name ) throws IOException { Adjunct a = adjuncts . get ( name ) ; if ( a != null ) return a ; synchronized ( this ) { a = adjuncts . get ( name ) ; if ( a != null ) return a ; a = new Adjunct ( this , name , classLoader ) ; adjuncts . put ( name , a ) ; return a ; } }
Obtains the adjunct .
5,384
public void doDynamic ( StaplerRequest req , StaplerResponse rsp ) throws IOException , ServletException { String path = req . getRestOfPath ( ) ; if ( path . charAt ( 0 ) == '/' ) path = path . substring ( 1 ) ; if ( ! allowedResources . containsKey ( path ) ) { if ( ! allowResourceToBeServed ( path ) ) { rsp . sendError ( SC_FORBIDDEN ) ; return ; } allowedResources . put ( path , path ) ; } URL res = classLoader . getResource ( path ) ; if ( res == null ) { throw HttpResponses . error ( SC_NOT_FOUND , new IllegalArgumentException ( "No such adjunct found: " + path ) ) ; } else { long expires = MetaClass . NO_CACHE ? 0 : expiration ; rsp . serveFile ( req , res , expires ) ; } }
Serves resources in the class loader .
5,385
protected boolean allowResourceToBeServed ( String absolutePath ) { int idx = absolutePath . lastIndexOf ( '/' ) ; if ( idx > 0 && classLoader . getResource ( absolutePath . substring ( 0 , idx ) + "/.adjunct" ) != null ) return true ; return absolutePath . endsWith ( ".gif" ) || absolutePath . endsWith ( ".png" ) || absolutePath . endsWith ( ".css" ) || absolutePath . endsWith ( ".js" ) ; }
Controls whether the given resource can be served to browsers .
5,386
public void validateCrumb ( StaplerRequest request , String submittedCrumb ) { if ( ! issueCrumb ( request ) . equals ( submittedCrumb ) ) { throw new SecurityException ( "Request failed to pass the crumb test (try clearing your cookies)" ) ; } }
Validates a crumb that was submitted along with the request .
5,387
public void doDelete ( StaplerRequest request , StaplerResponse response ) throws IOException , ServletException { BookStore . theStore . getItems ( ) . remove ( getSku ( ) ) ; response . sendRedirect ( request . getContextPath ( ) + '/' ) ; }
Defines an action to delete this book from the store .
5,388
protected String parse ( Reader reader ) throws IOException { if ( ! reader . markSupported ( ) ) { reader = new BufferedReader ( reader ) ; } StringWriter sw = new StringWriter ( ) ; startScript ( sw ) ; int c ; while ( ( c = reader . read ( ) ) != - 1 ) { if ( c == '<' ) { reader . mark ( 1 ) ; c = reader . read ( ) ; if ( c != '%' ) { sw . write ( '<' ) ; reader . reset ( ) ; } else { reader . mark ( 1 ) ; c = reader . read ( ) ; if ( c == '=' ) { groovyExpression ( reader , sw ) ; } else { reader . reset ( ) ; groovySection ( reader , sw ) ; } } continue ; } if ( c == '$' ) { reader . mark ( 1 ) ; c = reader . read ( ) ; if ( c != '{' ) { sw . write ( '$' ) ; reader . reset ( ) ; } else { reader . mark ( 1 ) ; sw . write ( "${" ) ; processGSstring ( reader , sw ) ; } continue ; } if ( c == '\"' ) { sw . write ( '\\' ) ; } if ( c == '\n' || c == '\r' ) { if ( c == '\r' ) { reader . mark ( 1 ) ; c = reader . read ( ) ; if ( c != '\n' ) { reader . reset ( ) ; } } sw . write ( "\n" ) ; continue ; } sw . write ( c ) ; } endScript ( sw ) ; return sw . toString ( ) ; }
Parse the text document looking for <% or <% = and then call out to the appropriate handler otherwise copy the text directly into the script while escaping quotes .
5,389
private void groovyExpression ( Reader reader , StringWriter sw ) throws IOException { sw . write ( "${" ) ; int c ; while ( ( c = reader . read ( ) ) != - 1 ) { if ( c == '%' ) { c = reader . read ( ) ; if ( c != '>' ) { sw . write ( '%' ) ; } else { break ; } } if ( c != '\n' && c != '\r' ) { sw . write ( c ) ; } } sw . write ( "}" ) ; }
Closes the currently open write and writes out the following text as a GString expression until it reaches an end % > .
5,390
private void groovySection ( Reader reader , StringWriter sw ) throws IOException { sw . write ( "\"\"\");" ) ; int c ; while ( ( c = reader . read ( ) ) != - 1 ) { if ( c == '%' ) { c = reader . read ( ) ; if ( c != '>' ) { sw . write ( '%' ) ; } else { break ; } } sw . write ( c ) ; } sw . write ( ";\n" + printCommand ( ) + "(\"\"\"" ) ; }
Closes the currently open write and writes the following text as normal Groovy script code until it reaches an end % > .
5,391
public < T extends TypedTagLibrary > T createInvoker ( Class < T > type ) { ProxyImpl handler = new ProxyImpl ( ) ; Object proxy = Proxy . newProxyInstance ( type . getClassLoader ( ) , new Class [ ] { type } , handler ) ; handler . setMetaClass ( InvokerHelper . getMetaClass ( proxy . getClass ( ) ) ) ; return type . cast ( proxy ) ; }
Creates a type - safe invoker for calling taglibs .
5,392
public Script resolveScript ( String name ) throws JellyException { String shortName ; int dot = name . lastIndexOf ( '.' ) ; if ( dot > name . lastIndexOf ( '/' ) ) shortName = name . substring ( 0 , dot ) ; else shortName = name ; for ( Facet f : owner . webApp . facets ) { if ( f instanceof JellyCompatibleFacet && ! ( f instanceof JellyFacet ) ) { JellyCompatibleFacet jcf = ( JellyCompatibleFacet ) f ; for ( Class < ? extends AbstractTearOff < ? , ? extends Script , ? > > ct : jcf . getClassTearOffTypes ( ) ) { try { Script s = owner . loadTearOff ( ct ) . resolveScript ( shortName ) ; if ( s != null ) return s ; } catch ( Exception e ) { throw new JellyException ( "Failed to load " + shortName + " from " + jcf , e ) ; } } } } return super . resolveScript ( name ) ; }
Aside from looking into our own consult other facets that can handle Jelly - compatible scripts .
5,393
public static boolean isTraceEnabled ( StaplerRequest req ) { if ( TRACE ) return true ; if ( TRACE_PER_REQUEST && "true" . equals ( req . getHeader ( "X-Stapler-Trace" ) ) ) return true ; return false ; }
Checks if tracing is enabled for the given request . Tracing can be enabled globally with the stapler . trace = true system property . Tracing can be enabled per - request by setting stapler . trace . per - request = true and sending an X - Stapler - Trace header set to true with the request .
5,394
protected boolean isBasename ( String potentialPath ) { if ( ALLOW_VIEW_NAME_PATH_TRAVERSAL ) { return true ; } else { if ( potentialPath . contains ( "\\" ) || potentialPath . contains ( "/" ) ) { return false ; } return true ; } }
Ensure the path that is passed is only the name of the file and not a path
5,395
public S resolveScript ( String name ) throws E { if ( name . lastIndexOf ( '.' ) <= name . lastIndexOf ( '/' ) ) name += getDefaultScriptExtension ( ) ; if ( ! hasAllowedExtension ( name ) ) return null ; URL res = getResource ( name ) ; if ( res == null ) { int dot = name . lastIndexOf ( '.' ) ; if ( name . lastIndexOf ( '/' ) < dot ) res = getResource ( name . substring ( 0 , dot ) + ".default" + name . substring ( dot ) ) ; } if ( res != null ) return parseScript ( res ) ; return null ; }
Loads the script just from the target class without considering inherited scripts from its base types .
5,396
public static boolean isNameChar ( char c ) { if ( isLetter2 ( c ) ) return true ; else if ( c == '>' ) return false ; else if ( c == '.' || c == '-' || c == '_' || c == ':' || isExtender ( c ) ) return true ; else return false ; }
Returns true if the character is allowed to be a non - initial character in names according to the XML recommendation .
5,397
public ForwardToView with ( String varName , Object value ) { attributes . put ( varName , value ) ; return this ; }
Forwards to the view with specified attributes exposed as a variable binding .
5,398
private String [ ] toStrings ( Locale l ) { String v = ISO639_MAP . get ( l . getLanguage ( ) ) ; if ( v == null ) return new String [ ] { '_' + l . toString ( ) } ; else return new String [ ] { '_' + l . toString ( ) , '_' + v + l . toString ( ) . substring ( 2 ) } ; }
Some language codes have changed over time such as Hebrew from iw to he . This method returns all such variations in an array .
5,399
public static ResourceBundle load ( String jellyUrl ) { if ( jellyUrl . endsWith ( ".jelly" ) ) jellyUrl = jellyUrl . substring ( 0 , jellyUrl . length ( ) - ".jelly" . length ( ) ) ; JellyFacet facet = WebApp . getCurrent ( ) . getFacet ( JellyFacet . class ) ; return facet . resourceBundleFactory . create ( jellyUrl ) ; }
Loads the resource bundle associated with the Jelly script .