Exception Fact Sheet for "fop"

The goal of an Exception Fact Sheet is to reveal the design of exception handling in an application.

--Maxence, Martin

For feedback, please contact Martin

Table of contents

Basic Statistics

Number of Classes 2071
Number of Domain Exception Types (Thrown or Caught) 20
Number of Domain Checked Exception Types 8
Number of Domain Runtime Exception Types 9
Number of Domain Unknown Exception Types 3
nTh = Number of Throw 1349
nTh = Number of Throw in Catch 359
Number of Catch-Rethrow (may not be correct) 15
nC = Number of Catch 713
nCTh = Number of Catch with Throw 355
Number of Empty Catch (really Empty) 0
Number of Empty Catch (with comments) 31
Number of Empty Catch 31
nM = Number of Methods 13847
nbFunctionWithCatch = Number of Methods with Catch 512 / 13847
nbFunctionWithThrow = Number of Methods with Throw 949 / 13847
nbFunctionWithThrowS = Number of Methods with ThrowS 2353 / 13847
nbFunctionTransmitting = Number of Methods with "Throws" but NO catch, NO throw (only transmitting) 1815 / 13847
P1 = nCTh / nC 49.8% (0.498)
P2 = nMC / nM 3.7% (0.037)
P3 = nbFunctionWithThrow / nbFunction 6.9% (0.069)
P4 = nbFunctionTransmitting / nbFunction 13.1% (0.131)
P5 = nbThrowInCatch / nbThrow 26.6% (0.266)
R2 = nCatch / nThrow 0.529
A1 = Number of Caught Exception Types From External Libraries 39
A2 = Number of Reused Exception Types From External Libraries (thrown from application code) 26

W1 is a rough estimation of the richness of the exception model. It does not take into account the inheritance relationships between domain exceptions.

Proportion P1 measures the overall exception flow. According to our experience, it varies from 5% to 70%. Early-catch design generally yields a low P1, libraries that must warn clients about errors (e.g. databases) generally have a high P1.

Proportion P2 measures the dispersion of catch blocks in the application. According to our experience, it varies from 2% to 15%. A small P2 indicates a rather centralized management of errors.

R1 shows how many exceptions types from libraries (incl. JDK) are thrown from application code. For instance, IllegalArgumentException comes from the JDK but is used in many applications.

A1 measures the awareness of the application to library exceptions. A high value of A1 means either that the application is polluted with checked exceptions or that it is able to apply specific recovery depending on the library exception.

Exception Hierachy

Exception Map

Each exception that is used at least once in the project is a dot. A orange dot represents a domain exception that is defined in the application. A blue dot exception is defined in the JDK or in a library. The x-axis represents the number of times an exception is caught, the y-axis the number of times an exception is thrown.

Exceptions With State

State means fields. Number of exceptions with state: 5
FOPException
              package org.apache.fop.apps;public class FOPException extends SAXException {

    private static final String EXCEPTION_SEPARATOR = "\n---------\n";

    private String systemId;
    private int line;
    private int column;

    private String localizedMessage;

    /**
     * Constructs a new FOP exception with the specified detail message.
     * @param message the detail message.
     */
    public FOPException(String message) {
        super(message);
    }

    /**
     * Constructs a new FOP exception with the specified detail message and location.
     * @param message the detail message
     * @param systemId the system id of the FO document which is associated with the exception
     *                 may be null.
     * @param line line number in the FO document which is associated with the exception.
     * @param column clolumn number in the line which is associated with the exception.
     */
    public FOPException(String message, String systemId, int line, int column) {
        super(message);
        this.systemId = systemId;
        this.line = line;
        this.column = column;
    }

    /**
     * Constructs a new FOP exception with the specified detail message and location.
     * @param message the detail message.
     * @param locator the locator holding the location.
     */
    public FOPException(String message, Locator locator) {
        super(message);
        setLocator(locator);
    }


    /**
     * Constructs a new FOP exception with the specified cause.
     * @param cause the cause.
     */
    public FOPException(Exception cause) {
        super(cause);
    }

    /**
     * Constructs a new exception with the specified detail message and cause.
     * @param message  the detail message
     * @param cause the cause
     */
    public FOPException(String message, Exception cause) {
        super(message, cause);
    }

    /**
     * Set a location associated with the exception.
     * @param locator the locator holding the location.
     */
    public void setLocator(Locator locator) {
        if (locator != null) {
            this.systemId = locator.getSystemId();
            this.line = locator.getLineNumber();
            this.column = locator.getColumnNumber();
        }
    }

    /**
     * Set a location associated with the exception.
     * @param systemId the system id of the FO document which is associated with the exception;
     *                 may be null.
     * @param line line number in the FO document which is associated with the exception.
     * @param column column number in the line which is associated with the exception.
     */
    public void setLocation(String systemId, int line, int column) {
        this.systemId = systemId;
        this.line = line;
        this.column = column;
    }

    /**
     * Indicate whether a location was set.
     * @return whether a location was set
     */
    public boolean isLocationSet() {
        // TODO: this is actually a dangerous assumption: A line
        // number of 0 or -1 might be used to indicate an unknown line
        // number, while the system ID might still be of use.
        return line > 0;
    }

    /**
     * Returns the detail message string of this FOP exception.
     * If a location was set, the message is prepended with it in the
     * form
     * <pre>
     *  SystemId:LL:CC: &amp;the message&amp;
     * </pre>
     * (the format used by most GNU tools)
     * @return the detail message string of this FOP exception
     */
    public String getMessage() {
        if (isLocationSet()) {
            return systemId + ":" + line + ":" + column + ": " + super.getMessage();
        } else {
            return super.getMessage();
        }
    }

    /**
     * Attempts to recast the exception as other Throwable types.
     * @return the exception recast as another type if possible, otherwise null.
     */
    protected Throwable getRootException() {
        Throwable result = getException();

        if (result instanceof SAXException) {
            result = ((SAXException)result).getException();
        }
        if (result instanceof java.lang.reflect.InvocationTargetException) {
            result
                = ((java.lang.reflect.InvocationTargetException)result).getTargetException();
        }
        if (result != getException()) {
            return result;
        }
        return null;
    }

    /**
     * Prints this FOP exception and its backtrace to the standard error stream.
     */
    public void printStackTrace() {
        synchronized (System.err) {
            super.printStackTrace();
            if (getException() != null) {
                System.err.println(EXCEPTION_SEPARATOR);
                getException().printStackTrace();
            }
            if (getRootException() != null) {
                System.err.println(EXCEPTION_SEPARATOR);
                getRootException().printStackTrace();
            }
        }
    }

    /**
     * Prints this FOP exception and its backtrace to the specified print stream.
     * @param stream PrintStream to use for output
     */
    public void printStackTrace(java.io.PrintStream stream) {
        synchronized (stream) {
            super.printStackTrace(stream);
            if (getException() != null) {
                stream.println(EXCEPTION_SEPARATOR);
                getException().printStackTrace(stream);
            }
            if (getRootException() != null) {
                stream.println(EXCEPTION_SEPARATOR);
                getRootException().printStackTrace(stream);
            }
        }
    }

    /**
     * Prints this FOP exception and its backtrace to the specified print writer.
     * @param writer PrintWriter to use for output
     */
    public void printStackTrace(java.io.PrintWriter writer) {
        synchronized (writer) {
            super.printStackTrace(writer);
            if (getException() != null) {
                writer.println(EXCEPTION_SEPARATOR);
                getException().printStackTrace(writer);
            }
            if (getRootException() != null) {
                writer.println(EXCEPTION_SEPARATOR);
                getRootException().printStackTrace(writer);
            }
        }
    }

    /**
     * Sets the localized message for this exception.
     * @param msg the localized message
     */
    public void setLocalizedMessage(String msg) {
        this.localizedMessage = msg;
    }

    /** {@inheritDoc} */
    public String getLocalizedMessage() {
        if (this.localizedMessage != null) {
            return this.localizedMessage;
        } else {
            return super.getLocalizedMessage();
        }
    }



}
            
PropertyException
              package org.apache.fop.fo.expr;public class PropertyException extends FOPException {
    private String propertyName;

    /**
     * Constructor
     * @param detail string containing the detail message
     */
    public PropertyException(String detail) {
        super(detail);
    }

    /**
     * Constructor
     * @param cause the Exception causing this PropertyException
     */
    public PropertyException(Exception cause) {
        super(cause);
        if (cause instanceof PropertyException) {
            this.propertyName = ((PropertyException)cause).propertyName;
        }
    }

    /**
     * Sets the property context information.
     * @param propInfo the property info instance
     */
    public void setPropertyInfo(PropertyInfo propInfo) {
        setLocator(propInfo.getPropertyList().getFObj().getLocator());
        propertyName = propInfo.getPropertyMaker().getName();
    }

    /**
     * Sets the name of the property.
     * @param propertyName the property name
     */
    public void setPropertyName(String propertyName) {
        this.propertyName = propertyName;
    }

    /** {@inheritDoc} */
    public String getMessage() {
        if (propertyName != null) {
            return super.getMessage() + "; property:'" + propertyName + "'";
        } else {
            return super.getMessage();
        }
    }
}
            
PageProductionException
              package org.apache.fop.fo.pagination;public class PageProductionException extends RuntimeException {

    private static final long serialVersionUID = -5126033718398975158L;

    private String localizedMessage;
    private Locator locator;


    /**
     * Creates a new PageProductionException.
     * @param message the message
     */
    public PageProductionException(String message) {
        super(message);
    }

    /**
     * Creates a new PageProductionException.
     * @param message the message
     * @param locator the optional locator that points to the error in the source file
     */
    public PageProductionException(String message, Locator locator) {
        super(message);
        setLocator(locator);
    }


    /**
     * Set a location associated with the exception.
     * @param locator the locator holding the location.
     */
    public void setLocator(Locator locator) {
        this.locator = locator != null ? new LocatorImpl(locator) : null;
    }


    /**
     * Returns the locattion associated with the exception.
     * @return the locator or null if the location information is not available
     */
    public Locator getLocator() {
        return this.locator;
    }

    /**
     * Sets the localized message for this exception.
     * @param msg the localized message
     */
    public void setLocalizedMessage(String msg) {
        this.localizedMessage = msg;
    }

    /** {@inheritDoc} */
    public String getLocalizedMessage() {
        if (this.localizedMessage != null) {
            return this.localizedMessage;
        } else {
            return super.getLocalizedMessage();
        }
    }

    /** Exception factory for {@link PageProductionException}. */
    public static class PageProductionExceptionFactory implements ExceptionFactory {

        /** {@inheritDoc} */
        public Throwable createException(Event event) {
            Object obj = event.getParam("loc");
            Locator loc = (obj instanceof Locator ? (Locator)obj : null);
            String msg = EventFormatter.format(event, Locale.ENGLISH);
            PageProductionException ex = new PageProductionException(msg, loc);
            if (!Locale.ENGLISH.equals(Locale.getDefault())) {
                ex.setLocalizedMessage(EventFormatter.format(event));
            }
            return ex;
        }

        /** {@inheritDoc} */
        public Class<PageProductionException> getExceptionClass() {
            return PageProductionException.class;
        }

    }
}
            
NestedRuntimeException
              package org.apache.fop.render.afp.exceptions;public abstract class NestedRuntimeException extends RuntimeException {

    /** Root cause of this nested exception */
    private Throwable underlyingException;

    /**
     * Construct a <code>NestedRuntimeException</code> with the specified detail message.
     * @param msg The detail message.
     */
    public NestedRuntimeException(String msg) {
        super(msg);
    }

    /**
     * Construct a <code>NestedRuntimeException</code> with the specified
     * detail message and nested exception.
     * @param msg The detail message.
     * @param t The nested exception.
     */
    public NestedRuntimeException(String msg, Throwable t) {
        super(msg);
        underlyingException = t;

    }

    /**
     * Gets the original triggering exception
     * @return The original exception as a throwable.
     */
    public Throwable getUnderlyingException() {

        return underlyingException;

    }

    /**
     * Return the detail message, including the message from the nested
     * exception if there is one.
     * @return The detail message.
     */
    public String getMessage() {

        if (underlyingException == null) {
            return super.getMessage();
        } else {
            return super.getMessage()
            + "; nested exception is "
                + underlyingException.getClass().getName();
        }

    }

    /**
     * Print the composite message and the embedded stack trace to the specified stream.
     * @param ps the print stream
     */
    public void printStackTrace(PrintStream ps) {
        if (underlyingException == null) {
            super.printStackTrace(ps);
        } else {
            ps.println(this);
            underlyingException.printStackTrace(ps);
        }
    }

    /**
     * Print the composite message and the embedded stack trace to the specified writer.
     * @param pw the print writer
     */
    public void printStackTrace(PrintWriter pw) {
        if (underlyingException == null) {
            super.printStackTrace(pw);
        } else {
            pw.println(this);
            underlyingException.printStackTrace(pw);
        }
    }

}
            
LayoutException
              package org.apache.fop.layoutmgr;public class LayoutException extends RuntimeException {

    private static final long serialVersionUID = 5157080040923740433L;

    private String localizedMessage;
    private LayoutManager layoutManager;

    /**
     * Constructs a new layout exception with the specified detail message.
     * @param message the detail message.
     */
    public LayoutException(String message) {
        this(message, null);
    }

    /**
     * Constructs a new layout exception with the specified detail message.
     * @param message the detail message
     * @param lm the layout manager that throws the exception
     */
    public LayoutException(String message, LayoutManager lm) {
        super(message);
        this.layoutManager = lm;
    }

    /**
     * Sets the localized message for this exception.
     * @param msg the localized message
     */
    public void setLocalizedMessage(String msg) {
        this.localizedMessage = msg;
    }

    /** {@inheritDoc} */
    public String getLocalizedMessage() {
        if (this.localizedMessage != null) {
            return this.localizedMessage;
        } else {
            return super.getLocalizedMessage();
        }
    }

    /**
     * Returns the layout manager that detected the problem.
     * @return the layout manager (or null)
     */
    public LayoutManager getLayoutManager() {
        return this.layoutManager;
    }

    /** Exception factory for {@link LayoutException}. */
    public static class LayoutExceptionFactory implements ExceptionFactory {

        /** {@inheritDoc} */
        public Throwable createException(Event event) {
            Object source = event.getSource();
            LayoutManager lm = (source instanceof LayoutManager) ? (LayoutManager)source : null;
            String msg = EventFormatter.format(event, Locale.ENGLISH);
            LayoutException ex = new LayoutException(msg, lm);
            if (!Locale.ENGLISH.equals(Locale.getDefault())) {
                ex.setLocalizedMessage(EventFormatter.format(event));
            }
            return ex;
        }

        /** {@inheritDoc} */
        public Class<LayoutException> getExceptionClass() {
            return LayoutException.class;
        }

    }
}
            

Thrown Exceptions Summary

A (Domain) exception is defined in the application. A (Lib) exception is defined in the JDK or in a library. An exception can be thrown, thrown from within a catch, or declared in the signature of a method (usually for checked exceptions). Hovering over a number triggers showing code snippets from the application code.

Type Exception Thrown Thrown
from Catch
Declared
- Unknown 32
              
//in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
throw (SAXException)te.getCause();

              
//in src/java/org/apache/fop/tools/anttasks/Fop.java
throw ex;

              
//in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
throw pe;

              
//in src/java/org/apache/fop/fo/properties/PropertyMaker.java
throw propEx;

              
//in src/java/org/apache/fop/fo/FOTreeBuilder.java
throw e;

              
//in src/java/org/apache/fop/fo/expr/FunctionBase.java
throw e;

              
//in src/java/org/apache/fop/fo/expr/PropertyParser.java
throw exc;

              
//in src/java/org/apache/fop/fo/expr/RGBICCColorFunction.java
throw pe;

              
//in src/java/org/apache/fop/fo/expr/RGBNamedColorFunction.java
throw pe;

              
//in src/java/org/apache/fop/fo/flow/table/TablePart.java
throw e;

              
//in src/java/org/apache/fop/hyphenation/PatternParser.java
throw ex;

              
//in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
throw te;

              
//in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
throw ioe;

              
//in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
throw new
                IFException("Can't resolve page reference @ index: " + action.getPageIndex(), null);

              
//in src/java/org/apache/fop/render/intermediate/IFParser.java
throw (IFException)se.getCause();

              
//in src/java/org/apache/fop/render/intermediate/IFParser.java
throw (IFException)te.getCause();

              
//in src/java/org/apache/fop/render/intermediate/IFParser.java
throw te;

              
//in src/java/org/apache/fop/render/intermediate/IFParser.java
throw (SAXException)ife.getCause();

              
//in src/java/org/apache/fop/render/intermediate/IFRenderer.java
throw (IOException)ife.getCause();

              
//in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
throw e;

              
//in src/java/org/apache/fop/events/EventExceptionManager.java
throw factory.createException(event);

              
//in src/java/org/apache/fop/area/RenderPagesModel.java
throw re;

              
//in src/java/org/apache/fop/area/RenderPagesModel.java
throw (RuntimeException)e;

              
//in src/java/org/apache/fop/layoutmgr/inline/ContentLayoutManager.java
throw e;

              
//in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
throw e;

              
//in src/java/org/apache/fop/util/DefaultErrorListener.java
throw exc;

              
//in src/java/org/apache/fop/util/DefaultErrorListener.java
throw exc;

              
//in src/java/org/apache/fop/util/LogUtil.java
throw (FOPException)e;

              
//in src/java/org/apache/fop/cli/InputHandler.java
throw exc;

              
//in src/java/org/apache/fop/cli/CommandLineOptions.java
throw e;

              
//in src/java/org/apache/fop/cli/CommandLineOptions.java
throw e;

              
//in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
throw e;

            
- -
- Builder 7
              
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
throw (SAXException)te.getCause();

              
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
throw new
                IFException("Can't resolve page reference @ index: " + action.getPageIndex(), null);

              
// in src/java/org/apache/fop/render/intermediate/IFParser.java
throw (IFException)se.getCause();

              
// in src/java/org/apache/fop/render/intermediate/IFParser.java
throw (IFException)te.getCause();

              
// in src/java/org/apache/fop/render/intermediate/IFParser.java
throw (SAXException)ife.getCause();

              
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
throw (IOException)ife.getCause();

              
// in src/java/org/apache/fop/events/EventExceptionManager.java
throw factory.createException(event);

            
- -
- Variable 30
              
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
throw (SAXException)te.getCause();

              
// in src/java/org/apache/fop/tools/anttasks/Fop.java
throw ex;

              
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
throw pe;

              
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
throw propEx;

              
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
throw e;

              
// in src/java/org/apache/fop/fo/expr/FunctionBase.java
throw e;

              
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
throw exc;

              
// in src/java/org/apache/fop/fo/expr/RGBICCColorFunction.java
throw pe;

              
// in src/java/org/apache/fop/fo/expr/RGBNamedColorFunction.java
throw pe;

              
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
throw e;

              
// in src/java/org/apache/fop/hyphenation/PatternParser.java
throw ex;

              
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
throw te;

              
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
throw ioe;

              
// in src/java/org/apache/fop/render/intermediate/IFParser.java
throw (IFException)se.getCause();

              
// in src/java/org/apache/fop/render/intermediate/IFParser.java
throw (IFException)te.getCause();

              
// in src/java/org/apache/fop/render/intermediate/IFParser.java
throw te;

              
// in src/java/org/apache/fop/render/intermediate/IFParser.java
throw (SAXException)ife.getCause();

              
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
throw (IOException)ife.getCause();

              
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
throw e;

              
// in src/java/org/apache/fop/area/RenderPagesModel.java
throw re;

              
// in src/java/org/apache/fop/area/RenderPagesModel.java
throw (RuntimeException)e;

              
// in src/java/org/apache/fop/layoutmgr/inline/ContentLayoutManager.java
throw e;

              
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
throw e;

              
// in src/java/org/apache/fop/util/DefaultErrorListener.java
throw exc;

              
// in src/java/org/apache/fop/util/DefaultErrorListener.java
throw exc;

              
// in src/java/org/apache/fop/util/LogUtil.java
throw (FOPException)e;

              
// in src/java/org/apache/fop/cli/InputHandler.java
throw exc;

              
// in src/java/org/apache/fop/cli/CommandLineOptions.java
throw e;

              
// in src/java/org/apache/fop/cli/CommandLineOptions.java
throw e;

              
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
throw e;

            
- -
(Lib) IllegalArgumentException 243
              
// in src/java/org/apache/fop/apps/FOUserAgent.java
public void setFontBaseURL(String fontBaseUrl) { try { getFactory().getFontManager().setFontBaseURL(fontBaseUrl); } catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); } }
// in src/java/org/apache/fop/pdf/PDFObject.java
public String referencePDF() { if (!hasObjectNumber()) { throw new IllegalArgumentException( "Cannot reference this object. It doesn't have an object number"); } String ref = getObjectNumber() + " " + getGeneration() + " R"; return ref; }
// in src/java/org/apache/fop/pdf/PDFPattern.java
public void setName(String name) { if (name.indexOf(" ") >= 0) { throw new IllegalArgumentException( "Pattern name must not contain any spaces"); } this.patternName = name; }
// in src/java/org/apache/fop/pdf/Version.java
public static Version getValueOf(String version) { for (Version pdfVersion : Version.values()) { if (pdfVersion.toString().equals(version)) { return pdfVersion; } } throw new IllegalArgumentException("Invalid PDF version given: " + version); }
// in src/java/org/apache/fop/pdf/PDFFactory.java
public AbstractPDFStream makeFontFile(FontDescriptor desc) { if (desc.getFontType() == FontType.OTHER) { throw new IllegalArgumentException("Trying to embed unsupported font type: " + desc.getFontType()); } CustomFont font = getCustomFont(desc); InputStream in = null; try { Source source = font.getEmbedFileSource(); if (source == null && font.getEmbedResourceName() != null) { source = new StreamSource(this.getClass() .getResourceAsStream(font.getEmbedResourceName())); } if (source == null) { return null; } if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null && source.getSystemId() != null) { try { in = new java.net.URL(source.getSystemId()).openStream(); } catch (MalformedURLException e) { //TODO: Why construct a new exception here, when it is not thrown? new FileNotFoundException( "File not found. URL could not be resolved: " + e.getMessage()); } } if (in == null) { return null; } //Make sure the InputStream is decorated with a BufferedInputStream if (!(in instanceof java.io.BufferedInputStream)) { in = new java.io.BufferedInputStream(in); } if (in == null) { return null; } else { try { AbstractPDFStream embeddedFont; if (desc.getFontType() == FontType.TYPE0) { MultiByteFont mbfont = (MultiByteFont)font; FontFileReader reader = new FontFileReader(in); TTFSubSetFile subset = new TTFSubSetFile(); byte[] subsetFont = subset.readFont(reader, mbfont.getTTCName(), mbfont.getUsedGlyphs()); // Only TrueType CID fonts are supported now embeddedFont = new PDFTTFStream(subsetFont.length); ((PDFTTFStream)embeddedFont).setData(subsetFont, subsetFont.length); } else if (desc.getFontType() == FontType.TYPE1) { PFBParser parser = new PFBParser(); PFBData pfb = parser.parsePFB(in); embeddedFont = new PDFT1Stream(); ((PDFT1Stream)embeddedFont).setData(pfb); } else { byte[] file = IOUtils.toByteArray(in); embeddedFont = new PDFTTFStream(file.length); ((PDFTTFStream)embeddedFont).setData(file, file.length); } /* embeddedFont.getFilterList().addFilter("flate"); if (getDocument().isEncryptionActive()) { getDocument().applyEncryption(embeddedFont); } else { embeddedFont.getFilterList().addFilter("ascii-85"); }*/ return embeddedFont; } finally { in.close(); } } } catch (IOException ioe) { log.error( "Failed to embed font [" + desc + "] " + desc.getEmbedFontName(), ioe); return null; } }
// in src/java/org/apache/fop/pdf/PDFFactory.java
private CustomFont getCustomFont(FontDescriptor desc) { Typeface tempFont; if (desc instanceof LazyFont) { tempFont = ((LazyFont)desc).getRealFont(); } else { tempFont = (Typeface)desc; } if (!(tempFont instanceof CustomFont)) { throw new IllegalArgumentException( "FontDescriptor must be instance of CustomFont, but is a " + desc.getClass().getName()); } return (CustomFont)tempFont; }
// in src/java/org/apache/fop/pdf/PDFFont.java
protected PDFName getPDFNameForFontType(FontType fontType) { if (fontType == FontType.TYPE0) { return new PDFName(fontType.getName()); } else if (fontType == FontType.TYPE1) { return new PDFName(fontType.getName()); } else if (fontType == FontType.MMTYPE1) { return new PDFName(fontType.getName()); } else if (fontType == FontType.TYPE3) { return new PDFName(fontType.getName()); } else if (fontType == FontType.TRUETYPE) { return new PDFName(fontType.getName()); } else { throw new IllegalArgumentException("Unsupported font type: " + fontType.getName()); } }
// in src/java/org/apache/fop/pdf/PDFTextUtil.java
public void setTextRenderingMode(int mode) { if (mode < 0 || mode > 7) { throw new IllegalArgumentException( "Illegal value for text rendering mode. Expected: 0-7"); } if (mode != this.textRenderingMode) { writeTJ(); this.textRenderingMode = mode; write(this.textRenderingMode + " Tr\n"); } }
// in src/java/org/apache/fop/pdf/PDFText.java
protected String toPDFString() { if (getText() == null) { throw new IllegalArgumentException( "The text of this PDFText must not be empty"); } StringBuffer sb = new StringBuffer(64); sb.append("("); sb.append(escapeText(getText())); sb.append(")"); return sb.toString(); }
// in src/java/org/apache/fop/pdf/PDFCIDFont.java
protected String getPDFNameForCIDFontType(CIDFontType cidFontType) { if (cidFontType == CIDFontType.CIDTYPE0) { return cidFontType.getName(); } else if (cidFontType == CIDFontType.CIDTYPE2) { return cidFontType.getName(); } else { throw new IllegalArgumentException("Unsupported CID font type: " + cidFontType.getName()); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public static int outputIndirectObject(PDFObject object, OutputStream stream) throws IOException { if (!object.hasObjectNumber()) { throw new IllegalArgumentException("Not an indirect object"); } byte[] obj = encode(object.getObjectID()); stream.write(obj); int length = object.output(stream); byte[] endobj = encode("\nendobj\n"); stream.write(endobj); return obj.length + length + endobj.length; }
// in src/java/org/apache/fop/pdf/PDFFilterList.java
public void addFilter(String filterType) { if (filterType == null) { return; } if (filterType.equals("flate")) { addFilter(new FlateFilter()); } else if (filterType.equals("null")) { addFilter(new NullFilter()); } else if (filterType.equals("ascii-85")) { if (this.ignoreASCIIFilters) { return; //ignore ASCII filter } addFilter(new ASCII85Filter()); } else if (filterType.equals("ascii-hex")) { if (this.ignoreASCIIFilters) { return; //ignore ASCII filter } addFilter(new ASCIIHexFilter()); } else if (filterType.equals("")) { return; } else { throw new IllegalArgumentException( "Unsupported filter type in stream-filter-list: " + filterType); } }
// in src/java/org/apache/fop/pdf/PDFCIELabColorSpace.java
private PDFArray toPDFArray(String name, float[] whitePoint) { PDFArray wp = new PDFArray(); if (whitePoint == null || whitePoint.length != 3) { throw new IllegalArgumentException(name + " must be given an have 3 components"); } for (int i = 0; i < 3; i++) { wp.add(whitePoint[i]); } return wp; }
// in src/java/org/apache/fop/pdf/PDFShading.java
public void setName(String name) { if (name.indexOf(" ") >= 0) { throw new IllegalArgumentException( "Shading name must not contain any spaces"); } this.shadingName = name; }
// in src/java/org/apache/fop/pdf/VersionController.java
public static VersionController getFixedVersionController(Version version) { if (version.compareTo(Version.V1_4) < 0) { throw new IllegalArgumentException("The PDF version cannot be set below version 1.4"); } return new FixedVersion(version); }
// in src/java/org/apache/fop/pdf/PDFNumber.java
public static String doubleOut(double doubleDown, int dec) { if (dec < 0 || dec > 16) { throw new IllegalArgumentException("Parameter dec must be between 1 and 16"); } StringBuffer buf = new StringBuffer(); DoubleFormatUtil.formatDouble(doubleDown, dec, dec, buf); return buf.toString(); }
// in src/java/org/apache/fop/pdf/PDFNumber.java
protected String toPDFString() { if (getNumber() == null) { throw new IllegalArgumentException( "The number of this PDFNumber must not be empty"); } StringBuffer sb = new StringBuffer(64); sb.append(doubleOut(getNumber().doubleValue(), 10)); return sb.toString(); }
// in src/java/org/apache/fop/pdf/PDFName.java
private static void toHex(char ch, StringBuilder sb) { if (ch >= 256) { throw new IllegalArgumentException( "Only 8-bit characters allowed by this implementation"); } sb.append(DIGITS[ch >>> 4 & 0x0F]); sb.append(DIGITS[ch & 0x0F]); }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void parseArguments(String[] args) { if (args.length > 0) { int idx = 0; if ("--help".equals(args[idx]) || "-?".equals(args[idx]) || "-h".equals(args[idx])) { printHelp(); System.exit(0); } if (idx < args.length - 1 && "-c".equals(args[idx])) { String filename = args[idx + 1]; this.configFile = new File(filename); idx += 2; } if (idx < args.length - 1 && "-f".equals(args[idx])) { this.configMime = args[idx + 1]; idx += 2; } if (idx < args.length) { String name = args[idx]; this.outputFile = new File(name); if (this.outputFile.isDirectory()) { this.mode = GENERATE_RENDERED; this.outputMime = MimeConstants.MIME_PDF; } else if (FilenameUtils.getExtension(name).equalsIgnoreCase("pdf")) { this.mode = GENERATE_RENDERED; this.outputMime = MimeConstants.MIME_PDF; } else if (FilenameUtils.getExtension(name).equalsIgnoreCase("fo")) { this.mode = GENERATE_FO; } else if (FilenameUtils.getExtension(name).equalsIgnoreCase("xml")) { this.mode = GENERATE_XML; } else { throw new IllegalArgumentException( "Operating mode for the output file cannot be determined" + " or is unsupported: " + name); } idx++; } if (idx < args.length) { this.singleFamilyFilter = args[idx]; } } else { System.out.println("use --help or -? for usage information."); } }
// in src/java/org/apache/fop/fo/properties/IndentPropertyMaker.java
public void setPaddingCorresponding(int[] paddingCorresponding) { if ( ( paddingCorresponding == null ) || ( paddingCorresponding.length != 4 ) ) { throw new IllegalArgumentException(); } this.paddingCorresponding = paddingCorresponding; }
// in src/java/org/apache/fop/fo/properties/IndentPropertyMaker.java
public void setBorderWidthCorresponding(int[] borderWidthCorresponding) { if ( ( borderWidthCorresponding == null ) || ( borderWidthCorresponding.length != 4 ) ) { throw new IllegalArgumentException(); } this.borderWidthCorresponding = borderWidthCorresponding; }
// in src/java/org/apache/fop/fo/properties/DimensionPropertyMaker.java
public void setExtraCorresponding(int[][] extraCorresponding) { if ( extraCorresponding == null ) { throw new NullPointerException(); } for ( int i = 0; i < extraCorresponding.length; i++ ) { int[] eca = extraCorresponding[i]; if ( ( eca == null ) || ( eca.length != 4 ) ) { throw new IllegalArgumentException ( "bad sub-array @ [" + i + "]" ); } } this.extraCorresponding = extraCorresponding; }
// in src/java/org/apache/fop/fo/flow/table/EffRow.java
public boolean getFlag(int which) { if (which == FIRST_IN_PART) { return getGridUnit(0).getFlag(GridUnit.FIRST_IN_PART); } else if (which == LAST_IN_PART) { return getGridUnit(0).getFlag(GridUnit.LAST_IN_PART); } else { throw new IllegalArgumentException("Illegal flag queried: " + which); } }
// in src/java/org/apache/fop/fo/pagination/Root.java
public void notifyPageSequenceFinished(int lastPageNumber, int additionalPages) throws IllegalArgumentException { if (additionalPages >= 0) { totalPagesGenerated += additionalPages; endingPageNumberOfPreviousSequence = lastPageNumber; } else { throw new IllegalArgumentException( "Number of additional pages must be zero or greater."); } }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
public void addElementMapping(String mappingClassName) throws IllegalArgumentException { try { ElementMapping mapping = (ElementMapping)Class.forName(mappingClassName).newInstance(); addElementMapping(mapping); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + mappingClassName); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + mappingClassName); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + mappingClassName); } catch (ClassCastException e) { throw new IllegalArgumentException(mappingClassName + " is not an ElementMapping"); } }
// in src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java
public boolean isAttributeProperty(QName attributeName) { if (!URI.equals(attributeName.getNamespaceURI())) { throw new IllegalArgumentException("The namespace URIs don't match"); } return PROPERTY_ATTRIBUTES.contains(attributeName.getLocalName()); }
// in src/java/org/apache/fop/fo/extensions/InternalElementMapping.java
public boolean isAttributeProperty(QName attributeName) { if (!URI.equals(attributeName.getNamespaceURI())) { throw new IllegalArgumentException("The namespace URIs don't match"); } return PROPERTY_ATTRIBUTES.contains(attributeName.getLocalName()); }
// in src/java/org/apache/fop/svg/PDFGraphics2D.java
public void addNativeImage(org.apache.xmlgraphics.image.loader.Image image, float x, float y, float width, float height) { preparePainting(); String key = image.getInfo().getOriginalURI(); if (key == null) { // Need to include hash code as when invoked from FO you // may have several 'independent' PDFGraphics2D so the // count is not enough. key = "__AddNative_" + hashCode() + "_" + nativeCount; nativeCount++; } PDFImage pdfImage; if (image instanceof ImageRawJPEG) { pdfImage = new ImageRawJPEGAdapter((ImageRawJPEG)image, key); } else if (image instanceof ImageRawCCITTFax) { pdfImage = new ImageRawCCITTFaxAdapter((ImageRawCCITTFax)image, key); } else { throw new IllegalArgumentException( "Unsupported Image subclass: " + image.getClass().getName()); } PDFXObject xObject = this.pdfDoc.addImage(resourceContext, pdfImage); flushPDFDocument(); AffineTransform at = new AffineTransform(); at.translate(x, y); useXObject(xObject, at, width, height); }
// in src/java/org/apache/fop/fonts/EncodingMode.java
public static EncodingMode getEncodingMode(String name) { for (EncodingMode em : EncodingMode.values()) { if (name.equalsIgnoreCase(em.getName())) { return em; } } throw new IllegalArgumentException("Invalid encoding mode: " + name); }
// in src/java/org/apache/fop/fonts/SimpleSingleByteEncoding.java
public char addCharacter(NamedCharacter ch) { if (!ch.hasSingleUnicodeValue()) { throw new IllegalArgumentException("Only NamedCharacters with a single Unicode value" + " are currently supported!"); } if (isFull()) { throw new IllegalStateException("Encoding is full!"); } char newSlot = (char)(getLastChar() + 1); this.mapping.add(ch); this.charMap.put(Character.valueOf(ch.getSingleUnicodeValue()), Character.valueOf(newSlot)); return newSlot; }
// in src/java/org/apache/fop/fonts/SimpleSingleByteEncoding.java
public NamedCharacter getCharacterForIndex(int codePoint) { if (codePoint < 0 || codePoint > 255) { throw new IllegalArgumentException("codePoint must be between 0 and 255"); } if (codePoint <= getLastChar()) { return this.mapping.get(codePoint - 1); } else { return null; } }
// in src/java/org/apache/fop/fonts/CIDFontType.java
public static CIDFontType byName(String name) { if (name.equalsIgnoreCase(CIDFontType.CIDTYPE0.getName())) { return CIDFontType.CIDTYPE0; } else if (name.equalsIgnoreCase(CIDFontType.CIDTYPE2.getName())) { return CIDFontType.CIDTYPE2; } else { throw new IllegalArgumentException("Invalid CID font type: " + name); } }
// in src/java/org/apache/fop/fonts/CIDFontType.java
public static CIDFontType byValue(int value) { if (value == CIDFontType.CIDTYPE0.getValue()) { return CIDFontType.CIDTYPE0; } else if (value == CIDFontType.CIDTYPE2.getValue()) { return CIDFontType.CIDTYPE2; } else { throw new IllegalArgumentException("Invalid CID font type: " + value); } }
// in src/java/org/apache/fop/fonts/FontUtil.java
public static int parseCSS2FontWeight(String text) { int weight = 400; try { weight = Integer.parseInt(text); weight = ((int)weight / 100) * 100; weight = Math.max(weight, 100); weight = Math.min(weight, 900); } catch (NumberFormatException nfe) { //weight is no number, so convert symbolic name to number if (text.equals("normal")) { weight = 400; } else if (text.equals("bold")) { weight = 700; } else { throw new IllegalArgumentException( "Illegal value for font weight: '" + text + "'. Use one of: 100, 200, 300, " + "400, 500, 600, 700, 800, 900, " + "normal (=400), bold (=700)"); } } return weight; }
// in src/java/org/apache/fop/fonts/FontInfo.java
public FontTriplet[] fontLookup(String[] families, String style, int weight) { if (families.length == 0) { throw new IllegalArgumentException("Specify at least one font family"); } // try matching without substitutions List<FontTriplet> matchedTriplets = fontLookup(families, style, weight, false); // if there are no matching font triplets found try with substitutions if (matchedTriplets.size() == 0) { matchedTriplets = fontLookup(families, style, weight, true); } // no matching font triplets found! if (matchedTriplets.size() == 0) { StringBuffer sb = new StringBuffer(); for (int i = 0, c = families.length; i < c; i++) { if (i > 0) { sb.append(", "); } sb.append(families[i]); } throw new IllegalStateException( "fontLookup must return an array with at least one " + "FontTriplet on the last call. Lookup: " + sb.toString()); } FontTriplet[] fontTriplets = new FontTriplet[matchedTriplets.size()]; matchedTriplets.toArray(fontTriplets); // found some matching fonts so return them return fontTriplets; }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static CustomFont loadFont(String fontFileURI, String subFontName, boolean embedded, EncodingMode encodingMode, boolean useKerning, boolean useAdvanced, FontResolver resolver) throws IOException { fontFileURI = fontFileURI.trim(); boolean type1 = isType1(fontFileURI); FontLoader loader; if (type1) { if (encodingMode == EncodingMode.CID) { throw new IllegalArgumentException( "CID encoding mode not supported for Type 1 fonts"); } loader = new Type1FontLoader(fontFileURI, embedded, useKerning, resolver); } else { loader = new TTFFontLoader(fontFileURI, subFontName, embedded, encodingMode, useKerning, useAdvanced, resolver); } return loader.getFont(); }
// in src/java/org/apache/fop/fonts/FontType.java
public static FontType byName(String name) { if (name.equalsIgnoreCase(FontType.OTHER.getName())) { return FontType.OTHER; } else if (name.equalsIgnoreCase(FontType.TYPE0.getName())) { return FontType.TYPE0; } else if (name.equalsIgnoreCase(FontType.TYPE1.getName())) { return FontType.TYPE1; } else if (name.equalsIgnoreCase(FontType.MMTYPE1.getName())) { return FontType.MMTYPE1; } else if (name.equalsIgnoreCase(FontType.TYPE3.getName())) { return FontType.TYPE3; } else if (name.equalsIgnoreCase(FontType.TRUETYPE.getName())) { return FontType.TRUETYPE; } else { throw new IllegalArgumentException("Invalid font type: " + name); } }
// in src/java/org/apache/fop/fonts/FontType.java
public static FontType byValue(int value) { if (value == FontType.OTHER.getValue()) { return FontType.OTHER; } else if (value == FontType.TYPE0.getValue()) { return FontType.TYPE0; } else if (value == FontType.TYPE1.getValue()) { return FontType.TYPE1; } else if (value == FontType.MMTYPE1.getValue()) { return FontType.MMTYPE1; } else if (value == FontType.TYPE3.getValue()) { return FontType.TYPE3; } else if (value == FontType.TRUETYPE.getValue()) { return FontType.TRUETYPE; } else { throw new IllegalArgumentException("Invalid font type: " + value); } }
// in src/java/org/apache/fop/fonts/MultiByteFont.java
private GlyphSequence mapCharsToGlyphs ( CharSequence cs ) { IntBuffer cb = IntBuffer.allocate ( cs.length() ); IntBuffer gb = IntBuffer.allocate ( cs.length() ); int gi; int giMissing = findGlyphIndex ( Typeface.NOT_FOUND ); for ( int i = 0, n = cs.length(); i < n; i++ ) { int cc = cs.charAt ( i ); if ( ( cc >= 0xD800 ) && ( cc < 0xDC00 ) ) { if ( ( i + 1 ) < n ) { int sh = cc; int sl = cs.charAt ( ++i ); if ( ( sl >= 0xDC00 ) && ( sl < 0xE000 ) ) { cc = 0x10000 + ( ( sh - 0xD800 ) << 10 ) + ( ( sl - 0xDC00 ) << 0 ); } else { throw new IllegalArgumentException ( "ill-formed UTF-16 sequence, " + "contains isolated high surrogate at index " + i ); } } else { throw new IllegalArgumentException ( "ill-formed UTF-16 sequence, " + "contains isolated high surrogate at end of sequence" ); } } else if ( ( cc >= 0xDC00 ) && ( cc < 0xE000 ) ) { throw new IllegalArgumentException ( "ill-formed UTF-16 sequence, " + "contains isolated low surrogate at index " + i ); } notifyMapOperation(); gi = findGlyphIndex ( cc ); if ( gi == SingleByteEncoding.NOT_FOUND_CODE_POINT ) { warnMissingGlyph ( (char) cc ); gi = giMissing; } cb.put ( cc ); gb.put ( gi ); } cb.flip(); gb.flip(); return new GlyphSequence ( cb, gb, null ); }
// in src/java/org/apache/fop/fonts/type1/PFBData.java
public void setPFBFormat(int format) { switch (format) { case PFB_RAW: case PFB_PC: this.pfbFormat = format; break; case PFB_MAC: throw new UnsupportedOperationException("Mac format is not yet implemented"); default: throw new IllegalArgumentException("Invalid value for PFB format: " + format); } }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
private void buildFont(AFMFile afm, PFMFile pfm) { if (afm == null && pfm == null) { throw new IllegalArgumentException("Need at least an AFM or a PFM!"); } singleFont = new SingleByteFont(); singleFont.setFontType(FontType.TYPE1); singleFont.setResolver(this.resolver); if (this.embedded) { singleFont.setEmbedFileName(this.fontFileURI); } returnFont = singleFont; handleEncoding(afm, pfm); handleFontName(afm, pfm); handleMetrics(afm, pfm); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
public boolean readFont(FontFileReader in, String name) throws IOException { /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(in, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(in); readFontHeader(in); getNumGlyphs(in); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(in); readHorizontalMetrics(in); initAnsiWidths(); readPostScript(in); readOS2(in); determineAscDesc(); if (!isCFF) { readIndexToLocation(in); readGlyf(in); } readName(in); boolean pcltFound = readPCLT(in); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(in); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); if ( useKerning ) { readKerning(in); } // Read advanced typographic tables. if ( useAdvanced ) { try { OTFAdvancedTypographicTableReader atr = new OTFAdvancedTypographicTableReader ( this, in ); atr.readAll(); this.advancedTableReader = atr; } catch ( AdvancedTypographicTableFormatException e ) { log.warn ( "Encountered format constraint violation in advanced (typographic) table (AT) " + "in font '" + getFullName() + "', ignoring AT data: " + e.getMessage() ); } } guessVerticalMetricsFromGlyphBBox(); return true; }
// in src/java/org/apache/fop/render/print/PrintRenderer.java
private void setRendererOptions() { Map rendererOptions = getUserAgent().getRendererOptions(); Object printerJobO = rendererOptions.get(PrintRenderer.PRINTER_JOB); if (printerJobO != null) { if (!(printerJobO instanceof PrinterJob)) { throw new IllegalArgumentException( "Renderer option " + PrintRenderer.PRINTER_JOB + " must be an instance of java.awt.print.PrinterJob, but an instance of " + printerJobO.getClass().getName() + " was given."); } printerJob = (PrinterJob)printerJobO; printerJob.setPageable(this); } Object o = rendererOptions.get(PrintRenderer.COPIES); if (o != null) { this.copies = getPositiveInteger(o); } initializePrinterJob(); }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
private void processOptions(Map rendererOptions) { Object o = rendererOptions.get(PageableRenderer.PAGES_MODE); if (o != null) { if (o instanceof PagesMode) { this.mode = (PagesMode)o; } else if (o instanceof String) { this.mode = PagesMode.byName((String)o); } else { throw new IllegalArgumentException( "Renderer option " + PageableRenderer.PAGES_MODE + " must be an 'all', 'even', 'odd' or a PagesMode instance."); } } o = rendererOptions.get(PageableRenderer.START_PAGE); if (o != null) { this.startNumber = getPositiveInteger(o); } o = rendererOptions.get(PageableRenderer.END_PAGE); if (o != null) { this.endNumber = getPositiveInteger(o); } if (this.endNumber >= 0 && this.endNumber < this.endNumber) { this.endNumber = this.startNumber; } }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
protected int getPositiveInteger(Object o) { if (o instanceof Integer) { Integer i = (Integer)o; if (i.intValue() < 1) { throw new IllegalArgumentException( "Value must be a positive Integer"); } return i.intValue(); } else if (o instanceof String) { return Integer.parseInt((String)o); } else { throw new IllegalArgumentException( "Value must be a positive integer"); } }
// in src/java/org/apache/fop/render/print/PagesMode.java
public static PagesMode byName(String name) { if (PagesMode.ALL.getName().equalsIgnoreCase(name)) { return PagesMode.ALL; } else if (PagesMode.EVEN.getName().equalsIgnoreCase(name)) { return PagesMode.EVEN; } else if (PagesMode.ODD.getName().equalsIgnoreCase(name)) { return PagesMode.ODD; } else { throw new IllegalArgumentException("Invalid value for PagesMode: " + name); } }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private static boolean booleanValueOf(Object obj) { if (obj instanceof Boolean) { return ((Boolean)obj).booleanValue(); } else if (obj instanceof String) { return Boolean.valueOf((String)obj).booleanValue(); } else { throw new IllegalArgumentException("Boolean or \"true\" or \"false\" expected."); } }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
public void addXMLHandler(String classname) { try { XMLHandler handlerInstance = (XMLHandler)Class.forName(classname).newInstance(); addXMLHandler(handlerInstance); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); } catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + XMLHandler.class.getName()); } }
// in src/java/org/apache/fop/render/RendererFactory.java
public void addRendererMaker(String className) { try { AbstractRendererMaker makerInstance = (AbstractRendererMaker)Class.forName(className).newInstance(); addRendererMaker(makerInstance); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); } catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractRendererMaker.class.getName()); } }
// in src/java/org/apache/fop/render/RendererFactory.java
public void addFOEventHandlerMaker(String className) { try { AbstractFOEventHandlerMaker makerInstance = (AbstractFOEventHandlerMaker)Class.forName(className).newInstance(); addFOEventHandlerMaker(makerInstance); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); } catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractFOEventHandlerMaker.class.getName()); } }
// in src/java/org/apache/fop/render/RendererFactory.java
public void addDocumentHandlerMaker(String className) { try { AbstractIFDocumentHandlerMaker makerInstance = (AbstractIFDocumentHandlerMaker)Class.forName(className).newInstance(); addDocumentHandlerMaker(makerInstance); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); } catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractIFDocumentHandlerMaker.class.getName()); } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected Rectangle getLineBoundingBox(Point start, Point end, int width) { if (start.y == end.y) { int topy = start.y - width / 2; return new Rectangle( start.x, topy, end.x - start.x, width); } else if (start.x == end.y) { int leftx = start.x - width / 2; return new Rectangle( leftx, start.x, width, end.y - start.y); } else { throw new IllegalArgumentException( "Only horizontal or vertical lines are supported at the moment."); } }
// in src/java/org/apache/fop/render/intermediate/IFUtil.java
public static int[][] copyDP ( int[][] dp, int offset, int count ) { if ( ( dp == null ) || ( offset > dp.length ) || ( ( offset + count ) > dp.length ) ) { throw new IllegalArgumentException(); } else { int[][] dpNew = new int [ count ] [ 4 ]; for ( int i = 0, n = count; i < n; i++ ) { int[] paDst = dpNew [ i ]; int[] paSrc = dp [ i + offset ]; for ( int k = 0; k < 4; k++ ) { paDst [ k ] = paSrc [ k ]; } } return dpNew; } }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void setResult(Result result) throws IFException { if (result instanceof StreamResult) { StreamResult streamResult = (StreamResult)result; OutputStream out = streamResult.getOutputStream(); if (out == null) { if (streamResult.getWriter() != null) { throw new IllegalArgumentException( "FOP cannot use a Writer. Please supply an OutputStream!"); } try { URL url = new URL(streamResult.getSystemId()); File f = FileUtils.toFile(url); if (f != null) { out = new java.io.FileOutputStream(f); } else { out = url.openConnection().getOutputStream(); } } catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); } out = new java.io.BufferedOutputStream(out); this.ownOutputStream = true; } if (out == null) { throw new IllegalArgumentException("Need a StreamResult with an OutputStream"); } this.outputStream = out; } else { throw new UnsupportedOperationException( "Unsupported Result subclass: " + result.getClass().getName()); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
private void renderDestination(DestinationData dd) { if (!hasDocumentNavigation()) { return; } String targetID = dd.getIDRef(); if (targetID == null || targetID.length() == 0) { throw new IllegalArgumentException("DestinationData must contain a ID reference"); } PageViewport pv = dd.getPageViewport(); if (pv != null) { GoToXYAction action = getGoToActionForID(targetID, pv.getPageIndex()); NamedDestination namedDestination = new NamedDestination(targetID, action); this.deferredDestinations.add(namedDestination); } else { //Warning already issued by AreaTreeHandler (debug level is sufficient) log.debug("Unresolved destination item received: " + dd.getIDRef()); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
private Bookmark renderBookmarkItem(BookmarkData bookmarkItem) { String targetID = bookmarkItem.getIDRef(); if (targetID == null || targetID.length() == 0) { throw new IllegalArgumentException("DestinationData must contain a ID reference"); } GoToXYAction action = null; PageViewport pv = bookmarkItem.getPageViewport(); if (pv != null) { action = getGoToActionForID(targetID, pv.getPageIndex()); } else { //Warning already issued by AreaTreeHandler (debug level is sufficient) log.debug("Bookmark with IDRef \"" + targetID + "\" has a null PageViewport."); } Bookmark b = new Bookmark( bookmarkItem.getBookmarkTitle(), bookmarkItem.showChildItems(), action); for (int i = 0; i < bookmarkItem.getCount(); i++) { b.addChildBookmark(renderBookmarkItem(bookmarkItem.getSubData(i))); } return b; }
// in src/java/org/apache/fop/render/intermediate/extensions/ActionSet.java
public synchronized String generateNewID(AbstractAction action) { this.lastGeneratedID++; String prefix = action.getIDPrefix(); if (prefix == null) { throw new IllegalArgumentException("Action class is not compatible"); } return prefix + this.lastGeneratedID; }
// in src/java/org/apache/fop/render/pcl/PCLRenderingMode.java
public static PCLRenderingMode valueOf(String name) { if (QUALITY.getName().equalsIgnoreCase(name)) { return QUALITY; } else if (SPEED.getName().equalsIgnoreCase(name)) { return SPEED; } else if (BITMAP.getName().equalsIgnoreCase(name)) { return BITMAP; } else { throw new IllegalArgumentException("Illegal value for enumeration: " + name); } }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void paintMonochromeBitmap(RenderedImage img, int resolution) throws IOException { if (!isValidPCLResolution(resolution)) { throw new IllegalArgumentException("Invalid PCL resolution: " + resolution); } boolean monochrome = isMonochromeImage(img); if (!monochrome) { throw new IllegalArgumentException("img must be a monochrome image"); } setRasterGraphicsResolution(resolution); writeCommand("*r0f" + img.getHeight() + "t" + img.getWidth() + "s1A"); Raster raster = img.getData(); Encoder encoder = new Encoder(img); // Transfer graphics data int imgw = img.getWidth(); IndexColorModel cm = (IndexColorModel)img.getColorModel(); if (cm.getTransferType() == DataBuffer.TYPE_BYTE) { DataBufferByte dataBuffer = (DataBufferByte)raster.getDataBuffer(); MultiPixelPackedSampleModel packedSampleModel = new MultiPixelPackedSampleModel( DataBuffer.TYPE_BYTE, img.getWidth(), img.getHeight(), 1); if (img.getSampleModel().equals(packedSampleModel) && dataBuffer.getNumBanks() == 1) { //Optimized packed encoding byte[] buf = dataBuffer.getData(); int scanlineStride = packedSampleModel.getScanlineStride(); int idx = 0; int c0 = toGray(cm.getRGB(0)); int c1 = toGray(cm.getRGB(1)); boolean zeroIsWhite = c0 > c1; for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { for (int x = 0, maxx = scanlineStride; x < maxx; x++) { if (zeroIsWhite) { encoder.add8Bits(buf[idx]); } else { encoder.add8Bits((byte)~buf[idx]); } idx++; } encoder.endLine(); } } else { //Optimized non-packed encoding for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { byte[] line = (byte[])raster.getDataElements(0, y, imgw, 1, null); for (int x = 0, maxx = imgw; x < maxx; x++) { encoder.addBit(line[x] == 0); } encoder.endLine(); } } } else { //Safe but slow fallback for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { for (int x = 0, maxx = imgw; x < maxx; x++) { int sample = raster.getSample(x, y, 0); encoder.addBit(sample == 0); } encoder.endLine(); } } // End raster graphics writeCommand("*rB"); }
// in src/java/org/apache/fop/render/afp/AFPShadingMode.java
public static AFPShadingMode valueOf(String name) { if (COLOR.getName().equalsIgnoreCase(name)) { return COLOR; } else if (DITHERED.getName().equalsIgnoreCase(name)) { return DITHERED; } else { throw new IllegalArgumentException("Illegal value for enumeration: " + name); } }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
public void addHandler(String classname) { try { ImageHandler handlerInstance = (ImageHandler)Class.forName(classname).newInstance(); addHandler(handlerInstance); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); } catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ImageHandler.class.getName()); } }
// in src/java/org/apache/fop/render/ps/PSRenderingUtil.java
private boolean booleanValueOf(Object obj) { if (obj instanceof Boolean) { return ((Boolean)obj).booleanValue(); } else if (obj instanceof String) { return Boolean.valueOf((String)obj).booleanValue(); } else { throw new IllegalArgumentException("Boolean or \"true\" or \"false\" expected."); } }
// in src/java/org/apache/fop/render/ps/PSRenderingUtil.java
private int intValueOf(Object obj) { if (obj instanceof Integer) { return ((Integer)obj).intValue(); } else if (obj instanceof String) { return Integer.parseInt((String)obj); } else { throw new IllegalArgumentException("Integer or String with a number expected."); } }
// in src/java/org/apache/fop/render/ps/PSRenderingUtil.java
public void setLanguageLevel(int level) { if (level == 2 || level == 3) { this.languageLevel = level; } else { throw new IllegalArgumentException("Only language levels 2 or 3 are allowed/supported"); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
protected PSResource getFormForImage(String uri) { if (uri == null || "".equals(uri)) { throw new IllegalArgumentException("uri must not be empty or null"); } if (this.formResources == null) { this.formResources = new java.util.HashMap(); } PSResource form = (PSResource)this.formResources.get(uri); if (form == null) { form = new PSImageFormResource(this.formResources.size() + 1, uri); this.formResources.put(uri, form); } return form; }
// in src/java/org/apache/fop/render/java2d/CustomFontMetricsMapper.java
private void initialize(final Source source) throws FontFormatException, IOException { int type = Font.TRUETYPE_FONT; if (FontType.TYPE1.equals(typeface.getFontType())) { type = TYPE1_FONT; //Font.TYPE1_FONT; only available in Java 1.5 } InputStream is = null; if (source instanceof StreamSource) { is = ((StreamSource) source).getInputStream(); } else if (source.getSystemId() != null) { is = new java.net.URL(source.getSystemId()).openStream(); } else { throw new IllegalArgumentException("No font source provided."); } this.font = Font.createFont(type, is); is.close(); }
// in src/java/org/apache/fop/render/extensions/prepress/PageBoundaries.java
private void calculate(Dimension pageSize, String bleed, String cropOffset, String cropBoxSelector) { this.trimBox = new Rectangle(pageSize); this.bleedBox = getBleedBoxRectangle(this.trimBox, bleed); Rectangle cropMarksBox = getCropMarksAreaRectangle(trimBox, cropOffset); //MediaBox includes all of the following three rectangles this.mediaBox = new Rectangle(); this.mediaBox.add(this.trimBox); this.mediaBox.add(this.bleedBox); this.mediaBox.add(cropMarksBox); if ("trim-box".equals(cropBoxSelector)) { this.cropBox = this.trimBox; } else if ("bleed-box".equals(cropBoxSelector)) { this.cropBox = this.bleedBox; } else if ("media-box".equals(cropBoxSelector) || cropBoxSelector == null || "".equals(cropBoxSelector)) { this.cropBox = this.mediaBox; } else { final String err = "The crop-box has invalid value: {0}, " + "possible values of crop-box: (trim-box|bleed-box|media-box)"; throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{cropBoxSelector})); } }
// in src/java/org/apache/fop/render/extensions/prepress/PageBoundaries.java
private static Rectangle getRectangleUsingOffset(Rectangle originalRect, String offset) { if (offset == null || "".equals(offset) || originalRect == null) { return originalRect; } String[] offsets = WHITESPACE_PATTERN.split(offset); int[] coords = new int[4]; // top, right, bottom, left switch (offsets.length) { case 1: coords[0] = getLengthIntValue(offsets[0]); coords[1] = coords[0]; coords[2] = coords[0]; coords[3] = coords[0]; break; case 2: coords[0] = getLengthIntValue(offsets[0]); coords[1] = getLengthIntValue(offsets[1]); coords[2] = coords[0]; coords[3] = coords[1]; break; case 3: coords[0] = getLengthIntValue(offsets[0]); coords[1] = getLengthIntValue(offsets[1]); coords[2] = getLengthIntValue(offsets[2]); coords[3] = coords[1]; break; case 4: coords[0] = getLengthIntValue(offsets[0]); coords[1] = getLengthIntValue(offsets[1]); coords[2] = getLengthIntValue(offsets[2]); coords[3] = getLengthIntValue(offsets[3]); break; default: // TODO throw appropriate exception that can be caught by the event // notification mechanism throw new IllegalArgumentException("Too many arguments"); } return new Rectangle(originalRect.x - coords[3], originalRect.y - coords[0], originalRect.width + coords[3] + coords[1], originalRect.height + coords[0] + coords[2]); }
// in src/java/org/apache/fop/render/extensions/prepress/PageBoundaries.java
private static int getLengthIntValue(final String length) { final String err = "Incorrect length value: {0}"; Matcher m = SIZE_UNIT_PATTERN.matcher(length); if (m.find()) { return FixedLength.getInstance(Double.parseDouble(m.group(1)), m.group(2)).getLength().getValue(); } else { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{length})); } }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
public static Point2D getScale(String scale) { // TODO throw appropriate exceptions that can be caught by the event // notification mechanism final String err = "Extension 'scale' attribute has incorrect value(s): {0}"; if (scale == null || scale.equals("")) { return null; } String[] scales = WHITESPACE_PATTERN.split(scale); double scaleX; try { scaleX = Double.parseDouble(scales[0]); } catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); } double scaleY; switch (scales.length) { case 1: scaleY = scaleX; break; case 2: try { scaleY = Double.parseDouble(scales[1]); } catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); } break; default: throw new IllegalArgumentException("Too many arguments"); } if (scaleX <= 0 || scaleY <= 0) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); } return new Point2D.Double(scaleX, scaleY); }
// in src/java/org/apache/fop/afp/AFPDataObjectFactory.java
public ImageObject createImage(AFPImageObjectInfo imageObjectInfo) { // IOCA bitmap image ImageObject imageObj = factory.createImageObject(); // set data object viewport (i.e. position, rotation, dimension, resolution) imageObj.setViewport(imageObjectInfo); if (imageObjectInfo.hasCompression()) { int compression = imageObjectInfo.getCompression(); switch (compression) { case TIFFImage.COMP_FAX_G3_1D: imageObj.setEncoding(ImageContent.COMPID_G3_MH); break; case TIFFImage.COMP_FAX_G3_2D: imageObj.setEncoding(ImageContent.COMPID_G3_MR); break; case TIFFImage.COMP_FAX_G4_2D: imageObj.setEncoding(ImageContent.COMPID_G3_MMR); break; case ImageContent.COMPID_JPEG: imageObj.setEncoding((byte)compression); break; default: throw new IllegalStateException( "Invalid compression scheme: " + compression); } } ImageContent content = imageObj.getImageSegment().getImageContent(); int bitsPerPixel = imageObjectInfo.getBitsPerPixel(); imageObj.setIDESize((byte) bitsPerPixel); IDEStructureParameter ideStruct; switch (bitsPerPixel) { case 1: //Skip IDE Structure Parameter break; case 4: case 8: //A grayscale image ideStruct = content.needIDEStructureParameter(); ideStruct.setBitsPerComponent(new int[] {bitsPerPixel}); ideStruct.setColorModel(IDEStructureParameter.COLOR_MODEL_YCBCR); break; case 24: ideStruct = content.needIDEStructureParameter(); ideStruct.setDefaultRGBColorModel(); break; case 32: ideStruct = content.needIDEStructureParameter(); ideStruct.setDefaultCMYKColorModel(); break; default: throw new IllegalArgumentException("Unsupported number of bits per pixel: " + bitsPerPixel); } if (bitsPerPixel > 1 && imageObjectInfo.isSubtractive()) { ideStruct = content.needIDEStructureParameter(); ideStruct.setSubtractive(imageObjectInfo.isSubtractive()); } imageObj.setData(imageObjectInfo.getData()); return imageObj; }
// in src/java/org/apache/fop/afp/fonts/CharactersetEncoder.java
public void writeTo(OutputStream out, int offset, int length) throws IOException { if (offset < 0 || length < 0 || offset + length > bytes.length) { throw new IllegalArgumentException(); } out.write(bytes, this.offset + offset, length); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetOrientation.java
public int getWidth(char character) { if (character >= charsWidths.length) { throw new IllegalArgumentException("Invalid character: " + character + " (" + Integer.toString(character) + "), maximum is " + (charsWidths.length - 1)); } return charsWidths[character]; }
// in src/java/org/apache/fop/afp/AFPPaintingState.java
public void setPortraitRotation(int rotation) { if (rotation == 0 || rotation == 90 || rotation == 180 || rotation == 270) { portraitRotation = rotation; } else { throw new IllegalArgumentException("The portrait rotation must be one" + " of the values 0, 90, 180, 270"); } }
// in src/java/org/apache/fop/afp/AFPPaintingState.java
public void setLandscapeRotation(int rotation) { if (rotation == 0 || rotation == 90 || rotation == 180 || rotation == 270) { landscapeRotation = rotation; } else { throw new IllegalArgumentException("The landscape rotation must be one" + " of the values 0, 90, 180, 270"); } }
// in src/java/org/apache/fop/afp/modca/MapPageSegment.java
public void addPageSegment(String name) throws MaximumSizeExceededException { if (getPageSegments().size() > MAX_SIZE) { throw new MaximumSizeExceededException(); } if (name.length() > 8) { throw new IllegalArgumentException("The name of page segment " + name + " must not be longer than 8 characters"); } if (LOG.isDebugEnabled()) { LOG.debug("addPageSegment():: adding page segment " + name); } getPageSegments().add(name); }
// in src/java/org/apache/fop/afp/modca/AxisOrientation.java
public static AxisOrientation getRightHandedAxisOrientationFor(int orientation) { switch (orientation) { case 0: return RIGHT_HANDED_0; case 90: return RIGHT_HANDED_90; case 180: return RIGHT_HANDED_180; case 270: return RIGHT_HANDED_270; default: throw new IllegalArgumentException( "The orientation must be one of the values 0, 90, 180, 270"); } }
// in src/java/org/apache/fop/afp/modca/IncludePageOverlay.java
public void setOrientation(int orientation) { if (orientation == 0 || orientation == 90 || orientation == 180 || orientation == 270) { this.orientation = orientation; } else { throw new IllegalArgumentException( "The orientation must be one of the values 0, 90, 180, 270"); } }
// in src/java/org/apache/fop/afp/modca/triplets/AttributeValueTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = super.getData(); data[2] = 0x00; // Reserved data[3] = 0x00; // Reserved // convert name and value to ebcdic byte[] tleByteValue = null; try { tleByteValue = attVal.getBytes(AFPConstants.EBCIDIC_ENCODING); } catch (UnsupportedEncodingException usee) { tleByteValue = attVal.getBytes(); throw new IllegalArgumentException(attVal + " encoding failed"); } System.arraycopy(tleByteValue, 0, data, 4, tleByteValue.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/FullyQualifiedNameTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = type; data[3] = format; // FQName byte[] fqNameBytes; String encoding = AFPConstants.EBCIDIC_ENCODING; if (format == FORMAT_URL) { encoding = AFPConstants.US_ASCII_ENCODING; } try { fqNameBytes = fqName.getBytes(encoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( encoding + " encoding failed"); } System.arraycopy(fqNameBytes, 0, data, 4, fqNameBytes.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
public void addFont(int fontReference, AFPFont font, int size, int orientation) throws MaximumSizeExceededException { FontDefinition fontDefinition = new FontDefinition(); fontDefinition.fontReferenceKey = BinaryUtils.convert(fontReference)[0]; switch (orientation) { case 90: fontDefinition.orientation = 0x2D; break; case 180: fontDefinition.orientation = 0x5A; break; case 270: fontDefinition.orientation = (byte) 0x87; break; default: fontDefinition.orientation = 0x00; break; } try { if (font instanceof RasterFont) { RasterFont raster = (RasterFont) font; CharacterSet cs = raster.getCharacterSet(size); if (cs == null) { String msg = "Character set not found for font " + font.getFontName() + " with point size " + size; LOG.error(msg); throw new FontRuntimeException(msg); } fontDefinition.characterSet = cs.getNameBytes(); if (fontDefinition.characterSet.length != 8) { throw new IllegalArgumentException("The character set " + new String(fontDefinition.characterSet, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof OutlineFont) { OutlineFont outline = (OutlineFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof DoubleByteFont) { DoubleByteFont outline = (DoubleByteFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); //TODO Relax requirement for 8 characters if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else { String msg = "Font of type " + font.getClass().getName() + " not recognized."; LOG.error(msg); throw new FontRuntimeException(msg); } if (fontList.size() > 253) { // Throw an exception if the size is exceeded throw new MaximumSizeExceededException(); } else { fontList.add(fontDefinition); } } catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); } }
// in src/java/org/apache/fop/afp/modca/InterchangeSet.java
public static InterchangeSet valueOf(String str) { if (MODCA_PRESENTATION_INTERCHANGE_SET_1.equals(str)) { return new InterchangeSet(SET_1); } else if (MODCA_PRESENTATION_INTERCHANGE_SET_2.equals(str)) { return new InterchangeSet(SET_2); } else if (MODCA_RESOURCE_INTERCHANGE_SET.equals(str)) { return new InterchangeSet(RESOURCE_SET); } else { throw new IllegalArgumentException("Invalid MO:DCA interchange set :" + str); } }
// in src/java/org/apache/fop/afp/modca/MapPageOverlay.java
public void addOverlay(String name) throws MaximumSizeExceededException { if (getOverlays().size() > MAX_SIZE) { throw new MaximumSizeExceededException(); } if (name.length() != 8) { throw new IllegalArgumentException("The name of overlay " + name + " must be 8 characters"); } if (LOG.isDebugEnabled()) { LOG.debug("addOverlay():: adding overlay " + name); } try { byte[] data = name.getBytes(AFPConstants.EBCIDIC_ENCODING); getOverlays().add(data); } catch (UnsupportedEncodingException usee) { LOG.error("addOverlay():: UnsupportedEncodingException translating the name " + name); } }
// in src/java/org/apache/fop/afp/util/CubicBezierApproximator.java
public static double[][] fixedMidPointApproximation(double[] cubicControlPointCoords) { if (cubicControlPointCoords.length < 8) { throw new IllegalArgumentException("Must have at least 8 coordinates"); } //extract point objects from source array Point2D p0 = new Point2D.Double(cubicControlPointCoords[0], cubicControlPointCoords[1]); Point2D p1 = new Point2D.Double(cubicControlPointCoords[2], cubicControlPointCoords[3]); Point2D p2 = new Point2D.Double(cubicControlPointCoords[4], cubicControlPointCoords[5]); Point2D p3 = new Point2D.Double(cubicControlPointCoords[6], cubicControlPointCoords[7]); //calculates the useful base points Point2D pa = getPointOnSegment(p0, p1, 3.0 / 4.0); Point2D pb = getPointOnSegment(p3, p2, 3.0 / 4.0); //get 1/16 of the [P3, P0] segment double dx = (p3.getX() - p0.getX()) / 16.0; double dy = (p3.getY() - p0.getY()) / 16.0; //calculates control point 1 Point2D pc1 = getPointOnSegment(p0, p1, 3.0 / 8.0); //calculates control point 2 Point2D pc2 = getPointOnSegment(pa, pb, 3.0 / 8.0); pc2 = movePoint(pc2, -dx, -dy); //calculates control point 3 Point2D pc3 = getPointOnSegment(pb, pa, 3.0 / 8.0); pc3 = movePoint(pc3, dx, dy); //calculates control point 4 Point2D pc4 = getPointOnSegment(p3, p2, 3.0 / 8.0); //calculates the 3 anchor points Point2D pa1 = getMidPoint(pc1, pc2); Point2D pa2 = getMidPoint(pa, pb); Point2D pa3 = getMidPoint(pc3, pc4); //return the points for the four quadratic curves return new double[][] { {pc1.getX(), pc1.getY(), pa1.getX(), pa1.getY()}, {pc2.getX(), pc2.getY(), pa2.getX(), pa2.getY()}, {pc3.getX(), pc3.getY(), pa3.getX(), pa3.getY()}, {pc4.getX(), pc4.getY(), p3.getX(), p3.getY()}}; }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
private static String getResourceName(UnparsedStructuredField field) throws UnsupportedEncodingException { //The first 8 bytes of the field data represent the resource name byte[] nameBytes = new byte[8]; byte[] fieldData = field.getData(); if (fieldData.length < 8) { throw new IllegalArgumentException("Field data does not contain a resource name"); } System.arraycopy(fieldData, 0, nameBytes, 0, 8); return new String(nameBytes, AFPConstants.EBCIDIC_ENCODING); }
// in src/java/org/apache/fop/afp/util/BinaryUtils.java
public static byte[] convert(String digits) { if (digits.length() % 2 == 0) { // Even number of digits, so ignore } else { // Convert to an even number of digits digits = "0" + digits; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int i = 0; i < digits.length(); i += 2) { char c1 = digits.charAt(i); char c2 = digits.charAt(i + 1); byte b = 0; if ((c1 >= '0') && (c1 <= '9')) { b += ((c1 - '0') * 16); } else if ((c1 >= 'a') && (c1 <= 'f')) { b += ((c1 - 'a' + 10) * 16); } else if ((c1 >= 'A') && (c1 <= 'F')) { b += ((c1 - 'A' + 10) * 16); } else { throw new IllegalArgumentException("Bad hexadecimal digit"); } if ((c2 >= '0') && (c2 <= '9')) { b += (c2 - '0'); } else if ((c2 >= 'a') && (c2 <= 'f')) { b += (c2 - 'a' + 10); } else if ((c2 >= 'A') && (c2 <= 'F')) { b += (c2 - 'A' + 10); } else { throw new IllegalArgumentException("Bad hexadecimal digit"); } baos.write(b); } return (baos.toByteArray()); }
// in src/java/org/apache/fop/afp/ioca/IDEStructureParameter.java
public void setUniformBitsPerComponent(int numComponents, int bitsPerComponent) { if (bitsPerComponent < 0 || bitsPerComponent >= 256) { throw new IllegalArgumentException( "The number of bits per component must be between 0 and 255"); } this.bitsPerIDE = new byte[numComponents]; for (int i = 0; i < numComponents; i++) { this.bitsPerIDE[i] = (byte)bitsPerComponent; } }
// in src/java/org/apache/fop/afp/ioca/IDEStructureParameter.java
public void setBitsPerComponent(int[] bitsPerComponent) { int numComponents = bitsPerComponent.length; this.bitsPerIDE = new byte[numComponents]; for (int i = 0; i < numComponents; i++) { int bits = bitsPerComponent[i]; if (bits < 0 || bits >= 256) { throw new IllegalArgumentException( "The number of bits per component must be between 0 and 255"); } this.bitsPerIDE[i] = (byte)bits; } }
// in src/java/org/apache/fop/afp/ioca/ImageOutputControl.java
public void setOrientation(int orientation) { if (orientation == 0 || orientation == 90 || orientation == 180 || orientation == 270) { this.orientation = orientation; } else { throw new IllegalArgumentException( "The orientation must be one of the values 0, 90, 180, 270"); } }
// in src/java/org/apache/fop/afp/AFPResourceLevelDefaults.java
private static byte getResourceType(String resourceTypeName) { Byte result = (Byte)RESOURCE_TYPE_NAMES.get(resourceTypeName.toLowerCase()); if (result == null) { throw new IllegalArgumentException("Unknown resource type name: " + resourceTypeName); } return result.byteValue(); }
// in src/java/org/apache/fop/events/EventExceptionManager.java
public static void throwException(Event event, String exceptionClass) throws Throwable { if (exceptionClass != null) { ExceptionFactory factory = (ExceptionFactory)EXCEPTION_FACTORIES.get(exceptionClass); if (factory != null) { throw factory.createException(event); } else { throw new IllegalArgumentException( "No such ExceptionFactory available: " + exceptionClass); } } else { String msg = EventFormatter.format(event); //Get original exception as cause if it is given as one of the parameters Throwable t = null; Iterator<Object> iter = event.getParams().values().iterator(); while (iter.hasNext()) { Object o = iter.next(); if (o instanceof Throwable) { t = (Throwable)o; break; } } if (t != null) { throw new RuntimeException(msg, t); } else { throw new RuntimeException(msg); } } }
// in src/java/org/apache/fop/events/model/EventSeverity.java
public static EventSeverity valueOf(String name) { if (INFO.getName().equalsIgnoreCase(name)) { return INFO; } else if (WARN.getName().equalsIgnoreCase(name)) { return WARN; } else if (ERROR.getName().equalsIgnoreCase(name)) { return ERROR; } else if (FATAL.getName().equalsIgnoreCase(name)) { return FATAL; } else { throw new IllegalArgumentException("Illegal value for enumeration: " + name); } }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
public EventProducer getEventProducerFor(Class clazz) { if (!EventProducer.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException( "Class must be an implementation of the EventProducer interface: " + clazz.getName()); } EventProducer producer; producer = (EventProducer)this.proxies.get(clazz); if (producer == null) { producer = createProxyFor(clazz); this.proxies.put(clazz, producer); } return producer; }
// in src/java/org/apache/fop/area/Page.java
public RegionViewport getRegionViewport(int areaClass) { switch (areaClass) { case FO_REGION_BEFORE: return regionBefore; case FO_REGION_START: return regionStart; case FO_REGION_BODY: return regionBody; case FO_REGION_END: return regionEnd; case FO_REGION_AFTER: return regionAfter; default: throw new IllegalArgumentException("No such area class with ID = " + areaClass); } }
// in src/java/org/apache/fop/area/inline/InlineBlockParent.java
Override public void addChildArea(Area childArea) { if (child != null) { throw new IllegalStateException("InlineBlockParent may have only one child area."); } if (childArea instanceof Block) { child = (Block) childArea; //Update extents from the child setIPD(childArea.getAllocIPD()); setBPD(childArea.getAllocBPD()); } else { throw new IllegalArgumentException("The child of an InlineBlockParent must be a" + " Block area"); } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
private void setTraits(Attributes attributes, Area area, Object[] traitSubset) { for (int i = traitSubset.length; --i >= 0;) { Integer trait = (Integer) traitSubset[i]; String traitName = Trait.getTraitName(trait); String value = attributes.getValue(traitName); if (value != null) { Class cl = Trait.getTraitClass(trait); if (cl == Integer.class) { area.addTrait(trait, new Integer(value)); } else if (cl == Boolean.class) { area.addTrait(trait, Boolean.valueOf(value)); } else if (cl == String.class) { area.addTrait(trait, value); if (Trait.PROD_ID.equals(trait) && !idFirstsAssigned.contains(value) && currentPageViewport != null) { currentPageViewport.setFirstWithID(value); idFirstsAssigned.add(value); } } else if (cl == Color.class) { try { area.addTrait(trait, ColorUtil.parseColorString(this.userAgent, value)); } catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); } } else if (cl == InternalLink.class) { area.addTrait(trait, new InternalLink(value)); } else if (cl == Trait.ExternalLink.class) { area.addTrait(trait, Trait.ExternalLink.makeFromTraitValue(value)); } else if (cl == Background.class) { Background bkg = new Background(); try { Color col = ColorUtil.parseColorString( this.userAgent, attributes.getValue("bkg-color")); bkg.setColor(col); } catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); } String uri = attributes.getValue("bkg-img"); if (uri != null) { bkg.setURL(uri); try { ImageManager manager = userAgent.getFactory().getImageManager(); ImageSessionContext sessionContext = userAgent.getImageSessionContext(); ImageInfo info = manager.getImageInfo(uri, sessionContext); bkg.setImageInfo(info); } catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageError(this, uri, e, getLocator()); } catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fnfe, getLocator()); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, getLocator()); } String repeat = attributes.getValue("bkg-repeat"); if (repeat != null) { bkg.setRepeat(repeat); } bkg.setHoriz(XMLUtil.getAttributeAsInt(attributes, "bkg-horz-offset", 0)); bkg.setVertical(XMLUtil.getAttributeAsInt(attributes, "bkg-vert-offset", 0)); } area.addTrait(trait, bkg); } else if (cl == BorderProps.class) { area.addTrait(trait, BorderProps.valueOf(this.userAgent, value)); } } else { if (Trait.FONT.equals(trait)) { String fontName = attributes.getValue("font-name"); if (fontName != null) { String fontStyle = attributes.getValue("font-style"); int fontWeight = XMLUtil.getAttributeAsInt( attributes, "font-weight", Font.WEIGHT_NORMAL); area.addTrait(trait, FontInfo.createFontKey(fontName, fontStyle, fontWeight)); } } } } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
private static CTM getAttributeAsCTM(Attributes attributes, String name) { String s = attributes.getValue(name).trim(); if (s.startsWith("[") && s.endsWith("]")) { s = s.substring(1, s.length() - 1); double[] values = ConversionUtils.toDoubleArray(s, "\\s"); if (values.length != 6) { throw new IllegalArgumentException("CTM must consist of 6 double values!"); } return new CTM(values[0], values[1], values[2], values[3], values[4], values[5]); } else { throw new IllegalArgumentException("CTM must be surrounded by square brackets!"); } }
// in src/java/org/apache/fop/area/Trait.java
protected static ExternalLink makeFromTraitValue(String traitValue) { String dest = null; boolean newWindow = false; String[] values = traitValue.split(","); for (int i = 0, c = values.length; i < c; i++) { String v = values[i]; if (v.startsWith("dest=")) { dest = v.substring(5); } else if (v.startsWith("newWindow=")) { newWindow = Boolean.valueOf(v.substring(10)); } else { throw new IllegalArgumentException( "Malformed trait value for Trait.ExternalLink: " + traitValue); } } return new ExternalLink(dest, newWindow); }
// in src/java/org/apache/fop/area/Area.java
public int getTraitAsInteger(Integer traitCode) { final Object obj = getTrait(traitCode); if (obj instanceof Integer) { return (Integer) obj; } else { throw new IllegalArgumentException("Trait " + traitCode.getClass().getName() + " could not be converted to an integer"); } }
// in src/java/org/apache/fop/area/Span.java
public NormalFlow getNormalFlow(int colRequested) { if (colRequested >= 0 && colRequested < colCount) { return flowAreas.get(colRequested); } else { // internal error throw new IllegalArgumentException("Invalid column number " + colRequested + " requested; only 0-" + (colCount - 1) + " available."); } }
// in src/java/org/apache/fop/traits/BorderProps.java
public static BorderProps valueOf(FOUserAgent foUserAgent, String s) { if (s.startsWith("(") && s.endsWith(")")) { s = s.substring(1, s.length() - 1); Pattern pattern = Pattern.compile("([^,\\(]+(?:\\(.*\\))?)"); Matcher m = pattern.matcher(s); boolean found; found = m.find(); String style = m.group(); found = m.find(); String color = m.group(); found = m.find(); int width = Integer.parseInt(m.group()); int mode = SEPARATE; found = m.find(); if (found) { String ms = m.group(); if ("collapse-inner".equalsIgnoreCase(ms)) { mode = COLLAPSE_INNER; } else if ("collapse-outer".equalsIgnoreCase(ms)) { mode = COLLAPSE_OUTER; } } Color c; try { c = ColorUtil.parseColorString(foUserAgent, color); } catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); } return new BorderProps(style, width, c, mode); } else { throw new IllegalArgumentException("BorderProps must be surrounded by parentheses"); } }
// in src/java/org/apache/fop/traits/Direction.java
public static Direction valueOf(String name) { for (int i = 0; i < DIRECTIONS.length; i++) { if (DIRECTIONS[i].getName().equalsIgnoreCase(name)) { return DIRECTIONS[i]; } } throw new IllegalArgumentException("Illegal direction: " + name); }
// in src/java/org/apache/fop/traits/Direction.java
public static Direction valueOf(int enumValue) { for (int i = 0; i < DIRECTIONS.length; i++) { if (DIRECTIONS[i].getEnumValue() == enumValue) { return DIRECTIONS[i]; } } throw new IllegalArgumentException("Illegal direction: " + enumValue); }
// in src/java/org/apache/fop/traits/WritingMode.java
public static WritingMode valueOf(String name) { for (int i = 0; i < WRITING_MODES.length; i++) { if (WRITING_MODES[i].getName().equalsIgnoreCase(name)) { return WRITING_MODES[i]; } } throw new IllegalArgumentException("Illegal writing mode: " + name); }
// in src/java/org/apache/fop/traits/WritingMode.java
public static WritingMode valueOf(int enumValue) { for (int i = 0; i < WRITING_MODES.length; i++) { if (WRITING_MODES[i].getEnumValue() == enumValue) { return WRITING_MODES[i]; } } throw new IllegalArgumentException("Illegal writing mode: " + enumValue); }
// in src/java/org/apache/fop/traits/RuleStyle.java
public static RuleStyle valueOf(String name) { for (int i = 0; i < STYLES.length; i++) { if (STYLES[i].getName().equalsIgnoreCase(name)) { return STYLES[i]; } } throw new IllegalArgumentException("Illegal rule style: " + name); }
// in src/java/org/apache/fop/traits/RuleStyle.java
public static RuleStyle valueOf(int enumValue) { for (int i = 0; i < STYLES.length; i++) { if (STYLES[i].getEnumValue() == enumValue) { return STYLES[i]; } } throw new IllegalArgumentException("Illegal rule style: " + enumValue); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public static MinOptMax getInstance(int min, int opt, int max) throws IllegalArgumentException { if (min > opt) { throw new IllegalArgumentException("min (" + min + ") > opt (" + opt + ")"); } if (max < opt) { throw new IllegalArgumentException("max (" + max + ") < opt (" + opt + ")"); } return new MinOptMax(min, opt, max); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax mult(int factor) throws IllegalArgumentException { if (factor < 0) { throw new IllegalArgumentException("factor < 0; was: " + factor); } else if (factor == 1) { return this; } else { return getInstance(min * factor, opt * factor, max * factor); } }
// in src/java/org/apache/fop/traits/BorderStyle.java
public static BorderStyle valueOf(String name) { for (int i = 0; i < STYLES.length; i++) { if (STYLES[i].getName().equalsIgnoreCase(name)) { return STYLES[i]; } } throw new IllegalArgumentException("Illegal border style: " + name); }
// in src/java/org/apache/fop/traits/BorderStyle.java
public static BorderStyle valueOf(int enumValue) { for (int i = 0; i < STYLES.length; i++) { if (STYLES[i].getEnumValue() == enumValue) { return STYLES[i]; } } throw new IllegalArgumentException("Illegal border style: " + enumValue); }
// in src/java/org/apache/fop/layoutmgr/SpaceResolver.java
private String toString(Object[] arr1, Object[] arr2) { if (arr1.length != arr2.length) { throw new IllegalArgumentException("The length of both arrays must be equal"); } StringBuffer sb = new StringBuffer("["); for (int i = 0; i < arr1.length; i++) { if (i > 0) { sb.append(", "); } sb.append(String.valueOf(arr1[i])); sb.append("/"); sb.append(String.valueOf(arr2[i])); } sb.append("]"); return sb.toString(); }
// in src/java/org/apache/fop/layoutmgr/PageProvider.java
public Page getPage(boolean isBlank, int index, int relativeTo) { if (relativeTo == RELTO_PAGE_SEQUENCE) { return getPage(isBlank, index); } else if (relativeTo == RELTO_CURRENT_ELEMENT_LIST) { int effIndex = startPageOfCurrentElementList + index; effIndex += startPageOfPageSequence - 1; return getPage(isBlank, effIndex); } else { throw new IllegalArgumentException( "Illegal value for relativeTo: " + relativeTo); } }
// in src/java/org/apache/fop/layoutmgr/LayoutContext.java
public void signalSpanChange(int span) { switch (span) { case Constants.NOT_SET: case Constants.EN_NONE: case Constants.EN_ALL: this.currentSpan = this.nextSpan; this.nextSpan = span; break; default: assert false; throw new IllegalArgumentException("Illegal value on signalSpanChange() for span: " + span); } }
// in src/java/org/apache/fop/layoutmgr/inline/ScaledBaselineTable.java
int getBaseline(int baselineIdentifier) { int offset = 0; if (!isHorizontalWritingMode()) { switch (baselineIdentifier) { case Constants.EN_TOP: case Constants.EN_TEXT_TOP: case Constants.EN_TEXT_BOTTOM: case Constants.EN_BOTTOM: throw new IllegalArgumentException("Baseline " + baselineIdentifier + " only supported for horizontal writing modes"); default: // TODO } } switch (baselineIdentifier) { case Constants.EN_TOP: // fall through case Constants.EN_BEFORE_EDGE: offset = beforeEdgeOffset; break; case Constants.EN_TEXT_TOP: case Constants.EN_TEXT_BEFORE_EDGE: case Constants.EN_HANGING: case Constants.EN_CENTRAL: case Constants.EN_MIDDLE: case Constants.EN_MATHEMATICAL: case Constants.EN_ALPHABETIC: case Constants.EN_IDEOGRAPHIC: case Constants.EN_TEXT_BOTTOM: case Constants.EN_TEXT_AFTER_EDGE: offset = getBaselineDefaultOffset(baselineIdentifier) - dominantBaselineOffset; break; case Constants.EN_BOTTOM: // fall through case Constants.EN_AFTER_EDGE: offset = afterEdgeOffset; break; default: throw new IllegalArgumentException(String.valueOf(baselineIdentifier)); } return offset; }
// in src/java/org/apache/fop/layoutmgr/inline/ScaledBaselineTable.java
private int getBaselineDefaultOffset(int baselineIdentifier) { int offset = 0; switch (baselineIdentifier) { case Constants.EN_TEXT_BEFORE_EDGE: offset = altitude; break; case Constants.EN_HANGING: offset = Math.round(altitude * HANGING_BASELINE_FACTOR); break; case Constants.EN_CENTRAL: offset = (altitude - depth) / 2 + depth; break; case Constants.EN_MIDDLE: offset = xHeight / 2; break; case Constants.EN_MATHEMATICAL: offset = Math.round(altitude * MATHEMATICAL_BASELINE_FACTOR); break; case Constants.EN_ALPHABETIC: offset = 0; break; case Constants.EN_IDEOGRAPHIC: // Fall through case Constants.EN_TEXT_AFTER_EDGE: offset = depth; break; default: throw new IllegalArgumentException(String.valueOf(baselineIdentifier)); } return offset; }
// in src/java/org/apache/fop/layoutmgr/inline/AlignmentContext.java
private void setAlignmentBaselineIdentifier(int alignmentBaseline , int parentDominantBaselineIdentifier) { switch (alignmentBaseline) { case EN_AUTO: // fall through case EN_BASELINE: this.alignmentBaselineIdentifier = parentDominantBaselineIdentifier; break; case EN_BEFORE_EDGE: case EN_TEXT_BEFORE_EDGE: case EN_CENTRAL: case EN_MIDDLE: case EN_AFTER_EDGE: case EN_TEXT_AFTER_EDGE: case EN_IDEOGRAPHIC: case EN_ALPHABETIC: case EN_HANGING: case EN_MATHEMATICAL: this.alignmentBaselineIdentifier = alignmentBaseline; break; default: throw new IllegalArgumentException(String.valueOf(alignmentBaseline)); } }
// in src/java/org/apache/fop/layoutmgr/inline/AlignmentContext.java
private void setBaselineShift(Length baselineShift) { baselineShiftValue = 0; switch (baselineShift.getEnum()) { case EN_BASELINE: //Nothing to do break; case EN_SUB: baselineShiftValue = Math.round(-(xHeight / 2) + parentAlignmentContext.getActualBaselineOffset(EN_ALPHABETIC) ); break; case EN_SUPER: baselineShiftValue = Math.round(parentAlignmentContext.getXHeight() + parentAlignmentContext.getActualBaselineOffset(EN_ALPHABETIC) ); break; case 0: // A <length> or <percentage> value baselineShiftValue = baselineShift.getValue( new SimplePercentBaseContext(null , LengthBase.CUSTOM_BASE , parentAlignmentContext.getLineHeight())); break; default: throw new IllegalArgumentException(String.valueOf(baselineShift.getEnum())); } }
// in src/java/org/apache/fop/layoutmgr/Keep.java
private static int getKeepContextPriority(int context) { switch (context) { case Constants.EN_LINE: return 0; case Constants.EN_COLUMN: return 1; case Constants.EN_PAGE: return 2; case Constants.EN_AUTO: return 3; default: throw new IllegalArgumentException(); } }
// in src/java/org/apache/fop/layoutmgr/AbstractLayoutManager.java
private void verifyNonNullPosition(Position pos) { if (pos == null || pos.getIndex() < 0) { throw new IllegalArgumentException( "Only non-null Positions with an index can be checked"); } }
// in src/java/org/apache/fop/layoutmgr/BreakingAlgorithm.java
protected final KnuthElement handleElementAt(int position, boolean previousIsBox, int allowedBreaks) { KnuthElement element = getElement(position); if (element.isBox()) { handleBox((KnuthBox) element); } else if (element.isGlue()) { handleGlueAt((KnuthGlue) element, position, previousIsBox, allowedBreaks); } else if (element.isPenalty()) { handlePenaltyAt((KnuthPenalty) element, position, allowedBreaks); } else { throw new IllegalArgumentException( "Unknown KnuthElement type: expecting KnuthBox, KnuthGlue or KnuthPenalty"); } return element; }
// in src/java/org/apache/fop/layoutmgr/PositionIterator.java
protected Position getPos(Object nextObj) { if (nextObj instanceof Position) { return (Position)nextObj; } throw new IllegalArgumentException( "Cannot obtain Position from the given object."); }
// in src/java/org/apache/fop/layoutmgr/table/CollapsingBorderModel.java
public static CollapsingBorderModel getBorderModelFor(int borderCollapse) { switch (borderCollapse) { case Constants.EN_COLLAPSE: if (collapse == null) { collapse = new CollapsingBorderModelEyeCatching(); } return collapse; case Constants.EN_COLLAPSE_WITH_PRECEDENCE: throw new UnsupportedOperationException ( "collapse-with-precedence not yet supported" ); default: throw new IllegalArgumentException("Illegal border-collapse mode."); } }
// in src/java/org/apache/fop/layoutmgr/table/CollapsingBorderModel.java
public/*TODO*/ static int getOtherSide(int side) { switch (side) { case CommonBorderPaddingBackground.BEFORE: return CommonBorderPaddingBackground.AFTER; case CommonBorderPaddingBackground.AFTER: return CommonBorderPaddingBackground.BEFORE; case CommonBorderPaddingBackground.START: return CommonBorderPaddingBackground.END; case CommonBorderPaddingBackground.END: return CommonBorderPaddingBackground.START; default: throw new IllegalArgumentException("Illegal parameter: side"); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphMappingTable.java
public int[] getInterval ( int[] interval ) { if ( ( interval == null ) || ( interval.length != 2 ) ) { throw new IllegalArgumentException(); } else { interval[0] = gidStart; interval[1] = gidEnd; } return interval; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphs ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { if ( count < 0 ) { count = getGlyphsAvailable ( offset, reverseOrder, ignoreTester ) [ 0 ]; } int start = index + offset; if ( start < 0 ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else if ( ! reverseOrder && ( ( start + count ) > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start + count ) ); } else if ( reverseOrder && ( ( start + 1 ) < count ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start - count ) ); } if ( glyphs == null ) { glyphs = new int [ count ]; } else if ( glyphs.length != count ) { throw new IllegalArgumentException ( "glyphs array is non-null, but its length (" + glyphs.length + "), is not equal to count (" + count + ")" ); } if ( ! reverseOrder ) { return getGlyphsForward ( start, count, ignoreTester, glyphs, counts ); } else { return getGlyphsReverse ( start, count, ignoreTester, glyphs, counts ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation[] getAssociations ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, GlyphSequence.CharAssociation[] associations, int[] counts ) throws IndexOutOfBoundsException { if ( count < 0 ) { count = getGlyphsAvailable ( offset, reverseOrder, ignoreTester ) [ 0 ]; } int start = index + offset; if ( start < 0 ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else if ( ! reverseOrder && ( ( start + count ) > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start + count ) ); } else if ( reverseOrder && ( ( start + 1 ) < count ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start - count ) ); } if ( associations == null ) { associations = new GlyphSequence.CharAssociation [ count ]; } else if ( associations.length != count ) { throw new IllegalArgumentException ( "associations array is non-null, but its length (" + associations.length + "), is not equal to count (" + count + ")" ); } if ( ! reverseOrder ) { return getAssociationsForward ( start, count, ignoreTester, associations, counts ); } else { return getAssociationsReverse ( start, count, ignoreTester, associations, counts ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int getGlyphForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( ci <= ciMax ) { return gi + delta; } else { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + ciMax ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int getGlyphForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( glyphs == null ) { return -1; } else if ( ci >= glyphs.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + glyphs.length ); } else { return glyphs [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int[] getGlyphsForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( gsa == null ) { return null; } else if ( ci >= gsa.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + gsa.length ); } else { return gsa [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int[] getAlternatesForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( gaa == null ) { return null; } else if ( ci >= gaa.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + gaa.length ); } else { return gaa [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public LigatureSet getLigatureSetForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( ligatureSets == null ) { return null; } else if ( ci >= ligatureSets.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + ligatureSets.length ); } else { return ligatureSets [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java
private static void resolveRuns ( int[] wca, int defaultLevel, int[] ea, int[] la ) { if ( la.length != wca.length ) { throw new IllegalArgumentException ( "levels sequence length must match classes sequence length" ); } else if ( la.length != ea.length ) { throw new IllegalArgumentException ( "levels sequence length must match embeddings sequence length" ); } else { for ( int i = 0, n = ea.length, lPrev = defaultLevel; i < n; ) { int s = i; int e = s; int l = findNextNonRetainedFormattingLevel ( wca, ea, s, lPrev ); while ( e < n ) { if ( la [ e ] != l ) { if ( startsWithRetainedFormattingRun ( wca, ea, e ) ) { e += getLevelRunLength ( ea, e ); } else { break; } } else { e++; } } lPrev = resolveRun ( wca, defaultLevel, ea, la, s, e, l, lPrev ); i = e; } } }
// in src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java
private static void resolveAdjacentBoundaryNeutrals ( int[] wca, int start, int end, int index, int bcNew ) { if ( ( index < start ) || ( index >= end ) ) { throw new IllegalArgumentException(); } else { for ( int i = index - 1; i >= start; i-- ) { int bc = wca [ i ]; if ( bc == BN ) { wca [ i ] = bcNew; } else { break; } } for ( int i = index + 1; i < end; i++ ) { int bc = wca [ i ]; if ( bc == BN ) { wca [ i ] = bcNew; } else { break; } } } }
// in src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java
private static boolean convertToScalar ( CharSequence cs, int[] chars ) throws IllegalArgumentException { boolean triggered = false; if ( chars.length != cs.length() ) { throw new IllegalArgumentException ( "characters array length must match input sequence length" ); } for ( int i = 0, n = chars.length; i < n; ) { int chIn = cs.charAt ( i ); int chOut; if ( chIn < 0xD800 ) { chOut = chIn; } else if ( chIn < 0xDC00 ) { int chHi = chIn; int chLo; if ( ( i + 1 ) < n ) { chLo = cs.charAt ( i + 1 ); if ( ( chLo >= 0xDC00 ) && ( chLo <= 0xDFFF ) ) { chOut = convertToScalar ( chHi, chLo ); } else { throw new IllegalArgumentException ( "isolated high surrogate" ); } } else { throw new IllegalArgumentException ( "truncated surrogate pair" ); } } else if ( chIn < 0xE000 ) { throw new IllegalArgumentException ( "isolated low surrogate" ); } else { chOut = chIn; } if ( ! triggered && triggersBidi ( chOut ) ) { triggered = true; } if ( ( chOut & 0xFF0000 ) == 0 ) { chars [ i++ ] = chOut; } else { chars [ i++ ] = chOut; chars [ i++ ] = -1; } } return triggered; }
// in src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java
private static int convertToScalar ( int chHi, int chLo ) { if ( ( chHi < 0xD800 ) || ( chHi > 0xDBFF ) ) { throw new IllegalArgumentException ( "bad high surrogate" ); } else if ( ( chLo < 0xDC00 ) || ( chLo > 0xDFFF ) ) { throw new IllegalArgumentException ( "bad low surrogate" ); } else { return ( ( ( chHi & 0x03FF ) << 10 ) | ( chLo & 0x03FF ) ) + 0x10000; } }
// in src/java/org/apache/fop/complexscripts/util/NumberConverter.java
private Integer[] formatNumber ( long number, Integer[] token ) { Integer[] fn = null; assert token.length > 0; if ( number < 0 ) { throw new IllegalArgumentException ( "number must be non-negative" ); } else if ( token.length == 1 ) { int s = token[0].intValue(); switch ( s ) { case (int) '1': { fn = formatNumberAsDecimal ( number, (int) '1', 1 ); break; } case (int) 'W': case (int) 'w': { fn = formatNumberAsWord ( number, ( s == (int) 'W' ) ? Character.UPPERCASE_LETTER : Character.LOWERCASE_LETTER ); break; } case (int) 'A': // handled as numeric sequence case (int) 'a': // handled as numeric sequence case (int) 'I': // handled as numeric special case (int) 'i': // handled as numeric special default: { if ( isStartOfDecimalSequence ( s ) ) { fn = formatNumberAsDecimal ( number, s, 1 ); } else if ( isStartOfAlphabeticSequence ( s ) ) { fn = formatNumberAsSequence ( number, s, getSequenceBase ( s ), null ); } else if ( isStartOfNumericSpecial ( s ) ) { fn = formatNumberAsSpecial ( number, s ); } else { fn = null; } break; } } } else if ( ( token.length == 2 ) && ( token[0] == (int) 'W' ) && ( token[1] == (int) 'w' ) ) { fn = formatNumberAsWord ( number, Character.TITLECASE_LETTER ); } else if ( isPaddedOne ( token ) ) { int s = token [ token.length - 1 ].intValue(); fn = formatNumberAsDecimal ( number, s, token.length ); } else { throw new IllegalArgumentException ( "invalid format token: \"" + UTF32.fromUTF32 ( token ) + "\"" ); } if ( fn == null ) { fn = formatNumber ( number, DEFAULT_TOKEN ); } assert fn != null; return fn; }
// in src/java/org/apache/fop/complexscripts/util/UTF32.java
public static Integer[] toUTF32 ( String s, int substitution, boolean errorOnSubstitution ) throws IllegalArgumentException { int n; if ( ( n = s.length() ) == 0 ) { return new Integer[0]; } else { Integer[] sa = new Integer [ n ]; int k = 0; for ( int i = 0; i < n; i++ ) { int c = (int) s.charAt(i); if ( ( c >= 0xD800 ) && ( c < 0xE000 ) ) { int s1 = c; int s2 = ( ( i + 1 ) < n ) ? (int) s.charAt ( i + 1 ) : 0; if ( s1 < 0xDC00 ) { if ( ( s2 >= 0xDC00 ) && ( s2 < 0xE000 ) ) { c = ( ( s1 - 0xD800 ) << 10 ) + ( s2 - 0xDC00 ) + 65536; i++; } else { if ( errorOnSubstitution ) { throw new IllegalArgumentException ( "isolated high (leading) surrogate" ); } else { c = substitution; } } } else { if ( errorOnSubstitution ) { throw new IllegalArgumentException ( "isolated low (trailing) surrogate" ); } else { c = substitution; } } } sa[k++] = c; } if ( k == n ) { return sa; } else { Integer[] na = new Integer [ k ]; System.arraycopy ( sa, 0, na, 0, k ); return na; } } }
// in src/java/org/apache/fop/complexscripts/util/UTF32.java
public static String fromUTF32 ( Integer[] sa ) throws IllegalArgumentException { StringBuffer sb = new StringBuffer(); for ( int s : sa ) { if ( s < 65535 ) { if ( ( s < 0xD800 ) || ( s > 0xDFFF ) ) { sb.append ( (char) s ); } else { String ncr = CharUtilities.charToNCRef(s); throw new IllegalArgumentException ( "illegal scalar value 0x" + ncr.substring(2, ncr.length() - 1) + "; cannot be UTF-16 surrogate" ); } } else if ( s < 1114112 ) { int s1 = ( ( ( s - 65536 ) >> 10 ) & 0x3FF ) + 0xD800; int s2 = ( ( ( s - 65536 ) >> 0 ) & 0x3FF ) + 0xDC00; sb.append ( (char) s1 ); sb.append ( (char) s2 ); } else { String ncr = CharUtilities.charToNCRef(s); throw new IllegalArgumentException ( "illegal scalar value 0x" + ncr.substring(2, ncr.length() - 1) + "; out of range for UTF-16" ); } } return sb.toString(); }
// in src/java/org/apache/fop/util/XMLUtil.java
public static Rectangle2D getAttributeAsRectangle2D(Attributes attributes, String name) { String s = attributes.getValue(name).trim(); double[] values = ConversionUtils.toDoubleArray(s, "\\s"); if (values.length != 4) { throw new IllegalArgumentException("Rectangle must consist of 4 double values!"); } return new Rectangle2D.Double(values[0], values[1], values[2], values[3]); }
// in src/java/org/apache/fop/util/XMLUtil.java
public static Rectangle getAttributeAsRectangle(Attributes attributes, String name) { String s = attributes.getValue(name); if (s == null) { return null; } int[] values = ConversionUtils.toIntArray(s.trim(), "\\s"); if (values.length != 4) { throw new IllegalArgumentException("Rectangle must consist of 4 int values!"); } return new Rectangle(values[0], values[1], values[2], values[3]); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
public void addContentHandlerFactory(String classname) { try { ContentHandlerFactory factory = (ContentHandlerFactory)Class.forName(classname).newInstance(); addContentHandlerFactory(factory); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); } catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ContentHandlerFactory.class.getName()); } }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsJavaAWTColor(String value) throws PropertyException { float red = 0.0f; float green = 0.0f; float blue = 0.0f; int poss = value.indexOf("["); int pose = value.indexOf("]"); try { if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); String[] args = value.split(","); if (args.length != 3) { throw new PropertyException( "Invalid number of arguments for a java.awt.Color: " + value); } red = Float.parseFloat(args[0].trim().substring(2)) / 255f; green = Float.parseFloat(args[1].trim().substring(2)) / 255f; blue = Float.parseFloat(args[2].trim().substring(2)) / 255f; if ((red < 0.0 || red > 1.0) || (green < 0.0 || green > 1.0) || (blue < 0.0 || blue > 1.0)) { throw new PropertyException("Color values out of range"); } } else { throw new IllegalArgumentException( "Invalid format for a java.awt.Color: " + value); } } catch (RuntimeException re) { throw new PropertyException(re); } return new Color(red, green, blue); }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsFopRgbNamedColor(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { String[] args = value.substring(poss + 1, pose).split(","); try { if (args.length != 6) { throw new PropertyException("rgb-named-color() function must have 6 arguments"); } //Set up fallback sRGB value Color sRGB = parseFallback(args, value); /* Get and verify ICC profile name */ String iccProfileName = args[3].trim(); if (iccProfileName == null || "".equals(iccProfileName)) { throw new PropertyException("ICC profile name missing"); } ICC_ColorSpace colorSpace = null; String iccProfileSrc; if (isPseudoProfile(iccProfileName)) { throw new IllegalArgumentException( "Pseudo-profiles are not allowed with fop-rgb-named-color()"); } else { /* Get and verify ICC profile source */ iccProfileSrc = args[4].trim(); if (iccProfileSrc == null || "".equals(iccProfileSrc)) { throw new PropertyException("ICC profile source missing"); } iccProfileSrc = unescapeString(iccProfileSrc); } // color name String colorName = unescapeString(args[5].trim()); /* Ask FOP factory to get ColorSpace for the specified ICC profile source */ if (foUserAgent != null && iccProfileSrc != null) { RenderingIntent renderingIntent = RenderingIntent.AUTO; //TODO connect to fo:color-profile/@rendering-intent colorSpace = (ICC_ColorSpace)foUserAgent.getFactory().getColorSpaceCache().get( iccProfileName, foUserAgent.getBaseURL(), iccProfileSrc, renderingIntent); } if (colorSpace != null) { ICC_Profile profile = colorSpace.getProfile(); if (NamedColorProfileParser.isNamedColorProfile(profile)) { NamedColorProfileParser parser = new NamedColorProfileParser(); NamedColorProfile ncp = parser.parseProfile(profile, iccProfileName, iccProfileSrc); NamedColorSpace ncs = ncp.getNamedColor(colorName); if (ncs != null) { parsedColor = new ColorWithFallback(ncs, new float[] {1.0f}, 1.0f, null, sRGB); } else { log.warn("Color '" + colorName + "' does not exist in named color profile: " + iccProfileSrc); parsedColor = sRGB; } } else { log.warn("ICC profile is no named color profile: " + iccProfileSrc); parsedColor = sRGB; } } else { // ICC profile could not be loaded - use rgb replacement values */ log.warn("Color profile '" + iccProfileSrc + "' not found. Using sRGB replacement values."); parsedColor = sRGB; } } catch (IOException ioe) { //wrap in a PropertyException throw new PropertyException(ioe); } catch (RuntimeException re) { throw new PropertyException(re); //wrap in a PropertyException } } else { throw new PropertyException("Unknown color format: " + value + ". Must be fop-rgb-named-color(r,g,b,NCNAME,src,color-name)"); } return parsedColor; }
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
public static boolean isZeroBlack(RenderedImage img) { if (!isMonochromeImage(img)) { throw new IllegalArgumentException("Image is not a monochrome image!"); } IndexColorModel icm = (IndexColorModel)img.getColorModel(); int gray0 = convertToGray(icm.getRGB(0)); int gray1 = convertToGray(icm.getRGB(1)); return gray0 < gray1; }
// in src/java/org/apache/fop/util/bitmap/DitherUtil.java
public static int[] getBayerBasePattern(int matrix) { int[] result = new int[matrix * matrix]; switch (matrix) { case DITHER_MATRIX_2X2: System.arraycopy(BAYER_D2, 0, result, 0, BAYER_D2.length); break; case DITHER_MATRIX_4X4: System.arraycopy(BAYER_D4, 0, result, 0, BAYER_D4.length); break; case DITHER_MATRIX_8X8: System.arraycopy(BAYER_D8, 0, result, 0, BAYER_D8.length); break; default: throw new IllegalArgumentException("Unsupported dither matrix: " + matrix); } return result; }
// in src/java/org/apache/fop/util/bitmap/DitherUtil.java
public static byte[] getBayerDither(int matrix, int gray255, boolean doubleMatrix) { int ditherIndex; byte[] dither; int[] bayer; switch (matrix) { case DITHER_MATRIX_4X4: ditherIndex = gray255 * 17 / 255; bayer = BAYER_D4; break; case DITHER_MATRIX_8X8: ditherIndex = gray255 * 65 / 255; bayer = BAYER_D8; break; default: throw new IllegalArgumentException("Unsupported dither matrix: " + matrix); } if (doubleMatrix) { if (doubleMatrix && (matrix != DITHER_MATRIX_4X4)) { throw new IllegalArgumentException("doubleMatrix=true is only allowed for 4x4"); } dither = new byte[bayer.length / 8 * 4]; for (int i = 0, c = bayer.length; i < c; i++) { boolean dot = !(bayer[i] < ditherIndex - 1); if (dot) { int byteIdx = i / 4; dither[byteIdx] |= 1 << (i % 4); dither[byteIdx] |= 1 << ((i % 4) + 4); dither[byteIdx + 4] |= 1 << (i % 4); dither[byteIdx + 4] |= 1 << ((i % 4) + 4); } } } else { dither = new byte[bayer.length / 8]; for (int i = 0, c = bayer.length; i < c; i++) { boolean dot = !(bayer[i] < ditherIndex - 1); if (dot) { int byteIdx = i / 8; dither[byteIdx] |= 1 << (i % 8); } } } return dither; }
// in src/java/org/apache/fop/util/BreakUtil.java
private static int getBreakClassPriority(int breakClass) { switch (breakClass) { case Constants.EN_AUTO: return 0; case Constants.EN_COLUMN: return 1; case Constants.EN_PAGE: return 2; case Constants.EN_EVEN_PAGE: return 3; case Constants.EN_ODD_PAGE: return 3; default: throw new IllegalArgumentException( "Illegal value for breakClass: " + breakClass); } }
// in src/java/org/apache/fop/util/text/AdvancedMessageFormat.java
private Part parseField(String field) { String[] parts = COMMA_SEPARATOR_REGEX.split(field, 3); String fieldName = parts[0]; if (parts.length == 1) { if (fieldName.startsWith("#")) { return new FunctionPart(fieldName.substring(1)); } else { return new SimpleFieldPart(fieldName); } } else { String format = parts[1]; PartFactory factory = (PartFactory)PART_FACTORIES.get(format); if (factory == null) { throw new IllegalArgumentException( "No PartFactory available under the name: " + format); } if (parts.length == 2) { return factory.newPart(fieldName, null); } else { return factory.newPart(fieldName, parts[2]); } } }
// in src/java/org/apache/fop/util/text/AdvancedMessageFormat.java
public void write(StringBuffer sb, Map<String, Object> params) { if (!params.containsKey(fieldName)) { throw new IllegalArgumentException( "Message pattern contains unsupported field name: " + fieldName); } Object obj = params.get(fieldName); formatObject(obj, sb); }
// in src/java/org/apache/fop/util/text/HexFieldPart.java
public void write(StringBuffer sb, Map params) { if (!params.containsKey(fieldName)) { throw new IllegalArgumentException( "Message pattern contains unsupported field name: " + fieldName); } Object obj = params.get(fieldName); if (obj instanceof Character) { sb.append(Integer.toHexString(((Character)obj).charValue())); } else if (obj instanceof Number) { sb.append(Integer.toHexString(((Number)obj).intValue())); } else { throw new IllegalArgumentException("Incompatible value for hex field part: " + obj.getClass().getName()); } }
// in src/java/org/apache/fop/util/text/EqualsFieldPart.java
protected void parseValues(String values) { String[] parts = AdvancedMessageFormat.COMMA_SEPARATOR_REGEX.split(values, 3); this.equalsValue = parts[0]; if (parts.length == 1) { throw new IllegalArgumentException( "'equals' format must have at least 2 parameters"); } if (parts.length == 3) { ifValue = AdvancedMessageFormat.unescapeComma(parts[1]); elseValue = AdvancedMessageFormat.unescapeComma(parts[2]); } else { ifValue = AdvancedMessageFormat.unescapeComma(parts[1]); } }
// in src/java/org/apache/fop/util/text/GlyphNameFieldPart.java
private String getGlyphName(Object obj) { if (obj instanceof Character) { return Glyphs.charToGlyphName(((Character)obj).charValue()); } else { throw new IllegalArgumentException( "Value for glyph name part must be a Character but was: " + obj.getClass().getName()); } }
// in src/java/org/apache/fop/util/text/GlyphNameFieldPart.java
public void write(StringBuffer sb, Map params) { if (!params.containsKey(fieldName)) { throw new IllegalArgumentException( "Message pattern contains unsupported field name: " + fieldName); } Object obj = params.get(fieldName); sb.append(getGlyphName(obj)); }
// in src/java/org/apache/fop/image/loader/batik/ImageConverterSVG2G2D.java
public Image convert(final Image src, Map hints) throws ImageException { checkSourceFlavor(src); final ImageXMLDOM svg = (ImageXMLDOM)src; if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(svg.getRootNamespace())) { throw new IllegalArgumentException("XML DOM is not in the SVG namespace: " + svg.getRootNamespace()); } //Prepare float pxToMillimeter = UnitConv.IN2MM / GraphicsConstants.DEFAULT_DPI; Number ptm = (Number)hints.get(ImageProcessingHints.SOURCE_RESOLUTION); if (ptm != null) { pxToMillimeter = (float)(UnitConv.IN2MM / ptm.doubleValue()); } UserAgent ua = createBatikUserAgent(pxToMillimeter); GVTBuilder builder = new GVTBuilder(); final ImageManager imageManager = (ImageManager)hints.get( ImageProcessingHints.IMAGE_MANAGER); final ImageSessionContext sessionContext = (ImageSessionContext)hints.get( ImageProcessingHints.IMAGE_SESSION_CONTEXT); boolean useEnhancedBridgeContext = (imageManager != null && sessionContext != null); final BridgeContext ctx = (useEnhancedBridgeContext ? new GenericFOPBridgeContext(ua, null, imageManager, sessionContext) : new BridgeContext(ua)); Document doc = svg.getDocument(); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(doc); //Build the GVT tree final GraphicsNode root; try { root = builder.build(ctx, clonedDoc); } catch (Exception e) { throw new ImageException("GVT tree could not be built for SVG graphic", e); } //Create the painter int width = svg.getSize().getWidthMpt(); int height = svg.getSize().getHeightMpt(); Dimension imageSize = new Dimension(width, height); Graphics2DImagePainter painter = createPainter(ctx, root, imageSize); //Create g2d image ImageInfo imageInfo = src.getInfo(); ImageGraphics2D g2dImage = new ImageGraphics2D(imageInfo, painter); return g2dImage; }
// in src/java/org/apache/fop/image/loader/batik/ImageLoaderSVG.java
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!MimeConstants.MIME_SVG.equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from an SVG image"); } Image img = info.getOriginalImage(); if (!(img instanceof ImageXMLDOM)) { throw new IllegalArgumentException( "ImageInfo was expected to contain the SVG document as DOM"); } ImageXMLDOM svgImage = (ImageXMLDOM)img; if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(svgImage.getRootNamespace())) { throw new IllegalArgumentException( "The Image is not in the SVG namespace: " + svgImage.getRootNamespace()); } return svgImage; }
// in src/java/org/apache/fop/image/loader/batik/ImageLoaderWMF.java
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!ImageWMF.MIME_WMF.equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from a WMF image"); } Image img = info.getOriginalImage(); if (!(img instanceof ImageWMF)) { throw new IllegalArgumentException( "ImageInfo was expected to contain the Windows Metafile (WMF)"); } ImageWMF wmfImage = (ImageWMF)img; return wmfImage; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private InputHandler createInputHandler() { switch (inputmode) { case FO_INPUT: return new InputHandler(fofile); case AREATREE_INPUT: return new AreaTreeInputHandler(areatreefile); case IF_INPUT: return new IFInputHandler(iffile); case XSLT_INPUT: InputHandler handler = new InputHandler(xmlfile, xsltfile, xsltParams); if (useCatalogResolver) { handler.createCatalogResolver(foUserAgent); } return handler; case IMAGE_INPUT: return new ImageInputHandler(imagefile, xsltfile, xsltParams); default: throw new IllegalArgumentException("Error creating InputHandler object."); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void parseTypeProperties ( String line, Map/*<Integer,List>*/ sm, Map/*<String,int[3]>*/ im ) { String[] sa = line.split(";"); if ( sa.length >= 5 ) { int uc = Integer.parseInt ( sa[0], 16 ); int bc = parseBidiClassAny ( sa[4] ); if ( bc >= 0 ) { String ucName = sa[1]; if ( isBlockStart ( ucName ) ) { String ucBlock = getBlockName ( ucName ); if ( ! im.containsKey ( ucBlock ) ) { im.put ( ucBlock, new int[] { uc, -1, bc } ); } else { throw new IllegalArgumentException ( "duplicate start of block '" + ucBlock + "' at entry: " + line ); } } else if ( isBlockEnd ( ucName ) ) { String ucBlock = getBlockName ( ucName ); if ( im.containsKey ( ucBlock ) ) { int[] ba = (int[]) im.get ( ucBlock ); assert ba.length == 3; if ( ba[1] < 0 ) { ba[1] = uc; } else { throw new IllegalArgumentException ( "duplicate end of block '" + ucBlock + "' at entry: " + line ); } } else { throw new IllegalArgumentException ( "missing start of block '" + ucBlock + "' at entry: " + line ); } } else { Integer k = Integer.valueOf ( bc ); List sl; if ( ! sm.containsKey ( k ) ) { sl = new ArrayList(); sm.put ( k, sl ); } else { sl = (List) sm.get ( k ); } assert sl != null; sl.add ( Integer.valueOf ( uc ) ); } } else { throw new IllegalArgumentException ( "invalid bidi class '" + sa[4] + "' at entry: " + line ); } } else { throw new IllegalArgumentException ( "invalid unicode character database entry: " + line ); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int parseBidiClass ( String bidiClass ) { int bc = 0; if ( "L".equals ( bidiClass ) ) { bc = BidiConstants.L; } else if ( "LRE".equals ( bidiClass ) ) { bc = BidiConstants.LRE; } else if ( "LRO".equals ( bidiClass ) ) { bc = BidiConstants.LRO; } else if ( "R".equals ( bidiClass ) ) { bc = BidiConstants.R; } else if ( "AL".equals ( bidiClass ) ) { bc = BidiConstants.AL; } else if ( "RLE".equals ( bidiClass ) ) { bc = BidiConstants.RLE; } else if ( "RLO".equals ( bidiClass ) ) { bc = BidiConstants.RLO; } else if ( "PDF".equals ( bidiClass ) ) { bc = BidiConstants.PDF; } else if ( "EN".equals ( bidiClass ) ) { bc = BidiConstants.EN; } else if ( "ES".equals ( bidiClass ) ) { bc = BidiConstants.ES; } else if ( "ET".equals ( bidiClass ) ) { bc = BidiConstants.ET; } else if ( "AN".equals ( bidiClass ) ) { bc = BidiConstants.AN; } else if ( "CS".equals ( bidiClass ) ) { bc = BidiConstants.CS; } else if ( "NSM".equals ( bidiClass ) ) { bc = BidiConstants.NSM; } else if ( "BN".equals ( bidiClass ) ) { bc = BidiConstants.BN; } else if ( "B".equals ( bidiClass ) ) { bc = BidiConstants.B; } else if ( "S".equals ( bidiClass ) ) { bc = BidiConstants.S; } else if ( "WS".equals ( bidiClass ) ) { bc = BidiConstants.WS; } else if ( "ON".equals ( bidiClass ) ) { bc = BidiConstants.ON; } else { throw new IllegalArgumentException ( "unknown bidi class: " + bidiClass ); } return bc; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badRangeSpec ( String reason, String charRanges ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad range specification: " + reason + ": \"" + charRanges + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badRangeSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad range specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int[] parseLevels ( List lines ) { int[] la = null; // levels array int[] ra = null; // reorder array List tal = new ArrayList(); if ( ( lines != null ) && ( lines.size() >= 3 ) ) { for ( Iterator it = lines.iterator(); it.hasNext(); ) { String line = (String) it.next(); if ( line.startsWith(PFX_LEVELS) ) { if ( la == null ) { la = parseLevelSpec ( line ); if ( verbose ) { if ( ( ++numLevelSpecs % 10 ) == 0 ) { System.out.print("&"); } } } else { throw new IllegalArgumentException ( "redundant levels array: \"" + line + "\"" ); } } else if ( line.startsWith(PFX_REORDER) ) { if ( la == null ) { throw new IllegalArgumentException ( "missing levels array before: \"" + line + "\"" ); } else if ( ra == null ) { ra = parseReorderSpec ( line, la ); } else { throw new IllegalArgumentException ( "redundant reorder array: \"" + line + "\"" ); } } else if ( ( la != null ) && ( ra != null ) ) { int[] ta = parseTestSpec ( line, la ); if ( ta != null ) { if ( verbose ) { if ( ( ++numTestSpecs % 100 ) == 0 ) { System.out.print("!"); } } tal.add ( ta ); } } else if ( la == null ) { throw new IllegalArgumentException ( "missing levels array before: \"" + line + "\"" ); } else if ( ra == null ) { throw new IllegalArgumentException ( "missing reorder array before: \"" + line + "\"" ); } } } if ( ( la != null ) && ( ra != null ) ) { return createLevelData ( la, ra, tal ); } else { return null; } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badLevelSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad level specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badReorderSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad reorder specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int[] createReorderArray ( List reorders, int[] levels ) { int nr = reorders.size(); int nl = levels.length; if ( nr <= nl ) { int[] ra = new int [ nl ]; Iterator it = reorders.iterator(); for ( int i = 0, n = nl; i < n; i++ ) { int r = -1; if ( levels [ i ] >= 0 ) { if ( it.hasNext() ) { r = ( (Integer) it.next() ).intValue(); } } ra [ i ] = r; } return ra; } else { throw new IllegalArgumentException ( "excessive number of reorder array entries, expected no more than " + nl + ", but got " + nr + " entries" ); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badTestSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad test specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int[] createTestArray ( List classes, int bitset, int[] levels ) { int nc = classes.size(); if ( nc <= levels.length ) { int[] ta = new int [ 1 + nc ]; int k = 0; ta [ k++ ] = bitset; for ( Iterator it = classes.iterator(); it.hasNext(); ) { ta [ k++ ] = ( (Integer) it.next() ).intValue(); } return ta; } else { throw new IllegalArgumentException ( "excessive number of test array entries, expected no more than " + levels.length + ", but got " + nc + " entries" ); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static int parseBidiClass ( String bidiClass ) { int bc = 0; if ( "L".equals ( bidiClass ) ) { bc = BidiConstants.L; } else if ( "LRE".equals ( bidiClass ) ) { bc = BidiConstants.LRE; } else if ( "LRO".equals ( bidiClass ) ) { bc = BidiConstants.LRO; } else if ( "R".equals ( bidiClass ) ) { bc = BidiConstants.R; } else if ( "AL".equals ( bidiClass ) ) { bc = BidiConstants.AL; } else if ( "RLE".equals ( bidiClass ) ) { bc = BidiConstants.RLE; } else if ( "RLO".equals ( bidiClass ) ) { bc = BidiConstants.RLO; } else if ( "PDF".equals ( bidiClass ) ) { bc = BidiConstants.PDF; } else if ( "EN".equals ( bidiClass ) ) { bc = BidiConstants.EN; } else if ( "ES".equals ( bidiClass ) ) { bc = BidiConstants.ES; } else if ( "ET".equals ( bidiClass ) ) { bc = BidiConstants.ET; } else if ( "AN".equals ( bidiClass ) ) { bc = BidiConstants.AN; } else if ( "CS".equals ( bidiClass ) ) { bc = BidiConstants.CS; } else if ( "NSM".equals ( bidiClass ) ) { bc = BidiConstants.NSM; } else if ( "BN".equals ( bidiClass ) ) { bc = BidiConstants.BN; } else if ( "B".equals ( bidiClass ) ) { bc = BidiConstants.B; } else if ( "S".equals ( bidiClass ) ) { bc = BidiConstants.S; } else if ( "WS".equals ( bidiClass ) ) { bc = BidiConstants.WS; } else if ( "ON".equals ( bidiClass ) ) { bc = BidiConstants.ON; } else { throw new IllegalArgumentException ( "unknown bidi class: " + bidiClass ); } return bc; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
public void setDestDir(File destDir) { if (!destDir.isDirectory()) { throw new IllegalArgumentException("destDir must be a directory"); } this.destDir = destDir; }
37
              
// in src/java/org/apache/fop/apps/FOUserAgent.java
catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + mappingClassName); }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + mappingClassName); }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + mappingClassName); }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(mappingClassName + " is not an ElementMapping"); }
// in src/java/org/apache/fop/fonts/FontUtil.java
catch (NumberFormatException nfe) { //weight is no number, so convert symbolic name to number if (text.equals("normal")) { weight = 400; } else if (text.equals("bold")) { weight = 700; } else { throw new IllegalArgumentException( "Illegal value for font weight: '" + text + "'. Use one of: 100, 200, 300, " + "400, 500, 600, 700, 800, 900, " + "normal (=400), bold (=700)"); } }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + XMLHandler.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractRendererMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractFOEventHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractIFDocumentHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ImageHandler.class.getName()); }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/java/org/apache/fop/afp/modca/triplets/AttributeValueTriplet.java
catch (UnsupportedEncodingException usee) { tleByteValue = attVal.getBytes(); throw new IllegalArgumentException(attVal + " encoding failed"); }
// in src/java/org/apache/fop/afp/modca/triplets/FullyQualifiedNameTriplet.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( encoding + " encoding failed"); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/traits/BorderProps.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ContentHandlerFactory.class.getName()); }
23
              
// in src/java/org/apache/fop/fo/pagination/Root.java
public void notifyPageSequenceFinished(int lastPageNumber, int additionalPages) throws IllegalArgumentException { if (additionalPages >= 0) { totalPagesGenerated += additionalPages; endingPageNumberOfPreviousSequence = lastPageNumber; } else { throw new IllegalArgumentException( "Number of additional pages must be zero or greater."); } }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
public void addElementMapping(String mappingClassName) throws IllegalArgumentException { try { ElementMapping mapping = (ElementMapping)Class.forName(mappingClassName).newInstance(); addElementMapping(mapping); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + mappingClassName); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + mappingClassName); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + mappingClassName); } catch (ClassCastException e) { throw new IllegalArgumentException(mappingClassName + " is not an ElementMapping"); } }
// in src/java/org/apache/fop/traits/MinOptMax.java
public static MinOptMax getInstance(int min, int opt, int max) throws IllegalArgumentException { if (min > opt) { throw new IllegalArgumentException("min (" + min + ") > opt (" + opt + ")"); } if (max < opt) { throw new IllegalArgumentException("max (" + max + ") < opt (" + opt + ")"); } return new MinOptMax(min, opt, max); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax plusMin(int minOperand) throws IllegalArgumentException { return getInstance(min + minOperand, opt, max); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax minusMin(int minOperand) throws IllegalArgumentException { return getInstance(min - minOperand, opt, max); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax plusMax(int maxOperand) throws IllegalArgumentException { return getInstance(min, opt, max + maxOperand); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax minusMax(int maxOperand) throws IllegalArgumentException { return getInstance(min, opt, max - maxOperand); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax mult(int factor) throws IllegalArgumentException { if (factor < 0) { throw new IllegalArgumentException("factor < 0; was: " + factor); } else if (factor == 1) { return this; } else { return getInstance(min * factor, opt * factor, max * factor); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int getGlyphForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( ci <= ciMax ) { return gi + delta; } else { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + ciMax ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int getGlyphForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( glyphs == null ) { return -1; } else if ( ci >= glyphs.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + glyphs.length ); } else { return glyphs [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int[] getGlyphsForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( gsa == null ) { return null; } else if ( ci >= gsa.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + gsa.length ); } else { return gsa [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int[] getAlternatesForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( gaa == null ) { return null; } else if ( ci >= gaa.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + gaa.length ); } else { return gaa [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public LigatureSet getLigatureSetForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( ligatureSets == null ) { return null; } else if ( ci >= ligatureSets.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + ligatureSets.length ); } else { return ligatureSets [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java
private static boolean convertToScalar ( CharSequence cs, int[] chars ) throws IllegalArgumentException { boolean triggered = false; if ( chars.length != cs.length() ) { throw new IllegalArgumentException ( "characters array length must match input sequence length" ); } for ( int i = 0, n = chars.length; i < n; ) { int chIn = cs.charAt ( i ); int chOut; if ( chIn < 0xD800 ) { chOut = chIn; } else if ( chIn < 0xDC00 ) { int chHi = chIn; int chLo; if ( ( i + 1 ) < n ) { chLo = cs.charAt ( i + 1 ); if ( ( chLo >= 0xDC00 ) && ( chLo <= 0xDFFF ) ) { chOut = convertToScalar ( chHi, chLo ); } else { throw new IllegalArgumentException ( "isolated high surrogate" ); } } else { throw new IllegalArgumentException ( "truncated surrogate pair" ); } } else if ( chIn < 0xE000 ) { throw new IllegalArgumentException ( "isolated low surrogate" ); } else { chOut = chIn; } if ( ! triggered && triggersBidi ( chOut ) ) { triggered = true; } if ( ( chOut & 0xFF0000 ) == 0 ) { chars [ i++ ] = chOut; } else { chars [ i++ ] = chOut; chars [ i++ ] = -1; } } return triggered; }
// in src/java/org/apache/fop/complexscripts/util/NumberConverter.java
private void parseFormatTokens ( String format ) throws IllegalArgumentException { List<Integer[]> tokens = new ArrayList<Integer[]>(); List<Integer[]> separators = new ArrayList<Integer[]>(); if ( ( format == null ) || ( format.length() == 0 ) ) { format = "1"; } int tokenType = TOKEN_NONE; List<Integer> token = new ArrayList<Integer>(); Integer[] ca = UTF32.toUTF32 ( format, 0, true ); for ( int i = 0, n = ca.length; i < n; i++ ) { int c = ca[i]; int tokenTypeNew = isAlphaNumeric ( c ) ? TOKEN_ALPHANUMERIC : TOKEN_NONALPHANUMERIC; if ( tokenTypeNew != tokenType ) { if ( token.size() > 0 ) { if ( tokenType == TOKEN_ALPHANUMERIC ) { tokens.add ( token.toArray ( new Integer [ token.size() ] ) ); } else { separators.add ( token.toArray ( new Integer [ token.size() ] ) ); } token.clear(); } tokenType = tokenTypeNew; } token.add ( c ); } if ( token.size() > 0 ) { if ( tokenType == TOKEN_ALPHANUMERIC ) { tokens.add ( token.toArray ( new Integer [ token.size() ] ) ); } else { separators.add ( token.toArray ( new Integer [ token.size() ] ) ); } } if ( ! separators.isEmpty() ) { this.prefix = separators.remove ( 0 ); } if ( ! separators.isEmpty() ) { this.suffix = separators.remove ( separators.size() - 1 ); } this.separators = separators.toArray ( new Integer [ separators.size() ] [] ); this.tokens = tokens.toArray ( new Integer [ tokens.size() ] [] ); }
// in src/java/org/apache/fop/complexscripts/util/UTF32.java
public static Integer[] toUTF32 ( String s, int substitution, boolean errorOnSubstitution ) throws IllegalArgumentException { int n; if ( ( n = s.length() ) == 0 ) { return new Integer[0]; } else { Integer[] sa = new Integer [ n ]; int k = 0; for ( int i = 0; i < n; i++ ) { int c = (int) s.charAt(i); if ( ( c >= 0xD800 ) && ( c < 0xE000 ) ) { int s1 = c; int s2 = ( ( i + 1 ) < n ) ? (int) s.charAt ( i + 1 ) : 0; if ( s1 < 0xDC00 ) { if ( ( s2 >= 0xDC00 ) && ( s2 < 0xE000 ) ) { c = ( ( s1 - 0xD800 ) << 10 ) + ( s2 - 0xDC00 ) + 65536; i++; } else { if ( errorOnSubstitution ) { throw new IllegalArgumentException ( "isolated high (leading) surrogate" ); } else { c = substitution; } } } else { if ( errorOnSubstitution ) { throw new IllegalArgumentException ( "isolated low (trailing) surrogate" ); } else { c = substitution; } } } sa[k++] = c; } if ( k == n ) { return sa; } else { Integer[] na = new Integer [ k ]; System.arraycopy ( sa, 0, na, 0, k ); return na; } } }
// in src/java/org/apache/fop/complexscripts/util/UTF32.java
public static String fromUTF32 ( Integer[] sa ) throws IllegalArgumentException { StringBuffer sb = new StringBuffer(); for ( int s : sa ) { if ( s < 65535 ) { if ( ( s < 0xD800 ) || ( s > 0xDFFF ) ) { sb.append ( (char) s ); } else { String ncr = CharUtilities.charToNCRef(s); throw new IllegalArgumentException ( "illegal scalar value 0x" + ncr.substring(2, ncr.length() - 1) + "; cannot be UTF-16 surrogate" ); } } else if ( s < 1114112 ) { int s1 = ( ( ( s - 65536 ) >> 10 ) & 0x3FF ) + 0xD800; int s2 = ( ( ( s - 65536 ) >> 0 ) & 0x3FF ) + 0xDC00; sb.append ( (char) s1 ); sb.append ( (char) s2 ); } else { String ncr = CharUtilities.charToNCRef(s); throw new IllegalArgumentException ( "illegal scalar value 0x" + ncr.substring(2, ncr.length() - 1) + "; out of range for UTF-16" ); } } return sb.toString(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badRangeSpec ( String reason, String charRanges ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad range specification: " + reason + ": \"" + charRanges + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badRangeSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad range specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badLevelSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad level specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badReorderSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad reorder specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badTestSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad test specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
(Domain) AdvancedTypographicTableFormatException 160
              
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( ( entries == null ) || ( entries.size() != 1 ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null and contain exactly one entry" ); } else { Value v; Object o = entries.get(0); if ( o instanceof Value ) { v = (Value) o; } else { throw new AdvancedTypographicTableFormatException ( "illegal entries entry, must be Value, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } assert this.value == null; this.value = v; this.ciMax = getCoverageSize() - 1; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof Value[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, single entry must be a Value[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { Value[] va = (Value[]) o; if ( va.length != getCoverageSize() ) { throw new AdvancedTypographicTableFormatException ( "illegal values array, " + entries.size() + " values present, but requires " + getCoverageSize() + " values" ); } else { assert this.values == null; this.values = va; } } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof PairValues[][] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first (and only) entry must be a PairValues[][], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { pvm = (PairValues[][]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 5 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 5 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphClassTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { cdt1 = (GlyphClassTable) o; } if ( ( ( o = entries.get(1) ) == null ) || ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an GlyphClassTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { cdt2 = (GlyphClassTable) o; } if ( ( ( o = entries.get(2) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { nc1 = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(3) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fourth entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { nc2 = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(4) ) == null ) || ! ( o instanceof PairValues[][] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fifth entry must be a PairValues[][], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { pvm = (PairValues[][]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof Anchor[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first (and only) entry must be a Anchor[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else if ( ( ( (Anchor[]) o ) . length % 2 ) != 0 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, Anchor[] array must have an even number of entries, but has: " + ( (Anchor[]) o ) . length ); } else { aa = (Anchor[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 4 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 4 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphCoverageTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphCoverageTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { bct = (GlyphCoverageTable) o; } if ( ( ( o = entries.get(1) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { nmc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(2) ) == null ) || ! ( o instanceof MarkAnchor[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be a MarkAnchor[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { maa = (MarkAnchor[]) o; } if ( ( ( o = entries.get(3) ) == null ) || ! ( o instanceof Anchor[][] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fourth entry must be a Anchor[][], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { bam = (Anchor[][]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 5 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 5 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphCoverageTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphCoverageTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { lct = (GlyphCoverageTable) o; } if ( ( ( o = entries.get(1) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { nmc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(2) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { mxc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(3) ) == null ) || ! ( o instanceof MarkAnchor[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fourth entry must be a MarkAnchor[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { maa = (MarkAnchor[]) o; } if ( ( ( o = entries.get(4) ) == null ) || ! ( o instanceof Anchor[][][] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fifth entry must be a Anchor[][][], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { lam = (Anchor[][][]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 4 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 4 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphCoverageTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphCoverageTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { mct2 = (GlyphCoverageTable) o; } if ( ( ( o = entries.get(1) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { nmc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(2) ) == null ) || ! ( o instanceof MarkAnchor[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be a MarkAnchor[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { maa = (MarkAnchor[]) o; } if ( ( ( o = entries.get(3) ) == null ) || ! ( o instanceof Anchor[][] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fourth entry must be a Anchor[][], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { mam = (Anchor[][]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 3 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 3 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphClassTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { cdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(1) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { ngc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(2) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; if ( rsa.length != ngc ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, RuleSet[] length is " + rsa.length + ", but expected " + ngc + " glyph classes" ); } } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 5 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 5 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphClassTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { icdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(1) ) != null ) && ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an GlyphClassTable, but is: " + o.getClass() ); } else { bcdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(2) ) != null ) && ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be an GlyphClassTable, but is: " + o.getClass() ); } else { lcdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(3) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fourth entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { ngc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(4) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fifth entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; if ( rsa.length != ngc ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, RuleSet[] length is " + rsa.length + ", but expected " + ngc + " glyph classes" ); } } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphCoverageTable.java
private void populate ( List entries ) { int i = 0; int skipped = 0; int n = entries.size(); int gidMax = -1; int[] map = new int [ n ]; for ( Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); if ( o instanceof Integer ) { int gid = ( (Integer) o ) . intValue(); if ( ( gid >= 0 ) && ( gid < 65536 ) ) { if ( gid > gidMax ) { map [ i++ ] = gidMax = gid; } else { log.info ( "ignoring out of order or duplicate glyph index: " + gid ); skipped++; } } else { throw new AdvancedTypographicTableFormatException ( "illegal glyph index: " + gid ); } } else { throw new AdvancedTypographicTableFormatException ( "illegal coverage entry, must be Integer: " + o ); } } assert ( i + skipped ) == n; assert this.map == null; this.map = map; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphTable.java
private void validateSubtable ( GlyphSubtable subtable ) { if ( subtable == null ) { throw new AdvancedTypographicTableFormatException ( "subtable must be non-null" ); } if ( subtable instanceof GlyphSubstitutionSubtable ) { if ( doesPos ) { throw new AdvancedTypographicTableFormatException ( "subtable must be positioning subtable, but is: " + subtable ); } else { doesSub = true; } } if ( subtable instanceof GlyphPositioningSubtable ) { if ( doesSub ) { throw new AdvancedTypographicTableFormatException ( "subtable must be substitution subtable, but is: " + subtable ); } else { doesPos = true; } } if ( subtables.size() > 0 ) { GlyphSubtable st = (GlyphSubtable) subtables.get(0); if ( ! st.isCompatible ( subtable ) ) { throw new AdvancedTypographicTableFormatException ( "subtable " + subtable + " is not compatible with subtable " + st ); } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphMappingTable.java
private void populate ( List entries ) { int i = 0; int n = entries.size(); int gidMax = -1; int miMax = -1; int[] sa = new int [ n ]; int[] ea = new int [ n ]; int[] ma = new int [ n ]; for ( Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); if ( o instanceof MappingRange ) { MappingRange r = (MappingRange) o; int gs = r.getStart(); int ge = r.getEnd(); int mi = r.getIndex(); if ( ( gs < 0 ) || ( gs > 65535 ) ) { throw new AdvancedTypographicTableFormatException ( "illegal glyph range: [" + gs + "," + ge + "]: bad start index" ); } else if ( ( ge < 0 ) || ( ge > 65535 ) ) { throw new AdvancedTypographicTableFormatException ( "illegal glyph range: [" + gs + "," + ge + "]: bad end index" ); } else if ( gs > ge ) { throw new AdvancedTypographicTableFormatException ( "illegal glyph range: [" + gs + "," + ge + "]: start index exceeds end index" ); } else if ( gs < gidMax ) { throw new AdvancedTypographicTableFormatException ( "out of order glyph range: [" + gs + "," + ge + "]" ); } else if ( mi < 0 ) { throw new AdvancedTypographicTableFormatException ( "illegal mapping index: " + mi ); } else { int miLast; sa [ i ] = gs; ea [ i ] = gidMax = ge; ma [ i ] = mi; if ( ( miLast = mi + ( ge - gs ) ) > miMax ) { miMax = miLast; } i++; } } else { throw new AdvancedTypographicTableFormatException ( "illegal mapping entry, must be Integer: " + o ); } } assert i == n; assert this.sa == null; assert this.ea == null; assert this.ma == null; this.sa = sa; this.ea = ea; this.ma = ma; this.miMax = miMax; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
public void readAll() throws AdvancedTypographicTableFormatException { try { readGDEF(); readGSUB(); readGPOS(); } catch ( AdvancedTypographicTableFormatException e ) { resetATStateAll(); throw e; } catch ( IOException e ) { resetATStateAll(); throw new AdvancedTypographicTableFormatException ( e.getMessage(), e ); } finally { resetATState(); } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphCoverageTable readCoverageTable(String label, long tableOffset) throws IOException { GlyphCoverageTable gct; long cp = in.getCurrentPos(); in.seekSet(tableOffset); // read coverage table format int cf = in.readTTFUShort(); if ( cf == 1 ) { gct = readCoverageTableFormat1 ( label, tableOffset, cf ); } else if ( cf == 2 ) { gct = readCoverageTableFormat2 ( label, tableOffset, cf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported coverage table format: " + cf ); } in.seekSet ( cp ); return gct; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphClassTable readClassDefTable(String label, long tableOffset) throws IOException { GlyphClassTable gct; long cp = in.getCurrentPos(); in.seekSet(tableOffset); // read class table format int cf = in.readTTFUShort(); if ( cf == 1 ) { gct = readClassDefTableFormat1 ( label, tableOffset, cf ); } else if ( cf == 2 ) { gct = readClassDefTableFormat2 ( label, tableOffset, cf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported class definition table format: " + cf ); } in.seekSet ( cp ); return gct; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readSingleSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readSingleSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readSingleSubTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported single substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMultipleSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMultipleSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported multiple substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readAlternateSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readAlternateSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported alternate substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readLigatureSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readLigatureSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported ligature substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readContextualSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readContextualSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readContextualSubTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readContextualSubTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported contextual substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readChainedContextualSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readChainedContextualSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readChainedContextualSubTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readChainedContextualSubTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported chained contextual substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readExtensionSubTable(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readExtensionSubTableFormat1 ( lookupType, lookupFlags, lookupSequence, subtableSequence, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported extension substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readReverseChainedSingleSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readReverseChainedSingleSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported reverse chained single substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readSinglePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positionining subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readSinglePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readSinglePosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported single positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readPairPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readPairPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readPairPosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported pair positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphPositioningTable.Anchor readPosAnchor(long anchorTableOffset) throws IOException { GlyphPositioningTable.Anchor a; long cp = in.getCurrentPos(); in.seekSet(anchorTableOffset); // read anchor table format int af = in.readTTFUShort(); if ( af == 1 ) { // read x coordinate int x = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read y coordinate int y = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); a = new GlyphPositioningTable.Anchor ( x, y ); } else if ( af == 2 ) { // read x coordinate int x = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read y coordinate int y = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read anchor point index int ap = in.readTTFUShort(); a = new GlyphPositioningTable.Anchor ( x, y, ap ); } else if ( af == 3 ) { // read x coordinate int x = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read y coordinate int y = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read x device table offset int xdo = in.readTTFUShort(); // read y device table offset int ydo = in.readTTFUShort(); // read x device table (if present) GlyphPositioningTable.DeviceTable xd; if ( xdo != 0 ) { xd = readPosDeviceTable ( cp, xdo ); } else { xd = null; } // read y device table (if present) GlyphPositioningTable.DeviceTable yd; if ( ydo != 0 ) { yd = readPosDeviceTable ( cp, ydo ); } else { yd = null; } a = new GlyphPositioningTable.Anchor ( x, y, xd, yd ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported positioning anchor format: " + af ); } in.seekSet(cp); return a; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readCursivePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readCursivePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported cursive positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMarkToBasePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMarkToBasePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark-to-base positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMarkToLigaturePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMarkToLigaturePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark-to-ligature positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMarkToMarkPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMarkToMarkPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark-to-mark positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readContextualPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readContextualPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readContextualPosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readContextualPosTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported contextual positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readChainedContextualPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readChainedContextualPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readChainedContextualPosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readChainedContextualPosTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported chained contextual positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readExtensionPosTable(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readExtensionPosTableFormat1 ( lookupType, lookupFlags, lookupSequence, subtableSequence, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported extension positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFMarkGlyphsTable(String tableTag, int lookupSequence, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read mark set subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readGDEFMarkGlyphsTableFormat1 ( tableTag, lookupSequence, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark glyph sets subtable format: " + sf ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphClassTable.java
private void populate ( List entries ) { // obtain entries iterator Iterator it = entries.iterator(); // extract first glyph int firstGlyph = 0; if ( it.hasNext() ) { Object o = it.next(); if ( o instanceof Integer ) { firstGlyph = ( (Integer) o ) . intValue(); } else { throw new AdvancedTypographicTableFormatException ( "illegal entry, first entry must be Integer denoting first glyph value, but is: " + o ); } } // extract glyph class array int i = 0; int n = entries.size() - 1; int gcMax = -1; int[] gca = new int [ n ]; while ( it.hasNext() ) { Object o = it.next(); if ( o instanceof Integer ) { int gc = ( (Integer) o ) . intValue(); gca [ i++ ] = gc; if ( gc > gcMax ) { gcMax = gc; } } else { throw new AdvancedTypographicTableFormatException ( "illegal mapping entry, must be Integer: " + o ); } } assert i == n; assert this.gca == null; this.firstGlyph = firstGlyph; this.gca = gca; this.gcMax = gcMax; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( ( entries == null ) || ( entries.size() != 1 ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null and contain exactly one entry" ); } else { Object o = entries.get(0); int delta = 0; if ( o instanceof Integer ) { delta = ( (Integer) o ) . intValue(); } else { throw new AdvancedTypographicTableFormatException ( "illegal entries entry, must be Integer, but is: " + o ); } this.delta = delta; this.ciMax = getCoverageSize() - 1; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { int i = 0; int n = entries.size(); int[] glyphs = new int [ n ]; for ( Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); if ( o instanceof Integer ) { int gid = ( (Integer) o ) .intValue(); if ( ( gid >= 0 ) && ( gid < 65536 ) ) { glyphs [ i++ ] = gid; } else { throw new AdvancedTypographicTableFormatException ( "illegal glyph index: " + gid ); } } else { throw new AdvancedTypographicTableFormatException ( "illegal entries entry, must be Integer: " + o ); } } assert i == n; assert this.glyphs == null; this.glyphs = glyphs; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof int[][] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an int[][], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { gsa = (int[][]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { int i = 0; int n = entries.size(); int[][] gaa = new int [ n ][]; for ( Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); if ( o instanceof int[] ) { gaa [ i++ ] = (int[]) o; } else { throw new AdvancedTypographicTableFormatException ( "illegal entries entry, must be int[]: " + o ); } } assert i == n; assert this.gaa == null; this.gaa = gaa; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { int i = 0; int n = entries.size(); LigatureSet[] ligatureSets = new LigatureSet [ n ]; for ( Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); if ( o instanceof LigatureSet ) { ligatureSets [ i++ ] = (LigatureSet) o; } else { throw new AdvancedTypographicTableFormatException ( "illegal ligatures entry, must be LigatureSet: " + o ); } } assert i == n; assert this.ligatureSets == null; this.ligatureSets = ligatureSets; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 3 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 3 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphClassTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { cdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(1) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { ngc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(2) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; if ( rsa.length != ngc ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, RuleSet[] length is " + rsa.length + ", but expected " + ngc + " glyph classes" ); } } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 5 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 5 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphClassTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { icdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(1) ) != null ) && ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an GlyphClassTable, but is: " + o.getClass() ); } else { bcdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(2) ) != null ) && ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be an GlyphClassTable, but is: " + o.getClass() ); } else { lcdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(3) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fourth entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { ngc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(4) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fifth entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; if ( rsa.length != ngc ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, RuleSet[] length is " + rsa.length + ", but expected " + ngc + " glyph classes" ); } } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
1
              
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( IOException e ) { resetATStateAll(); throw new AdvancedTypographicTableFormatException ( e.getMessage(), e ); }
3
              
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
public void readAll() throws AdvancedTypographicTableFormatException { try { readGDEF(); readGSUB(); readGPOS(); } catch ( AdvancedTypographicTableFormatException e ) { resetATStateAll(); throw e; } catch ( IOException e ) { resetATStateAll(); throw new AdvancedTypographicTableFormatException ( e.getMessage(), e ); } finally { resetATState(); } }
(Domain) IFException 139
              
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void startViewport(String transform, Dimension size, Rectangle clipRect) throws IFException { try { establish(MODE_NORMAL); AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { XMLUtil.addAttribute(atts, "transform", transform); } handler.startElement("g", atts); atts.clear(); XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(size.width)); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(size.height)); if (clipRect != null) { int[] v = new int[] { clipRect.y, -clipRect.x + size.width - clipRect.width, -clipRect.y + size.height - clipRect.height, clipRect.x}; int sum = 0; for (int i = 0; i < 4; i++) { sum += Math.abs(v[i]); } if (sum != 0) { StringBuffer sb = new StringBuffer("rect("); sb.append(SVGUtil.formatMptToPt(v[0])).append(','); sb.append(SVGUtil.formatMptToPt(v[1])).append(','); sb.append(SVGUtil.formatMptToPt(v[2])).append(','); sb.append(SVGUtil.formatMptToPt(v[3])).append(')'); XMLUtil.addAttribute(atts, "clip", sb.toString()); } XMLUtil.addAttribute(atts, "overflow", "hidden"); } else { XMLUtil.addAttribute(atts, "overflow", "visible"); } handler.startElement("svg", atts); } catch (SAXException e) { throw new IFException("SAX error in startBox()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void endViewport() throws IFException { try { establish(MODE_NORMAL); handler.endElement("svg"); handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endBox()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void startGroup(String transform) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { XMLUtil.addAttribute(atts, "transform", transform); } handler.startElement("g", atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void endGroup() throws IFException { try { establish(MODE_NORMAL); handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { try { establish(MODE_NORMAL); ImageManager manager = getUserAgent().getFactory().getImageManager(); ImageInfo info = null; try { ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); info = manager.getImageInfo(uri, sessionContext); String mime = info.getMimeType(); Map foreignAttributes = getContext().getForeignAttributes(); String conversionMode = (String)foreignAttributes.get( ImageHandlerUtil.CONVERSION_MODE); if ("reference".equals(conversionMode) && (MimeConstants.MIME_GIF.equals(mime) || MimeConstants.MIME_JPEG.equals(mime) || MimeConstants.MIME_PNG.equals(mime) || MimeConstants.MIME_SVG.equals(mime))) { //Just reference the image //TODO Some additional URI rewriting might be necessary AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, IFConstants.XLINK_HREF, uri); XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(rect.x)); XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(rect.y)); XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(rect.width)); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(rect.height)); handler.element("image", atts); } else { drawImageUsingImageHandler(info, rect); } } catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); } catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); } } catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { try { establish(MODE_NORMAL); drawImageUsingDocument(doc, rect); } catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } try { establish(MODE_NORMAL); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(rect.x)); XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(rect.y)); XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(rect.width)); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(rect.height)); if (fill != null) { XMLUtil.addAttribute(atts, "fill", toString(fill)); } /* disabled if (stroke != null) { XMLUtil.addAttribute(atts, "stroke", toString(stroke)); }*/ handler.element("rect", atts); } catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { establish(MODE_NORMAL); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "x1", SVGUtil.formatMptToPt(start.x)); XMLUtil.addAttribute(atts, "y1", SVGUtil.formatMptToPt(start.y)); XMLUtil.addAttribute(atts, "x2", SVGUtil.formatMptToPt(end.x)); XMLUtil.addAttribute(atts, "y2", SVGUtil.formatMptToPt(end.y)); XMLUtil.addAttribute(atts, "stroke-width", toString(color)); XMLUtil.addAttribute(atts, "fill", toString(color)); //TODO Handle style parameter handler.element("line", atts); } catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { establish(MODE_TEXT); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, XMLConstants.XML_SPACE, "preserve"); XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(x)); XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(y)); if (letterSpacing != 0) { XMLUtil.addAttribute(atts, "letter-spacing", SVGUtil.formatMptToPt(letterSpacing)); } if (wordSpacing != 0) { XMLUtil.addAttribute(atts, "word-spacing", SVGUtil.formatMptToPt(wordSpacing)); } if (dp != null) { int[] dx = IFUtil.convertDPToDX(dp); XMLUtil.addAttribute(atts, "dx", SVGUtil.formatMptArrayToPt(dx)); } handler.startElement("text", atts); char[] chars = text.toCharArray(); handler.characters(chars, 0, chars.length); handler.endElement("text"); } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof Metadata) { Metadata meta = (Metadata)extension; try { establish(MODE_NORMAL); handler.startElement("metadata"); meta.toSAX(this.handler); handler.endElement("metadata"); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { throw new UnsupportedOperationException( "Don't know how to handle extension object: " + extension); } }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
public void startDocumentHeader() throws IFException { try { handler.startElement("defs"); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
public void endDocumentHeader() throws IFException { try { handler.endElement("defs"); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof Metadata) { Metadata meta = (Metadata)extension; try { handler.startElement("metadata"); meta.toSAX(this.handler); handler.endElement("metadata"); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { log.debug("Don't know how to handle extension object. Ignoring: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); builderFactory.setValidating(false); try { DocumentBuilder builder = builderFactory.newDocumentBuilder(); this.reusedParts = builder.newDocument(); } catch (ParserConfigurationException e) { throw new IFException("Error while setting up a DOM for SVG generation", e); } try { TransformerHandler toDOMHandler = tFactory.newTransformerHandler(); toDOMHandler.setResult(new DOMResult(this.reusedParts)); this.handler = decorate(toDOMHandler); this.handler.startDocument(); } catch (SAXException se) { throw new IFException("SAX error in startDocument()", se); } catch (TransformerConfigurationException e) { throw new IFException( "Error while setting up a TransformerHandler for SVG generation", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endDocumentHeader() throws IFException { super.endDocumentHeader(); try { //Stop recording parts reused for each page this.handler.endDocument(); this.handler = null; } catch (SAXException e) { throw new IFException("SAX error in endDocumentHeader()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { if (this.multiFileUtil != null) { prepareHandlerWithOutputStream(index); } else { if (this.simpleResult == null) { //Only one page is supported with this approach at the moment throw new IFException( "Only one page is supported for output with the given Result instance!", null); } super.setResult(this.simpleResult); this.simpleResult = null; } try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "version", "1.1"); //SVG 1.1 /* XMLUtil.addAttribute(atts, "index", Integer.toString(index)); XMLUtil.addAttribute(atts, "name", name); */ XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(size.width) + "pt"); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(size.height) + "pt"); XMLUtil.addAttribute(atts, "viewBox", "0 0 " + SVGUtil.formatMptToPt(size.width) + " " + SVGUtil.formatMptToPt(size.height)); handler.startElement("svg", atts); try { Transformer transformer = tFactory.newTransformer(); Source src = new DOMSource(this.reusedParts.getDocumentElement()); Result res = new SAXResult(new DelegatingFragmentContentHandler(this.handler)); transformer.transform(src, res); } catch (TransformerConfigurationException tce) { throw new IFException("Error setting up a Transformer", tce); } catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException)te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } } } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
private void prepareHandlerWithOutputStream(int index) throws IFException { OutputStream out; try { if (index == 0) { out = null; } else { out = this.multiFileUtil.createOutputStream(index); if (out == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.stoppingAfterFirstPageNoFilename(this); } } } catch (IOException ioe) { throw new IFException("I/O exception while setting up output file", ioe); } if (out == null) { this.handler = decorate(createContentHandler(this.firstStream)); } else { this.currentStream = new StreamResult(out); this.handler = decorate(createContentHandler(this.currentStream)); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public IFPainter startPageContent() throws IFException { try { handler.startElement("g"); } catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); } return new SVGPainter(this, handler); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endPageContent() throws IFException { try { handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endPage() throws IFException { try { handler.endElement("svg"); this.handler.endDocument(); } catch (SAXException e) { throw new IFException("SAX error in endPage()", e); } closeCurrentStream(); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); handler.startPrefixMapping("if", IFConstants.NAMESPACE); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "version", "1.2"); //SVG Print is SVG 1.2 handler.startElement("svg", atts); } catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endDocument() throws IFException { try { handler.endElement("svg"); handler.endDocument(); } catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startPageSequence(String id) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (id != null) { atts.addAttribute(XML_NAMESPACE, "id", "xml:id", CDATA, id); } handler.startElement("pageSet", atts); } catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPageSequence() throws IFException { try { handler.endElement("pageSet"); } catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { AttributesImpl atts = new AttributesImpl(); /* XMLUtil.addAttribute(atts, "index", Integer.toString(index)); XMLUtil.addAttribute(atts, "name", name); */ //NOTE: SVG Print doesn't support individual page sizes for each page atts.addAttribute(IFConstants.NAMESPACE, "width", "if:width", CDATA, Integer.toString(size.width)); atts.addAttribute(IFConstants.NAMESPACE, "height", "if:height", CDATA, Integer.toString(size.height)); atts.addAttribute(IFConstants.NAMESPACE, "viewBox", "if:viewBox", CDATA, "0 0 " + Integer.toString(size.width) + " " + Integer.toString(size.height)); handler.startElement("page", atts); } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public IFPainter startPageContent() throws IFException { try { handler.startElement("g"); } catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); } return new SVGPainter(this, handler); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPageContent() throws IFException { try { handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPage() throws IFException { try { handler.endElement("page"); } catch (SAXException e) { throw new IFException("SAX error in endPage()", e); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
private void flushPDFDoc() throws IFException { // output new data try { generator.flushPDFDoc(); } catch (IOException ioe) { throw new IFException("I/O error flushing the PDF document", ioe); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
Override public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { generator.endTextObject(); try { this.borderPainter.drawBorders(rect, top, bottom, left, right); } catch (IOException ioe) { throw new IFException("I/O error while drawing borders", ioe); } } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); try { this.pdfDoc = pdfUtil.setupPDFDocument(this.outputStream); this.accessEnabled = getUserAgent().isAccessibilityEnabled(); if (accessEnabled) { setupAccessibility(); } } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endDocument() throws IFException { try { pdfDoc.getResources().addFonts(pdfDoc, fontInfo); pdfDoc.outputTrailer(this.outputStream); this.pdfDoc = null; pdfResources = null; this.generator = null; currentContext = null; currentPage = null; } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endPage() throws IFException { if (accessEnabled) { logicalStructureHandler.endPage(); } try { this.documentNavigationHandler.commit(); this.pdfDoc.registerObject(generator.getStream()); currentPage.setContents(generator.getStream()); PDFAnnotList annots = currentPage.getAnnotations(); if (annots != null) { this.pdfDoc.addObject(annots); } this.pdfDoc.addObject(currentPage); this.generator.flushPDFDoc(); this.generator = null; } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof XMPMetadata) { pdfUtil.renderXMPMetadata((XMPMetadata) extension); } else if (extension instanceof Metadata) { XMPMetadata wrapper = new XMPMetadata(((Metadata) extension)); pdfUtil.renderXMPMetadata(wrapper); } else if (extension instanceof PDFEmbeddedFileExtensionAttachment) { PDFEmbeddedFileExtensionAttachment embeddedFile = (PDFEmbeddedFileExtensionAttachment)extension; try { pdfUtil.addEmbeddedFile(embeddedFile); } catch (IOException ioe) { throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe); } } else { log.debug("Don't know how to handle extension object. Ignoring: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { String family = attributes.getValue("family"); String style = attributes.getValue("style"); Integer weight = XMLUtil.getAttributeAsInteger(attributes, "weight"); String variant = attributes.getValue("variant"); Integer size = XMLUtil.getAttributeAsInteger(attributes, "size"); Color color; try { color = getAttributeAsColor(attributes, "color"); } catch (PropertyException pe) { throw new IFException("Error parsing the color attribute", pe); } painter.setFont(family, style, weight, variant, size, color); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int x = Integer.parseInt(attributes.getValue("x")); int y = Integer.parseInt(attributes.getValue("y")); int width = Integer.parseInt(attributes.getValue("width")); int height = Integer.parseInt(attributes.getValue("height")); Color fillColor; try { fillColor = getAttributeAsColor(attributes, "fill"); } catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); } painter.fillRect(new Rectangle(x, y, width, height), fillColor); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int x1 = Integer.parseInt(attributes.getValue("x1")); int y1 = Integer.parseInt(attributes.getValue("y1")); int x2 = Integer.parseInt(attributes.getValue("x2")); int y2 = Integer.parseInt(attributes.getValue("y2")); int width = Integer.parseInt(attributes.getValue("stroke-width")); Color color; try { color = getAttributeAsColor(attributes, "color"); } catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); } RuleStyle style = RuleStyle.valueOf(attributes.getValue("style")); painter.drawLine(new Point(x1, y1), new Point(x2, y2), width, color, style); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { int x = Integer.parseInt(lastAttributes.getValue("x")); int y = Integer.parseInt(lastAttributes.getValue("y")); int width = Integer.parseInt(lastAttributes.getValue("width")); int height = Integer.parseInt(lastAttributes.getValue("height")); Map<QName, String> foreignAttributes = getForeignAttributes(lastAttributes); establishForeignAttributes(foreignAttributes); establishStructureTreeElement(lastAttributes); if (foreignObject != null) { painter.drawImage(foreignObject, new Rectangle(x, y, width, height)); foreignObject = null; } else { String uri = lastAttributes.getValue( XLINK_HREF.getNamespaceURI(), XLINK_HREF.getLocalName()); if (uri == null) { throw new IFException("xlink:href is missing on image", null); } painter.drawImage(uri, new Rectangle(x, y, width, height)); } resetForeignAttributes(); resetStructureTreeElement(); inForeignObject = false; }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startDocument() throws IFException { super.startDocument(); try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); handler.startPrefixMapping(DocumentNavigationExtensionConstants.PREFIX, DocumentNavigationExtensionConstants.NAMESPACE); handler.startPrefixMapping(InternalElementMapping.STANDARD_PREFIX, InternalElementMapping.URI); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "version", VERSION); handler.startElement(EL_DOCUMENT, atts); } catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startDocumentHeader() throws IFException { try { handler.startElement(EL_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endDocumentHeader() throws IFException { try { handler.endElement(EL_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startDocumentTrailer() throws IFException { try { handler.startElement(EL_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endDocumentTrailer() throws IFException { try { handler.endElement(EL_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in endDocumentTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endDocument() throws IFException { try { handler.endElement(EL_DOCUMENT); handler.endDocument(); finishDocumentNavigation(); } catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startPageSequence(String id) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (id != null) { atts.addAttribute(XML_NAMESPACE, "id", "xml:id", XMLUtil.CDATA, id); } Locale lang = getContext().getLanguage(); if (lang != null) { atts.addAttribute(XML_NAMESPACE, "lang", "xml:lang", XMLUtil.CDATA, LanguageTags.toLanguageTag(lang)); } XMLUtil.addAttribute(atts, XMLConstants.XML_SPACE, "preserve"); addForeignAttributes(atts); handler.startElement(EL_PAGE_SEQUENCE, atts); if (this.getUserAgent().isAccessibilityEnabled()) { assert (structureTreeBuilder != null); structureTreeBuilder.replayEventsForPageSequence(handler, pageSequenceIndex++); } } catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endPageSequence() throws IFException { try { handler.endElement(EL_PAGE_SEQUENCE); } catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "index", Integer.toString(index)); addAttribute(atts, "name", name); addAttribute(atts, "page-master-name", pageMasterName); addAttribute(atts, "width", Integer.toString(size.width)); addAttribute(atts, "height", Integer.toString(size.height)); addForeignAttributes(atts); handler.startElement(EL_PAGE, atts); } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startPageHeader() throws IFException { try { handler.startElement(EL_PAGE_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startPageHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endPageHeader() throws IFException { try { handler.endElement(EL_PAGE_HEADER); } catch (SAXException e) { throw new IFException("SAX error in endPageHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public IFPainter startPageContent() throws IFException { try { handler.startElement(EL_PAGE_CONTENT); this.state = IFState.create(); return this; } catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endPageContent() throws IFException { try { this.state = null; currentID = ""; handler.endElement(EL_PAGE_CONTENT); } catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startPageTrailer() throws IFException { try { handler.startElement(EL_PAGE_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in startPageTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endPageTrailer() throws IFException { try { commitNavigation(); handler.endElement(EL_PAGE_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in endPageTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endPage() throws IFException { try { handler.endElement(EL_PAGE); } catch (SAXException e) { throw new IFException("SAX error in endPage()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void startViewport(String transform, Dimension size, Rectangle clipRect) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { addAttribute(atts, "transform", transform); } addAttribute(atts, "width", Integer.toString(size.width)); addAttribute(atts, "height", Integer.toString(size.height)); if (clipRect != null) { addAttribute(atts, "clip-rect", IFUtil.toString(clipRect)); } handler.startElement(EL_VIEWPORT, atts); } catch (SAXException e) { throw new IFException("SAX error in startViewport()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endViewport() throws IFException { try { handler.endElement(EL_VIEWPORT); } catch (SAXException e) { throw new IFException("SAX error in endViewport()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void startGroup(String transform) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { addAttribute(atts, "transform", transform); } handler.startElement(EL_GROUP, atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endGroup() throws IFException { try { handler.endElement(EL_GROUP); } catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawImage(String uri, Rectangle rect) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, XLINK_HREF, uri); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addForeignAttributes(atts); addStructureReference(atts); handler.element(EL_IMAGE, atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawImage(Document doc, Rectangle rect) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addForeignAttributes(atts); addStructureReference(atts); handler.startElement(EL_IMAGE, atts); new DOM2SAX(handler).writeDocument(doc, true); handler.endElement(EL_IMAGE); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void clipRect(Rectangle rect) throws IFException { try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); handler.element(EL_CLIP_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in clipRect()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addAttribute(atts, "fill", toString(fill)); handler.element(EL_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top == null && bottom == null && left == null && right == null) { return; } try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); if (top != null) { addAttribute(atts, "top", top.toString()); } if (bottom != null) { addAttribute(atts, "bottom", bottom.toString()); } if (left != null) { addAttribute(atts, "left", left.toString()); } if (right != null) { addAttribute(atts, "right", right.toString()); } handler.element(EL_BORDER_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in drawBorderRect()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x1", Integer.toString(start.x)); addAttribute(atts, "y1", Integer.toString(start.y)); addAttribute(atts, "x2", Integer.toString(end.x)); addAttribute(atts, "y2", Integer.toString(end.y)); addAttribute(atts, "stroke-width", Integer.toString(width)); addAttribute(atts, "color", ColorUtil.colorToString(color)); addAttribute(atts, "style", style.getName()); handler.element(EL_LINE, atts); } catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(x)); addAttribute(atts, "y", Integer.toString(y)); if (letterSpacing != 0) { addAttribute(atts, "letter-spacing", Integer.toString(letterSpacing)); } if (wordSpacing != 0) { addAttribute(atts, "word-spacing", Integer.toString(wordSpacing)); } if (dp != null) { if ( IFUtil.isDPIdentity(dp) ) { // don't add dx or dp attribute } else if ( IFUtil.isDPOnlyDX(dp) ) { // add dx attribute only int[] dx = IFUtil.convertDPToDX(dp); addAttribute(atts, "dx", IFUtil.toString(dx)); } else { // add dp attribute only addAttribute(atts, "dp", XMLUtil.encodePositionAdjustments(dp)); } } addStructureReference(atts); handler.startElement(EL_TEXT, atts); char[] chars = text.toCharArray(); handler.characters(chars, 0, chars.length); handler.endElement(EL_TEXT); } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void setFont(String family, String style, Integer weight, String variant, Integer size, Color color) throws IFException { try { AttributesImpl atts = new AttributesImpl(); boolean changed; if (family != null) { changed = !family.equals(state.getFontFamily()); if (changed) { state.setFontFamily(family); addAttribute(atts, "family", family); } } if (style != null) { changed = !style.equals(state.getFontStyle()); if (changed) { state.setFontStyle(style); addAttribute(atts, "style", style); } } if (weight != null) { changed = (weight.intValue() != state.getFontWeight()); if (changed) { state.setFontWeight(weight.intValue()); addAttribute(atts, "weight", weight.toString()); } } if (variant != null) { changed = !variant.equals(state.getFontVariant()); if (changed) { state.setFontVariant(variant); addAttribute(atts, "variant", variant); } } if (size != null) { changed = (size.intValue() != state.getFontSize()); if (changed) { state.setFontSize(size.intValue()); addAttribute(atts, "size", size.toString()); } } if (color != null) { changed = !org.apache.xmlgraphics.java2d.color.ColorUtil.isSameColor( color, state.getTextColor()); if (changed) { state.setTextColor(color); addAttribute(atts, "color", toString(color)); } } if (atts.getLength() > 0) { handler.element(EL_FONT, atts); } } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof XMLizable) { try { ((XMLizable)extension).toSAX(this.handler); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { throw new UnsupportedOperationException( "Extension must implement XMLizable: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void renderNamedDestination(NamedDestination destination) throws IFException { noteAction(destination.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute(null, "name", "name", XMLConstants.CDATA, destination.getName()); try { handler.startElement(DocumentNavigationExtensionConstants.NAMED_DESTINATION, atts); serializeXMLizable(destination.getAction()); handler.endElement(DocumentNavigationExtensionConstants.NAMED_DESTINATION); } catch (SAXException e) { throw new IFException("SAX error serializing named destination", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void renderBookmarkTree(BookmarkTree tree) throws IFException { AttributesImpl atts = new AttributesImpl(); try { handler.startElement(DocumentNavigationExtensionConstants.BOOKMARK_TREE, atts); Iterator iter = tree.getBookmarks().iterator(); while (iter.hasNext()) { Bookmark b = (Bookmark)iter.next(); if (b.getAction() != null) { serializeBookmark(b); } } handler.endElement(DocumentNavigationExtensionConstants.BOOKMARK_TREE); } catch (SAXException e) { throw new IFException("SAX error serializing bookmark tree", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void renderLink(Link link) throws IFException { noteAction(link.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute(null, "rect", "rect", XMLConstants.CDATA, IFUtil.toString(link.getTargetRect())); if (getUserAgent().isAccessibilityEnabled()) { addStructRefAttribute(atts, ((IFStructureTreeElement) link.getAction().getStructureTreeElement()).getId()); } try { handler.startElement(DocumentNavigationExtensionConstants.LINK, atts); serializeXMLizable(link.getAction()); handler.endElement(DocumentNavigationExtensionConstants.LINK); } catch (SAXException e) { throw new IFException("SAX error serializing link", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void serializeXMLizable(XMLizable object) throws IFException { try { object.toSAX(handler); } catch (SAXException e) { throw new IFException("SAX error serializing object", e); } }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void setResult(Result result) throws IFException { if (result instanceof StreamResult) { StreamResult streamResult = (StreamResult)result; OutputStream out = streamResult.getOutputStream(); if (out == null) { if (streamResult.getWriter() != null) { throw new IllegalArgumentException( "FOP cannot use a Writer. Please supply an OutputStream!"); } try { URL url = new URL(streamResult.getSystemId()); File f = FileUtils.toFile(url); if (f != null) { out = new java.io.FileOutputStream(f); } else { out = url.openConnection().getOutputStream(); } } catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); } out = new java.io.BufferedOutputStream(out); this.ownOutputStream = true; } if (out == null) { throw new IllegalArgumentException("Need a StreamResult with an OutputStream"); } this.outputStream = out; } else { throw new UnsupportedOperationException( "Unsupported Result subclass: " + result.getClass().getName()); } }
// in src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
protected ContentHandler createContentHandler(Result result) throws IFException { try { TransformerHandler tHandler = tFactory.newTransformerHandler(); Transformer transformer = tHandler.getTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); tHandler.setResult(result); return tHandler; } catch (TransformerConfigurationException tce) { throw new IFException( "Error while setting up the serializer for XML output", tce); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
Override public void startDocument() throws IFException { super.startDocument(); try { this.gen = new PCLGenerator(this.outputStream, getResolution()); this.gen.setDitheringQuality(pclUtil.getDitheringQuality()); if (!pclUtil.isPJLDisabled()) { gen.universalEndOfLanguage(); gen.writeText("@PJL COMMENT Produced by " + getUserAgent().getProducer() + "\n"); if (getUserAgent().getTitle() != null) { gen.writeText("@PJL JOB NAME = \"" + getUserAgent().getTitle() + "\"\n"); } gen.writeText("@PJL SET RESOLUTION = " + getResolution() + "\n"); gen.writeText("@PJL ENTER LANGUAGE = PCL\n"); } gen.resetPrinter(); gen.setUnitOfMeasure(getResolution()); gen.setRasterGraphicsResolution(getResolution()); } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
Override public void endDocument() throws IFException { try { gen.separateJobs(); gen.resetPrinter(); if (!pclUtil.isPJLDisabled()) { gen.universalEndOfLanguage(); } } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { //Paper source Object paperSource = getContext().getForeignAttribute( PCLElementMapping.PCL_PAPER_SOURCE); if (paperSource != null) { gen.selectPaperSource(Integer.parseInt(paperSource.toString())); } //Output bin Object outputBin = getContext().getForeignAttribute( PCLElementMapping.PCL_OUTPUT_BIN); if (outputBin != null) { gen.selectOutputBin(Integer.parseInt(outputBin.toString())); } // Is Page duplex? Object pageDuplex = getContext().getForeignAttribute( PCLElementMapping.PCL_DUPLEX_MODE); if (pageDuplex != null) { gen.selectDuplexMode(Integer.parseInt(pageDuplex.toString())); } //Page size final long pagewidth = size.width; final long pageheight = size.height; selectPageFormat(pagewidth, pageheight); } catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void endPageContent() throws IFException { if (this.currentImage != null) { try { //ImageWriterUtil.saveAsPNG(this.currentImage, new java.io.File("D:/page.png")); Rectangle printArea = this.currentPageDefinition.getLogicalPageRect(); gen.setCursorPos(0, 0); gen.paintBitmap(this.currentImage, printArea.getSize(), true); } catch (IOException ioe) { throw new IFException("I/O error while encoding page image", ioe); } finally { this.currentImage = null; } } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void endPage() throws IFException { try { //Eject page gen.formFeed(); } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); /* PCL cannot clip! if (clipRect != null) { clipRect(clipRect); }*/ } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void startGroup(AffineTransform transform) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { Color fillColor = null; if (fill != null) { if (fill instanceof Color) { fillColor = (Color)fill; } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } try { setCursorPos(rect.x, rect.y); gen.fillRect(rect.width, rect.height, fillColor); } catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); } } } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
private void paintMarksAsBitmap(Graphics2DImagePainter painter, Rectangle boundingBox) throws IFException { ImageInfo info = new ImageInfo(null, null); ImageSize size = new ImageSize(); size.setSizeInMillipoints(boundingBox.width, boundingBox.height); info.setSize(size); ImageGraphics2D img = new ImageGraphics2D(info, painter); Map hints = new java.util.HashMap(); if (isSpeedOptimized()) { //Gray text may not be painted in this case! We don't get dithering in Sun JREs. //But this approach is about twice as fast as the grayscale image. hints.put(ImageProcessingHints.BITMAP_TYPE_INTENT, ImageProcessingHints.BITMAP_TYPE_INTENT_MONO); } else { hints.put(ImageProcessingHints.BITMAP_TYPE_INTENT, ImageProcessingHints.BITMAP_TYPE_INTENT_GRAY); } hints.put(ImageHandlerUtil.CONVERSION_MODE, ImageHandlerUtil.CONVERSION_MODE_BITMAP); PCLRenderingContext context = (PCLRenderingContext)createRenderingContext(); context.setSourceTransparencyEnabled(true); try { drawImage(img, boundingBox, context, true, hints); } catch (IOException ioe) { throw new IFException( "I/O error while painting marks using a bitmap", ioe); } catch (ImageException ie) { throw new IFException( "Error while painting marks using a bitmap", ie); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() //TODO Opportunity for font caching if font state is more heavily used String fontKey = parent.getFontInfo().getInternalFontKey(triplet); boolean pclFont = getPCLUtil().isAllTextAsBitmaps() ? false : HardcodedFonts.setFont(gen, fontKey, state.getFontSize(), text); if (pclFont) { drawTextNative(x, y, letterSpacing, wordSpacing, dp, text, triplet); } else { drawTextAsBitmap(x, y, letterSpacing, wordSpacing, dp, text, triplet); if (DEBUG) { state.setTextColor(Color.GRAY); HardcodedFonts.setFont(gen, "F1", state.getFontSize(), text); drawTextNative(x, y, letterSpacing, wordSpacing, dp, text, triplet); } } } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); try { // Creates writer this.imageWriter = ImageWriterRegistry.getInstance().getWriterFor(getMimeType()); if (this.imageWriter == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noImageWriterFound(this, getMimeType()); } if (this.imageWriter.supportsMultiImageWriter()) { this.multiImageWriter = this.imageWriter.createMultiImageWriter(outputStream); } else { this.multiFileUtil = new MultiFileRenderingUtil(getDefaultExtension(), getUserAgent().getOutputFile()); } this.pageCount = 0; } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endDocument() throws IFException { try { if (this.multiImageWriter != null) { this.multiImageWriter.close(); } this.multiImageWriter = null; this.imageWriter = null; } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endPageContent() throws IFException { try { if (this.multiImageWriter == null) { switch (this.pageCount) { case 1: this.imageWriter.writeImage( this.currentImage, this.outputStream, getSettings().getWriterParams()); IOUtils.closeQuietly(this.outputStream); this.outputStream = null; break; default: OutputStream out = this.multiFileUtil.createOutputStream(this.pageCount - 1); if (out == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.stoppingAfterFirstPageNoFilename(this); } else { try { this.imageWriter.writeImage( this.currentImage, out, getSettings().getWriterParams()); } finally { IOUtils.closeQuietly(out); } } } } else { this.multiImageWriter.writeImage(this.currentImage, getSettings().getWriterParams()); } this.currentImage = null; } catch (IOException ioe) { throw new IFException("I/O error while encoding BufferedImage", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void startDocument() throws IFException { super.startDocument(); try { paintingState.setColor(Color.WHITE); this.dataStream = resourceManager.createDataStream(paintingState, outputStream); this.dataStream.startDocument(); } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void endDocument() throws IFException { try { this.dataStream.endDocument(); this.dataStream = null; this.resourceManager.writeToStream(); this.resourceManager = null; } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void startPageSequence(String id) throws IFException { try { dataStream.startPageGroup(); } catch (IOException ioe) { throw new IFException("I/O error in startPageSequence()", ioe); } this.location = Location.FOLLOWING_PAGE_SEQUENCE; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void endPageSequence() throws IFException { try { //Process deferred page-sequence-level extensions Iterator<AFPPageSetup> iter = this.deferredPageSequenceExtensions.iterator(); while (iter.hasNext()) { AFPPageSetup aps = iter.next(); iter.remove(); if (AFPElementMapping.NO_OPERATION.equals(aps.getElementName())) { handleNOP(aps); } else { throw new UnsupportedOperationException("Don't know how to handle " + aps); } } //End page sequence dataStream.endPageGroup(); } catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); } this.location = Location.ELSEWHERE; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void endPage() throws IFException { try { AFPPageFonts pageFonts = paintingState.getPageFonts(); if (pageFonts != null && !pageFonts.isEmpty()) { dataStream.addFontsToCurrentPage(pageFonts); } dataStream.endPage(); } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof AFPPageSetup) { AFPPageSetup aps = (AFPPageSetup)extension; String element = aps.getElementName(); if (AFPElementMapping.TAG_LOGICAL_ELEMENT.equals(element)) { switch (this.location) { case FOLLOWING_PAGE_SEQUENCE: case IN_PAGE_HEADER: String name = aps.getName(); String value = aps.getValue(); dataStream.createTagLogicalElement(name, value); break; default: throw new IFException( "TLE extension must be in the page header or between page-sequence" + " and the first page: " + aps, null); } } else if (AFPElementMapping.NO_OPERATION.equals(element)) { switch (this.location) { case FOLLOWING_PAGE_SEQUENCE: if (aps.getPlacement() == ExtensionPlacement.BEFORE_END) { this.deferredPageSequenceExtensions.add(aps); break; } case IN_DOCUMENT_HEADER: case IN_PAGE_HEADER: handleNOP(aps); break; default: throw new IFException( "NOP extension must be in the document header, the page header" + " or between page-sequence" + " and the first page: " + aps, null); } } else { if (this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP page setup extension encountered outside the page header: " + aps, null); } if (AFPElementMapping.INCLUDE_PAGE_SEGMENT.equals(element)) { AFPPageSegmentElement.AFPPageSegmentSetup apse = (AFPPageSegmentElement.AFPPageSegmentSetup)aps; String name = apse.getName(); String source = apse.getValue(); String uri = apse.getResourceSrc(); pageSegmentMap.put(source, new PageSegmentDescriptor(name, uri)); } } } else if (extension instanceof AFPPageOverlay) { AFPPageOverlay ipo = (AFPPageOverlay)extension; if (this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP page overlay extension encountered outside the page header: " + ipo, null); } String overlay = ipo.getName(); if (overlay != null) { dataStream.createIncludePageOverlay(overlay, ipo.getX(), ipo.getY()); } } else if (extension instanceof AFPInvokeMediumMap) { if (this.location != Location.FOLLOWING_PAGE_SEQUENCE && this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP IMM extension must be between page-sequence" + " and the first page or child of page-header: " + extension, null); } AFPInvokeMediumMap imm = (AFPInvokeMediumMap)extension; String mediumMap = imm.getName(); if (mediumMap != null) { dataStream.createInvokeMediumMap(mediumMap); } } else if (extension instanceof AFPIncludeFormMap) { AFPIncludeFormMap formMap = (AFPIncludeFormMap)extension; ResourceAccessor accessor = new DefaultFOPResourceAccessor( getUserAgent(), null, null); try { getResourceManager().createIncludedResource(formMap.getName(), formMap.getSrc(), accessor, ResourceObject.TYPE_FORMDEF); } catch (IOException ioe) { throw new IFException( "I/O error while embedding form map resource: " + formMap.getName(), ioe); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { //AFP doesn't support clipping, so we treat viewport like a group //this is the same code as for startGroup() try { saveGraphicsState(); concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void endViewport() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void startGroup(AffineTransform transform) throws IFException { try { saveGraphicsState(); concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void endGroup() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { PageSegmentDescriptor pageSegment = documentHandler.getPageSegmentNameFor(uri); if (pageSegment != null) { float[] srcPts = {rect.x, rect.y}; int[] coords = unitConv.mpts2units(srcPts); int width = Math.round(unitConv.mpt2units(rect.width)); int height = Math.round(unitConv.mpt2units(rect.height)); getDataStream().createIncludePageSegment(pageSegment.getName(), coords[X], coords[Y], width, height); //Do we need to embed an external page segment? if (pageSegment.getURI() != null) { ResourceAccessor accessor = new DefaultFOPResourceAccessor ( documentHandler.getUserAgent(), null, null); try { URI resourceUri = new URI(pageSegment.getURI()); documentHandler.getResourceManager().createIncludedResourceFromExternal( pageSegment.getName(), resourceUri, accessor); } catch (URISyntaxException urie) { throw new IFException("Could not handle resource url" + pageSegment.getURI(), urie); } catch (IOException ioe) { throw new IFException("Could not handle resource" + pageSegment.getURI(), ioe); } } } else { drawImageUsingURI(uri, rect); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { if (fill instanceof Color) { getPaintingState().setColor((Color)fill); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } RectanglePaintingInfo rectanglePaintInfo = new RectanglePaintingInfo( toPoint(rect.x), toPoint(rect.y), toPoint(rect.width), toPoint(rect.height)); try { rectanglePainter.paint(rectanglePaintInfo); } catch (IOException ioe) { throw new IFException("IO error while painting rectangle", ioe); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { try { this.borderPainter.drawBorders(rect, top, bottom, left, right); } catch (IOException ife) { throw new IFException("IO error while painting borders", ife); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { this.borderPainter.drawLine(start, end, width, color, style); } catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void drawText( // CSOK: MethodLength int x, int y, final int letterSpacing, final int wordSpacing, final int[][] dp, final String text) throws IFException { final int fontSize = this.state.getFontSize(); getPaintingState().setFontSize(fontSize); FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() String fontKey = getFontInfo().getInternalFontKey(triplet); if (fontKey == null) { triplet = new FontTriplet("any", Font.STYLE_NORMAL, Font.WEIGHT_NORMAL); fontKey = getFontInfo().getInternalFontKey(triplet); } // register font as necessary Map<String, Typeface> fontMetricMap = documentHandler.getFontInfo().getFonts(); final AFPFont afpFont = (AFPFont)fontMetricMap.get(fontKey); final Font font = getFontInfo().getFontInstance(triplet, fontSize); AFPPageFonts pageFonts = getPaintingState().getPageFonts(); AFPFontAttributes fontAttributes = pageFonts.registerFont(fontKey, afpFont, fontSize); final int fontReference = fontAttributes.getFontReference(); final int[] coords = unitConv.mpts2units(new float[] {x, y} ); final CharacterSet charSet = afpFont.getCharacterSet(fontSize); if (afpFont.isEmbeddable()) { try { documentHandler.getResourceManager().embedFont(afpFont, charSet); } catch (IOException ioe) { throw new IFException("Error while embedding font resources", ioe); } } AbstractPageObject page = getDataStream().getCurrentPage(); PresentationTextObject pto = page.getPresentationTextObject(); try { pto.createControlSequences(new PtocaProducer() { public void produce(PtocaBuilder builder) throws IOException { Point p = getPaintingState().getPoint(coords[X], coords[Y]); builder.setTextOrientation(getPaintingState().getRotation()); builder.absoluteMoveBaseline(p.y); builder.absoluteMoveInline(p.x); builder.setExtendedTextColor(state.getTextColor()); builder.setCodedFont((byte)fontReference); int l = text.length(); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); StringBuffer sb = new StringBuffer(); if (dxl > 0 && dx[0] != 0) { int dxu = Math.round(unitConv.mpt2units(dx[0])); builder.relativeMoveInline(-dxu); } //Following are two variants for glyph placement. //SVI does not seem to be implemented in the same way everywhere, so //a fallback alternative is preserved here. final boolean usePTOCAWordSpacing = true; if (usePTOCAWordSpacing) { int interCharacterAdjustment = 0; if (letterSpacing != 0) { interCharacterAdjustment = Math.round(unitConv.mpt2units( letterSpacing)); } builder.setInterCharacterAdjustment(interCharacterAdjustment); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + letterSpacing)); int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement; if (wordSpacing != 0) { varSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + wordSpacing + letterSpacing)); } builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement); boolean fixedSpaceMode = false; for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( fixedSpaceCharacterIncrement); fixedSpaceMode = true; sb.append(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { if (fixedSpaceMode) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( varSpaceCharacterIncrement); fixedSpaceMode = false; } char ch; if (orgChar == CharUtilities.NBSPACE) { ch = ' '; //converted to normal space to allow word spacing } else { ch = orgChar; } sb.append(ch); } if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } else { for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { sb.append(CharUtilities.SPACE); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { sb.append(orgChar); } if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust += wordSpacing; } glyphAdjust += letterSpacing; if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } flushText(builder, sb, charSet); } private void flushText(PtocaBuilder builder, StringBuffer sb, final CharacterSet charSet) throws IOException { if (sb.length() > 0) { builder.addTransparentData(charSet.encodeChars(sb)); sb.setLength(0); } } }); } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); this.fontResources = new FontResourceCache(getFontInfo()); try { OutputStream out; if (psUtil.isOptimizeResources()) { this.tempFile = File.createTempFile("fop", null); out = new java.io.FileOutputStream(this.tempFile); out = new java.io.BufferedOutputStream(out); } else { out = this.outputStream; } //Setup for PostScript generation this.gen = new PSGenerator(out) { /** Need to subclass PSGenerator to have better URI resolution */ public Source resolveURI(String uri) { return getUserAgent().resolveURI(uri); } }; this.gen.setPSLevel(psUtil.getLanguageLevel()); this.currentPageNumber = 0; this.documentBoundingBox = new Rectangle2D.Double(); //Initial default page device dictionary settings this.pageDeviceDictionary = new PSPageDeviceDictionary(); pageDeviceDictionary.setFlushOnRetrieval(!psUtil.isDSCComplianceEnabled()); pageDeviceDictionary.put("/ImagingBBox", "null"); } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endDocumentHeader() throws IFException { try { writeHeader(); } catch (IOException ioe) { throw new IFException("I/O error writing the PostScript header", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endDocument() throws IFException { try { //Write trailer gen.writeDSCComment(DSCConstants.TRAILER); writeExtensions(COMMENT_DOCUMENT_TRAILER); gen.writeDSCComment(DSCConstants.PAGES, new Integer(this.currentPageNumber)); new DSCCommentBoundingBox(this.documentBoundingBox).generate(gen); new DSCCommentHiResBoundingBox(this.documentBoundingBox).generate(gen); gen.getResourceTracker().writeResources(false, gen); gen.writeDSCComment(DSCConstants.EOF); gen.flush(); log.debug("Rendering to PostScript complete."); if (psUtil.isOptimizeResources()) { IOUtils.closeQuietly(gen.getOutputStream()); rewritePostScriptFile(); } if (pageDeviceDictionary != null) { pageDeviceDictionary.clear(); } } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { if (this.currentPageNumber == 0) { //writeHeader(); } this.currentPageNumber++; gen.getResourceTracker().notifyStartNewPage(); gen.getResourceTracker().notifyResourceUsageOnPage(PSProcSets.STD_PROCSET); gen.writeDSCComment(DSCConstants.PAGE, new Object[] {name, new Integer(this.currentPageNumber)}); double pageWidth = size.width / 1000.0; double pageHeight = size.height / 1000.0; boolean rotate = false; List pageSizes = new java.util.ArrayList(); if (this.psUtil.isAutoRotateLandscape() && (pageHeight < pageWidth)) { rotate = true; pageSizes.add(new Long(Math.round(pageHeight))); pageSizes.add(new Long(Math.round(pageWidth))); } else { pageSizes.add(new Long(Math.round(pageWidth))); pageSizes.add(new Long(Math.round(pageHeight))); } pageDeviceDictionary.put("/PageSize", pageSizes); this.currentPageDefinition = new PageDefinition( new Dimension2DDouble(pageWidth, pageHeight), rotate); //TODO Handle extension attachments for the page!!!!!!! /* if (page.hasExtensionAttachments()) { for (Iterator iter = page.getExtensionAttachments().iterator(); iter.hasNext();) { ExtensionAttachment attachment = (ExtensionAttachment) iter.next(); if (attachment instanceof PSSetPageDevice) {*/ /** * Extract all PSSetPageDevice instances from the * attachment list on the s-p-m and add all * dictionary entries to our internal representation * of the the page device dictionary. *//* PSSetPageDevice setPageDevice = (PSSetPageDevice)attachment; String content = setPageDevice.getContent(); if (content != null) { try { pageDeviceDictionary.putAll(PSDictionary.valueOf(content)); } catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); } } } } }*/ final Integer zero = new Integer(0); Rectangle2D pageBoundingBox = new Rectangle2D.Double(); if (rotate) { pageBoundingBox.setRect(0, 0, pageHeight, pageWidth); gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[] { zero, zero, new Long(Math.round(pageHeight)), new Long(Math.round(pageWidth)) }); gen.writeDSCComment(DSCConstants.PAGE_HIRES_BBOX, new Object[] { zero, zero, new Double(pageHeight), new Double(pageWidth) }); gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Landscape"); } else { pageBoundingBox.setRect(0, 0, pageWidth, pageHeight); gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[] { zero, zero, new Long(Math.round(pageWidth)), new Long(Math.round(pageHeight)) }); gen.writeDSCComment(DSCConstants.PAGE_HIRES_BBOX, new Object[] { zero, zero, new Double(pageWidth), new Double(pageHeight) }); if (psUtil.isAutoRotateLandscape()) { gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Portrait"); } } this.documentBoundingBox.add(pageBoundingBox); gen.writeDSCComment(DSCConstants.PAGE_RESOURCES, new Object[] {DSCConstants.ATEND}); gen.commentln("%FOPSimplePageMaster: " + pageMasterName); } catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPageHeader() throws IFException { super.startPageHeader(); try { gen.writeDSCComment(DSCConstants.BEGIN_PAGE_SETUP); } catch (IOException ioe) { throw new IFException("I/O error in startPageHeader()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageHeader() throws IFException { try { // Write any unwritten changes to page device dictionary if (!pageDeviceDictionary.isEmpty()) { String content = pageDeviceDictionary.getContent(); if (psUtil.isSafeSetPageDevice()) { content += " SSPD"; } else { content += " setpagedevice"; } PSRenderingUtil.writeEnclosedExtensionAttachment(gen, new PSSetPageDevice(content)); } double pageHeight = this.currentPageDefinition.dimensions.getHeight(); if (this.currentPageDefinition.rotate) { gen.writeln(gen.formatDouble(pageHeight) + " 0 translate"); gen.writeln("90 rotate"); } gen.concatMatrix(1, 0, 0, -1, 0, pageHeight); gen.writeDSCComment(DSCConstants.END_PAGE_SETUP); } catch (IOException ioe) { throw new IFException("I/O error in endPageHeader()", ioe); } super.endPageHeader(); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageContent() throws IFException { try { gen.showPage(); } catch (IOException ioe) { throw new IFException("I/O error in endPageContent()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPageTrailer() throws IFException { try { writeExtensions(PAGE_TRAILER_CODE_BEFORE); super.startPageTrailer(); gen.writeDSCComment(DSCConstants.PAGE_TRAILER); } catch (IOException ioe) { throw new IFException("I/O error in startPageTrailer()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageTrailer() throws IFException { try { writeExtensions(COMMENT_PAGE_TRAILER); } catch (IOException ioe) { throw new IFException("I/O error in endPageTrailer()", ioe); } super.endPageTrailer(); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPage() throws IFException { try { gen.getResourceTracker().writeResources(true, gen); } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } this.currentPageDefinition = null; }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { try { if (extension instanceof PSSetupCode) { if (inPage()) { PSRenderingUtil.writeEnclosedExtensionAttachment(gen, (PSSetupCode)extension); } else { //A special collection for setup code as it's put in a different place //than the "before comments". if (setupCodeList == null) { setupCodeList = new java.util.ArrayList(); } if (!setupCodeList.contains(extension)) { setupCodeList.add(extension); } } } else if (extension instanceof PSSetPageDevice) { /** * Extract all PSSetPageDevice instances from the * attachment list on the s-p-m and add all dictionary * entries to our internal representation of the the * page device dictionary. */ PSSetPageDevice setPageDevice = (PSSetPageDevice)extension; String content = setPageDevice.getContent(); if (content != null) { try { this.pageDeviceDictionary.putAll(PSDictionary.valueOf(content)); } catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); } } } else if (extension instanceof PSCommentBefore) { if (inPage()) { PSRenderingUtil.writeEnclosedExtensionAttachment( gen, (PSCommentBefore)extension); } else { if (comments[COMMENT_DOCUMENT_HEADER] == null) { comments[COMMENT_DOCUMENT_HEADER] = new java.util.ArrayList(); } comments[COMMENT_DOCUMENT_HEADER].add(extension); } } else if (extension instanceof PSCommentAfter) { int targetCollection = (inPage() ? COMMENT_PAGE_TRAILER : COMMENT_DOCUMENT_TRAILER); if (comments[targetCollection] == null) { comments[targetCollection] = new java.util.ArrayList(); } comments[targetCollection].add(extension); } else if (extension instanceof PSPageTrailerCodeBefore) { if (comments[PAGE_TRAILER_CODE_BEFORE] == null) { comments[PAGE_TRAILER_CODE_BEFORE] = new ArrayList(); } comments[PAGE_TRAILER_CODE_BEFORE].add(extension); } } catch (IOException ioe) { throw new IFException("I/O error in handleExtensionObject()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { try { PSGenerator generator = getGenerator(); saveGraphicsState(); generator.concatMatrix(toPoints(transform)); } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } if (clipRect != null) { clipRect(clipRect); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void endViewport() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void startGroup(AffineTransform transform) throws IFException { try { PSGenerator generator = getGenerator(); saveGraphicsState(); generator.concatMatrix(toPoints(transform)); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void endGroup() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { try { endTextObject(); } catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); } drawImageUsingURI(uri, rect); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { try { endTextObject(); } catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); } drawImageUsingDocument(doc, rect); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void clipRect(Rectangle rect) throws IFException { try { PSGenerator generator = getGenerator(); endTextObject(); generator.defineRect(rect.x / 1000.0, rect.y / 1000.0, rect.width / 1000.0, rect.height / 1000.0); generator.writeln(generator.mapCommand("clip") + " " + generator.mapCommand("newpath")); } catch (IOException ioe) { throw new IFException("I/O error in clipRect()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { try { endTextObject(); PSGenerator generator = getGenerator(); if (fill != null) { if (fill instanceof Color) { generator.useColor((Color)fill); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } } generator.defineRect(rect.x / 1000.0, rect.y / 1000.0, rect.width / 1000.0, rect.height / 1000.0); generator.writeln(generator.mapCommand("fill")); } catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); } } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { try { endTextObject(); if (getPSUtil().getRenderingMode() == PSRenderingMode.SIZE && hasOnlySolidBorders(top, bottom, left, right)) { super.drawBorderRect(rect, top, bottom, left, right); } else { this.borderPainter.drawBorders(rect, top, bottom, left, right); } } catch (IOException ioe) { throw new IFException("I/O error in drawBorderRect()", ioe); } } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { endTextObject(); this.borderPainter.drawLine(start, end, width, color, style); } catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { //Do not draw text if font-size is 0 as it creates an invalid PostScript file if (state.getFontSize() == 0) { return; } PSGenerator generator = getGenerator(); generator.useColor(state.getTextColor()); beginTextObject(); FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() //TODO Opportunity for font caching if font state is more heavily used String fontKey = getFontInfo().getInternalFontKey(triplet); if (fontKey == null) { throw new IFException("Font not available: " + triplet, null); } int sizeMillipoints = state.getFontSize(); // This assumes that *all* CIDFonts use a /ToUnicode mapping Typeface tf = getTypeface(fontKey); SingleByteFont singleByteFont = null; if (tf instanceof SingleByteFont) { singleByteFont = (SingleByteFont)tf; } Font font = getFontInfo().getFontInstance(triplet, sizeMillipoints); useFont(fontKey, sizeMillipoints); generator.writeln("1 0 0 -1 " + formatMptAsPt(generator, x) + " " + formatMptAsPt(generator, y) + " Tm"); int textLen = text.length(); int start = 0; if (singleByteFont != null) { //Analyze string and split up in order to paint in different sub-fonts/encodings int currentEncoding = -1; for (int i = 0; i < textLen; i++) { char c = text.charAt(i); char mapped = tf.mapChar(c); int encoding = mapped / 256; if (currentEncoding != encoding) { if (i > 0) { writeText(text, start, i - start, letterSpacing, wordSpacing, dp, font, tf); } if (encoding == 0) { useFont(fontKey, sizeMillipoints); } else { useFont(fontKey + "_" + Integer.toString(encoding), sizeMillipoints); } currentEncoding = encoding; start = i; } } } else { //Simple single-font painting useFont(fontKey, sizeMillipoints); } writeText(text, start, textLen - start, letterSpacing, wordSpacing, dp, font, tf); } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); clipRect(clipRect); } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void startGroup(AffineTransform transform) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
131
              
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (ParserConfigurationException e) { throw new IFException("Error while setting up a DOM for SVG generation", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException se) { throw new IFException("SAX error in startDocument()", se); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException e) { throw new IFException( "Error while setting up a TransformerHandler for SVG generation", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException("Error setting up a Transformer", tce); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException)te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O exception while setting up output file", ioe); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error flushing the PDF document", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error while drawing borders", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the color attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in clipRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawBorderRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing named destination", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing bookmark tree", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing link", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing object", e); }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); }
// in src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException( "Error while setting up the serializer for XML output", tce); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding page image", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException( "I/O error while painting marks using a bitmap", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (ImageException ie) { throw new IFException( "Error while painting marks using a bitmap", ie); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding BufferedImage", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException( "I/O error while embedding form map resource: " + formMap.getName(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (URISyntaxException urie) { throw new IFException("Could not handle resource url" + pageSegment.getURI(), urie); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Could not handle resource" + pageSegment.getURI(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("IO error while painting rectangle", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ife) { throw new IFException("IO error while painting borders", ife); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Error while embedding font resources", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error writing the PostScript header", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageContent()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in handleExtensionObject()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in clipRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawBorderRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
296
              
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { startViewport(SVGUtil.formatAffineTransformMptToPt(transform), size, clipRect); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void startViewport(AffineTransform[] transforms, Dimension size, Rectangle clipRect) throws IFException { startViewport(SVGUtil.formatAffineTransformsMptToPt(transforms), size, clipRect); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void startViewport(String transform, Dimension size, Rectangle clipRect) throws IFException { try { establish(MODE_NORMAL); AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { XMLUtil.addAttribute(atts, "transform", transform); } handler.startElement("g", atts); atts.clear(); XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(size.width)); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(size.height)); if (clipRect != null) { int[] v = new int[] { clipRect.y, -clipRect.x + size.width - clipRect.width, -clipRect.y + size.height - clipRect.height, clipRect.x}; int sum = 0; for (int i = 0; i < 4; i++) { sum += Math.abs(v[i]); } if (sum != 0) { StringBuffer sb = new StringBuffer("rect("); sb.append(SVGUtil.formatMptToPt(v[0])).append(','); sb.append(SVGUtil.formatMptToPt(v[1])).append(','); sb.append(SVGUtil.formatMptToPt(v[2])).append(','); sb.append(SVGUtil.formatMptToPt(v[3])).append(')'); XMLUtil.addAttribute(atts, "clip", sb.toString()); } XMLUtil.addAttribute(atts, "overflow", "hidden"); } else { XMLUtil.addAttribute(atts, "overflow", "visible"); } handler.startElement("svg", atts); } catch (SAXException e) { throw new IFException("SAX error in startBox()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void endViewport() throws IFException { try { establish(MODE_NORMAL); handler.endElement("svg"); handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endBox()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void startGroup(AffineTransform[] transforms) throws IFException { startGroup(SVGUtil.formatAffineTransformsMptToPt(transforms)); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void startGroup(AffineTransform transform) throws IFException { startGroup(SVGUtil.formatAffineTransformMptToPt(transform)); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void startGroup(String transform) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { XMLUtil.addAttribute(atts, "transform", transform); } handler.startElement("g", atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void endGroup() throws IFException { try { establish(MODE_NORMAL); handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { try { establish(MODE_NORMAL); ImageManager manager = getUserAgent().getFactory().getImageManager(); ImageInfo info = null; try { ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); info = manager.getImageInfo(uri, sessionContext); String mime = info.getMimeType(); Map foreignAttributes = getContext().getForeignAttributes(); String conversionMode = (String)foreignAttributes.get( ImageHandlerUtil.CONVERSION_MODE); if ("reference".equals(conversionMode) && (MimeConstants.MIME_GIF.equals(mime) || MimeConstants.MIME_JPEG.equals(mime) || MimeConstants.MIME_PNG.equals(mime) || MimeConstants.MIME_SVG.equals(mime))) { //Just reference the image //TODO Some additional URI rewriting might be necessary AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, IFConstants.XLINK_HREF, uri); XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(rect.x)); XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(rect.y)); XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(rect.width)); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(rect.height)); handler.element("image", atts); } else { drawImageUsingImageHandler(info, rect); } } catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); } catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); } } catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { try { establish(MODE_NORMAL); drawImageUsingDocument(doc, rect); } catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void clipRect(Rectangle rect) throws IFException { //TODO Implement me!!! }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } try { establish(MODE_NORMAL); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(rect.x)); XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(rect.y)); XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(rect.width)); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(rect.height)); if (fill != null) { XMLUtil.addAttribute(atts, "fill", toString(fill)); } /* disabled if (stroke != null) { XMLUtil.addAttribute(atts, "stroke", toString(stroke)); }*/ handler.element("rect", atts); } catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawBorderRect(Rectangle rect, BorderProps before, BorderProps after, BorderProps start, BorderProps end) throws IFException { // TODO Auto-generated method stub }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { establish(MODE_NORMAL); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "x1", SVGUtil.formatMptToPt(start.x)); XMLUtil.addAttribute(atts, "y1", SVGUtil.formatMptToPt(start.y)); XMLUtil.addAttribute(atts, "x2", SVGUtil.formatMptToPt(end.x)); XMLUtil.addAttribute(atts, "y2", SVGUtil.formatMptToPt(end.y)); XMLUtil.addAttribute(atts, "stroke-width", toString(color)); XMLUtil.addAttribute(atts, "fill", toString(color)); //TODO Handle style parameter handler.element("line", atts); } catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { establish(MODE_TEXT); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, XMLConstants.XML_SPACE, "preserve"); XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(x)); XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(y)); if (letterSpacing != 0) { XMLUtil.addAttribute(atts, "letter-spacing", SVGUtil.formatMptToPt(letterSpacing)); } if (wordSpacing != 0) { XMLUtil.addAttribute(atts, "word-spacing", SVGUtil.formatMptToPt(wordSpacing)); } if (dp != null) { int[] dx = IFUtil.convertDPToDX(dp); XMLUtil.addAttribute(atts, "dx", SVGUtil.formatMptArrayToPt(dx)); } handler.startElement("text", atts); char[] chars = text.toCharArray(); handler.characters(chars, 0, chars.length); handler.endElement("text"); } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof Metadata) { Metadata meta = (Metadata)extension; try { establish(MODE_NORMAL); handler.startElement("metadata"); meta.toSAX(this.handler); handler.endElement("metadata"); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { throw new UnsupportedOperationException( "Don't know how to handle extension object: " + extension); } }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
public void startDocumentHeader() throws IFException { try { handler.startElement("defs"); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
public void endDocumentHeader() throws IFException { try { handler.endElement("defs"); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof Metadata) { Metadata meta = (Metadata)extension; try { handler.startElement("metadata"); meta.toSAX(this.handler); handler.endElement("metadata"); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { log.debug("Don't know how to handle extension object. Ignoring: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void setResult(Result result) throws IFException { if (result instanceof StreamResult) { multiFileUtil = new MultiFileRenderingUtil(FILE_EXTENSION_SVG, getUserAgent().getOutputFile()); this.firstStream = (StreamResult)result; } else { this.simpleResult = result; } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); builderFactory.setValidating(false); try { DocumentBuilder builder = builderFactory.newDocumentBuilder(); this.reusedParts = builder.newDocument(); } catch (ParserConfigurationException e) { throw new IFException("Error while setting up a DOM for SVG generation", e); } try { TransformerHandler toDOMHandler = tFactory.newTransformerHandler(); toDOMHandler.setResult(new DOMResult(this.reusedParts)); this.handler = decorate(toDOMHandler); this.handler.startDocument(); } catch (SAXException se) { throw new IFException("SAX error in startDocument()", se); } catch (TransformerConfigurationException e) { throw new IFException( "Error while setting up a TransformerHandler for SVG generation", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endDocument() throws IFException { //nop }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endDocumentHeader() throws IFException { super.endDocumentHeader(); try { //Stop recording parts reused for each page this.handler.endDocument(); this.handler = null; } catch (SAXException e) { throw new IFException("SAX error in endDocumentHeader()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void startPageSequence(String id) throws IFException { //nop }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endPageSequence() throws IFException { //nop }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { if (this.multiFileUtil != null) { prepareHandlerWithOutputStream(index); } else { if (this.simpleResult == null) { //Only one page is supported with this approach at the moment throw new IFException( "Only one page is supported for output with the given Result instance!", null); } super.setResult(this.simpleResult); this.simpleResult = null; } try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "version", "1.1"); //SVG 1.1 /* XMLUtil.addAttribute(atts, "index", Integer.toString(index)); XMLUtil.addAttribute(atts, "name", name); */ XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(size.width) + "pt"); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(size.height) + "pt"); XMLUtil.addAttribute(atts, "viewBox", "0 0 " + SVGUtil.formatMptToPt(size.width) + " " + SVGUtil.formatMptToPt(size.height)); handler.startElement("svg", atts); try { Transformer transformer = tFactory.newTransformer(); Source src = new DOMSource(this.reusedParts.getDocumentElement()); Result res = new SAXResult(new DelegatingFragmentContentHandler(this.handler)); transformer.transform(src, res); } catch (TransformerConfigurationException tce) { throw new IFException("Error setting up a Transformer", tce); } catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException)te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } } } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
private void prepareHandlerWithOutputStream(int index) throws IFException { OutputStream out; try { if (index == 0) { out = null; } else { out = this.multiFileUtil.createOutputStream(index); if (out == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.stoppingAfterFirstPageNoFilename(this); } } } catch (IOException ioe) { throw new IFException("I/O exception while setting up output file", ioe); } if (out == null) { this.handler = decorate(createContentHandler(this.firstStream)); } else { this.currentStream = new StreamResult(out); this.handler = decorate(createContentHandler(this.currentStream)); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public IFPainter startPageContent() throws IFException { try { handler.startElement("g"); } catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); } return new SVGPainter(this, handler); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endPageContent() throws IFException { try { handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endPage() throws IFException { try { handler.endElement("svg"); this.handler.endDocument(); } catch (SAXException e) { throw new IFException("SAX error in endPage()", e); } closeCurrentStream(); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); handler.startPrefixMapping("if", IFConstants.NAMESPACE); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "version", "1.2"); //SVG Print is SVG 1.2 handler.startElement("svg", atts); } catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endDocument() throws IFException { try { handler.endElement("svg"); handler.endDocument(); } catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startPageSequence(String id) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (id != null) { atts.addAttribute(XML_NAMESPACE, "id", "xml:id", CDATA, id); } handler.startElement("pageSet", atts); } catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPageSequence() throws IFException { try { handler.endElement("pageSet"); } catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { AttributesImpl atts = new AttributesImpl(); /* XMLUtil.addAttribute(atts, "index", Integer.toString(index)); XMLUtil.addAttribute(atts, "name", name); */ //NOTE: SVG Print doesn't support individual page sizes for each page atts.addAttribute(IFConstants.NAMESPACE, "width", "if:width", CDATA, Integer.toString(size.width)); atts.addAttribute(IFConstants.NAMESPACE, "height", "if:height", CDATA, Integer.toString(size.height)); atts.addAttribute(IFConstants.NAMESPACE, "viewBox", "if:viewBox", CDATA, "0 0 " + Integer.toString(size.width) + " " + Integer.toString(size.height)); handler.startElement("page", atts); } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startPageHeader() throws IFException { }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPageHeader() throws IFException { }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public IFPainter startPageContent() throws IFException { try { handler.startElement("g"); } catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); } return new SVGPainter(this, handler); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPageContent() throws IFException { try { handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startPageTrailer() throws IFException { }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPageTrailer() throws IFException { }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPage() throws IFException { try { handler.endElement("page"); } catch (SAXException e) { throw new IFException("SAX error in endPage()", e); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
public void renderNamedDestination(NamedDestination destination) throws IFException { PDFAction action = getAction(destination.getAction()); getPDFDoc().getFactory().makeDestination( destination.getName(), action.makeReference()); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
public void renderBookmarkTree(BookmarkTree tree) throws IFException { Iterator iter = tree.getBookmarks().iterator(); while (iter.hasNext()) { Bookmark b = (Bookmark)iter.next(); renderBookmark(b, null); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
private void renderBookmark(Bookmark bookmark, PDFOutline parent) throws IFException { if (parent == null) { parent = getPDFDoc().getOutlineRoot(); } PDFAction action = getAction(bookmark.getAction()); String actionRef = (action != null ? action.makeReference().toString() : null); PDFOutline pdfOutline = getPDFDoc().getFactory().makeOutline(parent, bookmark.getTitle(), actionRef, bookmark.isShown()); Iterator iter = bookmark.getChildBookmarks().iterator(); while (iter.hasNext()) { Bookmark b = (Bookmark)iter.next(); renderBookmark(b, pdfOutline); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
public void renderLink(Link link) throws IFException { Rectangle targetRect = link.getTargetRect(); int pageHeight = documentHandler.currentPageRef.getPageDimension().height; Rectangle2D targetRect2D = new Rectangle2D.Double( targetRect.getMinX() / 1000.0, (pageHeight - targetRect.getMinY() - targetRect.getHeight()) / 1000.0, targetRect.getWidth() / 1000.0, targetRect.getHeight() / 1000.0); PDFAction pdfAction = getAction(link.getAction()); //makeLink() currently needs a PDFAction and not a reference //TODO Revisit when PDFLink is converted to a PDFDictionary PDFLink pdfLink = getPDFDoc().getFactory().makeLink( targetRect2D, pdfAction); if (pdfLink != null) { PDFStructElem structure = (PDFStructElem) link.getAction().getStructureTreeElement(); if (documentHandler.getUserAgent().isAccessibilityEnabled() && structure != null) { documentHandler.getLogicalStructureHandler().addLinkContentItem(pdfLink, structure); } documentHandler.currentPage.addAnnotation(pdfLink); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
public void addResolvedAction(AbstractAction action) throws IFException { assert action.isComplete(); PDFAction pdfAction = (PDFAction)this.incompleteActions.remove(action.getID()); if (pdfAction == null) { getAction(action); } else if (pdfAction instanceof PDFGoTo) { PDFGoTo pdfGoTo = (PDFGoTo)pdfAction; updateTargetLocation(pdfGoTo, (GoToXYAction)action); } else { throw new UnsupportedOperationException( "Action type not supported: " + pdfAction.getClass().getName()); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
private PDFAction getAction(AbstractAction action) throws IFException { if (action == null) { return null; } PDFAction pdfAction = (PDFAction)this.completeActions.get(action.getID()); if (pdfAction != null) { return pdfAction; } else if (action instanceof GoToXYAction) { pdfAction = (PDFAction) incompleteActions.get(action.getID()); if (pdfAction != null) { return pdfAction; } else { GoToXYAction a = (GoToXYAction)action; PDFGoTo pdfGoTo = new PDFGoTo(null); getPDFDoc().assignObjectNumber(pdfGoTo); if (action.isComplete()) { updateTargetLocation(pdfGoTo, a); } else { this.incompleteActions.put(action.getID(), pdfGoTo); } return pdfGoTo; } } else if (action instanceof URIAction) { URIAction u = (URIAction)action; assert u.isComplete(); String uri = u.getURI(); PDFFactory factory = getPDFDoc().getFactory(); pdfAction = factory.getExternalAction(uri, u.isNewWindow()); if (!pdfAction.hasObjectNumber()) { //Some PDF actions are pooled getPDFDoc().registerObject(pdfAction); } this.completeActions.put(action.getID(), pdfAction); return pdfAction; } else { throw new UnsupportedOperationException("Unsupported action type: " + action + " (" + action.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
private void updateTargetLocation(PDFGoTo pdfGoTo, GoToXYAction action) throws IFException { PageReference pageRef = this.documentHandler.getPageReference(action.getPageIndex()); if ( pageRef == null ) { throw new IFException("Can't resolve page reference @ index: " + action.getPageIndex(), null); } else { //Convert target location from millipoints to points and adjust for different //page origin Point2D p2d = null; p2d = new Point2D.Double( action.getTargetLocation().x / 1000.0, (pageRef.getPageDimension().height - action.getTargetLocation().y) / 1000.0); String pdfPageRef = pageRef.getPageRef(); pdfGoTo.setPageReference(pdfPageRef); pdfGoTo.setPosition(p2d); //Queue this object now that it's complete getPDFDoc().addObject(pdfGoTo); this.completeActions.put(action.getID(), pdfGoTo); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { generator.saveGraphicsState(); generator.concatenate(toPoints(transform)); if (clipRect != null) { clipRect(clipRect); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void endViewport() throws IFException { generator.restoreGraphicsState(); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void startGroup(AffineTransform transform) throws IFException { generator.saveGraphicsState(); generator.concatenate(toPoints(transform)); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void endGroup() throws IFException { generator.restoreGraphicsState(); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { PDFXObject xobject = getPDFDoc().getXObject(uri); if (xobject != null) { if (accessEnabled) { PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement(); prepareImageMCID(structElem); placeImageAccess(rect, xobject); } else { placeImage(rect, xobject); } } else { if (accessEnabled) { PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement(); prepareImageMCID(structElem); } drawImageUsingURI(uri, rect); flushPDFDoc(); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { if (accessEnabled) { PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement(); prepareImageMCID(structElem); } drawImageUsingDocument(doc, rect); flushPDFDoc(); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
private void flushPDFDoc() throws IFException { // output new data try { generator.flushPDFDoc(); } catch (IOException ioe) { throw new IFException("I/O error flushing the PDF document", ioe); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void clipRect(Rectangle rect) throws IFException { generator.endTextObject(); generator.clipRect(rect); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { generator.endTextObject(); if (fill != null) { if (fill instanceof Color) { generator.updateColor((Color)fill, true, null); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } } StringBuffer sb = new StringBuffer(); sb.append(format(rect.x)).append(' '); sb.append(format(rect.y)).append(' '); sb.append(format(rect.width)).append(' '); sb.append(format(rect.height)).append(" re"); if (fill != null) { sb.append(" f"); } /* Removed from method signature as it is currently not used if (stroke != null) { sb.append(" S"); }*/ sb.append('\n'); generator.add(sb.toString()); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
Override public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { generator.endTextObject(); try { this.borderPainter.drawBorders(rect, top, bottom, left, right); } catch (IOException ioe) { throw new IFException("I/O error while drawing borders", ioe); } } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
Override public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { generator.endTextObject(); this.borderPainter.drawLine(start, end, width, color, style); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { if (accessEnabled) { PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement(); MarkedContentInfo mci = logicalStructureHandler.addTextContentItem(structElem); if (generator.getTextUtil().isInTextObject()) { generator.separateTextElements(mci.tag, mci.mcid); } generator.updateColor(state.getTextColor(), true, null); generator.beginTextObject(mci.tag, mci.mcid); } else { generator.updateColor(state.getTextColor(), true, null); generator.beginTextObject(); } FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); if ( ( dp == null ) || IFUtil.isDPOnlyDX ( dp ) ) { drawTextWithDX ( x, y, text, triplet, letterSpacing, wordSpacing, IFUtil.convertDPToDX ( dp ) ); } else { drawTextWithDP ( x, y, text, triplet, letterSpacing, wordSpacing, dp ); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); try { this.pdfDoc = pdfUtil.setupPDFDocument(this.outputStream); this.accessEnabled = getUserAgent().isAccessibilityEnabled(); if (accessEnabled) { setupAccessibility(); } } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endDocumentHeader() throws IFException { pdfUtil.generateDefaultXMPMetadata(); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endDocument() throws IFException { try { pdfDoc.getResources().addFonts(pdfDoc, fontInfo); pdfDoc.outputTrailer(this.outputStream); this.pdfDoc = null; pdfResources = null; this.generator = null; currentContext = null; currentPage = null; } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void startPageSequence(String id) throws IFException { //nop }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endPageSequence() throws IFException { //nop }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { this.pdfResources = this.pdfDoc.getResources(); PageBoundaries boundaries = new PageBoundaries(size, getContext().getForeignAttributes()); Rectangle trimBox = boundaries.getTrimBox(); Rectangle bleedBox = boundaries.getBleedBox(); Rectangle mediaBox = boundaries.getMediaBox(); Rectangle cropBox = boundaries.getCropBox(); // set scale attributes double scaleX = 1; double scaleY = 1; String scale = (String) getContext().getForeignAttribute( PageScale.EXT_PAGE_SCALE); Point2D scales = PageScale.getScale(scale); if (scales != null) { scaleX = scales.getX(); scaleY = scales.getY(); } //PDF uses the lower left as origin, need to transform from FOP's internal coord system AffineTransform boxTransform = new AffineTransform( scaleX / 1000, 0, 0, -scaleY / 1000, 0, scaleY * size.getHeight() / 1000); this.currentPage = this.pdfDoc.getFactory().makePage( this.pdfResources, index, toPDFCoordSystem(mediaBox, boxTransform), toPDFCoordSystem(cropBox, boxTransform), toPDFCoordSystem(bleedBox, boxTransform), toPDFCoordSystem(trimBox, boxTransform)); if (accessEnabled) { logicalStructureHandler.startPage(currentPage); } pdfUtil.generatePageLabel(index, name); currentPageRef = new PageReference(currentPage, size); this.pageReferences.put(Integer.valueOf(index), currentPageRef); this.generator = new PDFContentGenerator(this.pdfDoc, this.outputStream, this.currentPage); // Transform the PDF's default coordinate system (0,0 at lower left) to the PDFPainter's AffineTransform basicPageTransform = new AffineTransform(1, 0, 0, -1, 0, (scaleY * size.height) / 1000f); basicPageTransform.scale(scaleX, scaleY); generator.saveGraphicsState(); generator.concatenate(basicPageTransform); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public IFPainter startPageContent() throws IFException { return new PDFPainter(this, logicalStructureHandler); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endPageContent() throws IFException { generator.restoreGraphicsState(); //for top-level transform to change the default coordinate system }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endPage() throws IFException { if (accessEnabled) { logicalStructureHandler.endPage(); } try { this.documentNavigationHandler.commit(); this.pdfDoc.registerObject(generator.getStream()); currentPage.setContents(generator.getStream()); PDFAnnotList annots = currentPage.getAnnotations(); if (annots != null) { this.pdfDoc.addObject(annots); } this.pdfDoc.addObject(currentPage); this.generator.flushPDFDoc(); this.generator = null; } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof XMPMetadata) { pdfUtil.renderXMPMetadata((XMPMetadata) extension); } else if (extension instanceof Metadata) { XMPMetadata wrapper = new XMPMetadata(((Metadata) extension)); pdfUtil.renderXMPMetadata(wrapper); } else if (extension instanceof PDFEmbeddedFileExtensionAttachment) { PDFEmbeddedFileExtensionAttachment embeddedFile = (PDFEmbeddedFileExtensionAttachment)extension; try { pdfUtil.addEmbeddedFile(embeddedFile); } catch (IOException ioe) { throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe); } } else { log.debug("Don't know how to handle extension object. Ignoring: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void parse(Source src, IFDocumentHandler documentHandler, FOUserAgent userAgent) throws TransformerException, IFException { try { Transformer transformer = tFactory.newTransformer(); transformer.setErrorListener(new DefaultErrorListener(log)); SAXResult res = new SAXResult(getContentHandler(documentHandler, userAgent)); transformer.transform(src, res); } catch (TransformerException te) { //Unpack original IFException if applicable if (te.getCause() instanceof SAXException) { SAXException se = (SAXException)te.getCause(); if (se.getCause() instanceof IFException) { throw (IFException)se.getCause(); } } else if (te.getCause() instanceof IFException) { throw (IFException)te.getCause(); } throw te; } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException, SAXException { //nop }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { documentHandler.startDocument(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endDocument(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { documentHandler.startDocumentHeader(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endDocumentHeader(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { documentHandler.setDocumentLocale(getLanguage(attributes)); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { documentHandler.startDocumentTrailer(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endDocumentTrailer(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { String id = attributes.getValue("id"); Locale language = getLanguage(attributes); if (language != null) { documentHandler.getContext().setLanguage(language); } Map<QName, String> foreignAttributes = getForeignAttributes(lastAttributes); establishForeignAttributes(foreignAttributes); documentHandler.startPageSequence(id); resetForeignAttributes(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endPageSequence(); documentHandler.getContext().setLanguage(null); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int index = Integer.parseInt(attributes.getValue("index")); String name = attributes.getValue("name"); String pageMasterName = attributes.getValue("page-master-name"); int width = Integer.parseInt(attributes.getValue("width")); int height = Integer.parseInt(attributes.getValue("height")); Map<QName, String> foreignAttributes = getForeignAttributes(lastAttributes); establishForeignAttributes(foreignAttributes); documentHandler.startPage(index, name, pageMasterName, new Dimension(width, height)); resetForeignAttributes(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endPage(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { documentHandler.startPageHeader(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endPageHeader(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { painter = documentHandler.startPageContent(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { painter = null; documentHandler.getContext().setID(""); documentHandler.endPageContent(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { documentHandler.startPageTrailer(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endPageTrailer(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { String transform = attributes.getValue("transform"); AffineTransform[] transforms = AffineTransformArrayParser.createAffineTransform(transform); int width = Integer.parseInt(attributes.getValue("width")); int height = Integer.parseInt(attributes.getValue("height")); Rectangle clipRect = XMLUtil.getAttributeAsRectangle(attributes, "clip-rect"); painter.startViewport(transforms, new Dimension(width, height), clipRect); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { painter.endViewport(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { String transform = attributes.getValue("transform"); AffineTransform[] transforms = AffineTransformArrayParser.createAffineTransform(transform); painter.startGroup(transforms); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { painter.endGroup(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
Override public void startElement(Attributes attributes) throws IFException, SAXException { String id = attributes.getValue("name"); documentHandler.getContext().setID(id); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { String family = attributes.getValue("family"); String style = attributes.getValue("style"); Integer weight = XMLUtil.getAttributeAsInteger(attributes, "weight"); String variant = attributes.getValue("variant"); Integer size = XMLUtil.getAttributeAsInteger(attributes, "size"); Color color; try { color = getAttributeAsColor(attributes, "color"); } catch (PropertyException pe) { throw new IFException("Error parsing the color attribute", pe); } painter.setFont(family, style, weight, variant, size, color); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { int x = Integer.parseInt(lastAttributes.getValue("x")); int y = Integer.parseInt(lastAttributes.getValue("y")); String s = lastAttributes.getValue("letter-spacing"); int letterSpacing = (s != null ? Integer.parseInt(s) : 0); s = lastAttributes.getValue("word-spacing"); int wordSpacing = (s != null ? Integer.parseInt(s) : 0); int[] dx = XMLUtil.getAttributeAsIntArray(lastAttributes, "dx"); int[][] dp = XMLUtil.getAttributeAsPositionAdjustments(lastAttributes, "dp"); // if only DX present, then convert DX to DP; otherwise use only DP, // effectively ignoring DX if ( ( dp == null ) && ( dx != null ) ) { dp = IFUtil.convertDXToDP ( dx ); } establishStructureTreeElement(lastAttributes); painter.drawText(x, y, letterSpacing, wordSpacing, dp, content.toString()); resetStructureTreeElement(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int x = Integer.parseInt(attributes.getValue("x")); int y = Integer.parseInt(attributes.getValue("y")); int width = Integer.parseInt(attributes.getValue("width")); int height = Integer.parseInt(attributes.getValue("height")); painter.clipRect(new Rectangle(x, y, width, height)); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int x = Integer.parseInt(attributes.getValue("x")); int y = Integer.parseInt(attributes.getValue("y")); int width = Integer.parseInt(attributes.getValue("width")); int height = Integer.parseInt(attributes.getValue("height")); Color fillColor; try { fillColor = getAttributeAsColor(attributes, "fill"); } catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); } painter.fillRect(new Rectangle(x, y, width, height), fillColor); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int x1 = Integer.parseInt(attributes.getValue("x1")); int y1 = Integer.parseInt(attributes.getValue("y1")); int x2 = Integer.parseInt(attributes.getValue("x2")); int y2 = Integer.parseInt(attributes.getValue("y2")); int width = Integer.parseInt(attributes.getValue("stroke-width")); Color color; try { color = getAttributeAsColor(attributes, "color"); } catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); } RuleStyle style = RuleStyle.valueOf(attributes.getValue("style")); painter.drawLine(new Point(x1, y1), new Point(x2, y2), width, color, style); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int x = Integer.parseInt(attributes.getValue("x")); int y = Integer.parseInt(attributes.getValue("y")); int width = Integer.parseInt(attributes.getValue("width")); int height = Integer.parseInt(attributes.getValue("height")); BorderProps[] borders = new BorderProps[4]; for (int i = 0; i < 4; i++) { String b = attributes.getValue(SIDES[i]); if (b != null) { borders[i] = BorderProps.valueOf(userAgent, b); } } painter.drawBorderRect(new Rectangle(x, y, width, height), borders[0], borders[1], borders[2], borders[3]); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { inForeignObject = true; }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { int x = Integer.parseInt(lastAttributes.getValue("x")); int y = Integer.parseInt(lastAttributes.getValue("y")); int width = Integer.parseInt(lastAttributes.getValue("width")); int height = Integer.parseInt(lastAttributes.getValue("height")); Map<QName, String> foreignAttributes = getForeignAttributes(lastAttributes); establishForeignAttributes(foreignAttributes); establishStructureTreeElement(lastAttributes); if (foreignObject != null) { painter.drawImage(foreignObject, new Rectangle(x, y, width, height)); foreignObject = null; } else { String uri = lastAttributes.getValue( XLINK_HREF.getNamespaceURI(), XLINK_HREF.getLocalName()); if (uri == null) { throw new IFException("xlink:href is missing on image", null); } painter.drawImage(uri, new Rectangle(x, y, width, height)); } resetForeignAttributes(); resetStructureTreeElement(); inForeignObject = false; }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
public void startViewport(AffineTransform[] transforms, Dimension size, Rectangle clipRect) throws IFException { startViewport(combine(transforms), size, clipRect); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
public void startGroup(AffineTransform[] transforms) throws IFException { startGroup(combine(transforms)); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null) { Rectangle b = new Rectangle( rect.x, rect.y, rect.width, top.width); fillRect(b, top.color); } if (right != null) { Rectangle b = new Rectangle( rect.x + rect.width - right.width, rect.y, right.width, rect.height); fillRect(b, right.color); } if (bottom != null) { Rectangle b = new Rectangle( rect.x, rect.y + rect.height - bottom.width, rect.width, bottom.width); fillRect(b, bottom.color); } if (left != null) { Rectangle b = new Rectangle( rect.x, rect.y, left.width, rect.height); fillRect(b, left.color); } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { Rectangle rect = getLineBoundingBox(start, end, width); fillRect(rect, color); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
public void setFont(String family, String style, Integer weight, String variant, Integer size, Color color) throws IFException { if (family != null) { state.setFontFamily(family); } if (style != null) { state.setFontStyle(style); } if (weight != null) { state.setFontWeight(weight.intValue()); } if (variant != null) { state.setFontVariant(variant); } if (size != null) { state.setFontSize(size.intValue()); } if (color != null) { state.setTextColor(color); } }
// in src/java/org/apache/fop/render/intermediate/EventProducingFilter.java
Override public void endPage() throws IFException { super.endPage(); pageNumberEnded++; RendererEventProducer.Provider.get(userAgent.getEventBroadcaster()) .endPage(this, pageNumberEnded); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startDocument() throws IFException { super.startDocument(); try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); handler.startPrefixMapping(DocumentNavigationExtensionConstants.PREFIX, DocumentNavigationExtensionConstants.NAMESPACE); handler.startPrefixMapping(InternalElementMapping.STANDARD_PREFIX, InternalElementMapping.URI); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "version", VERSION); handler.startElement(EL_DOCUMENT, atts); } catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startDocumentHeader() throws IFException { try { handler.startElement(EL_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endDocumentHeader() throws IFException { try { handler.endElement(EL_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startDocumentTrailer() throws IFException { try { handler.startElement(EL_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endDocumentTrailer() throws IFException { try { handler.endElement(EL_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in endDocumentTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endDocument() throws IFException { try { handler.endElement(EL_DOCUMENT); handler.endDocument(); finishDocumentNavigation(); } catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startPageSequence(String id) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (id != null) { atts.addAttribute(XML_NAMESPACE, "id", "xml:id", XMLUtil.CDATA, id); } Locale lang = getContext().getLanguage(); if (lang != null) { atts.addAttribute(XML_NAMESPACE, "lang", "xml:lang", XMLUtil.CDATA, LanguageTags.toLanguageTag(lang)); } XMLUtil.addAttribute(atts, XMLConstants.XML_SPACE, "preserve"); addForeignAttributes(atts); handler.startElement(EL_PAGE_SEQUENCE, atts); if (this.getUserAgent().isAccessibilityEnabled()) { assert (structureTreeBuilder != null); structureTreeBuilder.replayEventsForPageSequence(handler, pageSequenceIndex++); } } catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endPageSequence() throws IFException { try { handler.endElement(EL_PAGE_SEQUENCE); } catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "index", Integer.toString(index)); addAttribute(atts, "name", name); addAttribute(atts, "page-master-name", pageMasterName); addAttribute(atts, "width", Integer.toString(size.width)); addAttribute(atts, "height", Integer.toString(size.height)); addForeignAttributes(atts); handler.startElement(EL_PAGE, atts); } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startPageHeader() throws IFException { try { handler.startElement(EL_PAGE_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startPageHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endPageHeader() throws IFException { try { handler.endElement(EL_PAGE_HEADER); } catch (SAXException e) { throw new IFException("SAX error in endPageHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public IFPainter startPageContent() throws IFException { try { handler.startElement(EL_PAGE_CONTENT); this.state = IFState.create(); return this; } catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endPageContent() throws IFException { try { this.state = null; currentID = ""; handler.endElement(EL_PAGE_CONTENT); } catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startPageTrailer() throws IFException { try { handler.startElement(EL_PAGE_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in startPageTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endPageTrailer() throws IFException { try { commitNavigation(); handler.endElement(EL_PAGE_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in endPageTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endPage() throws IFException { try { handler.endElement(EL_PAGE); } catch (SAXException e) { throw new IFException("SAX error in endPage()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { startViewport(IFUtil.toString(transform), size, clipRect); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startViewport(AffineTransform[] transforms, Dimension size, Rectangle clipRect) throws IFException { startViewport(IFUtil.toString(transforms), size, clipRect); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void startViewport(String transform, Dimension size, Rectangle clipRect) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { addAttribute(atts, "transform", transform); } addAttribute(atts, "width", Integer.toString(size.width)); addAttribute(atts, "height", Integer.toString(size.height)); if (clipRect != null) { addAttribute(atts, "clip-rect", IFUtil.toString(clipRect)); } handler.startElement(EL_VIEWPORT, atts); } catch (SAXException e) { throw new IFException("SAX error in startViewport()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endViewport() throws IFException { try { handler.endElement(EL_VIEWPORT); } catch (SAXException e) { throw new IFException("SAX error in endViewport()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startGroup(AffineTransform[] transforms) throws IFException { startGroup(IFUtil.toString(transforms)); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startGroup(AffineTransform transform) throws IFException { startGroup(IFUtil.toString(transform)); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void startGroup(String transform) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { addAttribute(atts, "transform", transform); } handler.startElement(EL_GROUP, atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endGroup() throws IFException { try { handler.endElement(EL_GROUP); } catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawImage(String uri, Rectangle rect) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, XLINK_HREF, uri); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addForeignAttributes(atts); addStructureReference(atts); handler.element(EL_IMAGE, atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawImage(Document doc, Rectangle rect) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addForeignAttributes(atts); addStructureReference(atts); handler.startElement(EL_IMAGE, atts); new DOM2SAX(handler).writeDocument(doc, true); handler.endElement(EL_IMAGE); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void clipRect(Rectangle rect) throws IFException { try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); handler.element(EL_CLIP_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in clipRect()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addAttribute(atts, "fill", toString(fill)); handler.element(EL_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top == null && bottom == null && left == null && right == null) { return; } try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); if (top != null) { addAttribute(atts, "top", top.toString()); } if (bottom != null) { addAttribute(atts, "bottom", bottom.toString()); } if (left != null) { addAttribute(atts, "left", left.toString()); } if (right != null) { addAttribute(atts, "right", right.toString()); } handler.element(EL_BORDER_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in drawBorderRect()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x1", Integer.toString(start.x)); addAttribute(atts, "y1", Integer.toString(start.y)); addAttribute(atts, "x2", Integer.toString(end.x)); addAttribute(atts, "y2", Integer.toString(end.y)); addAttribute(atts, "stroke-width", Integer.toString(width)); addAttribute(atts, "color", ColorUtil.colorToString(color)); addAttribute(atts, "style", style.getName()); handler.element(EL_LINE, atts); } catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(x)); addAttribute(atts, "y", Integer.toString(y)); if (letterSpacing != 0) { addAttribute(atts, "letter-spacing", Integer.toString(letterSpacing)); } if (wordSpacing != 0) { addAttribute(atts, "word-spacing", Integer.toString(wordSpacing)); } if (dp != null) { if ( IFUtil.isDPIdentity(dp) ) { // don't add dx or dp attribute } else if ( IFUtil.isDPOnlyDX(dp) ) { // add dx attribute only int[] dx = IFUtil.convertDPToDX(dp); addAttribute(atts, "dx", IFUtil.toString(dx)); } else { // add dp attribute only addAttribute(atts, "dp", XMLUtil.encodePositionAdjustments(dp)); } } addStructureReference(atts); handler.startElement(EL_TEXT, atts); char[] chars = text.toCharArray(); handler.characters(chars, 0, chars.length); handler.endElement(EL_TEXT); } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void setFont(String family, String style, Integer weight, String variant, Integer size, Color color) throws IFException { try { AttributesImpl atts = new AttributesImpl(); boolean changed; if (family != null) { changed = !family.equals(state.getFontFamily()); if (changed) { state.setFontFamily(family); addAttribute(atts, "family", family); } } if (style != null) { changed = !style.equals(state.getFontStyle()); if (changed) { state.setFontStyle(style); addAttribute(atts, "style", style); } } if (weight != null) { changed = (weight.intValue() != state.getFontWeight()); if (changed) { state.setFontWeight(weight.intValue()); addAttribute(atts, "weight", weight.toString()); } } if (variant != null) { changed = !variant.equals(state.getFontVariant()); if (changed) { state.setFontVariant(variant); addAttribute(atts, "variant", variant); } } if (size != null) { changed = (size.intValue() != state.getFontSize()); if (changed) { state.setFontSize(size.intValue()); addAttribute(atts, "size", size.toString()); } } if (color != null) { changed = !org.apache.xmlgraphics.java2d.color.ColorUtil.isSameColor( color, state.getTextColor()); if (changed) { state.setTextColor(color); addAttribute(atts, "color", toString(color)); } } if (atts.getLength() > 0) { handler.element(EL_FONT, atts); } } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof XMLizable) { try { ((XMLizable)extension).toSAX(this.handler); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { throw new UnsupportedOperationException( "Extension must implement XMLizable: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void renderNamedDestination(NamedDestination destination) throws IFException { noteAction(destination.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute(null, "name", "name", XMLConstants.CDATA, destination.getName()); try { handler.startElement(DocumentNavigationExtensionConstants.NAMED_DESTINATION, atts); serializeXMLizable(destination.getAction()); handler.endElement(DocumentNavigationExtensionConstants.NAMED_DESTINATION); } catch (SAXException e) { throw new IFException("SAX error serializing named destination", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void renderBookmarkTree(BookmarkTree tree) throws IFException { AttributesImpl atts = new AttributesImpl(); try { handler.startElement(DocumentNavigationExtensionConstants.BOOKMARK_TREE, atts); Iterator iter = tree.getBookmarks().iterator(); while (iter.hasNext()) { Bookmark b = (Bookmark)iter.next(); if (b.getAction() != null) { serializeBookmark(b); } } handler.endElement(DocumentNavigationExtensionConstants.BOOKMARK_TREE); } catch (SAXException e) { throw new IFException("SAX error serializing bookmark tree", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void serializeBookmark(Bookmark bookmark) throws SAXException, IFException { noteAction(bookmark.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute(null, "title", "title", XMLUtil.CDATA, bookmark.getTitle()); atts.addAttribute(null, "starting-state", "starting-state", XMLUtil.CDATA, bookmark.isShown() ? "show" : "hide"); handler.startElement(DocumentNavigationExtensionConstants.BOOKMARK, atts); serializeXMLizable(bookmark.getAction()); Iterator iter = bookmark.getChildBookmarks().iterator(); while (iter.hasNext()) { Bookmark b = (Bookmark)iter.next(); if (b.getAction() != null) { serializeBookmark(b); } } handler.endElement(DocumentNavigationExtensionConstants.BOOKMARK); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void renderLink(Link link) throws IFException { noteAction(link.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute(null, "rect", "rect", XMLConstants.CDATA, IFUtil.toString(link.getTargetRect())); if (getUserAgent().isAccessibilityEnabled()) { addStructRefAttribute(atts, ((IFStructureTreeElement) link.getAction().getStructureTreeElement()).getId()); } try { handler.startElement(DocumentNavigationExtensionConstants.LINK, atts); serializeXMLizable(link.getAction()); handler.endElement(DocumentNavigationExtensionConstants.LINK); } catch (SAXException e) { throw new IFException("SAX error serializing link", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void addResolvedAction(AbstractAction action) throws IFException { assert action.isComplete(); assert action.hasID(); AbstractAction noted = (AbstractAction)incompleteActions.remove(action.getID()); if (noted != null) { completeActions.add(action); } else { //ignore as it was already complete when it was first used. } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void commitNavigation() throws IFException { Iterator iter = this.completeActions.iterator(); while (iter.hasNext()) { AbstractAction action = (AbstractAction)iter.next(); iter.remove(); serializeXMLizable(action); } assert this.completeActions.size() == 0; }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void serializeXMLizable(XMLizable object) throws IFException { try { object.toSAX(handler); } catch (SAXException e) { throw new IFException("SAX error serializing object", e); } }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void setResult(Result result) throws IFException { if (result instanceof StreamResult) { StreamResult streamResult = (StreamResult)result; OutputStream out = streamResult.getOutputStream(); if (out == null) { if (streamResult.getWriter() != null) { throw new IllegalArgumentException( "FOP cannot use a Writer. Please supply an OutputStream!"); } try { URL url = new URL(streamResult.getSystemId()); File f = FileUtils.toFile(url); if (f != null) { out = new java.io.FileOutputStream(f); } else { out = url.openConnection().getOutputStream(); } } catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); } out = new java.io.BufferedOutputStream(out); this.ownOutputStream = true; } if (out == null) { throw new IllegalArgumentException("Need a StreamResult with an OutputStream"); } this.outputStream = out; } else { throw new UnsupportedOperationException( "Unsupported Result subclass: " + result.getClass().getName()); } }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); if (this.outputStream == null) { throw new IllegalStateException("OutputStream hasn't been set through setResult()"); } }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void endDocument() throws IFException { if (this.ownOutputStream) { IOUtils.closeQuietly(this.outputStream); this.outputStream = null; } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void startDocument() throws IFException { if (getUserAgent() == null) { throw new IllegalStateException( "User agent must be set before starting document generation"); } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void startDocumentHeader() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void endDocumentHeader() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void startDocumentTrailer() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void endDocumentTrailer() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void startPageHeader() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void endPageHeader() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void startPageTrailer() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void endPageTrailer() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
public void setResult(Result result) throws IFException { if (result instanceof SAXResult) { SAXResult saxResult = (SAXResult)result; this.handler = new GenerationHelperContentHandler( saxResult.getHandler(), getMainNamespace()); } else { this.handler = new GenerationHelperContentHandler( createContentHandler(result), getMainNamespace()); } }
// in src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
protected ContentHandler createContentHandler(Result result) throws IFException { try { TransformerHandler tHandler = tFactory.newTransformerHandler(); Transformer transformer = tHandler.getTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); tHandler.setResult(result); return tHandler; } catch (TransformerConfigurationException tce) { throw new IFException( "Error while setting up the serializer for XML output", tce); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
private void processExtensionAttachments(AreaTreeObject area) throws IFException { if (area.hasExtensionAttachments()) { for (Iterator iter = area.getExtensionAttachments().iterator(); iter.hasNext();) { ExtensionAttachment attachment = (ExtensionAttachment) iter.next(); this.documentHandler.handleExtensionObject(attachment); } } }
// in src/java/org/apache/fop/render/intermediate/IFGraphicContext.java
public void start(IFPainter painter) throws IFException { painter.startGroup(transforms); }
// in src/java/org/apache/fop/render/intermediate/IFGraphicContext.java
public void end(IFPainter painter) throws IFException { painter.endGroup(); }
// in src/java/org/apache/fop/render/intermediate/IFGraphicContext.java
public void start(IFPainter painter) throws IFException { painter.startViewport(getTransforms(), size, clipRect); }
// in src/java/org/apache/fop/render/intermediate/IFGraphicContext.java
public void end(IFPainter painter) throws IFException { painter.endViewport(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void setResult(Result result) throws IFException { this.delegate.setResult(result); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startDocument() throws IFException { this.delegate.startDocument(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startDocumentHeader() throws IFException { this.delegate.startDocumentHeader(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endDocumentHeader() throws IFException { this.delegate.endDocumentHeader(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startPageSequence(String id) throws IFException { this.delegate.startPageSequence(id); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { this.delegate.startPage(index, name, pageMasterName, size); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startPageHeader() throws IFException { this.delegate.startPageHeader(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endPageHeader() throws IFException { this.delegate.endPageHeader(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public IFPainter startPageContent() throws IFException { return this.delegate.startPageContent(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endPageContent() throws IFException { this.delegate.endPageContent(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startPageTrailer() throws IFException { this.delegate.startPageTrailer(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endPageTrailer() throws IFException { this.delegate.endPageTrailer(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endPage() throws IFException { this.delegate.endPage(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endPageSequence() throws IFException { this.delegate.endPageSequence(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startDocumentTrailer() throws IFException { this.delegate.startDocumentTrailer(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endDocumentTrailer() throws IFException { this.delegate.endDocumentTrailer(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endDocument() throws IFException { this.delegate.endDocument(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void handleExtensionObject(Object extension) throws IFException { this.delegate.handleExtensionObject(extension); }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
private void startDocument(Metadata metadata) throws IFException { this.targetHandler.startDocument(); this.targetHandler.startDocumentHeader(); if (metadata != null) { this.targetHandler.handleExtensionObject(metadata); } this.targetHandler.endDocumentHeader(); }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
private void endDocument() throws IFException { this.targetHandler.startPageTrailer(); this.targetHandler.endPageTrailer(); this.targetHandler.endDocument(); }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void finish() throws IFException { endDocument(); }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void appendDocument(Source src) throws TransformerException, IFException { IFParser parser = new IFParser(); parser.parse(src, new IFPageSequenceFilter(getTargetHandler()), getTargetHandler().getContext().getUserAgent()); }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void startDocument() throws IFException { //ignore }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void startDocumentHeader() throws IFException { //ignore }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void endDocumentHeader() throws IFException { //ignore }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void startPageSequence(String id) throws IFException { assert !this.inPageSequence; this.inPageSequence = true; super.startPageSequence(id); }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { //Adjust page indices super.startPage(nextPageIndex, name, pageMasterName, size); nextPageIndex++; }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void endPageSequence() throws IFException { super.endPageSequence(); assert this.inPageSequence; this.inPageSequence = false; }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void startDocumentTrailer() throws IFException { //ignore }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void endDocumentTrailer() throws IFException { //ignore }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void endDocument() throws IFException { //ignore inFirstDocument = false; }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void handleExtensionObject(Object extension) throws IFException { if (inPageSequence || inFirstDocument) { //Only pass through when inside page-sequence //or for the first document (for document-level extensions). super.handleExtensionObject(extension); } //Note:Extensions from non-first documents are ignored! }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
Override public void startDocument() throws IFException { super.startDocument(); try { this.gen = new PCLGenerator(this.outputStream, getResolution()); this.gen.setDitheringQuality(pclUtil.getDitheringQuality()); if (!pclUtil.isPJLDisabled()) { gen.universalEndOfLanguage(); gen.writeText("@PJL COMMENT Produced by " + getUserAgent().getProducer() + "\n"); if (getUserAgent().getTitle() != null) { gen.writeText("@PJL JOB NAME = \"" + getUserAgent().getTitle() + "\"\n"); } gen.writeText("@PJL SET RESOLUTION = " + getResolution() + "\n"); gen.writeText("@PJL ENTER LANGUAGE = PCL\n"); } gen.resetPrinter(); gen.setUnitOfMeasure(getResolution()); gen.setRasterGraphicsResolution(getResolution()); } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
Override public void endDocumentHeader() throws IFException { }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
Override public void endDocument() throws IFException { try { gen.separateJobs(); gen.resetPrinter(); if (!pclUtil.isPJLDisabled()) { gen.universalEndOfLanguage(); } } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void startPageSequence(String id) throws IFException { //nop }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void endPageSequence() throws IFException { //nop }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { //Paper source Object paperSource = getContext().getForeignAttribute( PCLElementMapping.PCL_PAPER_SOURCE); if (paperSource != null) { gen.selectPaperSource(Integer.parseInt(paperSource.toString())); } //Output bin Object outputBin = getContext().getForeignAttribute( PCLElementMapping.PCL_OUTPUT_BIN); if (outputBin != null) { gen.selectOutputBin(Integer.parseInt(outputBin.toString())); } // Is Page duplex? Object pageDuplex = getContext().getForeignAttribute( PCLElementMapping.PCL_DUPLEX_MODE); if (pageDuplex != null) { gen.selectDuplexMode(Integer.parseInt(pageDuplex.toString())); } //Page size final long pagewidth = size.width; final long pageheight = size.height; selectPageFormat(pagewidth, pageheight); } catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public IFPainter startPageContent() throws IFException { if (pclUtil.getRenderingMode() == PCLRenderingMode.BITMAP) { return createAllBitmapPainter(); } else { return new PCLPainter(this, this.currentPageDefinition); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void endPageContent() throws IFException { if (this.currentImage != null) { try { //ImageWriterUtil.saveAsPNG(this.currentImage, new java.io.File("D:/page.png")); Rectangle printArea = this.currentPageDefinition.getLogicalPageRect(); gen.setCursorPos(0, 0); gen.paintBitmap(this.currentImage, printArea.getSize(), true); } catch (IOException ioe) { throw new IFException("I/O error while encoding page image", ioe); } finally { this.currentImage = null; } } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void endPage() throws IFException { try { //Eject page gen.formFeed(); } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (false) { //TODO Handle extensions } else { log.debug("Don't know how to handle extension object. Ignoring: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); /* PCL cannot clip! if (clipRect != null) { clipRect(clipRect); }*/ } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void endViewport() throws IFException { restoreGraphicsState(); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void startGroup(AffineTransform transform) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void endGroup() throws IFException { restoreGraphicsState(); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { drawImageUsingURI(uri, rect); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { drawImageUsingDocument(doc, rect); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void clipRect(Rectangle rect) throws IFException { //PCL cannot clip (only HP GL/2 can) //If you need clipping support, switch to RenderingMode.BITMAP. }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { Color fillColor = null; if (fill != null) { if (fill instanceof Color) { fillColor = (Color)fill; } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } try { setCursorPos(rect.x, rect.y); gen.fillRect(rect.width, rect.height, fillColor); } catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); } } } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void drawBorderRect(final Rectangle rect, final BorderProps top, final BorderProps bottom, final BorderProps left, final BorderProps right) throws IFException { if (isSpeedOptimized()) { super.drawBorderRect(rect, top, bottom, left, right); return; } if (top != null || bottom != null || left != null || right != null) { final Rectangle boundingBox = rect; final Dimension dim = boundingBox.getSize(); Graphics2DImagePainter painter = new Graphics2DImagePainter() { public void paint(Graphics2D g2d, Rectangle2D area) { g2d.translate(-rect.x, -rect.y); Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state); try { painter.drawBorderRect(rect, top, bottom, left, right); } catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting borders", e); } } public Dimension getImageSize() { return dim.getSize(); } }; paintMarksAsBitmap(painter, boundingBox); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void drawLine(final Point start, final Point end, final int width, final Color color, final RuleStyle style) throws IFException { if (isSpeedOptimized()) { super.drawLine(start, end, width, color, style); return; } final Rectangle boundingBox = getLineBoundingBox(start, end, width); final Dimension dim = boundingBox.getSize(); Graphics2DImagePainter painter = new Graphics2DImagePainter() { public void paint(Graphics2D g2d, Rectangle2D area) { g2d.translate(-boundingBox.x, -boundingBox.y); Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state); try { painter.drawLine(start, end, width, color, style); } catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting a line", e); } } public Dimension getImageSize() { return dim.getSize(); } }; paintMarksAsBitmap(painter, boundingBox); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
private void paintMarksAsBitmap(Graphics2DImagePainter painter, Rectangle boundingBox) throws IFException { ImageInfo info = new ImageInfo(null, null); ImageSize size = new ImageSize(); size.setSizeInMillipoints(boundingBox.width, boundingBox.height); info.setSize(size); ImageGraphics2D img = new ImageGraphics2D(info, painter); Map hints = new java.util.HashMap(); if (isSpeedOptimized()) { //Gray text may not be painted in this case! We don't get dithering in Sun JREs. //But this approach is about twice as fast as the grayscale image. hints.put(ImageProcessingHints.BITMAP_TYPE_INTENT, ImageProcessingHints.BITMAP_TYPE_INTENT_MONO); } else { hints.put(ImageProcessingHints.BITMAP_TYPE_INTENT, ImageProcessingHints.BITMAP_TYPE_INTENT_GRAY); } hints.put(ImageHandlerUtil.CONVERSION_MODE, ImageHandlerUtil.CONVERSION_MODE_BITMAP); PCLRenderingContext context = (PCLRenderingContext)createRenderingContext(); context.setSourceTransparencyEnabled(true); try { drawImage(img, boundingBox, context, true, hints); } catch (IOException ioe) { throw new IFException( "I/O error while painting marks using a bitmap", ioe); } catch (ImageException ie) { throw new IFException( "Error while painting marks using a bitmap", ie); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() //TODO Opportunity for font caching if font state is more heavily used String fontKey = parent.getFontInfo().getInternalFontKey(triplet); boolean pclFont = getPCLUtil().isAllTextAsBitmaps() ? false : HardcodedFonts.setFont(gen, fontKey, state.getFontSize(), text); if (pclFont) { drawTextNative(x, y, letterSpacing, wordSpacing, dp, text, triplet); } else { drawTextAsBitmap(x, y, letterSpacing, wordSpacing, dp, text, triplet); if (DEBUG) { state.setTextColor(Color.GRAY); HardcodedFonts.setFont(gen, "F1", state.getFontSize(), text); drawTextNative(x, y, letterSpacing, wordSpacing, dp, text, triplet); } } } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
private void drawTextAsBitmap(final int x, final int y, final int letterSpacing, final int wordSpacing, final int[][] dp, final String text, FontTriplet triplet) throws IFException { //Use Java2D to paint different fonts via bitmap final Font font = parent.getFontInfo().getFontInstance(triplet, state.getFontSize()); //for cursive fonts, so the text isn't clipped final FontMetricsMapper mapper = (FontMetricsMapper)parent.getFontInfo().getMetricsFor( font.getFontName()); final int maxAscent = mapper.getMaxAscent(font.getFontSize()) / 1000; final int ascent = mapper.getAscender(font.getFontSize()) / 1000; final int descent = mapper.getDescender(font.getFontSize()) / 1000; int safetyMargin = (int)(SAFETY_MARGIN_FACTOR * font.getFontSize()); final int baselineOffset = maxAscent + safetyMargin; final Rectangle boundingBox = getTextBoundingBox(x, y, letterSpacing, wordSpacing, dp, text, font, mapper); final Dimension dim = boundingBox.getSize(); Graphics2DImagePainter painter = new Graphics2DImagePainter() { public void paint(Graphics2D g2d, Rectangle2D area) { if (DEBUG) { g2d.setBackground(Color.LIGHT_GRAY); g2d.clearRect(0, 0, (int)area.getWidth(), (int)area.getHeight()); } g2d.translate(-x, -y + baselineOffset); if (DEBUG) { Rectangle rect = new Rectangle(x, y - maxAscent, 3000, maxAscent); g2d.draw(rect); rect = new Rectangle(x, y - ascent, 2000, ascent); g2d.draw(rect); rect = new Rectangle(x, y, 1000, -descent); g2d.draw(rect); } Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state); try { painter.drawText(x, y, letterSpacing, wordSpacing, dp, text); } catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting text", e); } } public Dimension getImageSize() { return dim.getSize(); } }; paintMarksAsBitmap(painter, boundingBox); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); try { // Creates writer this.imageWriter = ImageWriterRegistry.getInstance().getWriterFor(getMimeType()); if (this.imageWriter == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noImageWriterFound(this, getMimeType()); } if (this.imageWriter.supportsMultiImageWriter()) { this.multiImageWriter = this.imageWriter.createMultiImageWriter(outputStream); } else { this.multiFileUtil = new MultiFileRenderingUtil(getDefaultExtension(), getUserAgent().getOutputFile()); } this.pageCount = 0; } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endDocumentHeader() throws IFException { }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endDocument() throws IFException { try { if (this.multiImageWriter != null) { this.multiImageWriter.close(); } this.multiImageWriter = null; this.imageWriter = null; } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void startPageSequence(String id) throws IFException { //nop }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endPageSequence() throws IFException { //nop }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { this.pageCount++; this.currentPageDimensions = new Dimension(size); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public IFPainter startPageContent() throws IFException { int bitmapWidth; int bitmapHeight; double scale; Point2D offset = null; if (targetBitmapSize != null) { //Fit the generated page proportionally into the given rectangle (in pixels) double scale2w = 1000 * targetBitmapSize.width / this.currentPageDimensions.getWidth(); double scale2h = 1000 * targetBitmapSize.height / this.currentPageDimensions.getHeight(); bitmapWidth = targetBitmapSize.width; bitmapHeight = targetBitmapSize.height; //Centering the page in the given bitmap offset = new Point2D.Double(); if (scale2w < scale2h) { scale = scale2w; double h = this.currentPageDimensions.height * scale / 1000; offset.setLocation(0, (bitmapHeight - h) / 2.0); } else { scale = scale2h; double w = this.currentPageDimensions.width * scale / 1000; offset.setLocation((bitmapWidth - w) / 2.0, 0); } } else { //Normal case: just scale according to the target resolution scale = scaleFactor * getUserAgent().getTargetResolution() / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION; bitmapWidth = (int) ((this.currentPageDimensions.width * scale / 1000f) + 0.5f); bitmapHeight = (int) ((this.currentPageDimensions.height * scale / 1000f) + 0.5f); } //Set up bitmap to paint on this.currentImage = createBufferedImage(bitmapWidth, bitmapHeight); Graphics2D graphics2D = this.currentImage.createGraphics(); // draw page background if (!getSettings().hasTransparentPageBackground()) { graphics2D.setBackground(getSettings().getPageBackgroundColor()); graphics2D.setPaint(getSettings().getPageBackgroundColor()); graphics2D.fillRect(0, 0, bitmapWidth, bitmapHeight); } //Set rendering hints graphics2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); if (getSettings().isAntiAliasingEnabled() && this.currentImage.getColorModel().getPixelSize() > 1) { graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } else { graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } if (getSettings().isQualityRenderingEnabled()) { graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); } else { graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); } graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); //Set up initial coordinate system for the page if (offset != null) { graphics2D.translate(offset.getX(), offset.getY()); } graphics2D.scale(scale / 1000f, scale / 1000f); return new Java2DPainter(graphics2D, getContext(), getFontInfo()); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endPageContent() throws IFException { try { if (this.multiImageWriter == null) { switch (this.pageCount) { case 1: this.imageWriter.writeImage( this.currentImage, this.outputStream, getSettings().getWriterParams()); IOUtils.closeQuietly(this.outputStream); this.outputStream = null; break; default: OutputStream out = this.multiFileUtil.createOutputStream(this.pageCount - 1); if (out == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.stoppingAfterFirstPageNoFilename(this); } else { try { this.imageWriter.writeImage( this.currentImage, out, getSettings().getWriterParams()); } finally { IOUtils.closeQuietly(out); } } } } else { this.multiImageWriter.writeImage(this.currentImage, getSettings().getWriterParams()); } this.currentImage = null; } catch (IOException ioe) { throw new IFException("I/O error while encoding BufferedImage", ioe); } }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endPage() throws IFException { this.currentPageDimensions = null; }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { log.debug("Don't know how to handle extension object. Ignoring: " + extension + " (" + extension.getClass().getName() + ")"); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void startDocument() throws IFException { super.startDocument(); try { paintingState.setColor(Color.WHITE); this.dataStream = resourceManager.createDataStream(paintingState, outputStream); this.dataStream.startDocument(); } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void startDocumentHeader() throws IFException { super.startDocumentHeader(); this.location = Location.IN_DOCUMENT_HEADER; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void endDocumentHeader() throws IFException { super.endDocumentHeader(); this.location = Location.ELSEWHERE; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void endDocument() throws IFException { try { this.dataStream.endDocument(); this.dataStream = null; this.resourceManager.writeToStream(); this.resourceManager = null; } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void startPageSequence(String id) throws IFException { try { dataStream.startPageGroup(); } catch (IOException ioe) { throw new IFException("I/O error in startPageSequence()", ioe); } this.location = Location.FOLLOWING_PAGE_SEQUENCE; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void endPageSequence() throws IFException { try { //Process deferred page-sequence-level extensions Iterator<AFPPageSetup> iter = this.deferredPageSequenceExtensions.iterator(); while (iter.hasNext()) { AFPPageSetup aps = iter.next(); iter.remove(); if (AFPElementMapping.NO_OPERATION.equals(aps.getElementName())) { handleNOP(aps); } else { throw new UnsupportedOperationException("Don't know how to handle " + aps); } } //End page sequence dataStream.endPageGroup(); } catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); } this.location = Location.ELSEWHERE; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { this.location = Location.ELSEWHERE; paintingState.clear(); AffineTransform baseTransform = getBaseTransform(); paintingState.concatenate(baseTransform); int pageWidth = Math.round(unitConv.mpt2units(size.width)); paintingState.setPageWidth(pageWidth); int pageHeight = Math.round(unitConv.mpt2units(size.height)); paintingState.setPageHeight(pageHeight); int pageRotation = paintingState.getPageRotation(); int resolution = paintingState.getResolution(); dataStream.startPage(pageWidth, pageHeight, pageRotation, resolution, resolution); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void startPageHeader() throws IFException { super.startPageHeader(); this.location = Location.IN_PAGE_HEADER; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void endPageHeader() throws IFException { this.location = Location.ELSEWHERE; super.endPageHeader(); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public IFPainter startPageContent() throws IFException { return new AFPPainter(this); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void endPageContent() throws IFException { }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void endPage() throws IFException { try { AFPPageFonts pageFonts = paintingState.getPageFonts(); if (pageFonts != null && !pageFonts.isEmpty()) { dataStream.addFontsToCurrentPage(pageFonts); } dataStream.endPage(); } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof AFPPageSetup) { AFPPageSetup aps = (AFPPageSetup)extension; String element = aps.getElementName(); if (AFPElementMapping.TAG_LOGICAL_ELEMENT.equals(element)) { switch (this.location) { case FOLLOWING_PAGE_SEQUENCE: case IN_PAGE_HEADER: String name = aps.getName(); String value = aps.getValue(); dataStream.createTagLogicalElement(name, value); break; default: throw new IFException( "TLE extension must be in the page header or between page-sequence" + " and the first page: " + aps, null); } } else if (AFPElementMapping.NO_OPERATION.equals(element)) { switch (this.location) { case FOLLOWING_PAGE_SEQUENCE: if (aps.getPlacement() == ExtensionPlacement.BEFORE_END) { this.deferredPageSequenceExtensions.add(aps); break; } case IN_DOCUMENT_HEADER: case IN_PAGE_HEADER: handleNOP(aps); break; default: throw new IFException( "NOP extension must be in the document header, the page header" + " or between page-sequence" + " and the first page: " + aps, null); } } else { if (this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP page setup extension encountered outside the page header: " + aps, null); } if (AFPElementMapping.INCLUDE_PAGE_SEGMENT.equals(element)) { AFPPageSegmentElement.AFPPageSegmentSetup apse = (AFPPageSegmentElement.AFPPageSegmentSetup)aps; String name = apse.getName(); String source = apse.getValue(); String uri = apse.getResourceSrc(); pageSegmentMap.put(source, new PageSegmentDescriptor(name, uri)); } } } else if (extension instanceof AFPPageOverlay) { AFPPageOverlay ipo = (AFPPageOverlay)extension; if (this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP page overlay extension encountered outside the page header: " + ipo, null); } String overlay = ipo.getName(); if (overlay != null) { dataStream.createIncludePageOverlay(overlay, ipo.getX(), ipo.getY()); } } else if (extension instanceof AFPInvokeMediumMap) { if (this.location != Location.FOLLOWING_PAGE_SEQUENCE && this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP IMM extension must be between page-sequence" + " and the first page or child of page-header: " + extension, null); } AFPInvokeMediumMap imm = (AFPInvokeMediumMap)extension; String mediumMap = imm.getName(); if (mediumMap != null) { dataStream.createInvokeMediumMap(mediumMap); } } else if (extension instanceof AFPIncludeFormMap) { AFPIncludeFormMap formMap = (AFPIncludeFormMap)extension; ResourceAccessor accessor = new DefaultFOPResourceAccessor( getUserAgent(), null, null); try { getResourceManager().createIncludedResource(formMap.getName(), formMap.getSrc(), accessor, ResourceObject.TYPE_FORMDEF); } catch (IOException ioe) { throw new IFException( "I/O error while embedding form map resource: " + formMap.getName(), ioe); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { //AFP doesn't support clipping, so we treat viewport like a group //this is the same code as for startGroup() try { saveGraphicsState(); concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void endViewport() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void startGroup(AffineTransform transform) throws IFException { try { saveGraphicsState(); concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void endGroup() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { PageSegmentDescriptor pageSegment = documentHandler.getPageSegmentNameFor(uri); if (pageSegment != null) { float[] srcPts = {rect.x, rect.y}; int[] coords = unitConv.mpts2units(srcPts); int width = Math.round(unitConv.mpt2units(rect.width)); int height = Math.round(unitConv.mpt2units(rect.height)); getDataStream().createIncludePageSegment(pageSegment.getName(), coords[X], coords[Y], width, height); //Do we need to embed an external page segment? if (pageSegment.getURI() != null) { ResourceAccessor accessor = new DefaultFOPResourceAccessor ( documentHandler.getUserAgent(), null, null); try { URI resourceUri = new URI(pageSegment.getURI()); documentHandler.getResourceManager().createIncludedResourceFromExternal( pageSegment.getName(), resourceUri, accessor); } catch (URISyntaxException urie) { throw new IFException("Could not handle resource url" + pageSegment.getURI(), urie); } catch (IOException ioe) { throw new IFException("Could not handle resource" + pageSegment.getURI(), ioe); } } } else { drawImageUsingURI(uri, rect); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { drawImageUsingDocument(doc, rect); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void clipRect(Rectangle rect) throws IFException { //Not supported! }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { if (fill instanceof Color) { getPaintingState().setColor((Color)fill); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } RectanglePaintingInfo rectanglePaintInfo = new RectanglePaintingInfo( toPoint(rect.x), toPoint(rect.y), toPoint(rect.width), toPoint(rect.height)); try { rectanglePainter.paint(rectanglePaintInfo); } catch (IOException ioe) { throw new IFException("IO error while painting rectangle", ioe); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { try { this.borderPainter.drawBorders(rect, top, bottom, left, right); } catch (IOException ife) { throw new IFException("IO error while painting borders", ife); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { this.borderPainter.drawLine(start, end, width, color, style); } catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void drawText( // CSOK: MethodLength int x, int y, final int letterSpacing, final int wordSpacing, final int[][] dp, final String text) throws IFException { final int fontSize = this.state.getFontSize(); getPaintingState().setFontSize(fontSize); FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() String fontKey = getFontInfo().getInternalFontKey(triplet); if (fontKey == null) { triplet = new FontTriplet("any", Font.STYLE_NORMAL, Font.WEIGHT_NORMAL); fontKey = getFontInfo().getInternalFontKey(triplet); } // register font as necessary Map<String, Typeface> fontMetricMap = documentHandler.getFontInfo().getFonts(); final AFPFont afpFont = (AFPFont)fontMetricMap.get(fontKey); final Font font = getFontInfo().getFontInstance(triplet, fontSize); AFPPageFonts pageFonts = getPaintingState().getPageFonts(); AFPFontAttributes fontAttributes = pageFonts.registerFont(fontKey, afpFont, fontSize); final int fontReference = fontAttributes.getFontReference(); final int[] coords = unitConv.mpts2units(new float[] {x, y} ); final CharacterSet charSet = afpFont.getCharacterSet(fontSize); if (afpFont.isEmbeddable()) { try { documentHandler.getResourceManager().embedFont(afpFont, charSet); } catch (IOException ioe) { throw new IFException("Error while embedding font resources", ioe); } } AbstractPageObject page = getDataStream().getCurrentPage(); PresentationTextObject pto = page.getPresentationTextObject(); try { pto.createControlSequences(new PtocaProducer() { public void produce(PtocaBuilder builder) throws IOException { Point p = getPaintingState().getPoint(coords[X], coords[Y]); builder.setTextOrientation(getPaintingState().getRotation()); builder.absoluteMoveBaseline(p.y); builder.absoluteMoveInline(p.x); builder.setExtendedTextColor(state.getTextColor()); builder.setCodedFont((byte)fontReference); int l = text.length(); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); StringBuffer sb = new StringBuffer(); if (dxl > 0 && dx[0] != 0) { int dxu = Math.round(unitConv.mpt2units(dx[0])); builder.relativeMoveInline(-dxu); } //Following are two variants for glyph placement. //SVI does not seem to be implemented in the same way everywhere, so //a fallback alternative is preserved here. final boolean usePTOCAWordSpacing = true; if (usePTOCAWordSpacing) { int interCharacterAdjustment = 0; if (letterSpacing != 0) { interCharacterAdjustment = Math.round(unitConv.mpt2units( letterSpacing)); } builder.setInterCharacterAdjustment(interCharacterAdjustment); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + letterSpacing)); int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement; if (wordSpacing != 0) { varSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + wordSpacing + letterSpacing)); } builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement); boolean fixedSpaceMode = false; for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( fixedSpaceCharacterIncrement); fixedSpaceMode = true; sb.append(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { if (fixedSpaceMode) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( varSpaceCharacterIncrement); fixedSpaceMode = false; } char ch; if (orgChar == CharUtilities.NBSPACE) { ch = ' '; //converted to normal space to allow word spacing } else { ch = orgChar; } sb.append(ch); } if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } else { for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { sb.append(CharUtilities.SPACE); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { sb.append(orgChar); } if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust += wordSpacing; } glyphAdjust += letterSpacing; if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } flushText(builder, sb, charSet); } private void flushText(PtocaBuilder builder, StringBuffer sb, final CharacterSet charSet) throws IOException { if (sb.length() > 0) { builder.addTransparentData(charSet.encodeChars(sb)); sb.setLength(0); } } }); } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); this.fontResources = new FontResourceCache(getFontInfo()); try { OutputStream out; if (psUtil.isOptimizeResources()) { this.tempFile = File.createTempFile("fop", null); out = new java.io.FileOutputStream(this.tempFile); out = new java.io.BufferedOutputStream(out); } else { out = this.outputStream; } //Setup for PostScript generation this.gen = new PSGenerator(out) { /** Need to subclass PSGenerator to have better URI resolution */ public Source resolveURI(String uri) { return getUserAgent().resolveURI(uri); } }; this.gen.setPSLevel(psUtil.getLanguageLevel()); this.currentPageNumber = 0; this.documentBoundingBox = new Rectangle2D.Double(); //Initial default page device dictionary settings this.pageDeviceDictionary = new PSPageDeviceDictionary(); pageDeviceDictionary.setFlushOnRetrieval(!psUtil.isDSCComplianceEnabled()); pageDeviceDictionary.put("/ImagingBBox", "null"); } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endDocumentHeader() throws IFException { try { writeHeader(); } catch (IOException ioe) { throw new IFException("I/O error writing the PostScript header", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endDocument() throws IFException { try { //Write trailer gen.writeDSCComment(DSCConstants.TRAILER); writeExtensions(COMMENT_DOCUMENT_TRAILER); gen.writeDSCComment(DSCConstants.PAGES, new Integer(this.currentPageNumber)); new DSCCommentBoundingBox(this.documentBoundingBox).generate(gen); new DSCCommentHiResBoundingBox(this.documentBoundingBox).generate(gen); gen.getResourceTracker().writeResources(false, gen); gen.writeDSCComment(DSCConstants.EOF); gen.flush(); log.debug("Rendering to PostScript complete."); if (psUtil.isOptimizeResources()) { IOUtils.closeQuietly(gen.getOutputStream()); rewritePostScriptFile(); } if (pageDeviceDictionary != null) { pageDeviceDictionary.clear(); } } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPageSequence(String id) throws IFException { //nop }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageSequence() throws IFException { //nop }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { if (this.currentPageNumber == 0) { //writeHeader(); } this.currentPageNumber++; gen.getResourceTracker().notifyStartNewPage(); gen.getResourceTracker().notifyResourceUsageOnPage(PSProcSets.STD_PROCSET); gen.writeDSCComment(DSCConstants.PAGE, new Object[] {name, new Integer(this.currentPageNumber)}); double pageWidth = size.width / 1000.0; double pageHeight = size.height / 1000.0; boolean rotate = false; List pageSizes = new java.util.ArrayList(); if (this.psUtil.isAutoRotateLandscape() && (pageHeight < pageWidth)) { rotate = true; pageSizes.add(new Long(Math.round(pageHeight))); pageSizes.add(new Long(Math.round(pageWidth))); } else { pageSizes.add(new Long(Math.round(pageWidth))); pageSizes.add(new Long(Math.round(pageHeight))); } pageDeviceDictionary.put("/PageSize", pageSizes); this.currentPageDefinition = new PageDefinition( new Dimension2DDouble(pageWidth, pageHeight), rotate); //TODO Handle extension attachments for the page!!!!!!! /* if (page.hasExtensionAttachments()) { for (Iterator iter = page.getExtensionAttachments().iterator(); iter.hasNext();) { ExtensionAttachment attachment = (ExtensionAttachment) iter.next(); if (attachment instanceof PSSetPageDevice) {*/ /** * Extract all PSSetPageDevice instances from the * attachment list on the s-p-m and add all * dictionary entries to our internal representation * of the the page device dictionary. *//* PSSetPageDevice setPageDevice = (PSSetPageDevice)attachment; String content = setPageDevice.getContent(); if (content != null) { try { pageDeviceDictionary.putAll(PSDictionary.valueOf(content)); } catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); } } } } }*/ final Integer zero = new Integer(0); Rectangle2D pageBoundingBox = new Rectangle2D.Double(); if (rotate) { pageBoundingBox.setRect(0, 0, pageHeight, pageWidth); gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[] { zero, zero, new Long(Math.round(pageHeight)), new Long(Math.round(pageWidth)) }); gen.writeDSCComment(DSCConstants.PAGE_HIRES_BBOX, new Object[] { zero, zero, new Double(pageHeight), new Double(pageWidth) }); gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Landscape"); } else { pageBoundingBox.setRect(0, 0, pageWidth, pageHeight); gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[] { zero, zero, new Long(Math.round(pageWidth)), new Long(Math.round(pageHeight)) }); gen.writeDSCComment(DSCConstants.PAGE_HIRES_BBOX, new Object[] { zero, zero, new Double(pageWidth), new Double(pageHeight) }); if (psUtil.isAutoRotateLandscape()) { gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Portrait"); } } this.documentBoundingBox.add(pageBoundingBox); gen.writeDSCComment(DSCConstants.PAGE_RESOURCES, new Object[] {DSCConstants.ATEND}); gen.commentln("%FOPSimplePageMaster: " + pageMasterName); } catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPageHeader() throws IFException { super.startPageHeader(); try { gen.writeDSCComment(DSCConstants.BEGIN_PAGE_SETUP); } catch (IOException ioe) { throw new IFException("I/O error in startPageHeader()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageHeader() throws IFException { try { // Write any unwritten changes to page device dictionary if (!pageDeviceDictionary.isEmpty()) { String content = pageDeviceDictionary.getContent(); if (psUtil.isSafeSetPageDevice()) { content += " SSPD"; } else { content += " setpagedevice"; } PSRenderingUtil.writeEnclosedExtensionAttachment(gen, new PSSetPageDevice(content)); } double pageHeight = this.currentPageDefinition.dimensions.getHeight(); if (this.currentPageDefinition.rotate) { gen.writeln(gen.formatDouble(pageHeight) + " 0 translate"); gen.writeln("90 rotate"); } gen.concatMatrix(1, 0, 0, -1, 0, pageHeight); gen.writeDSCComment(DSCConstants.END_PAGE_SETUP); } catch (IOException ioe) { throw new IFException("I/O error in endPageHeader()", ioe); } super.endPageHeader(); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public IFPainter startPageContent() throws IFException { return new PSPainter(this); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageContent() throws IFException { try { gen.showPage(); } catch (IOException ioe) { throw new IFException("I/O error in endPageContent()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPageTrailer() throws IFException { try { writeExtensions(PAGE_TRAILER_CODE_BEFORE); super.startPageTrailer(); gen.writeDSCComment(DSCConstants.PAGE_TRAILER); } catch (IOException ioe) { throw new IFException("I/O error in startPageTrailer()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageTrailer() throws IFException { try { writeExtensions(COMMENT_PAGE_TRAILER); } catch (IOException ioe) { throw new IFException("I/O error in endPageTrailer()", ioe); } super.endPageTrailer(); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPage() throws IFException { try { gen.getResourceTracker().writeResources(true, gen); } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } this.currentPageDefinition = null; }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { try { if (extension instanceof PSSetupCode) { if (inPage()) { PSRenderingUtil.writeEnclosedExtensionAttachment(gen, (PSSetupCode)extension); } else { //A special collection for setup code as it's put in a different place //than the "before comments". if (setupCodeList == null) { setupCodeList = new java.util.ArrayList(); } if (!setupCodeList.contains(extension)) { setupCodeList.add(extension); } } } else if (extension instanceof PSSetPageDevice) { /** * Extract all PSSetPageDevice instances from the * attachment list on the s-p-m and add all dictionary * entries to our internal representation of the the * page device dictionary. */ PSSetPageDevice setPageDevice = (PSSetPageDevice)extension; String content = setPageDevice.getContent(); if (content != null) { try { this.pageDeviceDictionary.putAll(PSDictionary.valueOf(content)); } catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); } } } else if (extension instanceof PSCommentBefore) { if (inPage()) { PSRenderingUtil.writeEnclosedExtensionAttachment( gen, (PSCommentBefore)extension); } else { if (comments[COMMENT_DOCUMENT_HEADER] == null) { comments[COMMENT_DOCUMENT_HEADER] = new java.util.ArrayList(); } comments[COMMENT_DOCUMENT_HEADER].add(extension); } } else if (extension instanceof PSCommentAfter) { int targetCollection = (inPage() ? COMMENT_PAGE_TRAILER : COMMENT_DOCUMENT_TRAILER); if (comments[targetCollection] == null) { comments[targetCollection] = new java.util.ArrayList(); } comments[targetCollection].add(extension); } else if (extension instanceof PSPageTrailerCodeBefore) { if (comments[PAGE_TRAILER_CODE_BEFORE] == null) { comments[PAGE_TRAILER_CODE_BEFORE] = new ArrayList(); } comments[PAGE_TRAILER_CODE_BEFORE].add(extension); } } catch (IOException ioe) { throw new IFException("I/O error in handleExtensionObject()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { try { PSGenerator generator = getGenerator(); saveGraphicsState(); generator.concatMatrix(toPoints(transform)); } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } if (clipRect != null) { clipRect(clipRect); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void endViewport() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void startGroup(AffineTransform transform) throws IFException { try { PSGenerator generator = getGenerator(); saveGraphicsState(); generator.concatMatrix(toPoints(transform)); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void endGroup() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { try { endTextObject(); } catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); } drawImageUsingURI(uri, rect); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { try { endTextObject(); } catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); } drawImageUsingDocument(doc, rect); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void clipRect(Rectangle rect) throws IFException { try { PSGenerator generator = getGenerator(); endTextObject(); generator.defineRect(rect.x / 1000.0, rect.y / 1000.0, rect.width / 1000.0, rect.height / 1000.0); generator.writeln(generator.mapCommand("clip") + " " + generator.mapCommand("newpath")); } catch (IOException ioe) { throw new IFException("I/O error in clipRect()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { try { endTextObject(); PSGenerator generator = getGenerator(); if (fill != null) { if (fill instanceof Color) { generator.useColor((Color)fill); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } } generator.defineRect(rect.x / 1000.0, rect.y / 1000.0, rect.width / 1000.0, rect.height / 1000.0); generator.writeln(generator.mapCommand("fill")); } catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); } } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { try { endTextObject(); if (getPSUtil().getRenderingMode() == PSRenderingMode.SIZE && hasOnlySolidBorders(top, bottom, left, right)) { super.drawBorderRect(rect, top, bottom, left, right); } else { this.borderPainter.drawBorders(rect, top, bottom, left, right); } } catch (IOException ioe) { throw new IFException("I/O error in drawBorderRect()", ioe); } } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { endTextObject(); this.borderPainter.drawLine(start, end, width, color, style); } catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { //Do not draw text if font-size is 0 as it creates an invalid PostScript file if (state.getFontSize() == 0) { return; } PSGenerator generator = getGenerator(); generator.useColor(state.getTextColor()); beginTextObject(); FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() //TODO Opportunity for font caching if font state is more heavily used String fontKey = getFontInfo().getInternalFontKey(triplet); if (fontKey == null) { throw new IFException("Font not available: " + triplet, null); } int sizeMillipoints = state.getFontSize(); // This assumes that *all* CIDFonts use a /ToUnicode mapping Typeface tf = getTypeface(fontKey); SingleByteFont singleByteFont = null; if (tf instanceof SingleByteFont) { singleByteFont = (SingleByteFont)tf; } Font font = getFontInfo().getFontInstance(triplet, sizeMillipoints); useFont(fontKey, sizeMillipoints); generator.writeln("1 0 0 -1 " + formatMptAsPt(generator, x) + " " + formatMptAsPt(generator, y) + " Tm"); int textLen = text.length(); int start = 0; if (singleByteFont != null) { //Analyze string and split up in order to paint in different sub-fonts/encodings int currentEncoding = -1; for (int i = 0; i < textLen; i++) { char c = text.charAt(i); char mapped = tf.mapChar(c); int encoding = mapped / 256; if (currentEncoding != encoding) { if (i > 0) { writeText(text, start, i - start, letterSpacing, wordSpacing, dp, font, tf); } if (encoding == 0) { useFont(fontKey, sizeMillipoints); } else { useFont(fontKey + "_" + Integer.toString(encoding), sizeMillipoints); } currentEncoding = encoding; start = i; } } } else { //Simple single-font painting useFont(fontKey, sizeMillipoints); } writeText(text, start, textLen - start, letterSpacing, wordSpacing, dp, font, tf); } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); clipRect(clipRect); } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void endViewport() throws IFException { restoreGraphicsState(); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void startGroup(AffineTransform transform) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void endGroup() throws IFException { restoreGraphicsState(); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { drawImageUsingURI(uri, rect); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { drawImageUsingDocument(doc, rect); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void clipRect(Rectangle rect) throws IFException { getState().updateClip(rect); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { g2dState.updatePaint(fill); g2dState.getGraph().fill(rect); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { try { this.borderPainter.drawBorders(rect, top, bottom, left, right); } catch (IOException e) { //Won't happen with Java2D throw new IllegalStateException("Unexpected I/O error"); } } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { this.borderPainter.drawLine(start, end, width, color, style); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { g2dState.updateColor(state.getTextColor()); FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() //TODO Opportunity for font caching if font state is more heavily used Font font = getFontInfo().getFontInstance(triplet, state.getFontSize()); //String fontName = font.getFontName(); //float fontSize = state.getFontSize() / 1000f; g2dState.updateFont(font.getFontName(), state.getFontSize() * 1000); Graphics2D g2d = this.g2dState.getGraph(); GlyphVector gv = g2d.getFont().createGlyphVector(g2d.getFontRenderContext(), text); Point2D cursor = new Point2D.Float(0, 0); int l = text.length(); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); if (dx != null && dxl > 0 && dx[0] != 0) { cursor.setLocation(cursor.getX() - (dx[0] / 10f), cursor.getY()); gv.setGlyphPosition(0, cursor); } for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; int cw = font.getCharWidth(orgChar); if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust += wordSpacing; } glyphAdjust += letterSpacing; if (dx != null && i < dxl - 1) { glyphAdjust += dx[i + 1]; } cursor.setLocation(cursor.getX() + cw + glyphAdjust, cursor.getY()); gv.setGlyphPosition(i + 1, cursor); } g2d.drawGlyphVector(gv, x, y); }
(Lib) IllegalStateException 118
              
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(FOUserAgent userAgent) throws FOPException { if (userAgent.getRendererOverride() == null && userAgent.getFOEventHandlerOverride() == null && userAgent.getDocumentHandlerOverride() == null) { throw new IllegalStateException("An overriding renderer," + " FOEventHandler or IFDocumentHandler must be set on the user agent" + " when this factory method is used!"); } return newFop(null, userAgent); }
// in src/java/org/apache/fop/apps/Fop.java
public FormattingResults getResults() { if (foTreeBuilder == null) { throw new IllegalStateException( "Results are only available after calling getDefaultHandler()."); } else { return foTreeBuilder.getResults(); } }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
public byte[] encrypt(byte[] data, PDFObject refObj) { PDFObject o = refObj; while (o != null && !o.hasObjectNumber()) { o = o.getParent(); } if (o == null) { throw new IllegalStateException("No object number could be obtained for a PDF object"); } byte[] key = createEncryptionKey(o.getObjectNumber(), o.getGeneration()); return encryptWithKey(key, data); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
private static byte[] encryptWithKey(byte[] key, byte[] data) { try { final Cipher c = initCipher(key); return c.doFinal(data); } catch (IllegalBlockSizeException e) { throw new IllegalStateException(e.getMessage()); } catch (BadPaddingException e) { throw new IllegalStateException(e.getMessage()); } }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
private static Cipher initCipher(byte[] key) { try { Cipher c = Cipher.getInstance("RC4"); SecretKeySpec keyspec = new SecretKeySpec(key, "RC4"); c.init(Cipher.ENCRYPT_MODE, keyspec); return c; } catch (InvalidKeyException e) { throw new IllegalStateException(e); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); } catch (NoSuchPaddingException e) { throw new UnsupportedOperationException(e); } }
// in src/java/org/apache/fop/pdf/PDFObject.java
public int getObjectNumber() { if (this.objnum == 0) { throw new IllegalStateException("Object has no number assigned: " + this.toString()); } return this.objnum; }
// in src/java/org/apache/fop/pdf/PDFObject.java
public final PDFDocument getDocumentSafely() { final PDFDocument doc = getDocument(); if (doc == null) { throw new IllegalStateException("Parent PDFDocument is unavailable on " + getClass().getName()); } return doc; }
// in src/java/org/apache/fop/pdf/PDFRoot.java
public int getPageMode() { PDFName mode = (PDFName)get("PageMode"); if (mode != null) { for (int i = 0; i < PAGEMODE_NAMES.length; i++) { if (PAGEMODE_NAMES[i].equals(mode)) { return i; } } throw new IllegalStateException("Unknown /PageMode encountered: " + mode); } else { return PAGEMODE_USENONE; } }
// in src/java/org/apache/fop/pdf/PDFFactory.java
private PDFAction getActionForEmbeddedFile(String filename, boolean newWindow) { PDFNames names = getDocument().getRoot().getNames(); if (names == null) { throw new IllegalStateException( "No Names dictionary present." + " Cannot create Launch Action for embedded file: " + filename); } PDFNameTreeNode embeddedFiles = names.getEmbeddedFiles(); if (embeddedFiles == null) { throw new IllegalStateException( "No /EmbeddedFiles name tree present." + " Cannot create Launch Action for embedded file: " + filename); } //Find filespec reference for the embedded file filename = PDFText.toPDFString(filename, '_'); PDFArray files = embeddedFiles.getNames(); PDFReference embeddedFileRef = null; int i = 0; while (i < files.length()) { String name = (String)files.get(i); i++; PDFReference ref = (PDFReference)files.get(i); if (name.equals(filename)) { embeddedFileRef = ref; break; } i++; } if (embeddedFileRef == null) { throw new IllegalStateException( "No embedded file with name " + filename + " present."); } //Finally create the action //PDFLaunch action = new PDFLaunch(embeddedFileRef); //This works with Acrobat 8 but not with Acrobat 9 //The following two options didn't seem to have any effect. //PDFGoToEmbedded action = new PDFGoToEmbedded(embeddedFileRef, 0, newWindow); //PDFGoToRemote action = new PDFGoToRemote(embeddedFileRef, 0, newWindow); //This finally seems to work: StringBuffer scriptBuffer = new StringBuffer(); scriptBuffer.append("this.exportDataObject({cName:\""); scriptBuffer.append(filename); scriptBuffer.append("\", nLaunch:2});"); PDFJavaScriptLaunchAction action = new PDFJavaScriptLaunchAction(scriptBuffer.toString()); return action; }
// in src/java/org/apache/fop/pdf/PDFDeviceColorSpace.java
public String getName() { switch (currentColorSpace) { case DEVICE_CMYK: return "DeviceCMYK"; case DEVICE_GRAY: return "DeviceGray"; case DEVICE_RGB: return "DeviceRGB"; default: throw new IllegalStateException("Unsupported color space in use."); } }
// in src/java/org/apache/fop/pdf/PDFNameTreeNode.java
private PDFArray prepareLimitsArray() { PDFArray limits = (PDFArray)get(LIMITS); if (limits == null) { limits = new PDFArray(this, new Object[2]); put(LIMITS, limits); } if (limits.length() != 2) { throw new IllegalStateException("Limits array must have 2 entries"); } return limits; }
// in src/java/org/apache/fop/pdf/PDFTextUtil.java
private void checkInTextObject() { if (!inTextObject) { throw new IllegalStateException("Not in text object"); } }
// in src/java/org/apache/fop/pdf/PDFTextUtil.java
public void beginTextObject() { if (inTextObject) { throw new IllegalStateException("Already in text object"); } write("BT\n"); this.inTextObject = true; }
// in src/java/org/apache/fop/pdf/PDFPages.java
public void notifyKidRegistered(PDFPage page) { int idx = page.getPageIndex(); if (idx >= 0) { while (idx > this.kids.size() - 1) { this.kids.add(null); } if (this.kids.get(idx) != null) { throw new IllegalStateException("A page already exists at index " + idx + " (zero-based)."); } this.kids.set(idx, page.referencePDF()); } else { this.kids.add(page.referencePDF()); } }
// in src/java/org/apache/fop/pdf/PDFPages.java
public String toPDFString() { StringBuffer sb = new StringBuffer(64); sb.append("<< /Type /Pages\n/Count ") .append(this.getCount()) .append("\n/Kids ["); for (int i = 0; i < kids.size(); i++) { Object kid = kids.get(i); if (kid == null) { throw new IllegalStateException("Gap in the kids list!"); } sb.append(kid).append(" "); } sb.append("] >>"); return sb.toString(); }
// in src/java/org/apache/fop/pdf/PDFText.java
public static final String escapeText(final String text, boolean forceHexMode) { if (text != null && text.length() > 0) { boolean unicode = false; boolean hexMode = false; if (forceHexMode) { hexMode = true; } else { for (int i = 0, c = text.length(); i < c; i++) { if (text.charAt(i) >= 128) { unicode = true; hexMode = true; break; } } } if (hexMode) { final byte[] uniBytes; try { uniBytes = text.getBytes("UTF-16"); } catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); } return toHex(uniBytes); } else { final StringBuffer result = new StringBuffer(text.length() * 2); result.append("("); final int l = text.length(); if (unicode) { // byte order marker (0xfeff) result.append("\\376\\377"); for (int i = 0; i < l; i++) { final char ch = text.charAt(i); final int high = (ch & 0xff00) >>> 8; final int low = ch & 0xff; result.append("\\"); result.append(Integer.toOctalString(high)); result.append("\\"); result.append(Integer.toOctalString(low)); } } else { for (int i = 0; i < l; i++) { final char ch = text.charAt(i); if (ch < 256) { escapeStringChar(ch, result); } else { throw new IllegalStateException( "Can only treat text in 8-bit ASCII/PDFEncoding"); } } } result.append(")"); return result.toString(); } } return "()"; }
// in src/java/org/apache/fop/pdf/PDFColorHandler.java
private void writeColor(StringBuffer codeBuffer, float[] comps, int componentCount, String command) { if (comps.length != componentCount) { throw new IllegalStateException("Color with unexpected component count encountered"); } for (int i = 0, c = comps.length; i < c; i++) { DoubleFormatUtil.formatDouble(comps[i], 4, 4, codeBuffer); codeBuffer.append(" "); } codeBuffer.append(command).append("\n"); }
// in src/java/org/apache/fop/pdf/PDFEncoding.java
public DifferencesBuilder addName(String name) { if (this.currentCode < 0) { throw new IllegalStateException("addDifference(int) must be called first"); } this.differences.add(new PDFName(name)); return this; }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void assignObjectNumber(PDFObject obj) { if (obj == null) { throw new NullPointerException("obj must not be null"); } if (obj.hasObjectNumber()) { throw new IllegalStateException( "Error registering a PDFObject: " + "PDFObject already has an object number"); } PDFDocument currentParent = obj.getDocument(); if (currentParent != null && currentParent != this) { throw new IllegalStateException( "Error registering a PDFObject: " + "PDFObject already has a parent PDFDocument"); } obj.setObjectNumber(++this.objectcount); if (currentParent == null) { obj.setDocument(this); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void addObject(PDFObject obj) { if (obj == null) { throw new NullPointerException("obj must not be null"); } if (!obj.hasObjectNumber()) { throw new IllegalStateException( "Error adding a PDFObject: " + "PDFObject doesn't have an object number"); } //Add object to list this.objects.add(obj); //Add object to special lists where necessary if (obj instanceof PDFFunction) { this.functions.add((PDFFunction) obj); } if (obj instanceof PDFShading) { final String shadingName = "Sh" + (++this.shadingCount); ((PDFShading)obj).setName(shadingName); this.shadings.add((PDFShading) obj); } if (obj instanceof PDFPattern) { final String patternName = "Pa" + (++this.patternCount); ((PDFPattern)obj).setName(patternName); this.patterns.add((PDFPattern) obj); } if (obj instanceof PDFFont) { final PDFFont font = (PDFFont)obj; this.fontMap.put(font.getName(), font); } if (obj instanceof PDFGState) { this.gstates.add((PDFGState) obj); } if (obj instanceof PDFPage) { this.pages.notifyKidRegistered((PDFPage)obj); } if (obj instanceof PDFLaunch) { this.launches.add((PDFLaunch) obj); } if (obj instanceof PDFLink) { this.links.add((PDFLink) obj); } if (obj instanceof PDFFileSpec) { this.filespecs.add((PDFFileSpec) obj); } if (obj instanceof PDFGoToRemote) { this.gotoremotes.add((PDFGoToRemote) obj); } }
// in src/java/org/apache/fop/pdf/PDFT1Stream.java
public int output(java.io.OutputStream stream) throws java.io.IOException { if (pfb == null) { throw new IllegalStateException("pfb must not be null at this point"); } if (log.isDebugEnabled()) { log.debug("Writing " + pfb.getLength() + " bytes of Type 1 font data"); } int length = super.output(stream); log.debug("Embedded Type1 font"); return length; }
// in src/java/org/apache/fop/pdf/VersionController.java
Override public void setPDFVersion(Version version) { throw new IllegalStateException("Cannot change the version of this PDF document."); }
// in src/java/org/apache/fop/pdf/PDFNumberTreeNode.java
private PDFArray prepareLimitsArray() { PDFArray limits = (PDFArray)get(LIMITS); if (limits == null) { limits = new PDFArray(this, new Object[2]); put(LIMITS, limits); } if (limits.length() != 2) { throw new IllegalStateException("Limits array must have 2 entries"); } return limits; }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void writeOutput(SortedMap fontFamilies) throws TransformerConfigurationException, SAXException, IOException { if (this.outputFile.isDirectory()) { System.out.println("Creating one file for each family..."); Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String familyName = (String)entry.getKey(); System.out.println("Creating output file for " + familyName + "..."); String filename; switch(this.mode) { case GENERATE_RENDERED: filename = familyName + ".pdf"; break; case GENERATE_FO: filename = familyName + ".fo"; break; case GENERATE_XML: filename = familyName + ".xml"; break; default: throw new IllegalStateException("Unsupported mode"); } File outFile = new File(this.outputFile, filename); generateXML(fontFamilies, outFile, familyName); } } else { System.out.println("Creating output file..."); generateXML(fontFamilies, this.outputFile, this.singleFamilyFilter); } System.out.println(this.outputFile + " written."); }
// in src/java/org/apache/fop/fo/properties/CondLengthProperty.java
public void setComponent(int cmpId, Property cmpnValue, boolean bIsDefault) { if (isCached) { throw new IllegalStateException( "CondLengthProperty.setComponent() called on a cached value!"); } if (cmpId == CP_LENGTH) { length = cmpnValue; } else if (cmpId == CP_CONDITIONALITY) { conditionality = (EnumProperty)cmpnValue; } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void startDocument() throws SAXException { if (used) { throw new IllegalStateException("FOTreeBuilder (and the Fop class) cannot be reused." + " Please instantiate a new instance."); } used = true; empty = true; rootFObj = null; // allows FOTreeBuilder to be reused if (LOG.isDebugEnabled()) { LOG.debug("Building formatting object tree"); } foEventHandler.startDocument(); this.mainFOHandler = new MainFOHandler(); this.mainFOHandler.startDocument(); this.delegate = this.mainFOHandler; }
// in src/java/org/apache/fop/fo/flow/table/CollapsingBorderResolver.java
void endTable() { throw new IllegalStateException(); }
// in src/java/org/apache/fop/fo/FOText.java
public void remove() { if (this.canRemove) { charBuffer.position(currentPosition); // Slice the buffer at the current position CharBuffer tmp = charBuffer.slice(); // Reset position to before current character charBuffer.position(--currentPosition); if (tmp.hasRemaining()) { // Transfer any remaining characters charBuffer.mark(); charBuffer.put(tmp); charBuffer.reset(); } // Decrease limit charBuffer.limit(charBuffer.limit() - 1); // Make sure following calls fail, unless nextChar() was called this.canRemove = false; } else { throw new IllegalStateException(); } }
// in src/java/org/apache/fop/fo/FOText.java
public void replaceChar(char c) { if (this.canReplace) { charBuffer.put(currentPosition - 1, c); } else { throw new IllegalStateException(); } }
// in src/java/org/apache/fop/fo/FObj.java
public void set(Object o) { if ((flags & F_SET_ALLOWED) == F_SET_ALLOWED) { FONode newNode = (FONode) o; if (currentNode == parentNode.firstChild) { parentNode.firstChild = newNode; } else { FONode.attachSiblings(currentNode.siblings[0], newNode); } if (currentNode.siblings != null && currentNode.siblings[1] != null) { FONode.attachSiblings(newNode, currentNode.siblings[1]); } if (currentNode == parentNode.lastChild) { parentNode.lastChild = newNode; } } else { throw new IllegalStateException(); } }
// in src/java/org/apache/fop/fo/FObj.java
public void remove() { if ((flags & F_REMOVE_ALLOWED) == F_REMOVE_ALLOWED) { parentNode.removeChild(currentNode); if (currentIndex == 0) { //first node removed currentNode = parentNode.firstChild; } else if (currentNode.siblings != null && currentNode.siblings[0] != null) { currentNode = currentNode.siblings[0]; currentIndex--; } else { currentNode = null; } flags &= F_NONE_ALLOWED; } else { throw new IllegalStateException(); } }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java
protected void startPage() throws IOException { if (pdfContext.isPagePending()) { throw new IllegalStateException("Close page first before starting another"); } //Start page paintingState = new PDFPaintingState(); if (this.initialTransform == null) { //Save initial transformation matrix this.initialTransform = getTransform(); this.initialClip = getClip(); } else { //Reset transformation matrix setTransform(this.initialTransform); setClip(this.initialClip); } currentFontName = ""; currentFontSize = 0; if (currentStream == null) { currentStream = new StringWriter(); } PDFResources pdfResources = this.pdfDoc.getResources(); PDFPage page = this.pdfDoc.getFactory().makePage(pdfResources, width, height); resourceContext = page; pdfContext.setCurrentPage(page); pageRef = page.referencePDF(); currentStream.write("q\n"); AffineTransform at = new AffineTransform(1.0, 0.0, 0.0, -1.0, 0.0, height); currentStream.write("1 0 0 -1 0 " + height + " cm\n"); if (svgWidth != 0) { double scaleX = width / svgWidth; double scaleY = height / svgHeight; at.scale(scaleX, scaleY); currentStream.write("" + PDFNumber.doubleOut(scaleX) + " 0 0 " + PDFNumber.doubleOut(scaleY) + " 0 0 cm\n"); } if (deviceDPI != NORMAL_PDF_RESOLUTION) { double s = NORMAL_PDF_RESOLUTION / deviceDPI; at.scale(s, s); currentStream.write("" + PDFNumber.doubleOut(s) + " 0 0 " + PDFNumber.doubleOut(s) + " 0 0 cm\n"); scale(1 / s, 1 / s); } // Remember the transform we installed. paintingState.concatenate(at); pdfContext.increasePageCount(); }
// in src/java/org/apache/fop/fonts/SimpleSingleByteEncoding.java
public char addCharacter(NamedCharacter ch) { if (!ch.hasSingleUnicodeValue()) { throw new IllegalArgumentException("Only NamedCharacters with a single Unicode value" + " are currently supported!"); } if (isFull()) { throw new IllegalStateException("Encoding is full!"); } char newSlot = (char)(getLastChar() + 1); this.mapping.add(ch); this.charMap.put(Character.valueOf(ch.getSingleUnicodeValue()), Character.valueOf(newSlot)); return newSlot; }
// in src/java/org/apache/fop/fonts/NamedCharacter.java
public char getSingleUnicodeValue() throws IllegalStateException { if (this.unicodeSequence == null) { return CharUtilities.NOT_A_CHARACTER; } if (this.unicodeSequence.length() > 1) { throw new IllegalStateException("getSingleUnicodeValue() may not be called for a" + " named character that has more than one Unicode value (a sequence)" + " associated with the named character!"); } return this.unicodeSequence.charAt(0); }
// in src/java/org/apache/fop/fonts/FontInfo.java
public FontTriplet[] fontLookup(String[] families, String style, int weight) { if (families.length == 0) { throw new IllegalArgumentException("Specify at least one font family"); } // try matching without substitutions List<FontTriplet> matchedTriplets = fontLookup(families, style, weight, false); // if there are no matching font triplets found try with substitutions if (matchedTriplets.size() == 0) { matchedTriplets = fontLookup(families, style, weight, true); } // no matching font triplets found! if (matchedTriplets.size() == 0) { StringBuffer sb = new StringBuffer(); for (int i = 0, c = families.length; i < c; i++) { if (i > 0) { sb.append(", "); } sb.append(families[i]); } throw new IllegalStateException( "fontLookup must return an array with at least one " + "FontTriplet on the last call. Lookup: " + sb.toString()); } FontTriplet[] fontTriplets = new FontTriplet[matchedTriplets.size()]; matchedTriplets.toArray(fontTriplets); // found some matching fonts so return them return fontTriplets; }
// in src/java/org/apache/fop/fonts/MultiByteFont.java
public void setGDEF ( GlyphDefinitionTable gdef ) { if ( ( this.gdef == null ) || ( gdef == null ) ) { this.gdef = gdef; } else { throw new IllegalStateException ( "font already associated with GDEF table" ); } }
// in src/java/org/apache/fop/fonts/MultiByteFont.java
public void setGSUB ( GlyphSubstitutionTable gsub ) { if ( ( this.gsub == null ) || ( gsub == null ) ) { this.gsub = gsub; } else { throw new IllegalStateException ( "font already associated with GSUB table" ); } }
// in src/java/org/apache/fop/fonts/MultiByteFont.java
public void setGPOS ( GlyphPositioningTable gpos ) { if ( ( this.gpos == null ) || ( gpos == null ) ) { this.gpos = gpos; } else { throw new IllegalStateException ( "font already associated with GPOS table" ); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public AFMFile parse(BufferedReader reader, String afmFileName) throws IOException { Stack<Object> stack = new Stack<Object>(); int parseMode = PARSE_NORMAL; while (true) { String line = reader.readLine(); if (line == null) { break; } String key = null; switch (parseMode) { case PARSE_NORMAL: key = parseLine(line, stack); break; case PARSE_CHAR_METRICS: key = parseCharMetrics(line, stack, afmFileName); break; default: throw new IllegalStateException("Invalid parse mode"); } Integer newParseMode = PARSE_MODE_CHANGES.get(key); if (newParseMode != null) { parseMode = newParseMode.intValue(); } } return (AFMFile)stack.pop(); }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addsRGBColorSpace() throws IOException { if (disableSRGBColorSpace) { if (this.pdfAMode != PDFAMode.DISABLED || this.pdfXMode != PDFXMode.DISABLED || this.outputProfileURI != null) { throw new IllegalStateException("It is not possible to disable the sRGB color" + " space if PDF/A or PDF/X functionality is enabled or an" + " output profile is set!"); } } else { if (this.sRGBColorSpace != null) { return; } //Map sRGB as default RGB profile for DeviceRGB this.sRGBColorSpace = PDFICCBasedColorSpace.setupsRGBAsDefaultRGBColorSpace(pdfDoc); } }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
public PDFDocument setupPDFDocument(OutputStream out) throws IOException { if (this.pdfDoc != null) { throw new IllegalStateException("PDFDocument already set up"); } String producer = userAgent.getProducer() != null ? userAgent.getProducer() : ""; if (maxPDFVersion == null) { this.pdfDoc = new PDFDocument(producer); } else { VersionController controller = VersionController.getFixedVersionController(maxPDFVersion); this.pdfDoc = new PDFDocument(producer, controller); } updateInfo(); updatePDFProfiles(); pdfDoc.setFilterMap(filterMap); pdfDoc.outputHeader(out); //Setup encryption if necessary PDFEncryptionManager.setupPDFEncryption(encryptionParams, pdfDoc); addsRGBColorSpace(); if (this.outputProfileURI != null) { addDefaultOutputProfile(); } if (pdfXMode != PDFXMode.DISABLED) { log.debug(pdfXMode + " is active."); log.warn("Note: " + pdfXMode + " support is work-in-progress and not fully implemented, yet!"); addPDFXOutputIntent(); } if (pdfAMode.isPDFA1LevelB()) { log.debug("PDF/A is active. Conformance Level: " + pdfAMode); addPDFA1OutputIntent(); } this.pdfDoc.enableAccessibility(userAgent.isAccessibilityEnabled()); return this.pdfDoc; }
// in src/java/org/apache/fop/render/pdf/ImageRawCCITTFaxAdapter.java
public void setup(PDFDocument doc) { pdfFilter = new CCFFilter(); pdfFilter.setApplied(true); PDFDictionary dict = new PDFDictionary(); dict.put("Columns", this.image.getSize().getWidthPx()); int compression = getImage().getCompression(); switch (compression) { case TIFFImage.COMP_FAX_G3_1D : dict.put("K", 0); break; case TIFFImage.COMP_FAX_G3_2D : dict.put("K", 1); break; case TIFFImage.COMP_FAX_G4_2D : dict.put("K", -1); break; default: throw new IllegalStateException("Invalid compression scheme: " + compression); } ((CCFFilter)pdfFilter).setDecodeParms(dict); super.setup(doc); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
protected void addTraitAttributes(Area area) { Map traitMap = area.getTraits(); if (traitMap != null) { Iterator iter = traitMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry traitEntry = (Map.Entry) iter.next(); Object key = traitEntry.getKey(); String name = Trait.getTraitName(key); Class clazz = Trait.getTraitClass(key); if ("break-before".equals(name) || "break-after".equals(name)) { continue; } Object value = traitEntry.getValue(); if (key == Trait.FONT) { FontTriplet triplet = (FontTriplet)value; addAttribute("font-name", triplet.getName()); addAttribute("font-style", triplet.getStyle()); addAttribute("font-weight", triplet.getWeight()); } else if (clazz.equals(InternalLink.class)) { InternalLink iLink = (InternalLink)value; addAttribute(name, iLink.xmlAttribute()); } else if (clazz.equals(Background.class)) { Background bkg = (Background)value; //TODO Remove the following line (makes changes in the test checks necessary) addAttribute(name, bkg.toString()); if (bkg.getColor() != null) { addAttribute("bkg-color", ColorUtil.colorToString(bkg.getColor())); } if (bkg.getURL() != null) { addAttribute("bkg-img", bkg.getURL()); String repString; int repeat = bkg.getRepeat(); switch (repeat) { case Constants.EN_REPEAT: repString = "repeat"; break; case Constants.EN_REPEATX: repString = "repeat-x"; break; case Constants.EN_REPEATY: repString = "repeat-y"; break; case Constants.EN_NOREPEAT: repString = "no-repeat"; break; default: throw new IllegalStateException( "Illegal value for repeat encountered: " + repeat); } addAttribute("bkg-repeat", repString); addAttribute("bkg-horz-offset", bkg.getHoriz()); addAttribute("bkg-vert-offset", bkg.getVertical()); } } else if (clazz.equals(Color.class)) { Color c = (Color)value; addAttribute(name, ColorUtil.colorToString(c)); } else if (key == Trait.START_INDENT || key == Trait.END_INDENT) { if (((Integer)value).intValue() != 0) { addAttribute(name, value.toString()); } } else { addAttribute(name, value.toString()); } } } transferForeignObjects(area); }
// in src/java/org/apache/fop/render/intermediate/IFContext.java
public void setUserAgent(FOUserAgent ua) { if (this.userAgent != null) { throw new IllegalStateException("The user agent was already set"); } this.userAgent = ua; }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
protected RenderingContext createRenderingContext() throws IllegalStateException { throw new IllegalStateException("Should never be called!"); }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); if (this.outputStream == null) { throw new IllegalStateException("OutputStream hasn't been set through setResult()"); } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void startDocument() throws IFException { if (getUserAgent() == null) { throw new IllegalStateException( "User agent must be set before starting document generation"); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
protected void clip() { throw new IllegalStateException("Not used"); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
protected void closePath() { throw new IllegalStateException("Not used"); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
protected void moveTo(float x, float y) { throw new IllegalStateException("Not used"); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
protected void lineTo(float x, float y) { throw new IllegalStateException("Not used"); }
// in src/java/org/apache/fop/render/AbstractRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { if (userAgent == null) { throw new IllegalStateException("FOUserAgent has not been set on Renderer"); } }
// in src/java/org/apache/fop/render/pcl/PCLRenderingUtil.java
public static Point2D transformedPoint(int x, int y, AffineTransform transform, PCLPageDefinition pageDefinition, int printDirection) { if (log.isTraceEnabled()) { log.trace("Current transform: " + transform); } Point2D.Float orgPoint = new Point2D.Float(x, y); Point2D.Float transPoint = new Point2D.Float(); transform.transform(orgPoint, transPoint); //At this point we have the absolute position in FOP's coordinate system //Now get PCL coordinates taking the current print direction and the logical page //into account. Dimension pageSize = pageDefinition.getPhysicalPageSize(); Rectangle logRect = pageDefinition.getLogicalPageRect(); switch (printDirection) { case 0: transPoint.x -= logRect.x; transPoint.y -= logRect.y; break; case 90: float ty = transPoint.x; transPoint.x = pageSize.height - transPoint.y; transPoint.y = ty; transPoint.x -= logRect.y; transPoint.y -= logRect.x; break; case 180: transPoint.x = pageSize.width - transPoint.x; transPoint.y = pageSize.height - transPoint.y; transPoint.x -= pageSize.width - logRect.x - logRect.width; transPoint.y -= pageSize.height - logRect.y - logRect.height; //The next line is odd and is probably necessary due to the default value of the //Text Length command: "1/2 inch less than maximum text length" //I wonder why this isn't necessary for the 90 degree rotation. *shrug* transPoint.y -= UnitConv.in2mpt(0.5); break; case 270: float tx = transPoint.y; transPoint.y = pageSize.width - transPoint.x; transPoint.x = tx; transPoint.x -= pageSize.height - logRect.y - logRect.height; transPoint.y -= pageSize.width - logRect.x - logRect.width; break; default: throw new IllegalStateException("Illegal print direction: " + printDirection); } return transPoint; }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
public void processPathIteratorFill(PathIterator iter) throws IOException { gen.writeText("\n"); double[] vals = new double[6]; boolean penDown = false; double x = 0; double y = 0; boolean pendingPM0 = true; StringBuffer sb = new StringBuffer(256); penUp(sb); while (!iter.isDone()) { int type = iter.currentSegment(vals); if (type == PathIterator.SEG_CLOSE) { sb.append("PM1;"); iter.next(); continue; } else if (type == PathIterator.SEG_MOVETO) { if (penDown) { penUp(sb); penDown = false; } } else { if (!penDown) { penDown(sb); penDown = true; } } switch (type) { case PathIterator.SEG_MOVETO: x = vals[0]; y = vals[1]; plotAbsolute(x, y, sb); break; case PathIterator.SEG_LINETO: x = vals[0]; y = vals[1]; plotAbsolute(x, y, sb); break; case PathIterator.SEG_CUBICTO: x = vals[4]; y = vals[5]; bezierAbsolute(vals[0], vals[1], vals[2], vals[3], x, y, sb); break; case PathIterator.SEG_QUADTO: double originX = x; double originY = y; x = vals[2]; y = vals[3]; quadraticBezierAbsolute(originX, originY, vals[0], vals[1], x, y, sb); break; default: throw new IllegalStateException("Must not get here"); } if (pendingPM0) { pendingPM0 = false; sb.append("PM;"); } iter.next(); } sb.append("PM2;"); fillPolygon(iter.getWindingRule(), sb); sb.append("\n"); gen.writeText(sb.toString()); }
// in src/java/org/apache/fop/render/rtf/rtflib/tools/TableContext.java
public float getColumnWidth() { if (colIndex < 0) { throw new IllegalStateException("colIndex must not be negative!"); } else if (colIndex >= getNumberOfColumns()) { log.warn("Column width for column " + (colIndex + 1) + " is not defined, using " + INVALID_COLUMN_WIDTH); while (colIndex >= getNumberOfColumns()) { setNextColumnWidth(new Float(INVALID_COLUMN_WIDTH)); } } return ((Float)colWidths.get(colIndex)).floatValue(); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
private boolean encodeInvertedBilevel(ImageEncodingHelper helper, AFPImageObjectInfo imageObjectInfo, OutputStream out) throws IOException { RenderedImage renderedImage = helper.getImage(); if (!BitmapImageUtil.isMonochromeImage(renderedImage)) { throw new IllegalStateException("This method only supports binary images!"); } int tiles = renderedImage.getNumXTiles() * renderedImage.getNumYTiles(); if (tiles > 1) { return false; } SampleModel sampleModel = renderedImage.getSampleModel(); SampleModel expectedSampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, renderedImage.getWidth(), renderedImage.getHeight(), 1); if (!expectedSampleModel.equals(sampleModel)) { return false; //Pixels are not packed } imageObjectInfo.setBitsPerPixel(1); Raster raster = renderedImage.getTile(0, 0); DataBuffer buffer = raster.getDataBuffer(); if (buffer instanceof DataBufferByte) { DataBufferByte byteBuffer = (DataBufferByte)buffer; log.debug("Encoding image as inverted bi-level..."); byte[] rawData = byteBuffer.getData(); int remaining = rawData.length; int pos = 0; byte[] data = new byte[4096]; while (remaining > 0) { int size = Math.min(remaining, data.length); for (int i = 0; i < size; i++) { data[i] = (byte)~rawData[pos]; //invert bits pos++; } out.write(data, 0, size); remaining -= size; } return true; } return false; }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRawJPEG.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { AFPRenderingContext afpContext = (AFPRenderingContext)context; AFPImageObjectInfo imageObjectInfo = (AFPImageObjectInfo)createDataObjectInfo(); AFPPaintingState paintingState = afpContext.getPaintingState(); // set resource information setResourceInformation(imageObjectInfo, image.getInfo().getOriginalURI(), afpContext.getForeignAttributes()); setDefaultResourceLevel(imageObjectInfo, afpContext.getResourceManager()); // Positioning imageObjectInfo.setObjectAreaInfo(createObjectAreaInfo(paintingState, pos)); updateIntrinsicSize(imageObjectInfo, paintingState, image.getSize()); // Image content ImageRawJPEG jpeg = (ImageRawJPEG)image; imageObjectInfo.setCompression(ImageContent.COMPID_JPEG); ColorSpace cs = jpeg.getColorSpace(); switch (cs.getType()) { case ColorSpace.TYPE_GRAY: imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS11); imageObjectInfo.setColor(false); imageObjectInfo.setBitsPerPixel(8); break; case ColorSpace.TYPE_RGB: imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS11); imageObjectInfo.setColor(true); imageObjectInfo.setBitsPerPixel(24); break; case ColorSpace.TYPE_CMYK: imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS45); imageObjectInfo.setColor(true); imageObjectInfo.setBitsPerPixel(32); break; default: throw new IllegalStateException( "Color space of JPEG image not supported: " + cs); } boolean included = afpContext.getResourceManager().tryIncludeObject(imageObjectInfo); if (!included) { log.debug("Embedding undecoded JPEG as IOCA image..."); InputStream inputStream = jpeg.createInputStream(); try { imageObjectInfo.setData(IOUtils.toByteArray(inputStream)); } finally { IOUtils.closeQuietly(inputStream); } // Create image afpContext.getResourceManager().createObject(imageObjectInfo); } }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private void generateFormForImage(PSGenerator gen, PSImageFormResource form) throws IOException { final String uri = form.getImageURI(); ImageManager manager = userAgent.getFactory().getImageManager(); ImageInfo info = null; try { ImageSessionContext sessionContext = userAgent.getImageSessionContext(); info = manager.getImageInfo(uri, sessionContext); //Create a rendering context for form creation PSRenderingContext formContext = new PSRenderingContext( userAgent, gen, fontInfo, true); ImageFlavor[] flavors; ImageHandlerRegistry imageHandlerRegistry = userAgent.getFactory().getImageHandlerRegistry(); flavors = imageHandlerRegistry.getSupportedFlavors(formContext); Map hints = ImageUtil.getDefaultHints(sessionContext); org.apache.xmlgraphics.image.loader.Image img = manager.getImage( info, flavors, hints, sessionContext); ImageHandler basicHandler = imageHandlerRegistry.getHandler(formContext, img); if (basicHandler == null) { throw new UnsupportedOperationException( "No ImageHandler available for image: " + img.getInfo() + " (" + img.getClass().getName() + ")"); } if (!(basicHandler instanceof PSImageHandler)) { throw new IllegalStateException( "ImageHandler implementation doesn't behave properly." + " It should have returned false in isCompatible(). Class: " + basicHandler.getClass().getName()); } PSImageHandler handler = (PSImageHandler)basicHandler; if (log.isTraceEnabled()) { log.trace("Using ImageHandler: " + handler.getClass().getName()); } handler.generateForm(formContext, img, form); } catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.imageError(resTracker, (info != null ? info.toString() : uri), ie, null); } }
// in src/java/org/apache/fop/render/ps/ImageEncoderCCITTFax.java
public String getImplicitFilter() { PSDictionary dict = new PSDictionary(); dict.put("/Columns", new Integer(ccitt.getSize().getWidthPx())); int compression = ccitt.getCompression(); switch (compression) { case TIFFImage.COMP_FAX_G3_1D : dict.put("/K", new Integer(0)); break; case TIFFImage.COMP_FAX_G3_2D : dict.put("/K", new Integer(1)); break; case TIFFImage.COMP_FAX_G4_2D : dict.put("/K", new Integer(-1)); break; default: throw new IllegalStateException( "Invalid compression scheme: " + compression); } return dict.toString() + " /CCITTFaxDecode"; }
// in src/java/org/apache/fop/render/ps/FontResourceCache.java
private String getPostScriptNameForFontKey(String key) { int pos = key.indexOf('_'); String postFix = null; if (pos > 0) { postFix = key.substring(pos); key = key.substring(0, pos); } Map<String, Typeface> fonts = fontInfo.getFonts(); Typeface tf = fonts.get(key); if (tf instanceof LazyFont) { tf = ((LazyFont)tf).getRealFont(); } if (tf == null) { throw new IllegalStateException("Font not available: " + key); } if (postFix == null) { return tf.getFontName(); } else { return tf.getFontName() + postFix; } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { try { this.borderPainter.drawBorders(rect, top, bottom, left, right); } catch (IOException e) { //Won't happen with Java2D throw new IllegalStateException("Unexpected I/O error"); } } }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
protected void clip() { if (currentPath == null) { throw new IllegalStateException("No current path available!"); } state.updateClip(currentPath); currentPath = null; }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public static void renderText(TextArea text, Graphics2D g2d, Font font) { Color col = (Color) text.getTrait(Trait.COLOR); g2d.setColor(col); float textCursor = 0; Iterator iter = text.getChildAreas().iterator(); while (iter.hasNext()) { InlineArea child = (InlineArea)iter.next(); if (child instanceof WordArea) { WordArea word = (WordArea)child; String s = word.getWord(); int[] letterAdjust = word.getLetterAdjustArray(); GlyphVector gv = g2d.getFont().createGlyphVector(g2d.getFontRenderContext(), s); double additionalWidth = 0.0; if (letterAdjust == null && text.getTextLetterSpaceAdjust() == 0 && text.getTextWordSpaceAdjust() == 0) { //nop } else { int[] offsets = getGlyphOffsets(s, font, text, letterAdjust); float cursor = 0.0f; for (int i = 0; i < offsets.length; i++) { Point2D pt = gv.getGlyphPosition(i); pt.setLocation(cursor, pt.getY()); gv.setGlyphPosition(i, pt); cursor += offsets[i] / 1000f; } additionalWidth = cursor - gv.getLogicalBounds().getWidth(); } g2d.drawGlyphVector(gv, textCursor, 0); textCursor += gv.getLogicalBounds().getWidth() + additionalWidth; } else if (child instanceof SpaceArea) { SpaceArea space = (SpaceArea)child; String s = space.getSpace(); char sp = s.charAt(0); int tws = (space.isAdjustable() ? text.getTextWordSpaceAdjust() + 2 * text.getTextLetterSpaceAdjust() : 0); textCursor += (font.getCharWidth(sp) + tws) / 1000f; } else { throw new IllegalStateException("Unsupported child element: " + child); } } }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException { if (pageIndex >= getNumberOfPages()) { return NO_SUCH_PAGE; } if (state != null) { throw new IllegalStateException("state must be null"); } Graphics2D graphics = (Graphics2D) g; try { PageViewport viewport = getPageViewport(pageIndex); AffineTransform at = graphics.getTransform(); state = new Java2DGraphicsState(graphics, this.fontInfo, at); // reset the current Positions currentBPPosition = 0; currentIPPosition = 0; renderPageAreas(viewport.getPage()); return PAGE_EXISTS; } catch (FOPException e) { log.error(e); return NO_SUCH_PAGE; } finally { state = null; } }
// in src/java/org/apache/fop/render/java2d/Java2DBorderPainter.java
protected void clip() { if (currentPath == null) { throw new IllegalStateException("No current path available!"); } getG2DState().updateClip(currentPath); currentPath = null; }
// in src/java/org/apache/fop/afp/DataStream.java
public void endDocument() throws IOException { if (complete) { String msg = "Invalid state - document already ended."; LOG.warn("endDocument():: " + msg); throw new IllegalStateException(msg); } if (currentPageObject != null) { // End the current page if necessary endPage(); } if (currentPageGroup != null) { // End the current page group if necessary endPageGroup(); } // Write out document if (document != null) { document.endDocument(); document.writeToStream(this.outputStream); } this.outputStream.flush(); this.complete = true; this.document = null; this.outputStream = null; }
// in src/java/org/apache/fop/afp/AFPDataObjectFactory.java
public ImageObject createImage(AFPImageObjectInfo imageObjectInfo) { // IOCA bitmap image ImageObject imageObj = factory.createImageObject(); // set data object viewport (i.e. position, rotation, dimension, resolution) imageObj.setViewport(imageObjectInfo); if (imageObjectInfo.hasCompression()) { int compression = imageObjectInfo.getCompression(); switch (compression) { case TIFFImage.COMP_FAX_G3_1D: imageObj.setEncoding(ImageContent.COMPID_G3_MH); break; case TIFFImage.COMP_FAX_G3_2D: imageObj.setEncoding(ImageContent.COMPID_G3_MR); break; case TIFFImage.COMP_FAX_G4_2D: imageObj.setEncoding(ImageContent.COMPID_G3_MMR); break; case ImageContent.COMPID_JPEG: imageObj.setEncoding((byte)compression); break; default: throw new IllegalStateException( "Invalid compression scheme: " + compression); } } ImageContent content = imageObj.getImageSegment().getImageContent(); int bitsPerPixel = imageObjectInfo.getBitsPerPixel(); imageObj.setIDESize((byte) bitsPerPixel); IDEStructureParameter ideStruct; switch (bitsPerPixel) { case 1: //Skip IDE Structure Parameter break; case 4: case 8: //A grayscale image ideStruct = content.needIDEStructureParameter(); ideStruct.setBitsPerComponent(new int[] {bitsPerPixel}); ideStruct.setColorModel(IDEStructureParameter.COLOR_MODEL_YCBCR); break; case 24: ideStruct = content.needIDEStructureParameter(); ideStruct.setDefaultRGBColorModel(); break; case 32: ideStruct = content.needIDEStructureParameter(); ideStruct.setDefaultCMYKColorModel(); break; default: throw new IllegalArgumentException("Unsupported number of bits per pixel: " + bitsPerPixel); } if (bitsPerPixel > 1 && imageObjectInfo.isSubtractive()) { ideStruct = content.needIDEStructureParameter(); ideStruct.setSubtractive(imageObjectInfo.isSubtractive()); } imageObj.setData(imageObjectInfo.getData()); return imageObj; }
// in src/java/org/apache/fop/afp/AFPDataObjectFactory.java
public IncludeObject createInclude(String includeName, AFPDataObjectInfo dataObjectInfo) { IncludeObject includeObj = factory.createInclude(includeName); if (dataObjectInfo instanceof AFPImageObjectInfo) { // IOCA image object includeObj.setObjectType(IncludeObject.TYPE_IMAGE); } else if (dataObjectInfo instanceof AFPGraphicsObjectInfo) { // graphics object includeObj.setObjectType(IncludeObject.TYPE_GRAPHIC); } else { // object container includeObj.setObjectType(IncludeObject.TYPE_OTHER); // set mandatory object classification (type other) Registry.ObjectType objectType = dataObjectInfo.getObjectType(); if (objectType != null) { // set object classification final boolean dataInContainer = true; final boolean containerHasOEG = false; // environment parameters set in include final boolean dataInOCD = true; includeObj.setObjectClassification( // object scope not defined ObjectClassificationTriplet.CLASS_TIME_VARIANT_PRESENTATION_OBJECT, objectType, dataInContainer, containerHasOEG, dataInOCD); } else { throw new IllegalStateException( "Failed to set Object Classification Triplet on Object Container."); } } AFPObjectAreaInfo objectAreaInfo = dataObjectInfo.getObjectAreaInfo(); int xOffset = objectAreaInfo.getX(); int yOffset = objectAreaInfo.getY(); includeObj.setObjectAreaOffset(xOffset, yOffset); int width = objectAreaInfo.getWidth(); int height = objectAreaInfo.getHeight(); includeObj.setObjectAreaSize(width, height); int rotation = objectAreaInfo.getRotation(); includeObj.setObjectAreaOrientation(rotation); int widthRes = objectAreaInfo.getWidthRes(); int heightRes = objectAreaInfo.getHeightRes(); includeObj.setMeasurementUnits(widthRes, heightRes); includeObj.setMappingOption(MappingOptionTriplet.SCALE_TO_FIT); return includeObj; }
// in src/java/org/apache/fop/afp/goca/GraphicsSetProcessColor.java
public void writeToStream(OutputStream os) throws IOException { float[] colorComponents = color.getColorComponents(null); // COLSPCE byte colspace; ColorSpace cs = color.getColorSpace(); int colSpaceType = cs.getType(); ByteArrayOutputStream baout = new ByteArrayOutputStream(); byte[] colsizes; if (colSpaceType == ColorSpace.TYPE_CMYK) { colspace = CMYK; colsizes = new byte[] {0x08, 0x08, 0x08, 0x08}; for (int i = 0; i < colorComponents.length; i++) { baout.write(Math.round(colorComponents[i] * 255)); } } else if (colSpaceType == ColorSpace.TYPE_RGB) { colspace = RGB; colsizes = new byte[] {0x08, 0x08, 0x08, 0x00}; for (int i = 0; i < colorComponents.length; i++) { baout.write(Math.round(colorComponents[i] * 255)); } } else if (cs instanceof CIELabColorSpace) { colspace = CIELAB; colsizes = new byte[] {0x08, 0x08, 0x08, 0x00}; DataOutput dout = new java.io.DataOutputStream(baout); //According to GOCA, I'd expect the multiplicator below to be 255f, not 100f //But only IBM AFP Workbench seems to support Lab colors and it requires "c * 100f" int l = Math.round(colorComponents[0] * 100f); int a = Math.round(colorComponents[1] * 255f) - 128; int b = Math.round(colorComponents[2] * 255f) - 128; dout.writeByte(l); dout.writeByte(a); dout.writeByte(b); } else { throw new IllegalStateException(); } int len = getDataLength(); byte[] data = new byte[12]; data[0] = getOrderCode(); // GSPCOL order code data[1] = (byte) (len - 2); // LEN data[2] = 0x00; // reserved; must be zero data[3] = colspace; // COLSPCE data[4] = 0x00; // reserved; must be zero data[5] = 0x00; // reserved; must be zero data[6] = 0x00; // reserved; must be zero data[7] = 0x00; // reserved; must be zero data[8] = colsizes[0]; // COLSIZE(S) data[9] = colsizes[1]; data[10] = colsizes[2]; data[11] = colsizes[3]; os.write(data); baout.writeTo(os); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
private static int determineOrientation(byte orientation) { int degrees = 0; switch (orientation) { case 0x00: degrees = 0; break; case 0x2D: degrees = 90; break; case 0x5A: degrees = 180; break; case (byte) 0x87: degrees = 270; break; default: throw new IllegalStateException("Invalid orientation: " + orientation); } return degrees; }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
public void addMapPageSegment(String name) { try { needMapPageSegment().addPageSegment(name); } catch (MaximumSizeExceededException e) { //Should not happen, handled internally throw new IllegalStateException("Internal error: " + e.getMessage()); } }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
protected EventProducer createProxyFor(Class clazz) { final EventProducerModel producerModel = getEventProducerModel(clazz); if (producerModel == null) { throw new IllegalStateException("Event model doesn't contain the definition for " + clazz.getName()); } return (EventProducer)Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] {clazz}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); EventMethodModel methodModel = producerModel.getMethod(methodName); String eventID = producerModel.getInterfaceName() + "." + methodName; if (methodModel == null) { throw new IllegalStateException( "Event model isn't consistent" + " with the EventProducer interface. Please rebuild FOP!" + " Affected method: " + eventID); } Map params = new java.util.HashMap(); int i = 1; Iterator iter = methodModel.getParameters().iterator(); while (iter.hasNext()) { EventMethodModel.Parameter param = (EventMethodModel.Parameter)iter.next(); params.put(param.getName(), args[i]); i++; } Event ev = new Event(args[0], eventID, methodModel.getSeverity(), params); broadcastEvent(ev); if (ev.getSeverity() == EventSeverity.FATAL) { EventExceptionManager.throwException(ev, methodModel.getExceptionClass()); } return null; } }); }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); EventMethodModel methodModel = producerModel.getMethod(methodName); String eventID = producerModel.getInterfaceName() + "." + methodName; if (methodModel == null) { throw new IllegalStateException( "Event model isn't consistent" + " with the EventProducer interface. Please rebuild FOP!" + " Affected method: " + eventID); } Map params = new java.util.HashMap(); int i = 1; Iterator iter = methodModel.getParameters().iterator(); while (iter.hasNext()) { EventMethodModel.Parameter param = (EventMethodModel.Parameter)iter.next(); params.put(param.getName(), args[i]); i++; } Event ev = new Event(args[0], eventID, methodModel.getSeverity(), params); broadcastEvent(ev); if (ev.getSeverity() == EventSeverity.FATAL) { EventExceptionManager.throwException(ev, methodModel.getExceptionClass()); } return null; }
// in src/java/org/apache/fop/area/PageViewport.java
public String getKey() { if (this.pageKey == null) { throw new IllegalStateException("No page key set on the PageViewport: " + toString()); } return this.pageKey; }
// in src/java/org/apache/fop/area/inline/InlineBlockParent.java
Override public void addChildArea(Area childArea) { if (child != null) { throw new IllegalStateException("InlineBlockParent may have only one child area."); } if (childArea instanceof Block) { child = (Block) childArea; //Update extents from the child setIPD(childArea.getAllocIPD()); setBPD(childArea.getAllocBPD()); } else { throw new IllegalArgumentException("The child of an InlineBlockParent must be a" + " Block area"); } }
// in src/java/org/apache/fop/area/inline/Leader.java
public String getRuleStyleAsString() { switch (getRuleStyle()) { case Constants.EN_DOTTED: return "dotted"; case Constants.EN_DASHED: return "dashed"; case Constants.EN_SOLID: return "solid"; case Constants.EN_DOUBLE: return "double"; case Constants.EN_GROOVE: return "groove"; case Constants.EN_RIDGE: return "ridge"; case Constants.EN_NONE: return "none"; default: throw new IllegalStateException("Unsupported rule style: " + getRuleStyle()); } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) { if (!areaStack.isEmpty()) { PageSequence pageSequence = (PageSequence)areaStack.peek(); treeModel.startPageSequence(pageSequence); areaStack.pop(); } if (currentPageViewport != null) { throw new IllegalStateException("currentPageViewport must be null"); } Rectangle viewArea = XMLUtil.getAttributeAsRectangle(attributes, "bounds"); int pageNumber = XMLUtil.getAttributeAsInt(attributes, "nr", -1); String key = attributes.getValue("key"); String pageNumberString = attributes.getValue("formatted-nr"); String pageMaster = attributes.getValue("simple-page-master-name"); boolean blank = XMLUtil.getAttributeAsBoolean(attributes, "blank", false); currentPageViewport = new PageViewport(viewArea, pageNumber, pageNumberString, pageMaster, blank); transferForeignObjects(attributes, currentPageViewport); currentPageViewport.setKey(key); pageViewportsByKey.put(key, currentPageViewport); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) { RegionViewport rv = getCurrentRegionViewport(); if (rv != null) { throw new IllegalStateException("Current RegionViewport must be null"); } Rectangle2D viewArea = XMLUtil.getAttributeAsRectangle2D(attributes, "rect"); rv = new RegionViewport(viewArea); transferForeignObjects(attributes, rv); rv.setClip(XMLUtil.getAttributeAsBoolean(attributes, "clipped", false)); setAreaAttributes(attributes, rv); setTraits(attributes, rv, SUBSET_COMMON); setTraits(attributes, rv, SUBSET_BOX); setTraits(attributes, rv, SUBSET_COLOR); areaStack.push(rv); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) { BodyRegion body = getCurrentBodyRegion(); if (body != null) { throw new IllegalStateException("Current BodyRegion must be null"); } String regionName = attributes.getValue("name"); int columnCount = XMLUtil.getAttributeAsInt(attributes, "columnCount", 1); int columnGap = XMLUtil.getAttributeAsInt(attributes, "columnGap", 0); RegionViewport rv = getCurrentRegionViewport(); body = new BodyRegion(FO_REGION_BODY, regionName, rv, columnCount, columnGap); transferForeignObjects(attributes, body); body.setCTM(getAttributeAsCTM(attributes, "ctm")); setAreaAttributes(attributes, body); setTraits(attributes, body, SUBSET_BORDER_PADDING); rv.setRegionReference(body); currentPageViewport.getPage().setRegionViewport(FO_REGION_BODY, rv); areaStack.push(body); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) { if (getCurrentText() != null) { throw new IllegalStateException("Current Text must be null"); } TextArea text = new TextArea(); setAreaAttributes(attributes, text); setTraits(attributes, text, SUBSET_COMMON); setTraits(attributes, text, SUBSET_BOX); setTraits(attributes, text, SUBSET_COLOR); setTraits(attributes, text, SUBSET_FONT); text.setBaselineOffset(XMLUtil.getAttributeAsInt(attributes, "baseline", 0)); text.setBlockProgressionOffset(XMLUtil.getAttributeAsInt(attributes, "offset", 0)); text.setTextLetterSpaceAdjust(XMLUtil.getAttributeAsInt(attributes, "tlsadjust", 0)); text.setTextWordSpaceAdjust(XMLUtil.getAttributeAsInt(attributes, "twsadjust", 0)); Area parent = (Area)areaStack.peek(); parent.addChildArea(text); areaStack.push(text); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
private void assertObjectOfClass(Object obj, Class clazz) { if (!clazz.isInstance(obj)) { throw new IllegalStateException("Object is not an instance of " + clazz.getName() + " but of " + obj.getClass().getName()); } }
// in src/java/org/apache/fop/area/Trait.java
private String getRepeatString() { switch (getRepeat()) { case EN_REPEAT: return "repeat"; case EN_REPEATX: return "repeat-x"; case EN_REPEATY: return "repeat-y"; case EN_NOREPEAT: return "no-repeat"; default: throw new IllegalStateException("Illegal repeat style: " + getRepeat()); } }
// in src/java/org/apache/fop/area/Trait.java
private static int getConstantForRepeat(String repeat) { if ("repeat".equalsIgnoreCase(repeat)) { return EN_REPEAT; } else if ("repeat-x".equalsIgnoreCase(repeat)) { return EN_REPEATX; } else if ("repeat-y".equalsIgnoreCase(repeat)) { return EN_REPEATY; } else if ("no-repeat".equalsIgnoreCase(repeat)) { return EN_NOREPEAT; } else { throw new IllegalStateException("Illegal repeat style: " + repeat); } }
// in src/java/org/apache/fop/area/RenderPagesModel.java
Override public void addPage(PageViewport page) { super.addPage(page); // for links the renderer needs to prepare the page // it is more appropriate to do this after queued pages but // it will mean that the renderer has not prepared a page that // could be referenced boolean ready = renderer.supportsOutOfOrder() && page.isResolved(); if (ready) { if (!renderer.supportsOutOfOrder() && page.getPageSequence().isFirstPage(page)) { renderer.startPageSequence(getCurrentPageSequence()); } try { renderer.renderPage(page); } catch (RuntimeException re) { String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, re); throw re; } catch (IOException ioe) { RendererEventProducer eventProducer = RendererEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.ioError(this, ioe); } catch (FOPException e) { //TODO use error handler to handle this FOPException or propagate exception String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, e); throw new IllegalStateException("Fatal error occurred. Cannot continue. " + e.getClass().getName() + ": " + err); } page.clear(); } else { preparePage(page); } // check prepared pages boolean cont = checkPreparedPages(page, false); if (cont) { processOffDocumentItems(pendingODI); pendingODI.clear(); } }
// in src/java/org/apache/fop/area/Span.java
public NormalFlow moveToNextFlow() { if (hasMoreFlows()) { curFlowIdx++; return getNormalFlow(curFlowIdx); } else { throw new IllegalStateException("(Internal error.) No more flows left in span."); } }
// in src/java/org/apache/fop/layoutmgr/PageBreaker.java
protected void startPart(BlockSequence list, int breakClass) { AbstractBreaker.log.debug("startPart() breakClass=" + getBreakClassName(breakClass)); if (pslm.getCurrentPage() == null) { throw new IllegalStateException("curPage must not be null"); } if (!pageBreakHandled) { //firstPart is necessary because we need the first page before we start the //algorithm so we have a BPD and IPD. This may subject to change later when we //start handling more complex cases. if (!firstPart) { // if this is the first page that will be created by // the current BlockSequence, it could have a break // condition that must be satisfied; // otherwise, we may simply need a new page handleBreakTrait(breakClass); } pageProvider.setStartOfNextElementList(pslm.getCurrentPageNum(), pslm.getCurrentPV().getCurrentSpan().getCurrentFlowIndex(), this.spanAllActive); } pageBreakHandled = false; // add static areas and resolve any new id areas // finish page and add to area tree firstPart = false; }
// in src/java/org/apache/fop/layoutmgr/SpaceResolver.java
private void resolve() { if (breakPoss != null) { if (hasFirstPart()) { removeConditionalBorderAndPadding(firstPart, firstPartLengths, true); performSpaceResolutionRule1(firstPart, firstPartLengths, true); performSpaceResolutionRules2to3(firstPart, firstPartLengths); } if (hasSecondPart()) { removeConditionalBorderAndPadding(secondPart, secondPartLengths, false); performSpaceResolutionRule1(secondPart, secondPartLengths, false); performSpaceResolutionRules2to3(secondPart, secondPartLengths); } if (noBreak != null) { performSpaceResolutionRules2to3(noBreak, noBreakLengths); } } else { if (isFirst) { removeConditionalBorderAndPadding(secondPart, secondPartLengths, false); performSpaceResolutionRule1(secondPart, secondPartLengths, false); } if (isLast) { removeConditionalBorderAndPadding(firstPart, firstPartLengths, true); performSpaceResolutionRule1(firstPart, firstPartLengths, true); } if (hasFirstPart()) { //Now that we've handled isFirst/isLast conditions, we need to look at the //active part in its normal order so swap it back. LOG.trace("Swapping first and second parts."); UnresolvedListElementWithLength[] tempList; MinOptMax[] tempLengths; tempList = secondPart; tempLengths = secondPartLengths; secondPart = firstPart; secondPartLengths = firstPartLengths; firstPart = tempList; firstPartLengths = tempLengths; if (hasFirstPart()) { throw new IllegalStateException("Didn't expect more than one parts in a" + "no-break condition."); } } performSpaceResolutionRules2to3(secondPart, secondPartLengths); } }
// in src/java/org/apache/fop/layoutmgr/SpaceResolver.java
private void generate(ListIterator iter) { MinOptMax spaceBeforeBreak = sum(firstPartLengths); MinOptMax spaceAfterBreak = sum(secondPartLengths); boolean hasPrecedingNonBlock = false; if (breakPoss != null) { if (spaceBeforeBreak.isNonZero()) { iter.add(new KnuthPenalty(0, KnuthPenalty.INFINITE, false, null, true)); iter.add(new KnuthGlue(spaceBeforeBreak, null, true)); if (breakPoss.isForcedBreak()) { //Otherwise, the preceding penalty and glue will be cut off iter.add(new KnuthBox(0, null, true)); } } iter.add(new KnuthPenalty(breakPoss.getPenaltyWidth(), breakPoss.getPenaltyValue(), false, breakPoss.getBreakClass(), new SpaceHandlingBreakPosition(this, breakPoss), false)); if (breakPoss.getPenaltyValue() <= -KnuthPenalty.INFINITE) { return; //return early. Not necessary (even wrong) to add additional elements } // No break // TODO: We can't use a MinOptMax for glue2, // because min <= opt <= max is not always true - why? MinOptMax noBreakLength = sum(noBreakLengths); MinOptMax spaceSum = spaceBeforeBreak.plus(spaceAfterBreak); int glue2width = noBreakLength.getOpt() - spaceSum.getOpt(); int glue2stretch = noBreakLength.getStretch() - spaceSum.getStretch(); int glue2shrink = noBreakLength.getShrink() - spaceSum.getShrink(); if (glue2width != 0 || glue2stretch != 0 || glue2shrink != 0) { iter.add(new KnuthGlue(glue2width, glue2stretch, glue2shrink, null, true)); } } else { if (spaceBeforeBreak.isNonZero()) { throw new IllegalStateException("spaceBeforeBreak should be 0 in this case"); } } Position pos = null; if (breakPoss == null) { pos = new SpaceHandlingPosition(this); } if (spaceAfterBreak.isNonZero() || pos != null) { iter.add(new KnuthBox(0, pos, true)); } if (spaceAfterBreak.isNonZero()) { iter.add(new KnuthPenalty(0, KnuthPenalty.INFINITE, false, null, true)); iter.add(new KnuthGlue(spaceAfterBreak, null, true)); hasPrecedingNonBlock = true; } if (isLast && hasPrecedingNonBlock) { //Otherwise, the preceding penalty and glue will be cut off iter.add(new KnuthBox(0, null, true)); } }
// in src/java/org/apache/fop/layoutmgr/SpaceResolver.java
public void notifySpaceSituation() { if (resolver.breakPoss != null) { throw new IllegalStateException("Only applicable to no-break situations"); } for (int i = 0; i < resolver.secondPart.length; i++) { resolver.secondPart[i].notifyLayoutManager(resolver.secondPartLengths[i]); } }
// in src/java/org/apache/fop/layoutmgr/BlockContainerLayoutManager.java
Override public void addAreas(PositionIterator parentIter, LayoutContext layoutContext) { getParentArea(null); // if this will create the first block area in a page // and display-align is bottom or center, add space before if (layoutContext.getSpaceBefore() > 0) { addBlockSpacing(0.0, MinOptMax.getInstance(layoutContext.getSpaceBefore())); } LayoutManager childLM; LayoutManager lastLM = null; LayoutContext lc = new LayoutContext(0); lc.setSpaceAdjust(layoutContext.getSpaceAdjust()); // set space after in the LayoutContext for children if (layoutContext.getSpaceAfter() > 0) { lc.setSpaceAfter(layoutContext.getSpaceAfter()); } BlockContainerPosition bcpos = null; PositionIterator childPosIter; // "unwrap" the NonLeafPositions stored in parentIter // and put them in a new list; List<Position> positionList = new LinkedList<Position>(); Position pos; Position firstPos = null; Position lastPos = null; while (parentIter.hasNext()) { pos = parentIter.next(); if (pos.getIndex() >= 0) { if (firstPos == null) { firstPos = pos; } lastPos = pos; } Position innerPosition = pos; if (pos instanceof NonLeafPosition) { innerPosition = pos.getPosition(); } if (pos instanceof BlockContainerPosition) { if (bcpos != null) { throw new IllegalStateException("Only one BlockContainerPosition allowed"); } bcpos = (BlockContainerPosition)pos; //Add child areas inside the reference area //bcpos.getBreaker().addContainedAreas(); } else if (innerPosition == null) { //ignore (probably a Position for a simple penalty between blocks) } else if (innerPosition.getLM() == this && !(innerPosition instanceof MappingPosition)) { // pos was created by this BlockLM and was inside a penalty // allowing or forbidding a page break // nothing to do } else { // innerPosition was created by another LM positionList.add(innerPosition); lastLM = innerPosition.getLM(); } } addId(); addMarkersToPage(true, isFirst(firstPos), isLast(lastPos)); if (bcpos == null) { // the Positions in positionList were inside the elements // created by the LineLM childPosIter = new PositionIterator(positionList.listIterator()); while ((childLM = childPosIter.getNextChildLM()) != null) { // set last area flag lc.setFlags(LayoutContext.LAST_AREA, (layoutContext.isLastArea() && childLM == lastLM)); lc.setStackLimitBP(layoutContext.getStackLimitBP()); // Add the line areas to Area childLM.addAreas(childPosIter, lc); } } else { //Add child areas inside the reference area bcpos.getBreaker().addContainedAreas(); } addMarkersToPage(false, isFirst(firstPos), isLast(lastPos)); TraitSetter.addSpaceBeforeAfter(viewportBlockArea, layoutContext.getSpaceAdjust(), effSpaceBefore, effSpaceAfter); flush(); viewportBlockArea = null; referenceArea = null; resetSpaces(); notifyEndOfLayout(); }
// in src/java/org/apache/fop/layoutmgr/BlockStackingLayoutManager.java
public KeepProperty getKeepTogetherProperty() { throw new IllegalStateException(); }
// in src/java/org/apache/fop/layoutmgr/BlockStackingLayoutManager.java
public KeepProperty getKeepWithPreviousProperty() { throw new IllegalStateException(); }
// in src/java/org/apache/fop/layoutmgr/BlockStackingLayoutManager.java
public KeepProperty getKeepWithNextProperty() { throw new IllegalStateException(); }
// in src/java/org/apache/fop/layoutmgr/FlowLayoutManager.java
List getNextKnuthElements(LayoutContext context, int alignment, Position restartPosition, LayoutManager restartLM) { List<ListElement> elements = new LinkedList<ListElement>(); boolean isRestart = (restartPosition != null); // always reset in case of restart (exception: see below) boolean doReset = isRestart; LayoutManager currentChildLM; Stack<LayoutManager> lmStack = new Stack<LayoutManager>(); if (isRestart) { currentChildLM = restartPosition.getLM(); if (currentChildLM == null) { throw new IllegalStateException("Cannot find layout manager to restart from"); } if (restartLM != null && restartLM.getParent() == this) { currentChildLM = restartLM; } else { while (currentChildLM.getParent() != this) { lmStack.push(currentChildLM); currentChildLM = currentChildLM.getParent(); } doReset = false; } setCurrentChildLM(currentChildLM); } else { currentChildLM = getChildLM(); } while (currentChildLM != null) { if (!isRestart || doReset) { if (doReset) { currentChildLM.reset(); // TODO won't work with forced breaks } if (addChildElements(elements, currentChildLM, context, alignment, null, null, null) != null) { return elements; } } else { if (addChildElements(elements, currentChildLM, context, alignment, lmStack, restartPosition, restartLM) != null) { return elements; } // restarted; force reset as of next child doReset = true; } currentChildLM = getChildLM(); } SpaceResolver.resolveElementList(elements); setFinished(true); assert !elements.isEmpty(); return elements; }
// in src/java/org/apache/fop/layoutmgr/FlowLayoutManager.java
Override public Area getParentArea(Area childArea) { BlockParent parentArea = null; int aclass = childArea.getAreaClass(); if (aclass == Area.CLASS_NORMAL) { parentArea = getCurrentPV().getCurrentFlow(); } else if (aclass == Area.CLASS_BEFORE_FLOAT) { parentArea = getCurrentPV().getBodyRegion().getBeforeFloat(); } else if (aclass == Area.CLASS_FOOTNOTE) { parentArea = getCurrentPV().getBodyRegion().getFootnote(); } else { throw new IllegalStateException("(internal error) Invalid " + "area class (" + aclass + ") requested."); } this.currentAreas[aclass] = parentArea; setCurrentArea(parentArea); return parentArea; }
// in src/java/org/apache/fop/layoutmgr/AbstractPageSequenceLayoutManager.java
public void reset() { throw new IllegalStateException(); }
// in src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java
private void addWordLevels ( int[] levels ) { int numLevels = ( levels != null ) ? levels.length : 0; if ( numLevels > 0 ) { int need = wordLevelsIndex + numLevels; if ( need <= wordLevels.length ) { System.arraycopy ( levels, 0, wordLevels, wordLevelsIndex, numLevels ); } else { throw new IllegalStateException ( "word levels array too short: expect at least " + need + " entries, but has only " + wordLevels.length + " entries" ); } } wordLevelsIndex += numLevels; }
// in src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java
private boolean addGlyphPositionAdjustments(AreaInfo wordAreaInfo) { boolean adjusted = false; int[][] gpa = wordAreaInfo.gposAdjustments; int numAdjusts = ( gpa != null ) ? gpa.length : 0; int wordLength = wordAreaInfo.getWordLength(); if ( numAdjusts > 0 ) { int need = gposAdjustmentsIndex + numAdjusts; if ( need <= gposAdjustments.length ) { for ( int i = 0, n = wordLength, j = 0; i < n; i++ ) { if ( i < numAdjusts ) { int[] wpa1 = gposAdjustments [ gposAdjustmentsIndex + i ]; int[] wpa2 = gpa [ j++ ]; for ( int k = 0; k < 4; k++ ) { int a = wpa2 [ k ]; if ( a != 0 ) { wpa1 [ k ] += a; adjusted = true; } } } } } else { throw new IllegalStateException ( "gpos adjustments array too short: expect at least " + need + " entries, but has only " + gposAdjustments.length + " entries" ); } } gposAdjustmentsIndex += wordLength; return adjusted; }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
public PageSequenceLayoutManager getPSLM() { throw new IllegalStateException("getPSLM() is illegal for " + getClass().getName()); }
// in src/java/org/apache/fop/layoutmgr/AbstractBreaker.java
protected int getNextBlockList(LayoutContext childLC, int nextSequenceStartsOn, Position positionAtIPDChange, LayoutManager restartAtLM, List<KnuthElement> firstElements) { updateLayoutContext(childLC); //Make sure the span change signal is reset childLC.signalSpanChange(Constants.NOT_SET); BlockSequence blockList; List<KnuthElement> returnedList; if (firstElements == null) { returnedList = getNextKnuthElements(childLC, alignment); } else if (positionAtIPDChange == null) { /* * No restartable element found after changing IPD break. Simply add the * non-restartable elements found after the break. */ returnedList = firstElements; /* * Remove the last 3 penalty-filler-forced break elements that were added by * the Knuth algorithm. They will be re-added later on. */ ListIterator iter = returnedList.listIterator(returnedList.size()); for (int i = 0; i < 3; i++) { iter.previous(); iter.remove(); } } else { returnedList = getNextKnuthElements(childLC, alignment, positionAtIPDChange, restartAtLM); returnedList.addAll(0, firstElements); } if (returnedList != null) { if (returnedList.isEmpty()) { nextSequenceStartsOn = handleSpanChange(childLC, nextSequenceStartsOn); return nextSequenceStartsOn; } blockList = new BlockSequence(nextSequenceStartsOn, getCurrentDisplayAlign()); //Only implemented by the PSLM nextSequenceStartsOn = handleSpanChange(childLC, nextSequenceStartsOn); Position breakPosition = null; if (ElementListUtils.endsWithForcedBreak(returnedList)) { KnuthPenalty breakPenalty = (KnuthPenalty) ListUtil .removeLast(returnedList); breakPosition = breakPenalty.getPosition(); log.debug("PLM> break - " + getBreakClassName(breakPenalty.getBreakClass())); switch (breakPenalty.getBreakClass()) { case Constants.EN_PAGE: nextSequenceStartsOn = Constants.EN_ANY; break; case Constants.EN_COLUMN: //TODO Fix this when implementing multi-column layout nextSequenceStartsOn = Constants.EN_COLUMN; break; case Constants.EN_ODD_PAGE: nextSequenceStartsOn = Constants.EN_ODD_PAGE; break; case Constants.EN_EVEN_PAGE: nextSequenceStartsOn = Constants.EN_EVEN_PAGE; break; default: throw new IllegalStateException("Invalid break class: " + breakPenalty.getBreakClass()); } } blockList.addAll(returnedList); BlockSequence seq; seq = blockList.endBlockSequence(breakPosition); if (seq != null) { blockLists.add(seq); } } return nextSequenceStartsOn; }
// in src/java/org/apache/fop/layoutmgr/AbstractLayoutManager.java
public Position notifyPos(Position pos) { if (pos.getIndex() >= 0) { throw new IllegalStateException("Position already got its index"); } pos.setIndex(++lastGeneratedPosition); return pos; }
// in src/java/org/apache/fop/layoutmgr/BreakingAlgorithm.java
protected int handleIpdChange() { throw new IllegalStateException(); }
// in src/java/org/apache/fop/layoutmgr/LayoutManagerMapping.java
public LayoutManager makeLayoutManager(FONode node) { List lms = new ArrayList(); makeLayoutManagers(node, lms); if (lms.size() == 0) { throw new IllegalStateException("LayoutManager for class " + node.getClass() + " is missing."); } else if (lms.size() > 1) { throw new IllegalStateException("Duplicate LayoutManagers for class " + node.getClass() + " found, only one may be declared."); } return (LayoutManager) lms.get(0); }
// in src/java/org/apache/fop/layoutmgr/table/CollapsingBorderModel.java
private static int getStylePreferenceValue(int style) { switch (style) { case Constants.EN_DOUBLE: return 0; case Constants.EN_SOLID: return -1; case Constants.EN_DASHED: return -2; case Constants.EN_DOTTED: return -3; case Constants.EN_RIDGE: return -4; case Constants.EN_OUTSET: return -5; case Constants.EN_GROOVE: return -6; case Constants.EN_INSET: return -7; default: throw new IllegalStateException("Illegal border style: " + style); } }
// in src/java/org/apache/fop/layoutmgr/table/CollapsingBorderModel.java
private static int getHolderPreferenceValue(int id) { switch (id) { case Constants.FO_TABLE_CELL: return 0; case Constants.FO_TABLE_ROW: return -1; case Constants.FO_TABLE_HEADER: case Constants.FO_TABLE_FOOTER: case Constants.FO_TABLE_BODY: return -2; case Constants.FO_TABLE_COLUMN: return -3; // TODO colgroup case Constants.FO_TABLE: return -4; default: throw new IllegalStateException(); } }
// in src/java/org/apache/fop/layoutmgr/StaticContentLayoutManager.java
public List getNextKnuthElements(LayoutContext context, int alignment) { throw new IllegalStateException(); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubtable.java
public synchronized void setTable ( GlyphTable table ) throws IllegalStateException { WeakReference r = this.table; if ( table == null ) { this.table = null; if ( r != null ) { r.clear(); } } else if ( r == null ) { this.table = new WeakReference ( table ); } else { throw new IllegalStateException ( "table already set" ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubtable.java
public static int getFlags ( GlyphSubtable[] subtables ) throws IllegalStateException { if ( ( subtables == null ) || ( subtables.length == 0 ) ) { return 0; } else { int flags = 0; // obtain first non-zero value of flags in array of subtables for ( int i = 0, n = subtables.length; i < n; i++ ) { int f = subtables[i].getFlags(); if ( flags == 0 ) { flags = f; break; } } // enforce flag consistency for ( int i = 0, n = subtables.length; i < n; i++ ) { int f = subtables[i].getFlags(); if ( f != flags ) { throw new IllegalStateException ( "inconsistent lookup flags " + f + ", expected " + flags ); } } return flags | ( usesReverseScan ( subtables ) ? LF_INTERNAL_USE_REVERSE_SCAN : 0 ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphTable.java
protected void addSubtable ( GlyphSubtable subtable ) { // ensure table is not frozen if ( frozen ) { throw new IllegalStateException ( "glyph table is frozen, subtable addition prohibited" ); } // set subtable's table reference to this table subtable.setTable ( this ); // add subtable to this table's subtable collection String lid = subtable.getLookupId(); if ( lookupTables.containsKey ( lid ) ) { LookupTable lt = (LookupTable) lookupTables.get ( lid ); lt.addSubtable ( subtable ); } else { LookupTable lt = new LookupTable ( lid, subtable ); lookupTables.put ( lid, lt ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphTable.java
public boolean addSubtable ( GlyphSubtable subtable ) { boolean added = false; // ensure table is not frozen if ( frozen ) { throw new IllegalStateException ( "glyph table is frozen, subtable addition prohibited" ); } // validate subtable to ensure consistency with current subtables validateSubtable ( subtable ); // insert subtable into ordered list for ( ListIterator/*<GlyphSubtable>*/ lit = subtables.listIterator(0); lit.hasNext(); ) { GlyphSubtable st = (GlyphSubtable) lit.next(); int d; if ( ( d = subtable.compareTo ( st ) ) < 0 ) { // insert within list lit.set ( subtable ); lit.add ( st ); added = true; } else if ( d == 0 ) { // duplicate entry is ignored added = false; subtable = null; } } // append at end of list if ( ! added && ( subtable != null ) ) { subtables.add ( subtable ); added = true; } return added; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int[] createLevelData ( int[] la, int[] ra, List tal ) { int nl = la.length; int[] data = new int [ 1 + nl * 2 + ( ( nl + 1 ) * tal.size() ) ]; int k = 0; data [ k++ ] = nl; for ( int i = 0, n = nl; i < n; i++ ) { data [ k++ ] = la [ i ]; } int nr = ra.length; for ( int i = 0, n = nr; i < n; i++ ) { data [ k++ ] = ra [ i ]; } for ( Iterator it = tal.iterator(); it.hasNext(); ) { int[] ta = (int[]) it.next(); if ( ta == null ) { throw new IllegalStateException ( "null test array" ); } else if ( ta.length == ( nl + 1 ) ) { for ( int i = 0, n = ta.length; i < n; i++ ) { data [ k++ ] = ta [ i ]; } } else { throw new IllegalStateException ( "test array length error, expected " + ( nl + 1 ) + " entries, got " + ta.length + " entries" ); } } assert k == data.length; return data; }
6
              
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (IllegalBlockSizeException e) { throw new IllegalStateException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (BadPaddingException e) { throw new IllegalStateException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (InvalidKeyException e) { throw new IllegalStateException(e); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException e) { //Won't happen with Java2D throw new IllegalStateException("Unexpected I/O error"); }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException e) { //Should not happen, handled internally throw new IllegalStateException("Internal error: " + e.getMessage()); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (FOPException e) { //TODO use error handler to handle this FOPException or propagate exception String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, e); throw new IllegalStateException("Fatal error occurred. Cannot continue. " + e.getClass().getName() + ": " + err); }
4
              
// in src/java/org/apache/fop/fonts/NamedCharacter.java
public char getSingleUnicodeValue() throws IllegalStateException { if (this.unicodeSequence == null) { return CharUtilities.NOT_A_CHARACTER; } if (this.unicodeSequence.length() > 1) { throw new IllegalStateException("getSingleUnicodeValue() may not be called for a" + " named character that has more than one Unicode value (a sequence)" + " associated with the named character!"); } return this.unicodeSequence.charAt(0); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
protected RenderingContext createRenderingContext() throws IllegalStateException { throw new IllegalStateException("Should never be called!"); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubtable.java
public synchronized void setTable ( GlyphTable table ) throws IllegalStateException { WeakReference r = this.table; if ( table == null ) { this.table = null; if ( r != null ) { r.clear(); } } else if ( r == null ) { this.table = new WeakReference ( table ); } else { throw new IllegalStateException ( "table already set" ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubtable.java
public static int getFlags ( GlyphSubtable[] subtables ) throws IllegalStateException { if ( ( subtables == null ) || ( subtables.length == 0 ) ) { return 0; } else { int flags = 0; // obtain first non-zero value of flags in array of subtables for ( int i = 0, n = subtables.length; i < n; i++ ) { int f = subtables[i].getFlags(); if ( flags == 0 ) { flags = f; break; } } // enforce flag consistency for ( int i = 0, n = subtables.length; i < n; i++ ) { int f = subtables[i].getFlags(); if ( f != flags ) { throw new IllegalStateException ( "inconsistent lookup flags " + f + ", expected " + flags ); } } return flags | ( usesReverseScan ( subtables ) ? LF_INTERNAL_USE_REVERSE_SCAN : 0 ); } }
(Lib) UnsupportedOperationException 98
              
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private static String toString(Paint paint) { //TODO Paint serialization: Fine-tune and extend! if (paint instanceof Color) { return ColorUtil.colorToString((Color)paint); } else { throw new UnsupportedOperationException("Paint not supported: " + paint); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof Metadata) { Metadata meta = (Metadata)extension; try { establish(MODE_NORMAL); handler.startElement("metadata"); meta.toSAX(this.handler); handler.endElement("metadata"); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { throw new UnsupportedOperationException( "Don't know how to handle extension object: " + extension); } }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
private static Cipher initCipher(byte[] key) { try { Cipher c = Cipher.getInstance("RC4"); SecretKeySpec keyspec = new SecretKeySpec(key, "RC4"); c.init(Cipher.ENCRYPT_MODE, keyspec); return c; } catch (InvalidKeyException e) { throw new IllegalStateException(e); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); } catch (NoSuchPaddingException e) { throw new UnsupportedOperationException(e); } }
// in src/java/org/apache/fop/pdf/PDFObject.java
public void outputInline(OutputStream out, Writer writer) throws IOException { throw new UnsupportedOperationException("Don't use anymore: " + getClass().getName()); }
// in src/java/org/apache/fop/pdf/PDFObject.java
protected String toPDFString() { throw new UnsupportedOperationException("Not implemented. " + "Use output(OutputStream) instead."); }
// in src/java/org/apache/fop/pdf/AlphaRasterImage.java
public void outputContents(OutputStream out) throws IOException { int w = getWidth(); int h = getHeight(); //Check Raster int nbands = alpha.getNumBands(); if (nbands != 1) { throw new UnsupportedOperationException( "Expected only one band/component for the alpha channel"); } //...and write the Raster line by line with a reusable buffer int dataType = alpha.getDataBuffer().getDataType(); if (dataType == DataBuffer.TYPE_BYTE) { byte[] line = new byte[nbands * w]; for (int y = 0; y < h; y++) { alpha.getDataElements(0, y, w, 1, line); out.write(line); } } else if (dataType == DataBuffer.TYPE_USHORT) { short[] sline = new short[nbands * w]; byte[] line = new byte[nbands * w]; for (int y = 0; y < h; y++) { alpha.getDataElements(0, y, w, 1, sline); for (int i = 0; i < w; i++) { //this compresses a 16-bit alpha channel to 8 bits! //we probably don't ever need a 16-bit channel line[i] = (byte)(sline[i] >> 8); } out.write(line); } } else if (dataType == DataBuffer.TYPE_INT) { //Is there an better way to get a 8bit raster from a TYPE_INT raster? int shift = 24; SampleModel sampleModel = alpha.getSampleModel(); if (sampleModel instanceof SinglePixelPackedSampleModel) { SinglePixelPackedSampleModel m = (SinglePixelPackedSampleModel)sampleModel; shift = m.getBitOffsets()[0]; } int[] iline = new int[nbands * w]; byte[] line = new byte[nbands * w]; for (int y = 0; y < h; y++) { alpha.getDataElements(0, y, w, 1, iline); for (int i = 0; i < w; i++) { line[i] = (byte)(iline[i] >> shift); } out.write(line); } } else { throw new UnsupportedOperationException("Unsupported DataBuffer type: " + alpha.getDataBuffer().getClass().getName()); } }
// in src/java/org/apache/fop/pdf/PDFInternalLink.java
protected String toPDFString() { throw new UnsupportedOperationException("This method should not be called"); }
// in src/java/org/apache/fop/fo/properties/TableColLength.java
public double getNumericValue() { throw new UnsupportedOperationException( "Must call getNumericValue with PercentBaseContext"); }
// in src/java/org/apache/fop/fo/properties/TableColLength.java
public int getValue() { throw new UnsupportedOperationException( "Must call getValue with PercentBaseContext"); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
Override public Property getComponent(int cmpId) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
Override public Property getConditionality() { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
Override public Length getLength() { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
Override public Property getLengthComponent() { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
Override public void setComponent(int cmpId, Property cmpnValue, boolean isDefault) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/flow/table/EmptyGridUnit.java
public PrimaryGridUnit getPrimary() { throw new UnsupportedOperationException(); // return this; TODO }
// in src/java/org/apache/fop/fo/FONode.java
public void setStructureTreeElement(StructureTreeElement structureTreeElement) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/CharIterator.java
public void remove() { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGElement.java
public AffineTransform getScreenTransform() { throw new UnsupportedOperationException("NYI"); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGElement.java
public void setScreenTransform(AffineTransform at) { throw new UnsupportedOperationException("NYI"); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
public static HyphenationTree getUserHyphenationTree(String key, HyphenationTreeResolver resolver) { HyphenationTree hTree = null; // I use here the following convention. The file name specified in // the configuration is taken as the base name. First we try // name + ".hyp" assuming a serialized HyphenationTree. If that fails // we try name + ".xml", assumming a raw hyphenation pattern file. // first try serialized object String name = key + ".hyp"; Source source = resolver.resolve(name); if (source != null) { try { InputStream in = null; if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null) { if (source.getSystemId() != null) { in = new java.net.URL(source.getSystemId()).openStream(); } else { throw new UnsupportedOperationException ("Cannot load hyphenation pattern file" + " with the supplied Source object: " + source); } } in = new BufferedInputStream(in); try { hTree = readHyphenationTree(in); } finally { IOUtils.closeQuietly(in); } return hTree; } catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("I/O problem while trying to load " + name, ioe); } } } // try the raw XML file name = key + ".xml"; source = resolver.resolve(name); if (source != null) { hTree = new HyphenationTree(); try { InputStream in = null; if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null) { if (source.getSystemId() != null) { in = new java.net.URL(source.getSystemId()).openStream(); } else { throw new UnsupportedOperationException( "Cannot load hyphenation pattern file" + " with the supplied Source object: " + source); } } if (!(in instanceof BufferedInputStream)) { in = new BufferedInputStream(in); } try { InputSource src = new InputSource(in); src.setSystemId(source.getSystemId()); hTree.loadPatterns(src); } finally { IOUtils.closeQuietly(in); } if (statisticsDump) { System.out.println("Stats: "); hTree.printStats(); } return hTree; } catch (HyphenationException ex) { log.error("Can't load user patterns from XML file " + source.getSystemId() + ": " + ex.getMessage()); return null; } catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("I/O problem while trying to load " + name, ioe); } return null; } } else { if (log.isDebugEnabled()) { log.debug("Could not load user hyphenation file for '" + key + "'."); } return null; } }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
public TTFFile loadTTF(String fileName, String fontName, boolean useKerning, boolean useAdvanced) throws IOException { TTFFile ttfFile = new TTFFile(useKerning, useAdvanced); log.info("Reading " + fileName + "..."); FontFileReader reader = new FontFileReader(fileName); boolean supported = ttfFile.readFont(reader, fontName); if (!supported) { return null; } log.info("Font Family: " + ttfFile.getFamilyNames()); if (ttfFile.isCFF()) { throw new UnsupportedOperationException( "OpenType fonts with CFF data are not supported, yet"); } return ttfFile; }
// in src/java/org/apache/fop/fonts/Font.java
public CharSequence performSubstitution ( CharSequence cs, String script, String language ) { if ( metric instanceof Substitutable ) { Substitutable s = (Substitutable) metric; return s.performSubstitution ( cs, script, language ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/fonts/Font.java
public CharSequence reorderCombiningMarks ( CharSequence cs, int[][] gpa, String script, String language ) { if ( metric instanceof Substitutable ) { Substitutable s = (Substitutable) metric; return s.reorderCombiningMarks ( cs, gpa, script, language ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/fonts/Font.java
public int[][] performPositioning ( CharSequence cs, String script, String language, int fontSize ) { if ( metric instanceof Positionable ) { Positionable p = (Positionable) metric; return p.performPositioning ( cs, script, language, fontSize ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/fonts/MultiByteFont.java
public int[][] performPositioning ( CharSequence cs, String script, String language ) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fonts/type1/PFBData.java
public void setPFBFormat(int format) { switch (format) { case PFB_RAW: case PFB_PC: this.pfbFormat = format; break; case PFB_MAC: throw new UnsupportedOperationException("Mac format is not yet implemented"); default: throw new IllegalArgumentException("Invalid value for PFB format: " + format); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private int determineTableCount() { int numTables = 4; //4 req'd tables: head,hhea,hmtx,maxp if (isCFF()) { throw new UnsupportedOperationException( "OpenType fonts with CFF glyphs are not supported"); } else { numTables += 2; //1 req'd table: glyf,loca if (hasCvt()) { numTables++; } if (hasFpgm()) { numTables++; } if (hasPrep()) { numTables++; } } return numTables; }
// in src/java/org/apache/fop/fonts/truetype/TTFFontLoader.java
private void buildFont(TTFFile ttf, String ttcFontName) { if (ttf.isCFF()) { throw new UnsupportedOperationException( "OpenType fonts with CFF data are not supported, yet"); } boolean isCid = this.embedded; if (this.encodingMode == EncodingMode.SINGLE_BYTE) { isCid = false; } if (isCid) { multiFont = new MultiByteFont(); returnFont = multiFont; multiFont.setTTCName(ttcFontName); } else { singleFont = new SingleByteFont(); returnFont = singleFont; } returnFont.setResolver(resolver); returnFont.setFontName(ttf.getPostScriptName()); returnFont.setFullName(ttf.getFullName()); returnFont.setFamilyNames(ttf.getFamilyNames()); returnFont.setFontSubFamilyName(ttf.getSubFamilyName()); returnFont.setCapHeight(ttf.getCapHeight()); returnFont.setXHeight(ttf.getXHeight()); returnFont.setAscender(ttf.getLowerCaseAscent()); returnFont.setDescender(ttf.getLowerCaseDescent()); returnFont.setFontBBox(ttf.getFontBBox()); returnFont.setFlags(ttf.getFlags()); returnFont.setStemV(Integer.parseInt(ttf.getStemV())); //not used for TTF returnFont.setItalicAngle(Integer.parseInt(ttf.getItalicAngle())); returnFont.setMissingWidth(0); returnFont.setWeight(ttf.getWeightClass()); if (isCid) { multiFont.setCIDType(CIDFontType.CIDTYPE2); int[] wx = ttf.getWidths(); multiFont.setWidthArray(wx); List entries = ttf.getCMaps(); BFEntry[] bfentries = new BFEntry[entries.size()]; int pos = 0; Iterator iter = ttf.getCMaps().listIterator(); while (iter.hasNext()) { TTFCmapEntry ce = (TTFCmapEntry)iter.next(); bfentries[pos] = new BFEntry(ce.getUnicodeStart(), ce.getUnicodeEnd(), ce.getGlyphStartIndex()); pos++; } multiFont.setBFEntries(bfentries); } else { singleFont.setFontType(FontType.TRUETYPE); singleFont.setEncoding(ttf.getCharSetName()); returnFont.setFirstChar(ttf.getFirstChar()); returnFont.setLastChar(ttf.getLastChar()); copyWidthsSingleByte(ttf); } if (useKerning) { copyKerning(ttf, isCid); } if (useAdvanced) { copyAdvanced(ttf); } if (this.embedded) { if (ttf.isEmbeddable()) { returnFont.setEmbedFileName(this.fontFileURI); } else { String msg = "The font " + this.fontFileURI + " is not embeddable due to a" + " licensing restriction."; throw new RuntimeException(msg); } } }
// in src/java/org/apache/fop/render/pdf/ImageRenderedAdapter.java
Override public void populateXObjectDictionary(PDFDictionary dict) { ColorModel cm = getEffectiveColorModel(); if (cm instanceof IndexColorModel) { IndexColorModel icm = (IndexColorModel)cm; PDFArray indexed = new PDFArray(dict); indexed.add(new PDFName("Indexed")); if (icm.getColorSpace().getType() != ColorSpace.TYPE_RGB) { log.warn("Indexed color space is not using RGB as base color space." + " The image may not be handled correctly." + " Base color space: " + icm.getColorSpace() + " Image: " + image.getInfo()); } indexed.add(new PDFName(toPDFColorSpace(icm.getColorSpace()).getName())); int c = icm.getMapSize(); int hival = c - 1; if (hival > MAX_HIVAL) { throw new UnsupportedOperationException("hival must not go beyond " + MAX_HIVAL); } indexed.add(Integer.valueOf(hival)); int[] palette = new int[c]; icm.getRGBs(palette); ByteArrayOutputStream baout = new ByteArrayOutputStream(); for (int i = 0; i < c; i++) { //TODO Probably doesn't work for non RGB based color spaces //See log warning above int entry = palette[i]; baout.write((entry & 0xFF0000) >> 16); baout.write((entry & 0xFF00) >> 8); baout.write(entry & 0xFF); } indexed.add(baout.toByteArray()); IOUtils.closeQuietly(baout); dict.put("ColorSpace", indexed); dict.put("BitsPerComponent", icm.getPixelSize()); Integer index = getIndexOfFirstTransparentColorInPalette(getImage().getRenderedImage()); if (index != null) { PDFArray mask = new PDFArray(dict); mask.add(index); mask.add(index); dict.put("Mask", mask); } } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
public void addResolvedAction(AbstractAction action) throws IFException { assert action.isComplete(); PDFAction pdfAction = (PDFAction)this.incompleteActions.remove(action.getID()); if (pdfAction == null) { getAction(action); } else if (pdfAction instanceof PDFGoTo) { PDFGoTo pdfGoTo = (PDFGoTo)pdfAction; updateTargetLocation(pdfGoTo, (GoToXYAction)action); } else { throw new UnsupportedOperationException( "Action type not supported: " + pdfAction.getClass().getName()); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
private PDFAction getAction(AbstractAction action) throws IFException { if (action == null) { return null; } PDFAction pdfAction = (PDFAction)this.completeActions.get(action.getID()); if (pdfAction != null) { return pdfAction; } else if (action instanceof GoToXYAction) { pdfAction = (PDFAction) incompleteActions.get(action.getID()); if (pdfAction != null) { return pdfAction; } else { GoToXYAction a = (GoToXYAction)action; PDFGoTo pdfGoTo = new PDFGoTo(null); getPDFDoc().assignObjectNumber(pdfGoTo); if (action.isComplete()) { updateTargetLocation(pdfGoTo, a); } else { this.incompleteActions.put(action.getID(), pdfGoTo); } return pdfGoTo; } } else if (action instanceof URIAction) { URIAction u = (URIAction)action; assert u.isComplete(); String uri = u.getURI(); PDFFactory factory = getPDFDoc().getFactory(); pdfAction = factory.getExternalAction(uri, u.isNewWindow()); if (!pdfAction.hasObjectNumber()) { //Some PDF actions are pooled getPDFDoc().registerObject(pdfAction); } this.completeActions.put(action.getID(), pdfAction); return pdfAction; } else { throw new UnsupportedOperationException("Unsupported action type: " + action + " (" + action.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
public void configure(Renderer renderer) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { generator.endTextObject(); if (fill != null) { if (fill instanceof Color) { generator.updateColor((Color)fill, true, null); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } } StringBuffer sb = new StringBuffer(); sb.append(format(rect.x)).append(' '); sb.append(format(rect.y)).append(' '); sb.append(format(rect.width)).append(' '); sb.append(format(rect.height)).append(" re"); if (fill != null) { sb.append(" f"); } /* Removed from method signature as it is currently not used if (stroke != null) { sb.append(" S"); }*/ sb.append('\n'); generator.add(sb.toString()); } }
// in src/java/org/apache/fop/render/pdf/PDFBorderPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) { if (start.y != end.y) { //TODO Support arbitrary lines if necessary throw new UnsupportedOperationException( "Can only deal with horizontal lines right now"); } saveGraphicsState(); int half = width / 2; int starty = start.y - half; Rectangle boundingRect = new Rectangle(start.x, start.y - half, end.x - start.x, width); switch (style.getEnumValue()) { case Constants.EN_SOLID: case Constants.EN_DASHED: case Constants.EN_DOUBLE: drawBorderLine(start.x, start.y - half, end.x, end.y + half, true, true, style.getEnumValue(), color); break; case Constants.EN_DOTTED: generator.clipRect(boundingRect); //This displaces the dots to the right by half a dot's width //TODO There's room for improvement here generator.add("1 0 0 1 " + format(half) + " 0 cm\n"); drawBorderLine(start.x, start.y - half, end.x, end.y + half, true, true, style.getEnumValue(), color); break; case Constants.EN_GROOVE: case Constants.EN_RIDGE: generator.setColor(ColorUtil.lightenColor(color, 0.6f), true); generator.add(format(start.x) + " " + format(starty) + " m\n"); generator.add(format(end.x) + " " + format(starty) + " l\n"); generator.add(format(end.x) + " " + format(starty + 2 * half) + " l\n"); generator.add(format(start.x) + " " + format(starty + 2 * half) + " l\n"); generator.add("h\n"); generator.add("f\n"); generator.setColor(color, true); if (style == RuleStyle.GROOVE) { generator.add(format(start.x) + " " + format(starty) + " m\n"); generator.add(format(end.x) + " " + format(starty) + " l\n"); generator.add(format(end.x) + " " + format(starty + half) + " l\n"); generator.add(format(start.x + half) + " " + format(starty + half) + " l\n"); generator.add(format(start.x) + " " + format(starty + 2 * half) + " l\n"); } else { generator.add(format(end.x) + " " + format(starty) + " m\n"); generator.add(format(end.x) + " " + format(starty + 2 * half) + " l\n"); generator.add(format(start.x) + " " + format(starty + 2 * half) + " l\n"); generator.add(format(start.x) + " " + format(starty + half) + " l\n"); generator.add(format(end.x - half) + " " + format(starty + half) + " l\n"); } generator.add("h\n"); generator.add("f\n"); break; default: throw new UnsupportedOperationException("rule style not supported"); } restoreGraphicsState(); }
// in src/java/org/apache/fop/render/RendererFactory.java
public Renderer createRenderer(FOUserAgent userAgent, String outputFormat) throws FOPException { if (userAgent.getDocumentHandlerOverride() != null) { return createRendererForDocumentHandler(userAgent.getDocumentHandlerOverride()); } else if (userAgent.getRendererOverride() != null) { return userAgent.getRendererOverride(); } else { Renderer renderer; if (isRendererPreferred()) { //Try renderer first renderer = tryRendererMaker(userAgent, outputFormat); if (renderer == null) { renderer = tryIFDocumentHandlerMaker(userAgent, outputFormat); } } else { //Try document handler first renderer = tryIFDocumentHandlerMaker(userAgent, outputFormat); if (renderer == null) { renderer = tryRendererMaker(userAgent, outputFormat); } } if (renderer == null) { throw new UnsupportedOperationException( "No renderer for the requested format available: " + outputFormat); } return renderer; } }
// in src/java/org/apache/fop/render/RendererFactory.java
public FOEventHandler createFOEventHandler(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { if (userAgent.getFOEventHandlerOverride() != null) { return userAgent.getFOEventHandlerOverride(); } else { AbstractFOEventHandlerMaker maker = getFOEventHandlerMaker(outputFormat); if (maker != null) { return maker.makeFOEventHandler(userAgent, out); } else { AbstractRendererMaker rendMaker = getRendererMaker(outputFormat); AbstractIFDocumentHandlerMaker documentHandlerMaker = null; boolean outputStreamMissing = (userAgent.getRendererOverride() == null) && (userAgent.getDocumentHandlerOverride() == null); if (rendMaker == null) { documentHandlerMaker = getDocumentHandlerMaker(outputFormat); if (documentHandlerMaker != null) { outputStreamMissing &= (out == null) && (documentHandlerMaker.needsOutputStream()); } } else { outputStreamMissing &= (out == null) && (rendMaker.needsOutputStream()); } if (userAgent.getRendererOverride() != null || rendMaker != null || userAgent.getDocumentHandlerOverride() != null || documentHandlerMaker != null) { if (outputStreamMissing) { throw new FOPException( "OutputStream has not been set"); } //Found a Renderer so we need to construct an AreaTreeHandler. return new AreaTreeHandler(userAgent, outputFormat, out); } else { throw new UnsupportedOperationException( "Don't know how to handle \"" + outputFormat + "\" as an output format." + " Neither an FOEventHandler, nor a Renderer could be found" + " for this output format."); } } } }
// in src/java/org/apache/fop/render/RendererFactory.java
public IFDocumentHandler createDocumentHandler(FOUserAgent userAgent, String outputFormat) throws FOPException { if (userAgent.getDocumentHandlerOverride() != null) { return userAgent.getDocumentHandlerOverride(); } AbstractIFDocumentHandlerMaker maker = getDocumentHandlerMaker(outputFormat); if (maker == null) { throw new UnsupportedOperationException( "No IF document handler for the requested format available: " + outputFormat); } IFDocumentHandler documentHandler = maker.makeIFDocumentHandler(userAgent); IFDocumentHandlerConfigurator configurator = documentHandler.getConfigurator(); if (configurator != null) { configurator.configure(documentHandler); } return new EventProducingFilter(documentHandler, userAgent); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImage(Image image, Rectangle rect, RenderingContext context, boolean convert, Map additionalHints) throws IOException, ImageException { ImageManager manager = getFopFactory().getImageManager(); ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry(); Image effImage; context.putHints(additionalHints); if (convert) { Map hints = createDefaultImageProcessingHints(getUserAgent().getImageSessionContext()); if (additionalHints != null) { hints.putAll(additionalHints); } effImage = manager.convertImage(image, imageHandlerRegistry.getSupportedFlavors(context), hints); } else { effImage = image; } //First check for a dynamically registered handler ImageHandler handler = imageHandlerRegistry.getHandler(context, effImage); if (handler == null) { throw new UnsupportedOperationException( "No ImageHandler available for image: " + effImage.getInfo() + " (" + effImage.getClass().getName() + ")"); } if (log.isTraceEnabled()) { log.trace("Using ImageHandler: " + handler.getClass().getName()); } handler.handleImage(context, effImage, rect); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private static String toString(Paint paint) { if (paint instanceof Color) { return ColorUtil.colorToString((Color)paint); } else { throw new UnsupportedOperationException("Paint not supported: " + paint); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof XMLizable) { try { ((XMLizable)extension).toSAX(this.handler); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { throw new UnsupportedOperationException( "Extension must implement XMLizable: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void setResult(Result result) throws IFException { if (result instanceof StreamResult) { StreamResult streamResult = (StreamResult)result; OutputStream out = streamResult.getOutputStream(); if (out == null) { if (streamResult.getWriter() != null) { throw new IllegalArgumentException( "FOP cannot use a Writer. Please supply an OutputStream!"); } try { URL url = new URL(streamResult.getSystemId()); File f = FileUtils.toFile(url); if (f != null) { out = new java.io.FileOutputStream(f); } else { out = url.openConnection().getOutputStream(); } } catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); } out = new java.io.BufferedOutputStream(out); this.ownOutputStream = true; } if (out == null) { throw new IllegalArgumentException("Need a StreamResult with an OutputStream"); } this.outputStream = out; } else { throw new UnsupportedOperationException( "Unsupported Result subclass: " + result.getClass().getName()); } }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
protected void handleUnsupportedFeature(String msg) { if (this.failOnUnsupportedFeature) { throw new UnsupportedOperationException(msg); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { Color fillColor = null; if (fill != null) { if (fill instanceof Color) { fillColor = (Color)fill; } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } try { setCursorPos(rect.x, rect.y); gen.fillRect(rect.width, rect.height, fillColor); } catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); } } } }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
public void configure(Renderer renderer) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
public void remove() { throw new UnsupportedOperationException( "Method 'remove' is not supported."); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
Override public void configure(Renderer renderer) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void endPageSequence() throws IFException { try { //Process deferred page-sequence-level extensions Iterator<AFPPageSetup> iter = this.deferredPageSequenceExtensions.iterator(); while (iter.hasNext()) { AFPPageSetup aps = iter.next(); iter.remove(); if (AFPElementMapping.NO_OPERATION.equals(aps.getElementName())) { handleNOP(aps); } else { throw new UnsupportedOperationException("Don't know how to handle " + aps); } } //End page sequence dataStream.endPageGroup(); } catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); } this.location = Location.ELSEWHERE; }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { if (fill instanceof Color) { getPaintingState().setColor((Color)fill); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } RectanglePaintingInfo rectanglePaintInfo = new RectanglePaintingInfo( toPoint(rect.x), toPoint(rect.y), toPoint(rect.width), toPoint(rect.height)); try { rectanglePainter.paint(rectanglePaintInfo); } catch (IOException ioe) { throw new IFException("IO error while painting rectangle", ioe); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IOException { if (start.y != end.y) { //TODO Support arbitrary lines if necessary throw new UnsupportedOperationException( "Can only deal with horizontal lines right now"); } //Simply delegates to drawBorderLine() as AFP line painting is not very sophisticated. int halfWidth = width / 2; drawBorderLine(start.x, start.y - halfWidth, end.x, start.y + halfWidth, true, true, style.getEnumValue(), color); }
// in src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java
public AFPResourceLevel getResourceLevel(Map/*<QName, String>*/ foreignAttributes) { AFPResourceLevel resourceLevel = null; if (foreignAttributes != null && !foreignAttributes.isEmpty()) { if (foreignAttributes.containsKey(RESOURCE_LEVEL)) { String levelString = (String)foreignAttributes.get(RESOURCE_LEVEL); resourceLevel = AFPResourceLevel.valueOf(levelString); // if external get resource group file attributes if (resourceLevel != null && resourceLevel.isExternal()) { String resourceGroupFile = (String)foreignAttributes.get(RESOURCE_GROUP_FILE); if (resourceGroupFile == null) { String msg = RESOURCE_GROUP_FILE + " not specified"; LOG.error(msg); throw new UnsupportedOperationException(msg); } File resourceExternalGroupFile = new File(resourceGroupFile); SecurityManager security = System.getSecurityManager(); try { if (security != null) { security.checkWrite(resourceExternalGroupFile.getPath()); } } catch (SecurityException ex) { String msg = "unable to gain write access to external resource file: " + resourceGroupFile; LOG.error(msg); } try { boolean exists = resourceExternalGroupFile.exists(); if (exists) { LOG.warn("overwriting external resource file: " + resourceGroupFile); } resourceLevel.setExternalFilePath(resourceGroupFile); } catch (SecurityException ex) { String msg = "unable to gain read access to external resource file: " + resourceGroupFile; LOG.error(msg); } } } } return resourceLevel; }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSetup.java
public void setPlacement(ExtensionPlacement placement) { if (!AFPElementMapping.NO_OPERATION.equals(getElementName())) { throw new UnsupportedOperationException( "The attribute 'placement' can currently only be set for NOPs!"); } this.placement = placement; }
// in src/java/org/apache/fop/render/ps/PSRendererConfigurator.java
public void configure(Renderer renderer) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private void generateFormForImage(PSGenerator gen, PSImageFormResource form) throws IOException { final String uri = form.getImageURI(); ImageManager manager = userAgent.getFactory().getImageManager(); ImageInfo info = null; try { ImageSessionContext sessionContext = userAgent.getImageSessionContext(); info = manager.getImageInfo(uri, sessionContext); //Create a rendering context for form creation PSRenderingContext formContext = new PSRenderingContext( userAgent, gen, fontInfo, true); ImageFlavor[] flavors; ImageHandlerRegistry imageHandlerRegistry = userAgent.getFactory().getImageHandlerRegistry(); flavors = imageHandlerRegistry.getSupportedFlavors(formContext); Map hints = ImageUtil.getDefaultHints(sessionContext); org.apache.xmlgraphics.image.loader.Image img = manager.getImage( info, flavors, hints, sessionContext); ImageHandler basicHandler = imageHandlerRegistry.getHandler(formContext, img); if (basicHandler == null) { throw new UnsupportedOperationException( "No ImageHandler available for image: " + img.getInfo() + " (" + img.getClass().getName() + ")"); } if (!(basicHandler instanceof PSImageHandler)) { throw new IllegalStateException( "ImageHandler implementation doesn't behave properly." + " It should have returned false in isCompatible(). Class: " + basicHandler.getClass().getName()); } PSImageHandler handler = (PSImageHandler)basicHandler; if (log.isTraceEnabled()) { log.trace("Using ImageHandler: " + handler.getClass().getName()); } handler.generateForm(formContext, img, form); } catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.imageError(resTracker, (info != null ? info.toString() : uri), ie, null); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { try { endTextObject(); PSGenerator generator = getGenerator(); if (fill != null) { if (fill instanceof Color) { generator.useColor((Color)fill); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } } generator.defineRect(rect.x / 1000.0, rect.y / 1000.0, rect.width / 1000.0, rect.height / 1000.0); generator.writeln(generator.mapCommand("fill")); } catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); } } }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IOException { if (start.y != end.y) { //TODO Support arbitrary lines if necessary throw new UnsupportedOperationException( "Can only deal with horizontal lines right now"); } saveGraphicsState(); int half = width / 2; int starty = start.y - half; //Rectangle boundingRect = new Rectangle(start.x, start.y - half, end.x - start.x, width); switch (style.getEnumValue()) { case Constants.EN_SOLID: case Constants.EN_DASHED: case Constants.EN_DOUBLE: drawBorderLine(start.x, starty, end.x, starty + width, true, true, style.getEnumValue(), color); break; case Constants.EN_DOTTED: clipRect(start.x, starty, end.x - start.x, width); //This displaces the dots to the right by half a dot's width //TODO There's room for improvement here generator.concatMatrix(1, 0, 0, 1, toPoints(half), 0); drawBorderLine(start.x, starty, end.x, starty + width, true, true, style.getEnumValue(), color); break; case Constants.EN_GROOVE: case Constants.EN_RIDGE: generator.useColor(ColorUtil.lightenColor(color, 0.6f)); moveTo(start.x, starty); lineTo(end.x, starty); lineTo(end.x, starty + 2 * half); lineTo(start.x, starty + 2 * half); closePath(); generator.write(" " + generator.mapCommand("fill")); generator.writeln(" " + generator.mapCommand("newpath")); generator.useColor(color); if (style == RuleStyle.GROOVE) { moveTo(start.x, starty); lineTo(end.x, starty); lineTo(end.x, starty + half); lineTo(start.x + half, starty + half); lineTo(start.x, starty + 2 * half); } else { moveTo(end.x, starty); lineTo(end.x, starty + 2 * half); lineTo(start.x, starty + 2 * half); lineTo(start.x, starty + half); lineTo(end.x - half, starty + half); } closePath(); generator.write(" " + generator.mapCommand("fill")); generator.writeln(" " + generator.mapCommand("newpath")); break; default: throw new UnsupportedOperationException("rule style not supported"); } restoreGraphicsState(); }
// in src/java/org/apache/fop/render/ps/NativeTextHandler.java
public void drawString(String text, float x, float y) throws IOException { // TODO Remove me after removing the deprecated method in TextHandler. throw new UnsupportedOperationException("Deprecated method!"); }
// in src/java/org/apache/fop/render/java2d/Java2DBorderPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) { if (start.y != end.y) { //TODO Support arbitrary lines if necessary throw new UnsupportedOperationException( "Can only deal with horizontal lines right now"); } saveGraphicsState(); int half = width / 2; int starty = start.y - half; Rectangle boundingRect = new Rectangle(start.x, start.y - half, end.x - start.x, width); getG2DState().updateClip(boundingRect); switch (style.getEnumValue()) { case Constants.EN_SOLID: case Constants.EN_DASHED: case Constants.EN_DOUBLE: drawBorderLine(start.x, start.y - half, end.x, end.y + half, true, true, style.getEnumValue(), color); break; case Constants.EN_DOTTED: int shift = half; //This shifts the dots to the right by half a dot's width drawBorderLine(start.x + shift, start.y - half, end.x + shift, end.y + half, true, true, style.getEnumValue(), color); break; case Constants.EN_GROOVE: case Constants.EN_RIDGE: getG2DState().updateColor(ColorUtil.lightenColor(color, 0.6f)); moveTo(start.x, starty); lineTo(end.x, starty); lineTo(end.x, starty + 2 * half); lineTo(start.x, starty + 2 * half); closePath(); getG2D().fill(currentPath); currentPath = null; getG2DState().updateColor(color); if (style.getEnumValue() == Constants.EN_GROOVE) { moveTo(start.x, starty); lineTo(end.x, starty); lineTo(end.x, starty + half); lineTo(start.x + half, starty + half); lineTo(start.x, starty + 2 * half); } else { moveTo(end.x, starty); lineTo(end.x, starty + 2 * half); lineTo(start.x, starty + 2 * half); lineTo(start.x, starty + half); lineTo(end.x - half, starty + half); } closePath(); getG2D().fill(currentPath); currentPath = null; case Constants.EN_NONE: // No rule is drawn break; default: } // end switch restoreGraphicsState(); }
// in src/java/org/apache/fop/afp/AFPDataObjectFactory.java
public ResourceObject createResource(AbstractNamedAFPObject namedObj, AFPResourceInfo resourceInfo, Registry.ObjectType objectType) { ResourceObject resourceObj = null; String resourceName = resourceInfo.getName(); if (resourceName != null) { resourceObj = factory.createResource(resourceName); } else { resourceObj = factory.createResource(); } if (namedObj instanceof Document) { resourceObj.setType(ResourceObject.TYPE_DOCUMENT); } else if (namedObj instanceof PageSegment) { resourceObj.setType(ResourceObject.TYPE_PAGE_SEGMENT); } else if (namedObj instanceof Overlay) { resourceObj.setType(ResourceObject.TYPE_OVERLAY_OBJECT); } else if (namedObj instanceof AbstractDataObject) { AbstractDataObject dataObj = (AbstractDataObject)namedObj; if (namedObj instanceof ObjectContainer) { resourceObj.setType(ResourceObject.TYPE_OBJECT_CONTAINER); // set object classification final boolean dataInContainer = true; final boolean containerHasOEG = false; // must be included final boolean dataInOCD = true; // mandatory triplet for object container resourceObj.setObjectClassification( ObjectClassificationTriplet.CLASS_TIME_INVARIANT_PAGINATED_PRESENTATION_OBJECT, objectType, dataInContainer, containerHasOEG, dataInOCD); } else if (namedObj instanceof ImageObject) { // ioca image type resourceObj.setType(ResourceObject.TYPE_IMAGE); } else if (namedObj instanceof GraphicsObject) { resourceObj.setType(ResourceObject.TYPE_GRAPHIC); } else { throw new UnsupportedOperationException( "Unsupported resource object for data object type " + dataObj); } } else { throw new UnsupportedOperationException( "Unsupported resource object type " + namedObj); } // set the resource information/classification on the data object resourceObj.setDataObject(namedObj); return resourceObj; }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public void add(LayoutManager lm) throws UnsupportedOperationException { throw new UnsupportedOperationException("LMiter doesn't support add"); }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public void set(LayoutManager lm) throws UnsupportedOperationException { throw new UnsupportedOperationException("LMiter doesn't support set"); }
// in src/java/org/apache/fop/layoutmgr/AbstractBaseLayoutManager.java
public int getContentAreaIPD() { throw new UnsupportedOperationException( "getContentAreaIPD() called when it should have been overridden"); }
// in src/java/org/apache/fop/layoutmgr/AbstractBaseLayoutManager.java
public int getContentAreaBPD() { throw new UnsupportedOperationException( "getContentAreaBPD() called when it should have been overridden"); }
// in src/java/org/apache/fop/layoutmgr/AbstractBaseLayoutManager.java
public void reset() { throw new UnsupportedOperationException("Not implemented"); }
// in src/java/org/apache/fop/layoutmgr/AbstractBaseLayoutManager.java
public List getNextKnuthElements(LayoutContext context, int alignment, Stack lmStack, Position positionAtIPDChange, LayoutManager restartAtLM) { throw new UnsupportedOperationException("Not implemented"); }
// in src/java/org/apache/fop/layoutmgr/AbstractBreaker.java
protected List<KnuthElement> getNextKnuthElements(LayoutContext context, int alignment, Position positionAtIPDChange, LayoutManager restartAtLM) { throw new UnsupportedOperationException("TODO: implement acceptable fallback"); }
// in src/java/org/apache/fop/layoutmgr/AbstractBreaker.java
private int getNextBlockListChangedIPD(LayoutContext childLC, PageBreakingAlgorithm alg, BlockSequence effectiveList) { int nextSequenceStartsOn; KnuthNode optimalBreak = alg.getBestNodeBeforeIPDChange(); int positionIndex = optimalBreak.position; log.trace("IPD changes at index " + positionIndex); KnuthElement elementAtBreak = alg.getElement(positionIndex); Position positionAtBreak = elementAtBreak.getPosition(); if (!(positionAtBreak instanceof SpaceResolver.SpaceHandlingBreakPosition)) { throw new UnsupportedOperationException( "Don't know how to restart at position " + positionAtBreak); } /* Retrieve the original position wrapped into this space position */ positionAtBreak = positionAtBreak.getPosition(); LayoutManager restartAtLM = null; List<KnuthElement> firstElements = Collections.emptyList(); if (containsNonRestartableLM(positionAtBreak)) { if (alg.getIPDdifference() > 0) { EventBroadcaster eventBroadcaster = getCurrentChildLM().getFObj() .getUserAgent().getEventBroadcaster(); BlockLevelEventProducer eventProducer = BlockLevelEventProducer.Provider.get(eventBroadcaster); eventProducer.nonRestartableContentFlowingToNarrowerPage(this); } firstElements = new LinkedList<KnuthElement>(); boolean boxFound = false; Iterator<KnuthElement> iter = effectiveList.listIterator(positionIndex + 1); Position position = null; while (iter.hasNext() && (position == null || containsNonRestartableLM(position))) { positionIndex++; KnuthElement element = iter.next(); position = element.getPosition(); if (element.isBox()) { boxFound = true; firstElements.add(element); } else if (boxFound) { firstElements.add(element); } } if (position instanceof SpaceResolver.SpaceHandlingBreakPosition) { /* Retrieve the original position wrapped into this space position */ positionAtBreak = position.getPosition(); } else { positionAtBreak = null; } } if (positionAtBreak != null && positionAtBreak.getIndex() == -1) { /* * This is an indication that we are between two blocks * (possibly surrounded by another block), not inside a * paragraph. */ Position position; Iterator<KnuthElement> iter = effectiveList.listIterator(positionIndex + 1); do { KnuthElement nextElement = iter.next(); position = nextElement.getPosition(); } while (position == null || position instanceof SpaceResolver.SpaceHandlingPosition || position instanceof SpaceResolver.SpaceHandlingBreakPosition && position.getPosition().getIndex() == -1); LayoutManager surroundingLM = positionAtBreak.getLM(); while (position.getLM() != surroundingLM) { position = position.getPosition(); } restartAtLM = position.getPosition().getLM(); } nextSequenceStartsOn = getNextBlockList(childLC, Constants.EN_COLUMN, positionAtBreak, restartAtLM, firstElements); return nextSequenceStartsOn; }
// in src/java/org/apache/fop/layoutmgr/PositionIterator.java
public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException("PositionIterator doesn't support remove"); }
// in src/java/org/apache/fop/layoutmgr/table/CollapsingBorderModel.java
public static CollapsingBorderModel getBorderModelFor(int borderCollapse) { switch (borderCollapse) { case Constants.EN_COLLAPSE: if (collapse == null) { collapse = new CollapsingBorderModelEyeCatching(); } return collapse; case Constants.EN_COLLAPSE_WITH_PRECEDENCE: throw new UnsupportedOperationException ( "collapse-with-precedence not yet supported" ); default: throw new IllegalArgumentException("Illegal border-collapse mode."); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new SingleSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new SingleSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new PairSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new PairSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new CursiveSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new MarkToBaseSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new MarkToLigatureSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new MarkToMarkSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new ContextualSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new ContextualSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 3 ) { return new ContextualSubtableFormat3 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new ChainedContextualSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new ChainedContextualSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 3 ) { return new ChainedContextualSubtableFormat3 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new SingleSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new SingleSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new MultipleSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new AlternateSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new LigatureSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new ContextualSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new ContextualSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 3 ) { return new ContextualSubtableFormat3 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new ChainedContextualSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new ChainedContextualSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 3 ) { return new ChainedContextualSubtableFormat3 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new ReverseChainedSingleSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java
protected void addSubtable ( GlyphSubtable subtable ) { if ( subtable instanceof GlyphClassSubtable ) { this.gct = (GlyphClassSubtable) subtable; } else if ( subtable instanceof AttachmentPointSubtable ) { // TODO - not yet used // this.apt = (AttachmentPointSubtable) subtable; } else if ( subtable instanceof LigatureCaretSubtable ) { // TODO - not yet used // this.lct = (LigatureCaretSubtable) subtable; } else if ( subtable instanceof MarkAttachmentSubtable ) { this.mat = (MarkAttachmentSubtable) subtable; } else { throw new UnsupportedOperationException ( "unsupported glyph definition subtable type: " + subtable ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java
static GlyphDefinitionSubtable create ( String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries ) { if ( format == 1 ) { return new GlyphClassSubtableFormat1 ( id, sequence, flags, format, mapping, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java
static GlyphDefinitionSubtable create ( String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries ) { if ( format == 1 ) { return new AttachmentPointSubtableFormat1 ( id, sequence, flags, format, mapping, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java
static GlyphDefinitionSubtable create ( String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries ) { if ( format == 1 ) { return new LigatureCaretSubtableFormat1 ( id, sequence, flags, format, mapping, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java
static GlyphDefinitionSubtable create ( String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries ) { if ( format == 1 ) { return new MarkAttachmentSubtableFormat1 ( id, sequence, flags, format, mapping, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
private EventMethodModel createMethodModel(JavaMethod method) throws EventConventionException, ClassNotFoundException { JavaClass clazz = method.getParentClass(); //Check EventProducer conventions if (!method.getReturnType().isVoid()) { throw new EventConventionException("All methods of interface " + clazz.getFullyQualifiedName() + " must have return type 'void'!"); } String methodSig = clazz.getFullyQualifiedName() + "." + method.getCallSignature(); JavaParameter[] params = method.getParameters(); if (params.length < 1) { throw new EventConventionException("The method " + methodSig + " must have at least one parameter: 'Object source'!"); } Type firstType = params[0].getType(); if (firstType.isPrimitive() || !"source".equals(params[0].getName())) { throw new EventConventionException("The first parameter of the method " + methodSig + " must be: 'Object source'!"); } //build method model DocletTag tag = method.getTagByName("event.severity"); EventSeverity severity; if (tag != null) { severity = EventSeverity.valueOf(tag.getValue()); } else { severity = EventSeverity.INFO; } EventMethodModel methodMeta = new EventMethodModel( method.getName(), severity); if (params.length > 1) { for (int j = 1, cj = params.length; j < cj; j++) { JavaParameter p = params[j]; Class<?> type; JavaClass pClass = p.getType().getJavaClass(); if (p.getType().isPrimitive()) { type = PRIMITIVE_MAP.get(pClass.getName()); if (type == null) { throw new UnsupportedOperationException( "Primitive datatype not supported: " + pClass.getName()); } } else { String className = pClass.getFullyQualifiedName(); type = Class.forName(className); } methodMeta.addParameter(type, p.getName()); } } Type[] exceptions = method.getExceptions(); if (exceptions != null && exceptions.length > 0) { //We only use the first declared exception because that is always thrown JavaClass cl = exceptions[0].getJavaClass(); methodMeta.setExceptionClass(cl.getFullyQualifiedName()); methodMeta.setSeverity(EventSeverity.FATAL); //In case it's not set in the comments } return methodMeta; }
3
              
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchPaddingException e) { throw new UnsupportedOperationException(e); }
3
              
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public void add(LayoutManager lm) throws UnsupportedOperationException { throw new UnsupportedOperationException("LMiter doesn't support add"); }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public void set(LayoutManager lm) throws UnsupportedOperationException { throw new UnsupportedOperationException("LMiter doesn't support set"); }
// in src/java/org/apache/fop/layoutmgr/PositionIterator.java
public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException("PositionIterator doesn't support remove"); }
(Domain) FOPException 87
              
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(File userConfigFile) throws SAXException, IOException { try { DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); setUserConfig(cfgBuilder.buildFromFile(userConfigFile)); } catch (ConfigurationException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(String uri) throws SAXException, IOException { try { DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); setUserConfig(cfgBuilder.build(uri)); } catch (ConfigurationException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
private void setBaseURI() throws FOPException { String loc = cfg.getLocation(); try { if (loc != null && loc.startsWith("file:")) { baseURI = new URI(loc); baseURI = baseURI.resolve(".").normalize(); } if (baseURI == null) { baseURI = new File(System.getProperty("user.dir")).toURI(); } } catch (URISyntaxException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
public Maker findFOMaker(String namespaceURI, String localName, Locator locator) throws FOPException { Map<String, Maker> table = fobjTable.get(namespaceURI); Maker fobjMaker = null; if (table != null) { fobjMaker = table.get(localName); // try default if (fobjMaker == null) { fobjMaker = table.get(ElementMapping.DEFAULT); } } if (fobjMaker == null) { if (namespaces.containsKey(namespaceURI.intern())) { throw new FOPException(FONode.errorText(locator) + "No element mapping definition found for " + FONode.getNodeString(namespaceURI, localName), locator); } else { fobjMaker = new UnknownXMLObj.Maker(namespaceURI); } } return fobjMaker; }
// in src/java/org/apache/fop/fonts/FontReader.java
private void createFont(InputSource source) throws FOPException { XMLReader parser = null; try { final SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); parser = factory.newSAXParser().getXMLReader(); } catch (Exception e) { throw new FOPException(e); } if (parser == null) { throw new FOPException("Unable to create SAX parser"); } try { parser.setFeature("http://xml.org/sax/features/namespace-prefixes", false); } catch (SAXException e) { throw new FOPException("You need a SAX parser which supports SAX version 2", e); } parser.setContentHandler(this); try { parser.parse(source); } catch (SAXException e) { throw new FOPException(e); } catch (IOException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/fonts/substitute/FontSubstitutionsConfigurator.java
private static FontQualifier getQualfierFromConfiguration(Configuration cfg) throws FOPException { String fontFamily = cfg.getAttribute("font-family", null); if (fontFamily == null) { throw new FOPException("substitution qualifier must have a font-family"); } FontQualifier qualifier = new FontQualifier(); qualifier.setFontFamily(fontFamily); String fontWeight = cfg.getAttribute("font-weight", null); if (fontWeight != null) { qualifier.setFontWeight(fontWeight); } String fontStyle = cfg.getAttribute("font-style", null); if (fontStyle != null) { qualifier.setFontStyle(fontStyle); } return qualifier; }
// in src/java/org/apache/fop/fonts/substitute/FontSubstitutionsConfigurator.java
public void configure(FontSubstitutions substitutions) throws FOPException { Configuration[] substitutionCfgs = cfg.getChildren("substitution"); for (int i = 0; i < substitutionCfgs.length; i++) { Configuration fromCfg = substitutionCfgs[i].getChild("from", false); if (fromCfg == null) { throw new FOPException("'substitution' element without child 'from' element"); } Configuration toCfg = substitutionCfgs[i].getChild("to", false); if (fromCfg == null) { throw new FOPException("'substitution' element without child 'to' element"); } FontQualifier fromQualifier = getQualfierFromConfiguration(fromCfg); FontQualifier toQualifier = getQualfierFromConfiguration(toCfg); FontSubstitution substitution = new FontSubstitution(fromQualifier, toQualifier); substitutions.add(substitution); } }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
private void setPDFDocVersion(Configuration cfg, PDFRenderingUtil pdfUtil) throws FOPException { Configuration pdfVersion = cfg.getChild(PDFConfigurationConstants.PDF_VERSION, false); if (pdfVersion != null) { String version = pdfVersion.getValue(null); if (version != null && version.length() != 0) { try { pdfUtil.setPDFVersion(version); } catch (IllegalArgumentException e) { throw new FOPException(e.getMessage()); } } else { throw new FOPException("The PDF version has not been set."); } } }
// in src/java/org/apache/fop/render/RendererFactory.java
public FOEventHandler createFOEventHandler(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { if (userAgent.getFOEventHandlerOverride() != null) { return userAgent.getFOEventHandlerOverride(); } else { AbstractFOEventHandlerMaker maker = getFOEventHandlerMaker(outputFormat); if (maker != null) { return maker.makeFOEventHandler(userAgent, out); } else { AbstractRendererMaker rendMaker = getRendererMaker(outputFormat); AbstractIFDocumentHandlerMaker documentHandlerMaker = null; boolean outputStreamMissing = (userAgent.getRendererOverride() == null) && (userAgent.getDocumentHandlerOverride() == null); if (rendMaker == null) { documentHandlerMaker = getDocumentHandlerMaker(outputFormat); if (documentHandlerMaker != null) { outputStreamMissing &= (out == null) && (documentHandlerMaker.needsOutputStream()); } } else { outputStreamMissing &= (out == null) && (rendMaker.needsOutputStream()); } if (userAgent.getRendererOverride() != null || rendMaker != null || userAgent.getDocumentHandlerOverride() != null || documentHandlerMaker != null) { if (outputStreamMissing) { throw new FOPException( "OutputStream has not been set"); } //Found a Renderer so we need to construct an AreaTreeHandler. return new AreaTreeHandler(userAgent, outputFormat, out); } else { throw new UnsupportedOperationException( "Don't know how to handle \"" + outputFormat + "\" as an output format." + " Neither an FOEventHandler, nor a Renderer could be found" + " for this output format."); } } } }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
private void configure(Configuration cfg, PCLRenderingUtil pclUtil) throws FOPException { String rendering = cfg.getChild("rendering").getValue(null); if (rendering != null) { try { pclUtil.setRenderingMode(PCLRenderingMode.valueOf(rendering)); } catch (IllegalArgumentException e) { throw new FOPException( "Valid values for 'rendering' are 'quality', 'speed' and 'bitmap'." + " Value found: " + rendering); } } String textRendering = cfg.getChild("text-rendering").getValue(null); if ("bitmap".equalsIgnoreCase(textRendering)) { pclUtil.setAllTextAsBitmaps(true); } else if ("auto".equalsIgnoreCase(textRendering)) { pclUtil.setAllTextAsBitmaps(false); } else if (textRendering != null) { throw new FOPException( "Valid values for 'text-rendering' are 'auto' and 'bitmap'. Value found: " + textRendering); } pclUtil.setPJLDisabled(cfg.getChild("disable-pjl").getValueAsBoolean(false)); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public RtfTableCell newTableCellMergedHorizontally (int cellWidth, RtfAttributes attrs) throws IOException, FOPException { highestCell++; // Added by Normand Masse // Inherit attributes from base cell for merge RtfAttributes wAttributes = null; if (attrs != null) { try { wAttributes = (RtfAttributes)attrs.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } } cell = new RtfTableCell(this, writer, cellWidth, wAttributes, highestCell); cell.setHMerge(RtfTableCell.MERGE_WITH_PREVIOUS); return cell; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfText.java
public RtfAttributes getTextContainerAttributes() throws FOPException { if (attrib == null) { return null; } try { return (RtfAttributes)this.attrib.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfAttributes getTextContainerAttributes() throws FOPException { if (attrib == null) { return null; } try { return (RtfAttributes)this.attrib.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public RtfAttributes getTextContainerAttributes() throws FOPException { if (attrib == null) { return null; } try { return (RtfAttributes) this.attrib.clone (); } catch (CloneNotSupportedException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
public RtfTableRow newTableRow(RtfAttributes attrs) throws IOException, FOPException { RtfAttributes attr = null; if (attrib != null) { try { attr = (RtfAttributes) attrib.clone (); } catch (CloneNotSupportedException e) { throw new FOPException(e); } attr.set (attrs); } else { attr = attrs; } if (row != null) { row.close(); } highestRow++; row = new RtfTableRow(this, writer, attr, highestRow); return row; }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
private float numberToTwips(String number, String units) throws FOPException { float result = 0; // convert number to integer try { if (number != null && number.trim().length() > 0) { result = Float.valueOf(number).floatValue(); } } catch (Exception e) { throw new FOPException("number format error: cannot convert '" + number + "' to float value"); } // find conversion factor if (units != null && units.trim().length() > 0) { final Float factor = (Float)TWIP_FACTORS.get(units.toLowerCase()); if (factor == null) { throw new FOPException("conversion factor not found for '" + units + "' units"); } result *= factor.floatValue(); } return result; }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
int convertFontSize(String size) throws FOPException { size = size.trim(); final String sFONTSUFFIX = FixedLength.POINT; if (!size.endsWith(sFONTSUFFIX)) { throw new FOPException("Invalid font size '" + size + "', must end with '" + sFONTSUFFIX + "'"); } float result = 0; size = size.substring(0, size.length() - sFONTSUFFIX.length()); try { result = (Float.valueOf(size).floatValue()); } catch (Exception e) { throw new FOPException("Invalid font size value '" + size + "'"); } // RTF font size units are in half-points return (int)(result * 2.0); }
// in src/java/org/apache/fop/render/bitmap/BitmapRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { super.configure(documentHandler); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { AbstractBitmapDocumentHandler bitmapHandler = (AbstractBitmapDocumentHandler)documentHandler; BitmapRenderingSettings settings = bitmapHandler.getSettings(); boolean transparent = cfg.getChild( Java2DRenderer.JAVA2D_TRANSPARENT_PAGE_BACKGROUND).getValueAsBoolean( settings.hasTransparentPageBackground()); if (transparent) { settings.setPageBackgroundColor(null); } else { String background = cfg.getChild("background-color").getValue(null); if (background != null) { settings.setPageBackgroundColor( ColorUtil.parseColorString(this.userAgent, background)); } } boolean antiAliasing = cfg.getChild("anti-aliasing").getValueAsBoolean( settings.isAntiAliasingEnabled()); settings.setAntiAliasing(antiAliasing); String optimization = cfg.getChild("rendering").getValue(null); if ("quality".equalsIgnoreCase(optimization)) { settings.setQualityRendering(true); } else if ("speed".equalsIgnoreCase(optimization)) { settings.setQualityRendering(false); } String color = cfg.getChild("color-mode").getValue(null); if (color != null) { if ("rgba".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_INT_ARGB); } else if ("rgb".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_INT_RGB); } else if ("gray".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_BYTE_GRAY); } else if ("binary".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_BYTE_BINARY); } else if ("bi-level".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_BYTE_BINARY); } else { throw new FOPException("Invalid value for color-mode: " + color); } } } }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private void configure(AFPCustomizable customizable, Configuration cfg) throws FOPException { // image information Configuration imagesCfg = cfg.getChild("images"); // default to grayscale images String imagesMode = imagesCfg.getAttribute("mode", IMAGES_MODE_GRAYSCALE); if (IMAGES_MODE_COLOR.equals(imagesMode)) { customizable.setColorImages(true); boolean cmyk = imagesCfg.getAttributeAsBoolean("cmyk", false); customizable.setCMYKImagesSupported(cmyk); } else { customizable.setColorImages(false); // default to 8 bits per pixel int bitsPerPixel = imagesCfg.getAttributeAsInteger("bits-per-pixel", 8); customizable.setBitsPerPixel(bitsPerPixel); } String dithering = imagesCfg.getAttribute("dithering-quality", "medium"); float dq = 0.5f; if (dithering.startsWith("min")) { dq = 0.0f; } else if (dithering.startsWith("max")) { dq = 1.0f; } else { try { dq = Float.parseFloat(dithering); } catch (NumberFormatException nfe) { //ignore and leave the default above } } customizable.setDitheringQuality(dq); // native image support boolean nativeImageSupport = imagesCfg.getAttributeAsBoolean("native", false); customizable.setNativeImagesSupported(nativeImageSupport); Configuration jpegConfig = imagesCfg.getChild("jpeg"); boolean allowEmbedding = false; float ieq = 1.0f; if (jpegConfig != null) { allowEmbedding = jpegConfig.getAttributeAsBoolean("allow-embedding", false); String bitmapEncodingQuality = jpegConfig.getAttribute("bitmap-encoding-quality", null); if (bitmapEncodingQuality != null) { try { ieq = Float.parseFloat(bitmapEncodingQuality); } catch (NumberFormatException nfe) { //ignore and leave the default above } } } customizable.canEmbedJpeg(allowEmbedding); customizable.setBitmapEncodingQuality(ieq); //FS11 and FS45 page segment wrapping boolean pSeg = imagesCfg.getAttributeAsBoolean("pseg", false); customizable.setWrapPSeg(pSeg); //FS45 image forcing boolean fs45 = imagesCfg.getAttributeAsBoolean("fs45", false); customizable.setFS45(fs45); // shading (filled rectangles) Configuration shadingCfg = cfg.getChild("shading"); AFPShadingMode shadingMode = AFPShadingMode.valueOf( shadingCfg.getValue(AFPShadingMode.COLOR.getName())); customizable.setShadingMode(shadingMode); // GOCA Support Configuration gocaCfg = cfg.getChild("goca"); boolean gocaEnabled = gocaCfg.getAttributeAsBoolean( "enabled", customizable.isGOCAEnabled()); customizable.setGOCAEnabled(gocaEnabled); String gocaText = gocaCfg.getAttribute( "text", customizable.isStrokeGOCAText() ? "stroke" : "default"); customizable.setStrokeGOCAText("stroke".equalsIgnoreCase(gocaText) || "shapes".equalsIgnoreCase(gocaText)); // renderer resolution Configuration rendererResolutionCfg = cfg.getChild("renderer-resolution", false); if (rendererResolutionCfg != null) { customizable.setResolution(rendererResolutionCfg.getValueAsInteger(240)); } // renderer resolution Configuration lineWidthCorrectionCfg = cfg.getChild("line-width-correction", false); if (lineWidthCorrectionCfg != null) { customizable.setLineWidthCorrection(lineWidthCorrectionCfg .getValueAsFloat(AFPConstants.LINE_WIDTH_CORRECTION)); } // a default external resource group file setting Configuration resourceGroupFileCfg = cfg.getChild("resource-group-file", false); if (resourceGroupFileCfg != null) { String resourceGroupDest = null; try { resourceGroupDest = resourceGroupFileCfg.getValue(); if (resourceGroupDest != null) { File resourceGroupFile = new File(resourceGroupDest); boolean created = resourceGroupFile.createNewFile(); if (created && resourceGroupFile.canWrite()) { customizable.setDefaultResourceGroupFilePath(resourceGroupDest); } else { log.warn("Unable to write to default external resource group file '" + resourceGroupDest + "'"); } } } catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); } catch (IOException ioe) { throw new FOPException("Could not create default external resource group file" , ioe); } } Configuration defaultResourceLevelCfg = cfg.getChild("default-resource-levels", false); if (defaultResourceLevelCfg != null) { AFPResourceLevelDefaults defaults = new AFPResourceLevelDefaults(); String[] types = defaultResourceLevelCfg.getAttributeNames(); for (int i = 0, c = types.length; i < c; i++) { String type = types[i]; try { String level = defaultResourceLevelCfg.getAttribute(type); defaults.setDefaultResourceLevel(type, AFPResourceLevel.valueOf(level)); } catch (IllegalArgumentException iae) { LogUtil.handleException(log, iae, userAgent.getFactory().validateUserConfigStrictly()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); } } customizable.setResourceLevelDefaults(defaults); } }
// in src/java/org/apache/fop/render/afp/extensions/AbstractAFPExtensionObject.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { getExtensionAttachment(); String attr = attlist.getValue("name"); if (attr != null && attr.length() > 0) { extensionAttachment.setName(attr); } else { throw new FOPException(elementName + " must have a name attribute."); } }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public void renderPage(PageViewport pageViewport) throws IOException, FOPException { try { rememberPage((PageViewport)pageViewport.clone()); } catch (CloneNotSupportedException e) { throw new FOPException(e); } //The clone() call is necessary as we store the page for later. Otherwise, the //RenderPagesModel calls PageViewport.clear() to release memory as early as possible. currentPageNumber++; }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public PageViewport getPageViewport(int pageIndex) throws FOPException { if (pageIndex < 0 || pageIndex >= pageViewportList.size()) { throw new FOPException("Requested page number is out of range: " + pageIndex + "; only " + pageViewportList.size() + " page(s) available."); } return (PageViewport) pageViewportList.get(pageIndex); }
// in src/java/org/apache/fop/util/LogUtil.java
public static void handleException(Log log, Exception e, boolean strict) throws FOPException { if (strict) { if (e instanceof FOPException) { throw (FOPException)e; } throw new FOPException(e); } log.error(e.getMessage()); }
// in src/java/org/apache/fop/cli/AreaTreeInputHandler.java
public void renderTo(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { FontInfo fontInfo = new FontInfo(); AreaTreeModel treeModel = new RenderPagesModel(userAgent, outputFormat, fontInfo, out); //Iterate over all intermediate files AreaTreeParser parser = new AreaTreeParser(); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(parser.getContentHandler(treeModel, userAgent)); transformTo(res); try { treeModel.endDocument(); } catch (SAXException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/cli/InputHandler.java
protected void transformTo(Result result) throws FOPException { try { // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer; Source xsltSource = createXSLTSource(); if (xsltSource == null) { // FO Input transformer = factory.newTransformer(); } else { // XML/XSLT input transformer = factory.newTransformer(xsltSource); // Set the value of parameters, if any, defined for stylesheet if (xsltParams != null) { for (int i = 0; i < xsltParams.size(); i += 2) { transformer.setParameter((String) xsltParams.elementAt(i), (String) xsltParams.elementAt(i + 1)); } } if (uriResolver != null) { transformer.setURIResolver(uriResolver); } } transformer.setErrorListener(this); // Create a SAXSource from the input Source file Source src = createMainSource(); // Start XSLT transformation and FOP processing transformer.transform(src, result); } catch (Exception e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private boolean parseOptions(String[] args) throws FOPException { // do not throw an exception for no args if (args.length == 0) { printVersion(); printUsage(System.out); return false; } for (int i = 0; i < args.length; i++) { if (args[i].equals("-x") || args[i].equals("--dump-config")) { showConfiguration = Boolean.TRUE; } else if (args[i].equals("-c")) { i = i + parseConfigurationOption(args, i); } else if (args[i].equals("-l")) { i = i + parseLanguageOption(args, i); } else if (args[i].equals("-s")) { suppressLowLevelAreas = Boolean.TRUE; } else if (args[i].equals("-d")) { setLogOption("debug", "debug"); } else if (args[i].equals("-r")) { factory.setStrictValidation(false); } else if (args[i].equals("-conserve")) { conserveMemoryPolicy = true; } else if (args[i].equals("-flush")) { flushCache = true; } else if (args[i].equals("-cache")) { parseCacheOption(args, i); } else if (args[i].equals("-dpi")) { i = i + parseResolution(args, i); } else if (args[i].equals("-q") || args[i].equals("--quiet")) { setLogOption("quiet", "error"); } else if (args[i].equals("-fo")) { i = i + parseFOInputOption(args, i); } else if (args[i].equals("-xsl")) { i = i + parseXSLInputOption(args, i); } else if (args[i].equals("-xml")) { i = i + parseXMLInputOption(args, i); } else if (args[i].equals("-atin")) { i = i + parseAreaTreeInputOption(args, i); } else if (args[i].equals("-ifin")) { i = i + parseIFInputOption(args, i); } else if (args[i].equals("-imagein")) { i = i + parseImageInputOption(args, i); } else if (args[i].equals("-awt")) { i = i + parseAWTOutputOption(args, i); } else if (args[i].equals("-pdf")) { i = i + parsePDFOutputOption(args, i, null); } else if (args[i].equals("-pdfa1b")) { i = i + parsePDFOutputOption(args, i, "PDF/A-1b"); } else if (args[i].equals("-mif")) { i = i + parseMIFOutputOption(args, i); } else if (args[i].equals("-rtf")) { i = i + parseRTFOutputOption(args, i); } else if (args[i].equals("-tiff")) { i = i + parseTIFFOutputOption(args, i); } else if (args[i].equals("-png")) { i = i + parsePNGOutputOption(args, i); } else if (args[i].equals("-print")) { // show print help if (i + 1 < args.length) { if (args[i + 1].equals("help")) { printUsagePrintOutput(); return false; } } i = i + parsePrintOutputOption(args, i); } else if (args[i].equals("-copies")) { i = i + parseCopiesOption(args, i); } else if (args[i].equals("-pcl")) { i = i + parsePCLOutputOption(args, i); } else if (args[i].equals("-ps")) { i = i + parsePostscriptOutputOption(args, i); } else if (args[i].equals("-txt")) { i = i + parseTextOutputOption(args, i); } else if (args[i].equals("-svg")) { i = i + parseSVGOutputOption(args, i); } else if (args[i].equals("-afp")) { i = i + parseAFPOutputOption(args, i); } else if (args[i].equals("-foout")) { i = i + parseFOOutputOption(args, i); } else if (args[i].equals("-out")) { i = i + parseCustomOutputOption(args, i); } else if (args[i].equals("-at")) { i = i + parseAreaTreeOption(args, i); } else if (args[i].equals("-if")) { i = i + parseIntermediateFormatOption(args, i); } else if (args[i].equals("-a")) { this.renderingOptions.put(Accessibility.ACCESSIBILITY, Boolean.TRUE); } else if (args[i].equals("-v")) { /* verbose mode although users may expect version; currently just print the version */ printVersion(); if (args.length == 1) { return false; } } else if (args[i].equals("-param")) { if (i + 2 < args.length) { String name = args[++i]; String expression = args[++i]; addXSLTParameter(name, expression); } else { throw new FOPException("invalid param usage: use -param <name> <value>"); } } else if (args[i].equals("-catalog")) { useCatalogResolver = true; } else if (args[i].equals("-o")) { i = i + parsePDFOwnerPassword(args, i); } else if (args[i].equals("-u")) { i = i + parsePDFUserPassword(args, i); } else if (args[i].equals("-pdfprofile")) { i = i + parsePDFProfile(args, i); } else if (args[i].equals("-noprint")) { getPDFEncryptionParams().setAllowPrint(false); } else if (args[i].equals("-nocopy")) { getPDFEncryptionParams().setAllowCopyContent(false); } else if (args[i].equals("-noedit")) { getPDFEncryptionParams().setAllowEditContent(false); } else if (args[i].equals("-noannotations")) { getPDFEncryptionParams().setAllowEditAnnotations(false); } else if (args[i].equals("-nocs")) { useComplexScriptFeatures = false; } else if (args[i].equals("-nofillinforms")) { getPDFEncryptionParams().setAllowFillInForms(false); } else if (args[i].equals("-noaccesscontent")) { getPDFEncryptionParams().setAllowAccessContent(false); } else if (args[i].equals("-noassembledoc")) { getPDFEncryptionParams().setAllowAssembleDocument(false); } else if (args[i].equals("-noprinthq")) { getPDFEncryptionParams().setAllowPrintHq(false); } else if (args[i].equals("-version")) { printVersion(); return false; } else if (!isOption(args[i])) { i = i + parseUnknownOption(args, i); } else { printUsage(System.err); System.exit(1); } } return true; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseCacheOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("if you use '-cache', you must specify " + "the name of the font cache file"); } else { factory.getFontManager().setCacheFile(new File(args[i + 1])); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseConfigurationOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("if you use '-c', you must specify " + "the name of the configuration file"); } else { userConfigFile = new File(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseLanguageOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("if you use '-l', you must specify a language"); } else { Locale.setDefault(new Locale(args[i + 1], "")); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseResolution(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException( "if you use '-dpi', you must specify a resolution (dots per inch)"); } else { this.targetResolution = Integer.parseInt(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseFOInputOption(String[] args, int i) throws FOPException { setInputFormat(FO_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the fo file for the '-fo' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { fofile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseXSLInputOption(String[] args, int i) throws FOPException { setInputFormat(XSLT_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the stylesheet " + "file for the '-xsl' option"); } else { xsltfile = new File(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseXMLInputOption(String[] args, int i) throws FOPException { setInputFormat(XSLT_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the input file " + "for the '-xml' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { xmlfile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePDFOutputOption(String[] args, int i, String pdfAMode) throws FOPException { setOutputMode(MimeConstants.MIME_PDF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PDF output file"); } else { setOutputFile(args[i + 1]); if (pdfAMode != null) { if (renderingOptions.get("pdf-a-mode") != null) { throw new FOPException("PDF/A mode already set"); } renderingOptions.put("pdf-a-mode", pdfAMode); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseMIFOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_MIF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the MIF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseRTFOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_RTF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the RTF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseTIFFOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_TIFF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the TIFF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePNGOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_PNG); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PNG output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseCopiesOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the number of copies"); } else { renderingOptions.put(PrintRenderer.COPIES, new Integer(args[i + 1])); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePCLOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_PCL); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PDF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePostscriptOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_POSTSCRIPT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PostScript output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseTextOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_PLAIN_TEXT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the text output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseSVGOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_SVG); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the SVG output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAFPOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_AFP); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the AFP output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseFOOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_XSL_FO); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the FO output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseCustomOutputOption(String[] args, int i) throws FOPException { String mime = null; if ((i + 1 < args.length) || (args[i + 1].charAt(0) != '-')) { mime = args[i + 1]; if ("list".equals(mime)) { String[] mimes = factory.getRendererFactory().listSupportedMimeTypes(); System.out.println("Supported MIME types:"); for (int j = 0; j < mimes.length; j++) { System.out.println(" " + mimes[j]); } System.exit(0); } } if ((i + 2 >= args.length) || (isOption(args[i + 1])) || (isOption(args[i + 2]))) { throw new FOPException("you must specify the output format and the output file"); } else { setOutputMode(mime); setOutputFile(args[i + 2]); return 2; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseUnknownOption(String[] args, int i) throws FOPException { if (inputmode == NOT_SET) { inputmode = FO_INPUT; String filename = args[i]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { fofile = new File(filename); } } else if (outputmode == null) { outputmode = MimeConstants.MIME_PDF; setOutputFile(args[i]); } else { throw new FOPException("Don't know what to do with " + args[i]); } return 0; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAreaTreeOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_FOP_AREA_TREE); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the area-tree output file"); } else if ((i + 2 == args.length) || (isOption(args[i + 2]))) { // only output file is specified setOutputFile(args[i + 1]); return 1; } else { // mimic format and output file have been specified mimicRenderer = args[i + 1]; setOutputFile(args[i + 2]); return 2; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseIntermediateFormatOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_FOP_IF); if ((i + 1 == args.length) || (args[i + 1].charAt(0) == '-')) { throw new FOPException("you must specify the intermediate format output file"); } else if ((i + 2 == args.length) || (args[i + 2].charAt(0) == '-')) { // only output file is specified setOutputFile(args[i + 1]); return 1; } else { // mimic format and output file have been specified mimicRenderer = args[i + 1]; setOutputFile(args[i + 2]); return 2; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAreaTreeInputOption(String[] args, int i) throws FOPException { setInputFormat(AREATREE_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the Area Tree file for the '-atin' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { areatreefile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseIFInputOption(String[] args, int i) throws FOPException { setInputFormat(IF_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the intermediate file for the '-ifin' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { iffile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseImageInputOption(String[] args, int i) throws FOPException { setInputFormat(IMAGE_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the image file for the '-imagein' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { imagefile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private PDFEncryptionParams getPDFEncryptionParams() throws FOPException { PDFEncryptionParams params = (PDFEncryptionParams)renderingOptions.get( PDFConfigurationConstants.ENCRYPTION_PARAMS); if (params == null) { if (!PDFEncryptionManager.checkAvailableAlgorithms()) { throw new FOPException("PDF encryption requested but it is not available." + " Please make sure MD5 and RC4 algorithms are available."); } params = new PDFEncryptionParams(); renderingOptions.put(PDFConfigurationConstants.ENCRYPTION_PARAMS, params); } return params; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePDFProfile(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("You must specify a PDF profile"); } else { String profile = args[i + 1]; PDFAMode pdfAMode = PDFAMode.valueOf(profile); if (pdfAMode != null && pdfAMode != PDFAMode.DISABLED) { if (renderingOptions.get("pdf-a-mode") != null) { throw new FOPException("PDF/A mode already set"); } renderingOptions.put("pdf-a-mode", pdfAMode.getName()); return 1; } else { PDFXMode pdfXMode = PDFXMode.valueOf(profile); if (pdfXMode != null && pdfXMode != PDFXMode.DISABLED) { if (renderingOptions.get("pdf-x-mode") != null) { throw new FOPException("PDF/X mode already set"); } renderingOptions.put("pdf-x-mode", pdfXMode.getName()); return 1; } } throw new FOPException("Unsupported PDF profile: " + profile); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setOutputMode(String mime) throws FOPException { if (outputmode == null) { outputmode = mime; } else { throw new FOPException("you can only set one output method"); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setInputFormat(int format) throws FOPException { if (inputmode == NOT_SET || inputmode == format) { inputmode = format; } else { throw new FOPException("Only one input mode can be specified!"); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void checkSettings() throws FOPException, FileNotFoundException { if (inputmode == NOT_SET) { throw new FOPException("No input file specified"); } if (outputmode == null) { throw new FOPException("No output file specified"); } if ((outputmode.equals(MimeConstants.MIME_FOP_AWT_PREVIEW) || outputmode.equals(MimeConstants.MIME_FOP_PRINT)) && outfile != null) { throw new FOPException("Output file may not be specified " + "for AWT or PRINT output"); } if (inputmode == XSLT_INPUT) { // check whether xml *and* xslt file have been set if (xmlfile == null && !this.useStdIn) { throw new FOPException("XML file must be specified for the transform mode"); } if (xsltfile == null) { throw new FOPException("XSLT file must be specified for the transform mode"); } // warning if fofile has been set in xslt mode if (fofile != null) { log.warn("Can't use fo file with transform mode! Ignoring.\n" + "Your input is " + "\n xmlfile: " + xmlfile.getAbsolutePath() + "\nxsltfile: " + xsltfile.getAbsolutePath() + "\n fofile: " + fofile.getAbsolutePath()); } if (xmlfile != null && !xmlfile.exists()) { throw new FileNotFoundException("Error: xml file " + xmlfile.getAbsolutePath() + " not found "); } if (!xsltfile.exists()) { throw new FileNotFoundException("Error: xsl file " + xsltfile.getAbsolutePath() + " not found "); } } else if (inputmode == FO_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (fofile != null && !fofile.exists()) { throw new FileNotFoundException("Error: fo file " + fofile.getAbsolutePath() + " not found "); } } else if (inputmode == AREATREE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Area Tree is used as input!"); } if (areatreefile != null && !areatreefile.exists()) { throw new FileNotFoundException("Error: area tree file " + areatreefile.getAbsolutePath() + " not found "); } } else if (inputmode == IF_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Intermediate Format" + " is used as input!"); } else if (outputmode.equals(MimeConstants.MIME_FOP_IF)) { throw new FOPException( "Intermediate Output is not available if Intermediate Format" + " is used as input!"); } if (iffile != null && !iffile.exists()) { throw new FileNotFoundException("Error: intermediate format file " + iffile.getAbsolutePath() + " not found "); } } else if (inputmode == IMAGE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (imagefile != null && !imagefile.exists()) { throw new FileNotFoundException("Error: image file " + imagefile.getAbsolutePath() + " not found "); } } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setUserConfig() throws FOPException, IOException { if (userConfigFile == null) { return; } try { factory.setUserConfig(userConfigFile); } catch (SAXException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
protected String getOutputFormat() throws FOPException { if (outputmode == null) { throw new FOPException("Renderer has not been set!"); } if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { renderingOptions.put("fineDetail", isCoarseAreaXml()); } return outputmode; }
// in src/java/org/apache/fop/cli/IFInputHandler.java
public void renderTo(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { IFDocumentHandler documentHandler = userAgent.getFactory().getRendererFactory().createDocumentHandler( userAgent, outputFormat); try { documentHandler.setResult(new StreamResult(out)); IFUtil.setupFonts(documentHandler); //Create IF parser IFParser parser = new IFParser(); // Resulting SAX events are sent to the parser Result res = new SAXResult(parser.getContentHandler(documentHandler, userAgent)); transformTo(res); } catch (IFException ife) { throw new FOPException(ife); } }
24
              
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (URISyntaxException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException("You need a SAX parser which supports SAX version 2", e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (IOException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException(e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException( "Valid values for 'rendering' are 'quality', 'speed' and 'bitmap'." + " Value found: " + rendering); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfText.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("number format error: cannot convert '" + number + "' to float value"); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("Invalid font size value '" + size + "'"); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IOException ioe) { throw new FOPException("Could not create default external resource group file" , ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/area/PageViewport.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/AreaTreeInputHandler.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (Exception e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/IFInputHandler.java
catch (IFException ife) { throw new FOPException(ife); }
380
              
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(String outputFormat) throws FOPException { return newFop(outputFormat, newFOUserAgent()); }
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(String outputFormat, FOUserAgent userAgent) throws FOPException { return newFop(outputFormat, userAgent, null); }
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(String outputFormat, OutputStream stream) throws FOPException { return newFop(outputFormat, newFOUserAgent(), stream); }
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(String outputFormat, FOUserAgent userAgent, OutputStream stream) throws FOPException { if (userAgent == null) { throw new NullPointerException("The userAgent parameter must not be null!"); } return new Fop(outputFormat, userAgent, stream); }
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(FOUserAgent userAgent) throws FOPException { if (userAgent.getRendererOverride() == null && userAgent.getFOEventHandlerOverride() == null && userAgent.getDocumentHandlerOverride() == null) { throw new IllegalStateException("An overriding renderer," + " FOEventHandler or IFDocumentHandler must be set on the user agent" + " when this factory method is used!"); } return newFop(null, userAgent); }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setUserConfig(Configuration userConfig) throws FOPException { config.setUserConfig(userConfig); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void configure(FopFactory factory) throws FOPException { // CSOK: MethodLength // strict configuration if (cfg.getChild("strict-configuration", false) != null) { try { factory.setStrictUserConfigValidation( cfg.getChild("strict-configuration").getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, false); } } boolean strict = factory.validateUserConfigStrictly(); if (log.isDebugEnabled()) { log.debug("Initializing FopFactory Configuration" + "with " + (strict ? "strict" : "permissive") + " validation"); } if (cfg.getChild("accessibility", false) != null) { try { this.factory.setAccessibility( cfg.getChild("accessibility").getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); } } // strict fo validation if (cfg.getChild("strict-validation", false) != null) { try { factory.setStrictValidation( cfg.getChild("strict-validation").getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); } } // base definitions for relative path resolution if (cfg.getChild("base", false) != null) { String path = cfg.getChild("base").getValue(null); if (baseURI != null) { path = baseURI.resolve(path).normalize().toString(); } try { factory.setBaseURL(path); } catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, strict); } } if (cfg.getChild("hyphenation-base", false) != null) { String path = cfg.getChild("hyphenation-base").getValue(null); if (baseURI != null) { path = baseURI.resolve(path).normalize().toString(); } try { factory.setHyphenBaseURL(path); } catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, strict); } } /** * Read configuration elements hyphenation-pattern, * construct a map ll_CC => filename, and set it on the factory */ Configuration[] hyphPatConfig = cfg.getChildren("hyphenation-pattern"); if (hyphPatConfig.length != 0) { Map/*<String,String>*/ hyphPatNames = new HashMap/*<String,String>*/(); for (int i = 0; i < hyphPatConfig.length; ++i) { String lang; String country; String filename; StringBuffer error = new StringBuffer(); String location = hyphPatConfig[i].getLocation(); lang = hyphPatConfig[i].getAttribute("lang", null); if (lang == null) { addError("The lang attribute of a hyphenation-pattern configuration" + " element must exist (" + location + ")", error); } else if (!lang.matches("[a-zA-Z]{2}")) { addError("The lang attribute of a hyphenation-pattern configuration" + " element must consist of exactly two letters (" + location + ")", error); } lang = lang.toLowerCase(); country = hyphPatConfig[i].getAttribute("country", null); if ("".equals(country)) { country = null; } if (country != null) { if (!country.matches("[a-zA-Z]{2}")) { addError("The country attribute of a hyphenation-pattern configuration" + " element must consist of exactly two letters (" + location + ")", error); } country = country.toUpperCase(); } filename = hyphPatConfig[i].getValue(null); if (filename == null) { addError("The value of a hyphenation-pattern configuration" + " element may not be empty (" + location + ")", error); } if (error.length() != 0) { LogUtil.handleError(log, error.toString(), strict); continue; } String llccKey = HyphenationTreeCache.constructLlccKey(lang, country); hyphPatNames.put(llccKey, filename); if (log.isDebugEnabled()) { log.debug("Using hyphenation pattern filename " + filename + " for lang=\"" + lang + "\"" + (country != null ? ", country=\"" + country + "\"" : "")); } } factory.setHyphPatNames(hyphPatNames); } // renderer options if (cfg.getChild("source-resolution", false) != null) { factory.setSourceResolution( cfg.getChild("source-resolution").getValueAsFloat( FopFactoryConfigurator.DEFAULT_SOURCE_RESOLUTION)); if (log.isDebugEnabled()) { log.debug("source-resolution set to: " + factory.getSourceResolution() + "dpi (px2mm=" + factory.getSourcePixelUnitToMillimeter() + ")"); } } if (cfg.getChild("target-resolution", false) != null) { factory.setTargetResolution( cfg.getChild("target-resolution").getValueAsFloat( FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION)); if (log.isDebugEnabled()) { log.debug("target-resolution set to: " + factory.getTargetResolution() + "dpi (px2mm=" + factory.getTargetPixelUnitToMillimeter() + ")"); } } if (cfg.getChild("break-indent-inheritance", false) != null) { try { factory.setBreakIndentInheritanceOnReferenceAreaBoundary( cfg.getChild("break-indent-inheritance").getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); } } Configuration pageConfig = cfg.getChild("default-page-settings"); if (pageConfig.getAttribute("height", null) != null) { factory.setPageHeight( pageConfig.getAttribute("height", FopFactoryConfigurator.DEFAULT_PAGE_HEIGHT)); if (log.isInfoEnabled()) { log.info("Default page-height set to: " + factory.getPageHeight()); } } if (pageConfig.getAttribute("width", null) != null) { factory.setPageWidth( pageConfig.getAttribute("width", FopFactoryConfigurator.DEFAULT_PAGE_WIDTH)); if (log.isInfoEnabled()) { log.info("Default page-width set to: " + factory.getPageWidth()); } } // prefer Renderer over IFDocumentHandler if (cfg.getChild(PREFER_RENDERER, false) != null) { try { factory.getRendererFactory().setRendererPreferred( cfg.getChild(PREFER_RENDERER).getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); } } // configure complex script support Configuration csConfig = cfg.getChild("complex-scripts"); if (csConfig != null) { this.factory.setComplexScriptFeaturesEnabled (!csConfig.getAttributeAsBoolean ( "disabled", false )); } // configure font manager new FontManagerConfigurator(cfg, baseURI).configure(factory.getFontManager(), strict); // configure image loader framework configureImageLoading(cfg.getChild("image-loading", false), strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
private void configureImageLoading(Configuration parent, boolean strict) throws FOPException { if (parent == null) { return; } ImageImplRegistry registry = factory.getImageManager().getRegistry(); Configuration[] penalties = parent.getChildren("penalty"); try { for (int i = 0, c = penalties.length; i < c; i++) { Configuration penaltyCfg = penalties[i]; String className = penaltyCfg.getAttribute("class"); String value = penaltyCfg.getAttribute("value"); Penalty p = null; if (value.toUpperCase().startsWith("INF")) { p = Penalty.INFINITE_PENALTY; } else { try { p = Penalty.toPenalty(Integer.parseInt(value)); } catch (NumberFormatException nfe) { LogUtil.handleException(log, nfe, strict); } } if (p != null) { registry.setAdditionalPenalty(className, p); } } } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); } }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(Configuration cfg) throws FOPException { this.cfg = cfg; setBaseURI(); configure(this.factory); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
private void setBaseURI() throws FOPException { String loc = cfg.getLocation(); try { if (loc != null && loc.startsWith("file:")) { baseURI = new URI(loc); baseURI = baseURI.resolve(".").normalize(); } if (baseURI == null) { baseURI = new File(System.getProperty("user.dir")).toURI(); } } catch (URISyntaxException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/apps/Fop.java
private void createDefaultHandler() throws FOPException { this.foTreeBuilder = new FOTreeBuilder(outputFormat, foUserAgent, stream); }
// in src/java/org/apache/fop/apps/Fop.java
public DefaultHandler getDefaultHandler() throws FOPException { if (foTreeBuilder == null) { createDefaultHandler(); } return this.foTreeBuilder; }
// in src/java/org/apache/fop/tools/fontlist/FontListGenerator.java
public SortedMap listFonts(FopFactory fopFactory, String mime, FontEventListener listener) throws FOPException { FontInfo fontInfo = setupFonts(fopFactory, mime, listener); SortedMap fontFamilies = buildFamilyMap(fontInfo); return fontFamilies; }
// in src/java/org/apache/fop/tools/fontlist/FontListGenerator.java
private FontInfo setupFonts(FopFactory fopFactory, String mime, FontEventListener listener) throws FOPException { FOUserAgent userAgent = fopFactory.newFOUserAgent(); //The document handler is only instantiated to get access to its configurator! IFDocumentHandler documentHandler = fopFactory.getRendererFactory().createDocumentHandler(userAgent, mime); IFDocumentHandlerConfigurator configurator = documentHandler.getConfigurator(); FontInfo fontInfo = new FontInfo(); configurator.setupFontInfo(documentHandler, fontInfo); return fontInfo; }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private ContentHandler getFOPContentHandler(OutputStream out) throws FOPException { Fop fop = fopFactory.newFop(this.outputMime, out); return fop.getDefaultHandler(); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
public void run() throws FOPException { //Set base directory if (task.getBasedir() != null) { try { this.baseURL = task.getBasedir().toURI().toURL().toExternalForm(); } catch (MalformedURLException mfue) { logger.error("Error creating base URL from base directory", mfue); } } else { try { if (task.getFofile() != null) { this.baseURL = task.getFofile().getParentFile().toURI().toURL() .toExternalForm(); } } catch (MalformedURLException mfue) { logger.error("Error creating base URL from XSL-FO input file", mfue); } } task.log("Using base URL: " + baseURL, Project.MSG_DEBUG); String outputFormat = normalizeOutputFormat(task.getFormat()); String newExtension = determineExtension(outputFormat); // actioncount = # of fofiles actually processed through FOP int actioncount = 0; // skippedcount = # of fofiles which haven't changed (force = "false") int skippedcount = 0; // deal with single source file if (task.getFofile() != null) { if (task.getFofile().exists()) { File outf = task.getOutfile(); if (outf == null) { throw new BuildException("outfile is required when fofile is used"); } if (task.getOutdir() != null) { outf = new File(task.getOutdir(), outf.getName()); } // Render if "force" flag is set OR // OR output file doesn't exist OR // output file is older than input file if (task.getForce() || !outf.exists() || (task.getFofile().lastModified() > outf.lastModified() )) { render(task.getFofile(), outf, outputFormat); actioncount++; } else if (outf.exists() && (task.getFofile().lastModified() <= outf.lastModified() )) { skippedcount++; } } } else if (task.getXmlFile() != null && task.getXsltFile() != null) { if (task.getXmlFile().exists() && task.getXsltFile().exists()) { File outf = task.getOutfile(); if (outf == null) { throw new BuildException("outfile is required when fofile is used"); } if (task.getOutdir() != null) { outf = new File(task.getOutdir(), outf.getName()); } // Render if "force" flag is set OR // OR output file doesn't exist OR // output file is older than input file if (task.getForce() || !outf.exists() || (task.getXmlFile().lastModified() > outf.lastModified() || task.getXsltFile().lastModified() > outf.lastModified())) { render(task.getXmlFile(), task.getXsltFile(), outf, outputFormat); actioncount++; } else if (outf.exists() && (task.getXmlFile().lastModified() <= outf.lastModified() || task.getXsltFile().lastModified() <= outf.lastModified())) { skippedcount++; } } } GlobPatternMapper mapper = new GlobPatternMapper(); String inputExtension = ".fo"; File xsltFile = task.getXsltFile(); if (xsltFile != null) { inputExtension = ".xml"; } mapper.setFrom("*" + inputExtension); mapper.setTo("*" + newExtension); // deal with the filesets for (int i = 0; i < task.getFilesets().size(); i++) { FileSet fs = (FileSet) task.getFilesets().get(i); DirectoryScanner ds = fs.getDirectoryScanner(task.getProject()); String[] files = ds.getIncludedFiles(); for (int j = 0; j < files.length; j++) { File f = new File(fs.getDir(task.getProject()), files[j]); File outf = null; if (task.getOutdir() != null && files[j].endsWith(inputExtension)) { String[] sa = mapper.mapFileName(files[j]); outf = new File(task.getOutdir(), sa[0]); } else { outf = replaceExtension(f, inputExtension, newExtension); if (task.getOutdir() != null) { outf = new File(task.getOutdir(), outf.getName()); } } File dir = outf.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } try { if (task.getRelativebase()) { this.baseURL = f.getParentFile().toURI().toURL() .toExternalForm(); } if (this.baseURL == null) { this.baseURL = fs.getDir(task.getProject()).toURI().toURL() .toExternalForm(); } } catch (Exception e) { task.log("Error setting base URL", Project.MSG_DEBUG); } // Render if "force" flag is set OR // OR output file doesn't exist OR // output file is older than input file if (task.getForce() || !outf.exists() || (f.lastModified() > outf.lastModified() )) { if (xsltFile != null) { render(f, xsltFile, outf, outputFormat); } else { render(f, outf, outputFormat); } actioncount++; } else if (outf.exists() && (f.lastModified() <= outf.lastModified() )) { skippedcount++; } } } if (actioncount + skippedcount == 0) { task.log("No files processed. No files were selected by the filesets " + "and no fofile was set." , Project.MSG_WARN); } else if (skippedcount > 0) { task.log(skippedcount + " xslfo file(s) skipped (no change found" + " since last generation; set force=\"true\" to override)." , Project.MSG_INFO); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
private void render(File foFile, File outFile, String outputFormat) throws FOPException { InputHandler inputHandler = new InputHandler(foFile); try { renderInputHandler(inputHandler, outFile, outputFormat); } catch (Exception ex) { logger.error("Error rendering fo file: " + foFile, ex); } if (task.getLogFiles()) { task.log(foFile + " -> " + outFile, Project.MSG_INFO); } }
// in src/java/org/apache/fop/servlet/FopPrintServlet.java
protected void render(Source src, Transformer transformer, HttpServletResponse response) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_FOP_PRINT, foUserAgent); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer.transform(src, res); //Return the result reportOK(response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void renderFO(String fo, HttpServletResponse response) throws FOPException, TransformerException, IOException { //Setup source Source foSrc = convertString2Source(fo); //Setup the identity transformation Transformer transformer = this.transFactory.newTransformer(); transformer.setURIResolver(this.uriResolver); //Start transformation and rendering process render(foSrc, transformer, response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void renderXML(String xml, String xslt, HttpServletResponse response) throws FOPException, TransformerException, IOException { //Setup sources Source xmlSrc = convertString2Source(xml); Source xsltSrc = convertString2Source(xslt); //Setup the XSL transformation Transformer transformer = this.transFactory.newTransformer(xsltSrc); transformer.setURIResolver(this.uriResolver); //Start transformation and rendering process render(xmlSrc, transformer, response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void render(Source src, Transformer transformer, HttpServletResponse response) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(); //Setup output ByteArrayOutputStream out = new ByteArrayOutputStream(); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer.transform(src, res); //Return the result sendPDF(out.toByteArray(), response); }
// in src/java/org/apache/fop/fo/UnknownXMLObj.java
protected void characters(char[] data, int start, int length, PropertyList pList, Locator locator) throws FOPException { if (doc == null) { createBasicDocument(); } super.characters(data, start, length, pList, locator); }
// in src/java/org/apache/fop/fo/XMLObj.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { setLocator(locator); name = elementName; attr = attlist; }
// in src/java/org/apache/fop/fo/XMLObj.java
protected void characters(char[] data, int start, int length, PropertyList pList, Locator locator) throws FOPException { super.characters(data, start, length, pList, locator); String str = new String(data, start, length); org.w3c.dom.Text text = doc.createTextNode(str); element.appendChild(text); }
// in src/java/org/apache/fop/fo/FObjMixed.java
Override protected void characters(char[] data, int start, int length, PropertyList pList, Locator locator) throws FOPException { if (ft == null) { ft = new FOText(this); ft.setLocator(locator); if (!inMarker()) { ft.bind(pList); } } ft.characters(data, start, length, null, null); }
// in src/java/org/apache/fop/fo/FObjMixed.java
Override protected void endOfNode() throws FOPException { super.endOfNode(); if (!inMarker() || getNameId() == FO_MARKER) { // send character[s]() events to the FOEventHandler sendCharacters(); } }
// in src/java/org/apache/fop/fo/FObjMixed.java
private void flushText() throws FOPException { if (ft != null) { FOText lft = ft; /* make sure nested calls to itself have no effect */ ft = null; if (getNameId() == FO_BLOCK) { lft.createBlockPointers((org.apache.fop.fo.flow.Block) this); this.lastFOTextProcessed = lft; } else if (getNameId() != FO_MARKER && getNameId() != FO_TITLE && getNameId() != FO_BOOKMARK_TITLE) { FONode fo = parent; int foNameId = fo.getNameId(); while (foNameId != FO_BLOCK && foNameId != FO_MARKER && foNameId != FO_TITLE && foNameId != FO_BOOKMARK_TITLE && foNameId != FO_PAGE_SEQUENCE) { fo = fo.getParent(); foNameId = fo.getNameId(); } if (foNameId == FO_BLOCK) { lft.createBlockPointers((org.apache.fop.fo.flow.Block) fo); ((FObjMixed) fo).lastFOTextProcessed = lft; } else if (foNameId == FO_PAGE_SEQUENCE && lft.willCreateArea()) { log.error("Could not create block pointers." + " FOText w/o Block ancestor."); } } this.addChildNode(lft); } }
// in src/java/org/apache/fop/fo/FObjMixed.java
private void sendCharacters() throws FOPException { if (this.currentTextNode != null) { FONodeIterator nodeIter = this.getChildNodes(this.currentTextNode); FONode node; while (nodeIter.hasNext()) { node = nodeIter.nextNode(); assert (node instanceof FOText || node.getNameId() == FO_CHARACTER); if (node.getNameId() == FO_CHARACTER) { node.startOfNode(); } node.endOfNode(); } } this.currentTextNode = null; }
// in src/java/org/apache/fop/fo/FObjMixed.java
Override protected void addChildNode(FONode child) throws FOPException { flushText(); if (!inMarker()) { if (child instanceof FOText || child.getNameId() == FO_CHARACTER) { if (this.currentTextNode == null) { this.currentTextNode = child; } } else { // handle white-space for all text up to here handleWhiteSpaceFor(this, child); // send character[s]() events to the FOEventHandler sendCharacters(); } } super.addChildNode(child); }
// in src/java/org/apache/fop/fo/FObjMixed.java
Override public void finalizeNode() throws FOPException { flushText(); if (!inMarker() || getNameId() == FO_MARKER) { handleWhiteSpaceFor(this, null); } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void characters(char[] data, int start, int length) throws FOPException { if (currentFObj != null) { currentFObj.characters(data, start, length, currentPropertyList, getEffectiveLocator()); } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
private Maker findFOMaker(String namespaceURI, String localName) throws FOPException { Maker maker = elementMappingRegistry.findFOMaker(namespaceURI, localName, locator); if (maker instanceof UnknownXMLObj.Maker) { FOValidationEventProducer eventProducer = FOValidationEventProducer.Provider.get( userAgent.getEventBroadcaster()); String name = (currentFObj != null ? currentFObj.getName() : "{" + namespaceURI + "}" + localName); eventProducer.unknownFormattingObject(this, name, new QName(namespaceURI, localName), getEffectiveLocator()); } return maker; }
// in src/java/org/apache/fop/fo/flow/AbstractListItemPart.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); }
// in src/java/org/apache/fop/fo/flow/AbstractListItemPart.java
protected void endOfNode() throws FOPException { if (!this.blockItemFound) { String contentModel = "marker* (%block;)+"; getFOValidationEventProducer().missingChildElement(this, getName(), contentModel, true, getLocator()); } }
// in src/java/org/apache/fop/fo/flow/ListItemBody.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startListBody(this); }
// in src/java/org/apache/fop/fo/flow/ListItemBody.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endListBody(this); }
// in src/java/org/apache/fop/fo/flow/ListItemLabel.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startListLabel(this); }
// in src/java/org/apache/fop/fo/flow/ListItemLabel.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endListLabel(this); }
// in src/java/org/apache/fop/fo/flow/ListItem.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonMarginBlock = pList.getMarginBlockProps(); breakAfter = pList.get(PR_BREAK_AFTER).getEnum(); breakBefore = pList.get(PR_BREAK_BEFORE).getEnum(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); }
// in src/java/org/apache/fop/fo/flow/ListItem.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startListItem(this); }
// in src/java/org/apache/fop/fo/flow/ListItem.java
protected void endOfNode() throws FOPException { if (label == null || body == null) { missingChildElementError("marker* (list-item-label,list-item-body)"); } getFOEventHandler().endListItem(this); }
// in src/java/org/apache/fop/fo/flow/RetrieveTableMarker.java
public void processNode (String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { if (findAncestor(FO_TABLE_HEADER) < 0 && findAncestor(FO_TABLE_FOOTER) < 0) { invalidChildError(locator, getParent().getName(), FO_URI, getName(), "rule.retrieveTableMarkerDescendantOfHeaderOrFooter"); } else { super.processNode(elementName, locator, attlist, pList); } }
// in src/java/org/apache/fop/fo/flow/RetrieveTableMarker.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); this.retrievePositionWithinTable = pList.get(PR_RETRIEVE_POSITION_WITHIN_TABLE).getEnum(); this.retrieveBoundaryWithinTable = pList.get(PR_RETRIEVE_BOUNDARY_WITHIN_TABLE).getEnum(); }
// in src/java/org/apache/fop/fo/flow/Float.java
public void bind(PropertyList pList) throws FOPException { // No active properties -> Nothing to do. }
// in src/java/org/apache/fop/fo/flow/Float.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("(%block;)+"); } }
// in src/java/org/apache/fop/fo/flow/PageNumber.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonFont = pList.getFontProps(); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); // letterSpacing = pList.get(PR_LETTER_SPACING); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); textDecoration = pList.getTextDecorationProps(); // textShadow = pList.get(PR_TEXT_SHADOW); // implicit properties color = pList.get(Constants.PR_COLOR).getColor(getUserAgent()); }
// in src/java/org/apache/fop/fo/flow/PageNumber.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startPageNumber(this); }
// in src/java/org/apache/fop/fo/flow/PageNumber.java
protected void endOfNode() throws FOPException { getFOEventHandler().endPageNumber(this); }
// in src/java/org/apache/fop/fo/flow/Wrapper.java
Override public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/flow/Wrapper.java
Override protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startWrapper(this); }
// in src/java/org/apache/fop/fo/flow/Wrapper.java
Override protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endWrapper(this); }
// in src/java/org/apache/fop/fo/flow/Wrapper.java
protected void addChildNode(FONode child) throws FOPException { super.addChildNode(child); /* If the child is a text node, and it generates areas * (i.e. contains either non-white-space or preserved * white-space), then check whether the nearest non-wrapper * ancestor allows this. */ if (child instanceof FOText && ((FOText)child).willCreateArea()) { FONode ancestor = parent; while (ancestor.getNameId() == Constants.FO_WRAPPER) { ancestor = ancestor.getParent(); } if (!(ancestor instanceof FObjMixed)) { invalidChildError( getLocator(), getLocalName(), FONode.FO_URI, "#PCDATA", "rule.wrapperInvalidChildForParent"); } } }
// in src/java/org/apache/fop/fo/flow/PageNumberCitationLast.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startPageNumberCitationLast(this); }
// in src/java/org/apache/fop/fo/flow/PageNumberCitationLast.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endPageNumberCitationLast(this); }
// in src/java/org/apache/fop/fo/flow/InlineContainer.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonMarginInline = pList.getMarginInlineProps(); clip = pList.get(PR_CLIP).getEnum(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); inlineProgressionDimension = pList.get(PR_INLINE_PROGRESSION_DIMENSION).getLengthRange(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); overflow = pList.get(PR_OVERFLOW).getEnum(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); writingModeTraits = new WritingModeTraits ( WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()) ); }
// in src/java/org/apache/fop/fo/flow/InlineContainer.java
protected void endOfNode() throws FOPException { if (!blockItemFound) { missingChildElementError("marker* (%block;)+"); } }
// in src/java/org/apache/fop/fo/flow/InlineLevel.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonMarginInline = pList.getMarginInlineProps(); commonFont = pList.getFontProps(); color = pList.get(PR_COLOR).getColor(getUserAgent()); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); }
// in src/java/org/apache/fop/fo/flow/MultiCase.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); startingState = pList.get(PR_STARTING_STATE).getEnum(); // caseName = pList.get(PR_CASE_NAME); // caseTitle = pList.get(PR_CASE_TITLE); }
// in src/java/org/apache/fop/fo/flow/BasicLink.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); // destinationPlacementOffset = pList.get(PR_DESTINATION_PLACEMENT_OFFSET); externalDestination = pList.get(PR_EXTERNAL_DESTINATION).getString(); // indicateDestination = pList.get(PR_INDICATE_DESTINATION); internalDestination = pList.get(PR_INTERNAL_DESTINATION).getString(); showDestination = pList.get(PR_SHOW_DESTINATION).getEnum(); // targetProcessingContext = pList.get(PR_TARGET_PROCESSING_CONTEXT); // targetPresentationContext = pList.get(PR_TARGET_PRESENTATION_CONTEXT); // targetStylesheet = pList.get(PR_TARGET_STYLESHEET); // per spec, internal takes precedence if both specified if (internalDestination.length() > 0) { externalDestination = null; } else if (externalDestination.length() == 0) { // slightly stronger than spec "should be specified" getFOValidationEventProducer().missingLinkDestination(this, getName(), locator); } }
// in src/java/org/apache/fop/fo/flow/BasicLink.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startLink(this); }
// in src/java/org/apache/fop/fo/flow/BasicLink.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endLink(this); }
// in src/java/org/apache/fop/fo/flow/FootnoteBody.java
public void bind(PropertyList pList) throws FOPException { commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/flow/FootnoteBody.java
protected void startOfNode() throws FOPException { getFOEventHandler().startFootnoteBody(this); }
// in src/java/org/apache/fop/fo/flow/FootnoteBody.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("(%block;)+"); } getFOEventHandler().endFootnoteBody(this); }
// in src/java/org/apache/fop/fo/flow/Leader.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); }
// in src/java/org/apache/fop/fo/flow/Leader.java
Override protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startLeader(this); }
// in src/java/org/apache/fop/fo/flow/Leader.java
Override protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endLeader(this); }
// in src/java/org/apache/fop/fo/flow/InitialPropertySet.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); // letterSpacing = pList.get(PR_LETTER_SPACING); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); // textShadow = pList.get(PR_TEXT_SHADOW); }
// in src/java/org/apache/fop/fo/flow/AbstractPageNumberCitation.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonFont = pList.getFontProps(); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); // letterSpacing = pList.get(PR_LETTER_SPACING); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); refId = pList.get(PR_REF_ID).getString(); textDecoration = pList.getTextDecorationProps(); // textShadow = pList.get(PR_TEXT_SHADOW); // implicit properties color = pList.get(Constants.PR_COLOR).getColor(getUserAgent()); }
// in src/java/org/apache/fop/fo/flow/AbstractPageNumberCitation.java
public void processNode (String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { super.processNode(elementName, locator, attlist, pList); if (!inMarker() && (refId == null || "".equals(refId))) { missingPropertyError("ref-id"); } }
// in src/java/org/apache/fop/fo/flow/ListBlock.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonMarginBlock = pList.getMarginBlockProps(); breakAfter = pList.get(PR_BREAK_AFTER).getEnum(); breakBefore = pList.get(PR_BREAK_BEFORE).getEnum(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); //Bind extension properties widowContentLimit = pList.get(PR_X_WIDOW_CONTENT_LIMIT).getLength(); orphanContentLimit = pList.get(PR_X_ORPHAN_CONTENT_LIMIT).getLength(); }
// in src/java/org/apache/fop/fo/flow/ListBlock.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startList(this); }
// in src/java/org/apache/fop/fo/flow/ListBlock.java
protected void endOfNode() throws FOPException { if (!hasListItem) { missingChildElementError("marker* (list-item)+"); } getFOEventHandler().endList(this); }
// in src/java/org/apache/fop/fo/flow/Inline.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); }
// in src/java/org/apache/fop/fo/flow/Inline.java
protected void startOfNode() throws FOPException { super.startOfNode(); /* Check to see if this node can have block-level children. * See validateChildNode() below. */ int lvlLeader = findAncestor(FO_LEADER); int lvlFootnote = findAncestor(FO_FOOTNOTE); int lvlInCntr = findAncestor(FO_INLINE_CONTAINER); if (lvlLeader > 0) { if (lvlInCntr < 0 || (lvlInCntr > 0 && lvlInCntr > lvlLeader)) { canHaveBlockLevelChildren = false; } } else if (lvlFootnote > 0) { if (lvlInCntr < 0 || lvlInCntr > lvlFootnote) { canHaveBlockLevelChildren = false; } } getFOEventHandler().startInline(this); }
// in src/java/org/apache/fop/fo/flow/Inline.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endInline(this); }
// in src/java/org/apache/fop/fo/flow/MultiToggle.java
public void bind(PropertyList pList) throws FOPException { // prSwitchTo = pList.get(PR_SWITCH_TO); }
// in src/java/org/apache/fop/fo/flow/InstreamForeignObject.java
Override protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startInstreamForeignObject(this); }
// in src/java/org/apache/fop/fo/flow/InstreamForeignObject.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("one (1) non-XSL namespace child"); } getFOEventHandler().endInstreamForeignObject(this); }
// in src/java/org/apache/fop/fo/flow/InstreamForeignObject.java
protected void addChildNode(FONode child) throws FOPException { super.addChildNode(child); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); src = pList.get(PR_SRC).getString(); //Additional processing: obtain the image's intrinsic size and baseline information url = URISpecification.getURL(src); FOUserAgent userAgent = getUserAgent(); ImageManager manager = userAgent.getFactory().getImageManager(); ImageInfo info = null; try { info = manager.getImageInfo(url, userAgent.getImageSessionContext()); } catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, url, e, getLocator()); } catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, url, fnfe, getLocator()); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, url, ioe, getLocator()); } if (info != null) { this.intrinsicWidth = info.getSize().getWidthMpt(); this.intrinsicHeight = info.getSize().getHeightMpt(); int baseline = info.getSize().getBaselinePositionFromBottom(); if (baseline != 0) { this.intrinsicAlignmentAdjust = FixedLength.getInstance(-baseline); } } }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().image(this); }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); this.retrieveClassName = pList.get(PR_RETRIEVE_CLASS_NAME).getString(); if (retrieveClassName == null || retrieveClassName.equals("")) { missingPropertyError("retrieve-class-name"); } this.propertyList = pList.getParentPropertyList(); }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
private void cloneSingleNode(FONode child, FONode newParent, Marker marker, PropertyList parentPropertyList) throws FOPException { if (child != null) { FONode newChild = child.clone(newParent, true); if (child instanceof FObj) { Marker.MarkerPropertyList pList; PropertyList newPropertyList = createPropertyListFor( (FObj) newChild, parentPropertyList); pList = marker.getPropertyListFor(child); newChild.processNode( child.getLocalName(), getLocator(), pList, newPropertyList); addChildTo(newChild, newParent); switch ( newChild.getNameId() ) { case FO_TABLE: Table t = (Table) child; cloneSubtree(t.getColumns().iterator(), newChild, marker, newPropertyList); cloneSingleNode(t.getTableHeader(), newChild, marker, newPropertyList); cloneSingleNode(t.getTableFooter(), newChild, marker, newPropertyList); cloneSubtree(child.getChildNodes(), newChild, marker, newPropertyList); break; case FO_LIST_ITEM: ListItem li = (ListItem) child; cloneSingleNode(li.getLabel(), newChild, marker, newPropertyList); cloneSingleNode(li.getBody(), newChild, marker, newPropertyList); break; default: cloneSubtree(child.getChildNodes(), newChild, marker, newPropertyList); break; } } else if (child instanceof FOText) { FOText ft = (FOText) newChild; ft.bind(parentPropertyList); addChildTo(newChild, newParent); } else if (child instanceof XMLObj) { addChildTo(newChild, newParent); } // trigger end-of-node white-space handling // and finalization for table-FOs newChild.finalizeNode(); } }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
private void cloneSubtree(Iterator parentIter, FONode newParent, Marker marker, PropertyList parentPropertyList) throws FOPException { if (parentIter != null) { FONode child; while (parentIter.hasNext()) { child = (FONode) parentIter.next(); cloneSingleNode(child, newParent, marker, parentPropertyList); } } }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
private void cloneFromMarker(Marker marker) throws FOPException { cloneSubtree(marker.getChildNodes(), this, marker, propertyList); handleWhiteSpaceFor(this, null); }
// in src/java/org/apache/fop/fo/flow/MultiProperties.java
protected void endOfNode() throws FOPException { if (!hasMultiPropertySet || !hasWrapper) { missingChildElementError("(multi-property-set+, wrapper)"); } }
// in src/java/org/apache/fop/fo/flow/PageNumberCitation.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startPageNumberCitation(this); }
// in src/java/org/apache/fop/fo/flow/PageNumberCitation.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endPageNumberCitation(this); }
// in src/java/org/apache/fop/fo/flow/BlockContainer.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAbsolutePosition = pList.getAbsolutePositionProps(); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonMarginBlock = pList.getMarginBlockProps(); blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); breakAfter = pList.get(PR_BREAK_AFTER).getEnum(); breakBefore = pList.get(PR_BREAK_BEFORE).getEnum(); // clip = pList.get(PR_CLIP); displayAlign = pList.get(PR_DISPLAY_ALIGN).getEnum(); inlineProgressionDimension = pList.get(PR_INLINE_PROGRESSION_DIMENSION).getLengthRange(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); overflow = pList.get(PR_OVERFLOW).getEnum(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); span = pList.get(PR_SPAN).getEnum(); writingModeTraits = new WritingModeTraits ( WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()) ); disableColumnBalancing = pList.get(PR_X_DISABLE_COLUMN_BALANCING).getEnum(); }
// in src/java/org/apache/fop/fo/flow/BlockContainer.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startBlockContainer(this); }
// in src/java/org/apache/fop/fo/flow/BlockContainer.java
protected void endOfNode() throws FOPException { if (!blockItemFound) { missingChildElementError("marker* (%block;)+"); } getFOEventHandler().endBlockContainer(this); }
// in src/java/org/apache/fop/fo/flow/BidiOverride.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); letterSpacing = pList.get(PR_LETTER_SPACING); wordSpacing = pList.get(PR_WORD_SPACING); direction = pList.get(PR_DIRECTION).getEnum(); unicodeBidi = pList.get(PR_UNICODE_BIDI).getEnum(); }
// in src/java/org/apache/fop/fo/flow/AbstractGraphics.java
public void bind(PropertyList pList) throws FOPException { commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); // clip = pList.get(PR_CLIP); contentHeight = pList.get(PR_CONTENT_HEIGHT).getLength(); contentWidth = pList.get(PR_CONTENT_WIDTH).getLength(); displayAlign = pList.get(PR_DISPLAY_ALIGN).getEnum(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); height = pList.get(PR_HEIGHT).getLength(); id = pList.get(PR_ID).getString(); inlineProgressionDimension = pList.get(PR_INLINE_PROGRESSION_DIMENSION).getLengthRange(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); overflow = pList.get(PR_OVERFLOW).getEnum(); scaling = pList.get(PR_SCALING).getEnum(); textAlign = pList.get(PR_TEXT_ALIGN).getEnum(); width = pList.get(PR_WIDTH).getLength(); if (getUserAgent().isAccessibilityEnabled()) { altText = pList.get(PR_X_ALT_TEXT).getString(); if (altText.equals("")) { getFOValidationEventProducer().altTextMissing(this, getLocalName(), getLocator()); } } }
// in src/java/org/apache/fop/fo/flow/MultiPropertySet.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); // activeState = pList.get(PR_ACTIVE_STATE); }
// in src/java/org/apache/fop/fo/flow/RetrieveMarker.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { if (findAncestor(FO_STATIC_CONTENT) < 0) { invalidChildError(locator, getParent().getName(), FO_URI, getLocalName(), "rule.retrieveMarkerDescendantOfStaticContent"); } else { super.processNode(elementName, locator, attlist, pList); } }
// in src/java/org/apache/fop/fo/flow/RetrieveMarker.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); this.retrievePosition = pList.get(PR_RETRIEVE_POSITION).getEnum(); this.retrieveBoundary = pList.get(PR_RETRIEVE_BOUNDARY).getEnum(); }
// in src/java/org/apache/fop/fo/flow/Character.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonFont = pList.getFontProps(); commonHyphenation = pList.getHyphenationProps(); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); character = pList.get(PR_CHARACTER).getCharacter(); color = pList.get(PR_COLOR).getColor(getUserAgent()); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); letterSpacing = pList.get(PR_LETTER_SPACING); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); textDecoration = pList.getTextDecorationProps(); wordSpacing = pList.get(PR_WORD_SPACING); }
// in src/java/org/apache/fop/fo/flow/Character.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().character(this); }
// in src/java/org/apache/fop/fo/flow/Footnote.java
public void bind(PropertyList pList) throws FOPException { commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/flow/Footnote.java
protected void startOfNode() throws FOPException { getFOEventHandler().startFootnote(this); }
// in src/java/org/apache/fop/fo/flow/Footnote.java
protected void endOfNode() throws FOPException { super.endOfNode(); if (footnoteCitation == null || footnoteBody == null) { missingChildElementError("(inline,footnote-body)"); } getFOEventHandler().endFootnote(this); }
// in src/java/org/apache/fop/fo/flow/Marker.java
public void bind(PropertyList pList) throws FOPException { if (findAncestor(FO_FLOW) < 0) { invalidChildError(locator, getParent().getName(), FO_URI, getLocalName(), "rule.markerDescendantOfFlow"); } markerClassName = pList.get(PR_MARKER_CLASS_NAME).getString(); if (markerClassName == null || markerClassName.equals("")) { missingPropertyError("marker-class-name"); } }
// in src/java/org/apache/fop/fo/flow/Marker.java
protected void endOfNode() throws FOPException { super.endOfNode(); // Pop the MarkerPropertyList maker. getBuilderContext().setPropertyListMaker(savePropertyListMaker); savePropertyListMaker = null; }
// in src/java/org/apache/fop/fo/flow/Block.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonFont = pList.getFontProps(); commonHyphenation = pList.getHyphenationProps(); commonMarginBlock = pList.getMarginBlockProps(); commonRelativePosition = pList.getRelativePositionProps(); breakAfter = pList.get(PR_BREAK_AFTER).getEnum(); breakBefore = pList.get(PR_BREAK_BEFORE).getEnum(); color = pList.get(PR_COLOR).getColor(getUserAgent()); hyphenationKeep = pList.get(PR_HYPHENATION_KEEP).getEnum(); hyphenationLadderCount = pList.get(PR_HYPHENATION_LADDER_COUNT).getNumeric(); intrusionDisplace = pList.get(PR_INTRUSION_DISPLACE).getEnum(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); lastLineEndIndent = pList.get(PR_LAST_LINE_END_INDENT).getLength(); linefeedTreatment = pList.get(PR_LINEFEED_TREATMENT).getEnum(); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); lineHeightShiftAdjustment = pList.get(PR_LINE_HEIGHT_SHIFT_ADJUSTMENT).getEnum(); lineStackingStrategy = pList.get(PR_LINE_STACKING_STRATEGY).getEnum(); orphans = pList.get(PR_ORPHANS).getNumeric(); whiteSpaceTreatment = pList.get(PR_WHITE_SPACE_TREATMENT).getEnum(); span = pList.get(PR_SPAN).getEnum(); textAlign = pList.get(PR_TEXT_ALIGN).getEnum(); textAlignLast = pList.get(PR_TEXT_ALIGN_LAST).getEnum(); textIndent = pList.get(PR_TEXT_INDENT).getLength(); whiteSpaceCollapse = pList.get(PR_WHITE_SPACE_COLLAPSE).getEnum(); widows = pList.get(PR_WIDOWS).getNumeric(); wrapOption = pList.get(PR_WRAP_OPTION).getEnum(); disableColumnBalancing = pList.get(PR_X_DISABLE_COLUMN_BALANCING).getEnum(); }
// in src/java/org/apache/fop/fo/flow/Block.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startBlock(this); }
// in src/java/org/apache/fop/fo/flow/Block.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endBlock(this); }
// in src/java/org/apache/fop/fo/flow/table/TableCellContainer.java
Override public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/flow/table/TableCellContainer.java
protected void addTableCellChild(TableCell cell, boolean firstRow) throws FOPException { int colNumber = cell.getColumnNumber(); int colSpan = cell.getNumberColumnsSpanned(); int rowSpan = cell.getNumberRowsSpanned(); Table t = getTable(); if (t.hasExplicitColumns()) { if (colNumber + colSpan - 1 > t.getNumberOfColumns()) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.tooManyCells(this, getLocator()); } } else { t.ensureColumnNumber(colNumber + colSpan - 1); // re-cap the size of pendingSpans while (pendingSpans.size() < colNumber + colSpan - 1) { pendingSpans.add(null); } } if (firstRow) { handleCellWidth(cell, colNumber, colSpan); } /* if the current cell spans more than one row, * update pending span list for the next row */ if (rowSpan > 1) { for (int i = 0; i < colSpan; i++) { pendingSpans.set(colNumber - 1 + i, new PendingSpan(rowSpan)); } } columnNumberManager.signalUsedColumnNumbers(colNumber, colNumber + colSpan - 1); t.getRowGroupBuilder().addTableCell(cell); }
// in src/java/org/apache/fop/fo/flow/table/TableCellContainer.java
private void handleCellWidth(TableCell cell, int colNumber, int colSpan) throws FOPException { Table t = getTable(); Length colWidth = null; if (cell.getWidth().getEnum() != EN_AUTO && colSpan == 1) { colWidth = cell.getWidth(); } for (int i = colNumber; i < colNumber + colSpan; ++i) { TableColumn col = t.getColumn(i - 1); if (colWidth != null) { col.setColumnWidth(colWidth); } } }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
public void bind(PropertyList pList) throws FOPException { blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); breakAfter = pList.get(PR_BREAK_AFTER).getEnum(); breakBefore = pList.get(PR_BREAK_BEFORE).getEnum(); height = pList.get(PR_HEIGHT).getLength(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); super.bind(pList); }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { super.processNode(elementName, locator, attlist, pList); if (!inMarker()) { TablePart part = (TablePart) parent; pendingSpans = part.pendingSpans; columnNumberManager = part.columnNumberManager; } }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
protected void addChildNode(FONode child) throws FOPException { if (!inMarker()) { TableCell cell = (TableCell) child; TablePart part = (TablePart) getParent(); addTableCellChild(cell, part.isFirst(this)); } super.addChildNode(child); }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startRow(this); }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endRow(this); }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
public void finalizeNode() throws FOPException { if (firstChild == null) { missingChildElementError("(table-cell+)"); } if (!inMarker()) { pendingSpans = null; columnNumberManager = null; } }
// in src/java/org/apache/fop/fo/flow/table/TableFooter.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startFooter(this); }
// in src/java/org/apache/fop/fo/flow/table/TableFooter.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endFooter(this); }
// in src/java/org/apache/fop/fo/flow/table/TableCell.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); displayAlign = pList.get(PR_DISPLAY_ALIGN).getEnum(); emptyCells = pList.get(PR_EMPTY_CELLS).getEnum(); startsRow = pList.get(PR_STARTS_ROW).getEnum(); // For properly computing columnNumber if (startsRow() && getParent().getNameId() != FO_TABLE_ROW) { ((TablePart) getParent()).signalNewRow(); } endsRow = pList.get(PR_ENDS_ROW).getEnum(); columnNumber = pList.get(PR_COLUMN_NUMBER).getNumeric().getValue(); numberColumnsSpanned = pList.get(PR_NUMBER_COLUMNS_SPANNED).getNumeric().getValue(); numberRowsSpanned = pList.get(PR_NUMBER_ROWS_SPANNED).getNumeric().getValue(); width = pList.get(PR_WIDTH).getLength(); }
// in src/java/org/apache/fop/fo/flow/table/TableCell.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startCell(this); }
// in src/java/org/apache/fop/fo/flow/table/TableCell.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endCell(this); }
// in src/java/org/apache/fop/fo/flow/table/TableCell.java
public void finalizeNode() throws FOPException { if (!blockItemFound) { missingChildElementError("marker* (%block;)+", true); } if ((startsRow() || endsRow()) && getParent().getNameId() == FO_TABLE_ROW ) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.startEndRowUnderTableRowWarning(this, getLocator()); } }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
public void bind(PropertyList pList) throws FOPException { commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); super.bind(pList); }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { super.processNode(elementName, locator, attlist, pList); if (!inMarker()) { Table t = getTable(); if (t.hasExplicitColumns()) { int size = t.getNumberOfColumns(); pendingSpans = new ArrayList(size); for (int i = 0; i < size; i++) { pendingSpans.add(null); } } else { pendingSpans = new ArrayList(); } columnNumberManager = new ColumnNumberManager(); } }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
public void finalizeNode() throws FOPException { if (!inMarker()) { pendingSpans = null; columnNumberManager = null; } if (!(tableRowsFound || tableCellsFound)) { missingChildElementError("marker* (table-row+|table-cell+)", true); getParent().removeChild(this); } else { finishLastRowGroup(); } }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
protected void addChildNode(FONode child) throws FOPException { if (!inMarker()) { switch (child.getNameId()) { case FO_TABLE_ROW: if (!rowsStarted) { getTable().getRowGroupBuilder().startTablePart(this); } else { columnNumberManager.prepareForNextRow(pendingSpans); getTable().getRowGroupBuilder().endTableRow(); } rowsStarted = true; getTable().getRowGroupBuilder().startTableRow((TableRow)child); break; case FO_TABLE_CELL: if (!rowsStarted) { getTable().getRowGroupBuilder().startTablePart(this); } rowsStarted = true; TableCell cell = (TableCell) child; addTableCellChild(cell, firstRow); lastCellEndsRow = cell.endsRow(); if (lastCellEndsRow) { firstRow = false; columnNumberManager.prepareForNextRow(pendingSpans); getTable().getRowGroupBuilder().endRow(this); } break; default: //nop } } //TODO: possible performance problems in case of large tables... //If the number of children grows significantly large, the default //implementation in FObj will get slower and slower... super.addChildNode(child); }
// in src/java/org/apache/fop/fo/flow/table/TableColumn.java
public void bind(PropertyList pList) throws FOPException { commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); columnNumber = pList.get(PR_COLUMN_NUMBER).getNumeric().getValue(); columnWidth = pList.get(PR_COLUMN_WIDTH).getLength(); numberColumnsRepeated = pList.get(PR_NUMBER_COLUMNS_REPEATED) .getNumeric().getValue(); numberColumnsSpanned = pList.get(PR_NUMBER_COLUMNS_SPANNED) .getNumeric().getValue(); super.bind(pList); if (numberColumnsRepeated <= 0) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.valueMustBeBiggerGtEqOne(this, "number-columns-repeated", numberColumnsRepeated, getLocator()); } if (numberColumnsSpanned <= 0) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.valueMustBeBiggerGtEqOne(this, "number-columns-spanned", numberColumnsSpanned, getLocator()); } /* check for unspecified width and replace with default of * proportional-column-width(1), in case of fixed table-layout * warn only for explicit columns */ if (columnWidth.getEnum() == EN_AUTO) { if (!this.implicitColumn && !getTable().isAutoLayout()) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.warnImplicitColumns(this, getLocator()); } columnWidth = new TableColLength(1.0, this); } /* in case of explicit columns, from-table-column() * can be used on descendants of the table-cells, so * we need a reference to the column's property list * (cleared in Table.endOfNode()) */ if (!this.implicitColumn) { this.pList = pList; } }
// in src/java/org/apache/fop/fo/flow/table/TableColumn.java
public void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startColumn(this); }
// in src/java/org/apache/fop/fo/flow/table/TableColumn.java
public void endOfNode() throws FOPException { getFOEventHandler().endColumn(this); }
// in src/java/org/apache/fop/fo/flow/table/TableCaption.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/flow/table/TableCaption.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("marker* (%block;)"); } }
// in src/java/org/apache/fop/fo/flow/table/TableFObj.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); borderAfterPrecedence = pList.get(PR_BORDER_AFTER_PRECEDENCE).getNumeric(); borderBeforePrecedence = pList.get(PR_BORDER_BEFORE_PRECEDENCE).getNumeric(); borderEndPrecedence = pList.get(PR_BORDER_END_PRECEDENCE).getNumeric(); borderStartPrecedence = pList.get(PR_BORDER_START_PRECEDENCE).getNumeric(); if (getNameId() != FO_TABLE //Separate check for fo:table in Table.java && getNameId() != FO_TABLE_CELL && getCommonBorderPaddingBackground().hasPadding( ValidationPercentBaseContext.getPseudoContext())) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.paddingNotApplicable(this, getName(), getLocator()); } }
// in src/java/org/apache/fop/fo/flow/table/TableFObj.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { super.processNode(elementName, locator, attlist, pList); Table table = getTable(); if (!inMarker() && !table.isSeparateBorderModel()) { collapsingBorderModel = CollapsingBorderModel.getBorderModelFor(table .getBorderCollapse()); setCollapsedBorders(); } }
// in src/java/org/apache/fop/fo/flow/table/TableBody.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startBody(this); }
// in src/java/org/apache/fop/fo/flow/table/TableBody.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endBody(this); }
// in src/java/org/apache/fop/fo/flow/table/Table.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonMarginBlock = pList.getMarginBlockProps(); blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); borderCollapse = pList.get(PR_BORDER_COLLAPSE).getEnum(); borderSeparation = pList.get(PR_BORDER_SEPARATION).getLengthPair(); breakAfter = pList.get(PR_BREAK_AFTER).getEnum(); breakBefore = pList.get(PR_BREAK_BEFORE).getEnum(); inlineProgressionDimension = pList.get(PR_INLINE_PROGRESSION_DIMENSION).getLengthRange(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); tableLayout = pList.get(PR_TABLE_LAYOUT).getEnum(); tableOmitFooterAtBreak = pList.get(PR_TABLE_OMIT_FOOTER_AT_BREAK).getEnum(); tableOmitHeaderAtBreak = pList.get(PR_TABLE_OMIT_HEADER_AT_BREAK).getEnum(); writingModeTraits = new WritingModeTraits ( WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()) ); //Bind extension properties widowContentLimit = pList.get(PR_X_WIDOW_CONTENT_LIMIT).getLength(); orphanContentLimit = pList.get(PR_X_ORPHAN_CONTENT_LIMIT).getLength(); if (!blockProgressionDimension.getOptimum(null).isAuto()) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.nonAutoBPDOnTable(this, getLocator()); // Anyway, the bpd of a table is not used by the layout code } if (tableLayout == EN_AUTO) { getFOValidationEventProducer().unimplementedFeature(this, getName(), "table-layout=\"auto\"", getLocator()); } if (!isSeparateBorderModel()) { if (borderCollapse == EN_COLLAPSE_WITH_PRECEDENCE) { getFOValidationEventProducer().unimplementedFeature(this, getName(), "border-collapse=\"collapse-with-precedence\"; defaulting to \"collapse\"", getLocator()); borderCollapse = EN_COLLAPSE; } if (getCommonBorderPaddingBackground().hasPadding( ValidationPercentBaseContext.getPseudoContext())) { //See "17.6.2 The collapsing border model" in CSS2 TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noTablePaddingWithCollapsingBorderModel(this, getLocator()); } } /* Store reference to the property list, so * new lists can be created in case the table has no * explicit columns * (see addDefaultColumn()) */ this.propList = pList; }
// in src/java/org/apache/fop/fo/flow/table/Table.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startTable(this); }
// in src/java/org/apache/fop/fo/flow/table/Table.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endTable(this); }
// in src/java/org/apache/fop/fo/flow/table/Table.java
public void finalizeNode() throws FOPException { if (!tableBodyFound) { missingChildElementError( "(marker*,table-column*,table-header?,table-footer?" + ",table-body+)"); } if (!hasChildren()) { getParent().removeChild(this); return; } if (!inMarker()) { rowGroupBuilder.endTable(); /* clean up */ for (int i = columns.size(); --i >= 0;) { TableColumn col = (TableColumn) columns.get(i); if (col != null) { col.releasePropertyList(); } } this.propList = null; rowGroupBuilder = null; } }
// in src/java/org/apache/fop/fo/flow/table/Table.java
protected void addChildNode(FONode child) throws FOPException { int childId = child.getNameId(); switch (childId) { case FO_TABLE_COLUMN: hasExplicitColumns = true; if (!inMarker()) { addColumnNode((TableColumn) child); } else { columns.add(child); } break; case FO_TABLE_HEADER: case FO_TABLE_FOOTER: case FO_TABLE_BODY: if (!inMarker() && !columnsFinalized) { columnsFinalized = true; if (hasExplicitColumns) { finalizeColumns(); rowGroupBuilder = new FixedColRowGroupBuilder(this); } else { rowGroupBuilder = new VariableColRowGroupBuilder(this); } } switch (childId) { case FO_TABLE_FOOTER: tableFooter = (TableFooter) child; break; case FO_TABLE_HEADER: tableHeader = (TableHeader) child; break; default: super.addChildNode(child); } break; default: super.addChildNode(child); } }
// in src/java/org/apache/fop/fo/flow/table/Table.java
private void finalizeColumns() throws FOPException { for (int i = 0; i < columns.size(); i++) { if (columns.get(i) == null) { columns.set(i, createImplicitColumn(i + 1)); } } }
// in src/java/org/apache/fop/fo/flow/table/Table.java
void ensureColumnNumber(int columnNumber) throws FOPException { assert !hasExplicitColumns; for (int i = columns.size() + 1; i <= columnNumber; i++) { columns.add(createImplicitColumn(i)); } }
// in src/java/org/apache/fop/fo/flow/table/Table.java
private TableColumn createImplicitColumn(int colNumber) throws FOPException { TableColumn implicitColumn = new TableColumn(this, true); PropertyList pList = new StaticPropertyList( implicitColumn, this.propList); implicitColumn.bind(pList); implicitColumn.setColumnWidth(new TableColLength(1.0, implicitColumn)); implicitColumn.setColumnNumber(colNumber); if (!isSeparateBorderModel()) { implicitColumn.setCollapsedBorders(collapsingBorderModel); // TODO } return implicitColumn; }
// in src/java/org/apache/fop/fo/flow/table/Table.java
public FONode clone(FONode parent, boolean removeChildren) throws FOPException { Table clone = (Table) super.clone(parent, removeChildren); if (removeChildren) { clone.columns = new ArrayList(); clone.columnsFinalized = false; clone.columnNumberManager = new ColumnNumberManager(); clone.tableHeader = null; clone.tableFooter = null; clone.rowGroupBuilder = null; } return clone; }
// in src/java/org/apache/fop/fo/flow/table/TableAndCaption.java
Override public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/flow/table/TableAndCaption.java
protected void endOfNode() throws FOPException { if (!tableFound) { missingChildElementError("marker* table-caption? table"); } }
// in src/java/org/apache/fop/fo/flow/table/TableHeader.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startHeader(this); }
// in src/java/org/apache/fop/fo/flow/table/TableHeader.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endHeader(this); }
// in src/java/org/apache/fop/fo/flow/MultiSwitch.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); // autoRestore = pList.get(PR_AUTO_RESTORE); }
// in src/java/org/apache/fop/fo/flow/MultiSwitch.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("(multi-case+)"); } }
// in src/java/org/apache/fop/fo/FOText.java
protected void characters(char[] data, int start, int length, PropertyList list, Locator locator) throws FOPException { if (charBuffer == null) { // buffer not yet initialized, do so now int newLength = ( length < 16 ) ? 16 : length; charBuffer = CharBuffer.allocate(newLength); } else { // allocate a larger buffer, and transfer contents int requires = charBuffer.position() + length; int capacity = charBuffer.capacity(); if ( requires > capacity ) { int newCapacity = capacity * 2; if ( requires > newCapacity ) { newCapacity = requires; } CharBuffer newBuffer = CharBuffer.allocate(newCapacity); charBuffer.rewind(); newBuffer.put(charBuffer); charBuffer = newBuffer; } } // extend limit to capacity charBuffer.limit(charBuffer.capacity()); // append characters charBuffer.put(data, start, length); // shrink limit to position charBuffer.limit(charBuffer.position()); }
// in src/java/org/apache/fop/fo/FOText.java
public FONode clone(FONode parent, boolean removeChildren) throws FOPException { FOText ft = (FOText) super.clone(parent, removeChildren); if (removeChildren) { // not really removing, just make sure the char buffer // pointed to is really a different one if (charBuffer != null) { ft.charBuffer = CharBuffer.allocate(charBuffer.limit()); charBuffer.rewind(); ft.charBuffer.put(charBuffer); ft.charBuffer.rewind(); } } ft.prevFOTextThisBlock = null; ft.nextFOTextThisBlock = null; ft.ancestorBlock = null; return ft; }
// in src/java/org/apache/fop/fo/FOText.java
public void bind(PropertyList pList) throws FOPException { this.commonFont = pList.getFontProps(); this.commonHyphenation = pList.getHyphenationProps(); this.color = pList.get(Constants.PR_COLOR).getColor(getUserAgent()); this.keepTogether = pList.get(Constants.PR_KEEP_TOGETHER).getKeep(); this.lineHeight = pList.get(Constants.PR_LINE_HEIGHT).getSpace(); this.letterSpacing = pList.get(Constants.PR_LETTER_SPACING); this.whiteSpaceCollapse = pList.get(Constants.PR_WHITE_SPACE_COLLAPSE).getEnum(); this.whiteSpaceTreatment = pList.get(Constants.PR_WHITE_SPACE_TREATMENT).getEnum(); this.textTransform = pList.get(Constants.PR_TEXT_TRANSFORM).getEnum(); this.wordSpacing = pList.get(Constants.PR_WORD_SPACING); this.wrapOption = pList.get(Constants.PR_WRAP_OPTION).getEnum(); this.textDecoration = pList.getTextDecorationProps(); this.baselineShift = pList.get(Constants.PR_BASELINE_SHIFT).getLength(); this.country = pList.get(Constants.PR_COUNTRY).getString(); this.language = pList.get(Constants.PR_LANGUAGE).getString(); this.script = pList.get(Constants.PR_SCRIPT).getString(); }
// in src/java/org/apache/fop/fo/FOText.java
protected void endOfNode() throws FOPException { if ( charBuffer != null ) { charBuffer.rewind(); } super.endOfNode(); getFOEventHandler().characters(this); }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
public void bind(PropertyList pList) throws FOPException { // No properties in layout-master-set. }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
protected void startOfNode() throws FOPException { getRoot().setLayoutMasterSet(this); simplePageMasters = new java.util.HashMap<String, SimplePageMaster>(); pageSequenceMasters = new java.util.HashMap<String, PageSequenceMaster>(); }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("(simple-page-master|page-sequence-master)+"); } checkRegionNames(); resolveSubSequenceReferences(); }
// in src/java/org/apache/fop/fo/pagination/Declarations.java
public void bind(PropertyList pList) throws FOPException { // No properties defined for fo:declarations }
// in src/java/org/apache/fop/fo/pagination/Declarations.java
protected void endOfNode() throws FOPException { if (firstChild != null) { for (FONodeIterator iter = getChildNodes(); iter.hasNext();) { FONode node = iter.nextNode(); if (node.getName().equals("fo:color-profile")) { ColorProfile cp = (ColorProfile)node; if (!"".equals(cp.getColorProfileName())) { addColorProfile(cp); } else { getFOValidationEventProducer().missingProperty(this, cp.getName(), "color-profile-name", locator); } } else { log.debug("Ignoring element " + node.getName() + " inside fo:declarations."); } } } firstChild = null; }
// in src/java/org/apache/fop/fo/pagination/Root.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); mediaUsage = pList.get(PR_MEDIA_USAGE).getEnum(); String language = pList.get(PR_LANGUAGE).getString(); String country = pList.get(PR_COUNTRY).getString(); if (isLocalePropertySet(language)) { if (isLocalePropertySet(country)) { locale = new Locale(language, country); } else { locale = new Locale(language); } } }
// in src/java/org/apache/fop/fo/pagination/Root.java
protected void startOfNode() throws FOPException { foEventHandler.startRoot(this); }
// in src/java/org/apache/fop/fo/pagination/Root.java
protected void endOfNode() throws FOPException { if (!pageSequenceFound || layoutMasterSet == null) { missingChildElementError("(layout-master-set, declarations?, " + "bookmark-tree?, (page-sequence|fox:external-document)+)"); } foEventHandler.endRoot(this); }
// in src/java/org/apache/fop/fo/pagination/SimplePageMaster.java
public void bind(PropertyList pList) throws FOPException { commonMarginBlock = pList.getMarginBlockProps(); masterName = pList.get(PR_MASTER_NAME).getString(); pageHeight = pList.get(PR_PAGE_HEIGHT).getLength(); pageWidth = pList.get(PR_PAGE_WIDTH).getLength(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); writingMode = WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()); if (masterName == null || masterName.equals("")) { missingPropertyError("master-name"); } }
// in src/java/org/apache/fop/fo/pagination/SimplePageMaster.java
protected void startOfNode() throws FOPException { LayoutMasterSet layoutMasterSet = (LayoutMasterSet) parent; if (masterName == null) { missingPropertyError("master-name"); } else { layoutMasterSet.addSimplePageMaster(this); } //Well, there are only 5 regions so we can save a bit of memory here regions = new HashMap<String, Region>(5); }
// in src/java/org/apache/fop/fo/pagination/SimplePageMaster.java
protected void endOfNode() throws FOPException { if (!hasRegionBody) { missingChildElementError( "(region-body, region-before?, region-after?, region-start?, region-end?)"); } }
// in src/java/org/apache/fop/fo/pagination/SimplePageMaster.java
protected void addChildNode(FONode child) throws FOPException { if (child instanceof Region) { addRegion((Region)child); } else { super.addChildNode(child); } }
// in src/java/org/apache/fop/fo/pagination/Flow.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); flowName = pList.get(PR_FLOW_NAME).getString(); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/pagination/Flow.java
protected void startOfNode() throws FOPException { if (flowName == null || flowName.equals("")) { missingPropertyError("flow-name"); } // according to communication from Paul Grosso (XSL-List, // 001228, Number 406), confusion in spec section 6.4.5 about // multiplicity of fo:flow in XSL 1.0 is cleared up - one (1) // fo:flow per fo:page-sequence only. /* if (pageSequence.isFlowSet()) { if (this.name.equals("fo:flow")) { throw new FOPException("Only a single fo:flow permitted" + " per fo:page-sequence"); } else { throw new FOPException(this.name + " not allowed after fo:flow"); } } */ // Now done in addChild of page-sequence //pageSequence.addFlow(this); getFOEventHandler().startFlow(this); }
// in src/java/org/apache/fop/fo/pagination/Flow.java
protected void endOfNode() throws FOPException { if (!blockItemFound) { missingChildElementError("marker* (%block;)+"); } getFOEventHandler().endFlow(this); }
// in src/java/org/apache/fop/fo/pagination/SideRegion.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); extent = pList.get(PR_EXTENT).getLength(); }
// in src/java/org/apache/fop/fo/pagination/StaticContent.java
protected void startOfNode() throws FOPException { if (getFlowName() == null || getFlowName().equals("")) { missingPropertyError("flow-name"); } getFOEventHandler().startStatic(this); }
// in src/java/org/apache/fop/fo/pagination/StaticContent.java
protected void endOfNode() throws FOPException { if (firstChild == null && getUserAgent().validateStrictly()) { missingChildElementError("(%block;)+"); } getFOEventHandler().endStatic(this); }
// in src/java/org/apache/fop/fo/pagination/RegionBA.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); precedence = pList.get(PR_PRECEDENCE).getEnum(); }
// in src/java/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java
public void bind(PropertyList pList) throws FOPException { masterReference = pList.get(PR_MASTER_REFERENCE).getString(); pagePosition = pList.get(PR_PAGE_POSITION).getEnum(); oddOrEven = pList.get(PR_ODD_OR_EVEN).getEnum(); blankOrNotBlank = pList.get(PR_BLANK_OR_NOT_BLANK).getEnum(); if (masterReference == null || masterReference.equals("")) { missingPropertyError("master-reference"); } }
// in src/java/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java
protected void startOfNode() throws FOPException { getConcreteParent().addConditionalPageMasterReference(this); }
// in src/java/org/apache/fop/fo/pagination/RegionSE.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
public void bind(PropertyList pList) throws FOPException { maximumRepeats = pList.get(PR_MAXIMUM_REPEATS); }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
protected void startOfNode() throws FOPException { conditionalPageMasterRefs = new java.util.ArrayList<ConditionalPageMasterReference>(); assert parent.getName().equals("fo:page-sequence-master"); //Validation by the parent PageSequenceMaster pageSequenceMaster = (PageSequenceMaster)parent; pageSequenceMaster.addSubsequenceSpecifier(this); }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("(conditional-page-master-reference+)"); } }
// in src/java/org/apache/fop/fo/pagination/bookmarks/BookmarkTitle.java
Override public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/pagination/bookmarks/Bookmark.java
public void bind(PropertyList pList) throws FOPException { commonAccessibility = CommonAccessibility.getInstance(pList); externalDestination = pList.get(PR_EXTERNAL_DESTINATION).getString(); internalDestination = pList.get(PR_INTERNAL_DESTINATION).getString(); bShow = (pList.get(PR_STARTING_STATE).getEnum() == EN_SHOW); // per spec, internal takes precedence if both specified if (internalDestination.length() > 0) { externalDestination = null; } else if (externalDestination.length() == 0) { // slightly stronger than spec "should be specified" getFOValidationEventProducer().missingLinkDestination(this, getName(), locator); } else { getFOValidationEventProducer().unimplementedFeature(this, getName(), "external-destination", getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/bookmarks/Bookmark.java
protected void endOfNode() throws FOPException { if (bookmarkTitle == null) { missingChildElementError("(bookmark-title, bookmark*)"); } }
// in src/java/org/apache/fop/fo/pagination/bookmarks/BookmarkTree.java
protected void endOfNode() throws FOPException { if (bookmarks == null) { missingChildElementError("(fo:bookmark+)"); } ((Root) parent).setBookmarkTree(this); }
// in src/java/org/apache/fop/fo/pagination/SinglePageMasterReference.java
public void bind(PropertyList pList) throws FOPException { masterReference = pList.get(PR_MASTER_REFERENCE).getString(); if (masterReference == null || masterReference.equals("")) { missingPropertyError("master-reference"); } }
// in src/java/org/apache/fop/fo/pagination/SinglePageMasterReference.java
protected void startOfNode() throws FOPException { PageSequenceMaster pageSequenceMaster = (PageSequenceMaster) parent; pageSequenceMaster.addSubsequenceSpecifier(this); }
// in src/java/org/apache/fop/fo/pagination/RegionBody.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonMarginBlock = pList.getMarginBlockProps(); columnCount = pList.get(PR_COLUMN_COUNT).getNumeric(); columnGap = pList.get(PR_COLUMN_GAP).getLength(); if ((getColumnCount() > 1) && (getOverflow() == EN_SCROLL)) { /* This is an error (See XSL Rec, fo:region-body description). * The Rec allows for acting as if "1" is chosen in * these cases, but we will need to be able to change Numeric * values in order to do this. */ getFOValidationEventProducer().columnCountErrorOnRegionBodyOverflowScroll(this, getName(), getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/AbstractPageSequence.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); initialPageNumber = pList.get(PR_INITIAL_PAGE_NUMBER).getNumeric(); forcePageCount = pList.get(PR_FORCE_PAGE_COUNT).getEnum(); format = pList.get(PR_FORMAT).getString(); letterValue = pList.get(PR_LETTER_VALUE).getEnum(); groupingSeparator = pList.get(PR_GROUPING_SEPARATOR).getCharacter(); groupingSize = pList.get(PR_GROUPING_SIZE).getNumber().intValue(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); language = pList.get(PR_LANGUAGE).getString(); country = pList.get(PR_COUNTRY).getString(); numberConversionFeatures = pList.get(PR_X_NUMBER_CONVERSION_FEATURES).getString(); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/pagination/AbstractPageSequence.java
protected void startOfNode() throws FOPException { this.pageNumberGenerator = new PageNumberGenerator( format, groupingSeparator, groupingSize, letterValue, numberConversionFeatures, language, country); }
// in src/java/org/apache/fop/fo/pagination/PageSequenceWrapper.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); indexClass = pList.get(PR_INDEX_CLASS).getString(); indexKey = pList.get(PR_INDEX_KEY).getString(); }
// in src/java/org/apache/fop/fo/pagination/ColorProfile.java
public void bind(PropertyList pList) throws FOPException { src = pList.get(PR_SRC).getString(); colorProfileName = pList.get(PR_COLOR_PROFILE_NAME).getString(); renderingIntent = pList.get(PR_RENDERING_INTENT).getEnum(); }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java
public void bind(PropertyList pList) throws FOPException { masterReference = pList.get(PR_MASTER_REFERENCE).getString(); maximumRepeats = pList.get(PR_MAXIMUM_REPEATS); if (masterReference == null || masterReference.equals("")) { missingPropertyError("master-reference"); } }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java
protected void startOfNode() throws FOPException { PageSequenceMaster pageSequenceMaster = (PageSequenceMaster) parent; if (masterReference == null) { missingPropertyError("master-reference"); } else { pageSequenceMaster.addSubsequenceSpecifier(this); } }
// in src/java/org/apache/fop/fo/pagination/Region.java
public void bind(PropertyList pList) throws FOPException { commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); // clip = pList.get(PR_CLIP); displayAlign = pList.get(PR_DISPLAY_ALIGN).getEnum(); overflow = pList.get(PR_OVERFLOW).getEnum(); regionName = pList.get(PR_REGION_NAME).getString(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); writingMode = WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()); // regions may have name, or default if (regionName.equals("")) { regionName = getDefaultRegionName(); } else { // check that name is OK. Not very pretty. if (isReserved(getRegionName()) && !getRegionName().equals(getDefaultRegionName())) { getFOValidationEventProducer().illegalRegionName(this, getName(), regionName, getLocator()); } } //TODO do we need context for getBPPaddingAndBorder() and getIPPaddingAndBorder()? if ((getCommonBorderPaddingBackground().getBPPaddingAndBorder(false, null) != 0 || getCommonBorderPaddingBackground().getIPPaddingAndBorder(false, null) != 0)) { getFOValidationEventProducer().nonZeroBorderPaddingOnRegion(this, getName(), regionName, true, getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); country = pList.get(PR_COUNTRY).getString(); language = pList.get(PR_LANGUAGE).getString(); masterReference = pList.get(PR_MASTER_REFERENCE).getString(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); writingModeTraits = new WritingModeTraits ( WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()) ); if (masterReference == null || masterReference.equals("")) { missingPropertyError("master-reference"); } }
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
protected void startOfNode() throws FOPException { super.startOfNode(); flowMap = new java.util.HashMap<String, FONode>(); this.simplePageMaster = getRoot().getLayoutMasterSet().getSimplePageMaster(masterReference); if (simplePageMaster == null) { this.pageSequenceMaster = getRoot().getLayoutMasterSet().getPageSequenceMaster(masterReference); if (pageSequenceMaster == null) { getFOValidationEventProducer().masterNotFound(this, getName(), masterReference, getLocator()); } } getFOEventHandler().startPageSequence(this); }
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
protected void endOfNode() throws FOPException { if (mainFlow == null) { missingChildElementError("(title?,static-content*,flow)"); } getFOEventHandler().endPageSequence(this); }
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
public void addChildNode(FONode child) throws FOPException { int childId = child.getNameId(); switch (childId) { case FO_TITLE: this.titleFO = (Title)child; break; case FO_FLOW: this.mainFlow = (Flow)child; addFlow(mainFlow); break; case FO_STATIC_CONTENT: addFlow((StaticContent)child); flowMap.put(((Flow)child).getFlowName(), (Flow)child); break; default: super.addChildNode(child); } }
// in src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java
public void bind(PropertyList pList) throws FOPException { masterName = pList.get(PR_MASTER_NAME).getString(); if (masterName == null || masterName.equals("")) { missingPropertyError("master-name"); } }
// in src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java
protected void startOfNode() throws FOPException { subSequenceSpecifiers = new java.util.ArrayList<SubSequenceSpecifier>(); layoutMasterSet = parent.getRoot().getLayoutMasterSet(); layoutMasterSet.addPageSequenceMaster(masterName, this); }
// in src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("(single-page-master-reference|" + "repeatable-page-master-reference|repeatable-page-master-alternatives)+"); } }
// in src/java/org/apache/fop/fo/FObj.java
public FONode clone(FONode parent, boolean removeChildren) throws FOPException { FObj fobj = (FObj) super.clone(parent, removeChildren); if (removeChildren) { fobj.firstChild = null; } return fobj; }
// in src/java/org/apache/fop/fo/FObj.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { setLocator(locator); pList.addAttributesToList(attlist); if (!inMarker() || "marker".equals(elementName)) { bind(pList); } }
// in src/java/org/apache/fop/fo/FObj.java
protected PropertyList createPropertyList(PropertyList parent, FOEventHandler foEventHandler) throws FOPException { return getBuilderContext().getPropertyListMaker().make(this, parent); }
// in src/java/org/apache/fop/fo/FObj.java
public void bind(PropertyList pList) throws FOPException { id = pList.get(PR_ID).getString(); }
// in src/java/org/apache/fop/fo/FObj.java
protected void startOfNode() throws FOPException { if (id != null) { checkId(id); } }
// in src/java/org/apache/fop/fo/FObj.java
protected void addChildNode(FONode child) throws FOPException { if (child.getNameId() == FO_MARKER) { addMarker((Marker) child); } else { ExtensionAttachment attachment = child.getExtensionAttachment(); if (attachment != null) { /* This removes the element from the normal children, * so no layout manager is being created for them * as they are only additional information. */ addExtensionAttachment(attachment); } else { if (firstChild == null) { firstChild = child; lastChild = child; } else { if (lastChild == null) { FONode prevChild = firstChild; while (prevChild.siblings != null && prevChild.siblings[1] != null) { prevChild = prevChild.siblings[1]; } FONode.attachSiblings(prevChild, child); } else { FONode.attachSiblings(lastChild, child); lastChild = child; } } } } }
// in src/java/org/apache/fop/fo/FObj.java
protected static void addChildTo(FONode child, FONode parent) throws FOPException { parent.addChildNode(child); }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
public Maker findFOMaker(String namespaceURI, String localName, Locator locator) throws FOPException { Map<String, Maker> table = fobjTable.get(namespaceURI); Maker fobjMaker = null; if (table != null) { fobjMaker = table.get(localName); // try default if (fobjMaker == null) { fobjMaker = table.get(ElementMapping.DEFAULT); } } if (fobjMaker == null) { if (namespaces.containsKey(namespaceURI.intern())) { throw new FOPException(FONode.errorText(locator) + "No element mapping definition found for " + FONode.getNodeString(namespaceURI, localName), locator); } else { fobjMaker = new UnknownXMLObj.Maker(namespaceURI); } } return fobjMaker; }
// in src/java/org/apache/fop/fo/FONode.java
public FONode clone(FONode cloneparent, boolean removeChildren) throws FOPException { FONode foNode = (FONode) clone(); foNode.parent = cloneparent; foNode.siblings = null; return foNode; }
// in src/java/org/apache/fop/fo/FONode.java
public void bind(PropertyList propertyList) throws FOPException { //nop }
// in src/java/org/apache/fop/fo/FONode.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { if (log.isDebugEnabled()) { log.debug("Unhandled element: " + elementName + (locator != null ? " at " + getLocatorString(locator) : "")); } }
// in src/java/org/apache/fop/fo/FONode.java
protected PropertyList createPropertyList( PropertyList pList, FOEventHandler foEventHandler) throws FOPException { return null; }
// in src/java/org/apache/fop/fo/FONode.java
protected void addCharacters(char[] data, int start, int end, PropertyList pList, Locator locator) throws FOPException { // ignore }
// in src/java/org/apache/fop/fo/FONode.java
protected void characters(char[] data, int start, int length, PropertyList pList, Locator locator) throws FOPException { addCharacters(data, start, start + length, pList, locator); }
// in src/java/org/apache/fop/fo/FONode.java
protected void startOfNode() throws FOPException { // do nothing by default }
// in src/java/org/apache/fop/fo/FONode.java
protected void endOfNode() throws FOPException { this.finalizeNode(); }
// in src/java/org/apache/fop/fo/FONode.java
protected void addChildNode(FONode child) throws FOPException { // do nothing by default }
// in src/java/org/apache/fop/fo/FONode.java
public void finalizeNode() throws FOPException { // do nothing by default }
// in src/java/org/apache/fop/fo/extensions/ExternalDocument.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); contentHeight = pList.get(PR_CONTENT_HEIGHT).getLength(); contentWidth = pList.get(PR_CONTENT_WIDTH).getLength(); displayAlign = pList.get(PR_DISPLAY_ALIGN).getEnum(); height = pList.get(PR_HEIGHT).getLength(); inlineProgressionDimension = pList.get(PR_INLINE_PROGRESSION_DIMENSION).getLengthRange(); overflow = pList.get(PR_OVERFLOW).getEnum(); scaling = pList.get(PR_SCALING).getEnum(); textAlign = pList.get(PR_TEXT_ALIGN).getEnum(); width = pList.get(PR_WIDTH).getLength(); src = pList.get(PR_SRC).getString(); if (this.src == null || this.src.length() == 0) { missingPropertyError("src"); } }
// in src/java/org/apache/fop/fo/extensions/ExternalDocument.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startExternalDocument(this); }
// in src/java/org/apache/fop/fo/extensions/ExternalDocument.java
protected void endOfNode() throws FOPException { getFOEventHandler().endExternalDocument(this); super.endOfNode(); }
// in src/java/org/apache/fop/fo/extensions/destination/Destination.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { internalDestination = attlist.getValue("internal-destination"); if (internalDestination == null || internalDestination.length() == 0) { missingPropertyError("internal-destination"); } }
// in src/java/org/apache/fop/fo/extensions/destination/Destination.java
protected void endOfNode() throws FOPException { root.addDestination(this); }
// in src/java/org/apache/fop/fo/extensions/ExtensionObj.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { }
// in src/java/org/apache/fop/fo/extensions/ExtensionObj.java
protected PropertyList createPropertyList(PropertyList parent, FOEventHandler foEventHandler) throws FOPException { return null; }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java
public static FontInfo createFontInfo(Configuration cfg, boolean useComplexScriptFeatures) throws FOPException { FontInfo fontInfo = new FontInfo(); final boolean strict = false; FontResolver fontResolver = FontManager.createMinimalFontResolver(useComplexScriptFeatures); //TODO The following could be optimized by retaining the FontManager somewhere FontManager fontManager = new FontManager(); if (cfg != null) { FontManagerConfigurator fmConfigurator = new FontManagerConfigurator(cfg); fmConfigurator.configure(fontManager, strict); } List fontCollections = new java.util.ArrayList(); fontCollections.add(new Base14FontCollection(fontManager.isBase14KerningEnabled())); if (cfg != null) { //TODO Wire in the FontEventListener FontEventListener listener = null; //new FontEventAdapter(eventBroadcaster); FontInfoConfigurator fontInfoConfigurator = new FontInfoConfigurator(cfg, fontManager, fontResolver, listener, strict); List/*<EmbedFontInfo>*/ fontInfoList = new java.util.ArrayList/*<EmbedFontInfo>*/(); fontInfoConfigurator.configure(fontInfoList); fontCollections.add(new CustomFontCollection(fontResolver, fontInfoList, fontResolver.isComplexScriptFeaturesEnabled())); } fontManager.setup(fontInfo, (FontCollection[])fontCollections.toArray( new FontCollection[fontCollections.size()])); return fontInfo; }
// in src/java/org/apache/fop/fonts/FontReader.java
private void createFont(InputSource source) throws FOPException { XMLReader parser = null; try { final SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); parser = factory.newSAXParser().getXMLReader(); } catch (Exception e) { throw new FOPException(e); } if (parser == null) { throw new FOPException("Unable to create SAX parser"); } try { parser.setFeature("http://xml.org/sax/features/namespace-prefixes", false); } catch (SAXException e) { throw new FOPException("You need a SAX parser which supports SAX version 2", e); } parser.setContentHandler(this); try { parser.parse(source); } catch (SAXException e) { throw new FOPException(e); } catch (IOException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/fonts/FontManager.java
public void saveCache() throws FOPException { if (useCache) { if (fontCache != null && fontCache.hasChanged()) { if (cacheFile != null) { fontCache.saveTo(cacheFile); } else { fontCache.save(); } } } }
// in src/java/org/apache/fop/fonts/substitute/FontSubstitutionsConfigurator.java
private static FontQualifier getQualfierFromConfiguration(Configuration cfg) throws FOPException { String fontFamily = cfg.getAttribute("font-family", null); if (fontFamily == null) { throw new FOPException("substitution qualifier must have a font-family"); } FontQualifier qualifier = new FontQualifier(); qualifier.setFontFamily(fontFamily); String fontWeight = cfg.getAttribute("font-weight", null); if (fontWeight != null) { qualifier.setFontWeight(fontWeight); } String fontStyle = cfg.getAttribute("font-style", null); if (fontStyle != null) { qualifier.setFontStyle(fontStyle); } return qualifier; }
// in src/java/org/apache/fop/fonts/substitute/FontSubstitutionsConfigurator.java
public void configure(FontSubstitutions substitutions) throws FOPException { Configuration[] substitutionCfgs = cfg.getChildren("substitution"); for (int i = 0; i < substitutionCfgs.length; i++) { Configuration fromCfg = substitutionCfgs[i].getChild("from", false); if (fromCfg == null) { throw new FOPException("'substitution' element without child 'from' element"); } Configuration toCfg = substitutionCfgs[i].getChild("to", false); if (fromCfg == null) { throw new FOPException("'substitution' element without child 'to' element"); } FontQualifier fromQualifier = getQualfierFromConfiguration(fromCfg); FontQualifier toQualifier = getQualfierFromConfiguration(toCfg); FontSubstitution substitution = new FontSubstitution(fromQualifier, toQualifier); substitutions.add(substitution); } }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
public void configure(FontManager fontManager, boolean strict) throws FOPException { // caching (fonts) if (cfg.getChild("use-cache", false) != null) { try { fontManager.setUseCache(cfg.getChild("use-cache").getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, true); } } if (cfg.getChild("cache-file", false) != null) { try { fontManager.setCacheFile(new File(cfg.getChild("cache-file").getValue())); } catch (ConfigurationException e) { LogUtil.handleException(log, e, true); } } if (cfg.getChild("font-base", false) != null) { String path = cfg.getChild("font-base").getValue(null); if (baseURI != null) { path = baseURI.resolve(path).normalize().toString(); } try { fontManager.setFontBaseURL(path); } catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, true); } } // [GA] permit configuration control over base14 kerning; without this, // there is no way for a user to enable base14 kerning other than by // programmatic API; if (cfg.getChild("base14-kerning", false) != null) { try { fontManager .setBase14KerningEnabled(cfg.getChild("base14-kerning").getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, true); } } // global font configuration Configuration fontsCfg = cfg.getChild("fonts", false); if (fontsCfg != null) { // font substitution Configuration substitutionsCfg = fontsCfg.getChild("substitutions", false); if (substitutionsCfg != null) { FontSubstitutions substitutions = new FontSubstitutions(); new FontSubstitutionsConfigurator(substitutionsCfg).configure(substitutions); fontManager.setFontSubstitutions(substitutions); } // referenced fonts (fonts which are not to be embedded) Configuration referencedFontsCfg = fontsCfg.getChild("referenced-fonts", false); if (referencedFontsCfg != null) { FontTriplet.Matcher matcher = createFontsMatcher( referencedFontsCfg, strict); fontManager.setReferencedFontsMatcher(matcher); } } }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
public static FontTriplet.Matcher createFontsMatcher( Configuration cfg, boolean strict) throws FOPException { List<FontTriplet.Matcher> matcherList = new java.util.ArrayList<FontTriplet.Matcher>(); Configuration[] matches = cfg.getChildren("match"); for (int i = 0; i < matches.length; i++) { try { matcherList.add(new FontFamilyRegExFontTripletMatcher( matches[i].getAttribute("font-family"))); } catch (ConfigurationException ce) { LogUtil.handleException(log, ce, strict); continue; } } FontTriplet.Matcher orMatcher = new OrFontTripletMatcher( matcherList.toArray(new FontTriplet.Matcher[matcherList.size()])); return orMatcher; }
// in src/java/org/apache/fop/fonts/FontCache.java
public void save() throws FOPException { saveTo(getDefaultCacheFile(true)); }
// in src/java/org/apache/fop/fonts/FontCache.java
public void saveTo(File cacheFile) throws FOPException { synchronized (changeLock) { if (changed) { try { log.trace("Writing font cache to " + cacheFile.getCanonicalPath()); OutputStream out = new java.io.FileOutputStream(cacheFile); out = new java.io.BufferedOutputStream(out); ObjectOutputStream oout = new ObjectOutputStream(out); try { oout.writeObject(this); } finally { IOUtils.closeQuietly(oout); } } catch (IOException ioe) { LogUtil.handleException(log, ioe, true); } changed = false; log.trace("Cache file written."); } } }
// in src/java/org/apache/fop/fonts/FontDetector.java
public void detect(List<EmbedFontInfo> fontInfoList) throws FOPException { // search in font base if it is defined and // is a directory but don't recurse FontFileFinder fontFileFinder = new FontFileFinder(eventListener); String fontBaseURL = fontManager.getFontBaseURL(); if (fontBaseURL != null) { try { File fontBase = FileUtils.toFile(new URL(fontBaseURL)); if (fontBase != null) { List<URL> fontURLList = fontFileFinder.find(fontBase.getAbsolutePath()); fontAdder.add(fontURLList, fontInfoList); //Can only use the font base URL if it's a file URL } } catch (IOException e) { LogUtil.handleException(log, e, strict); } } // native o/s font directory finding List<URL> systemFontList; try { systemFontList = fontFileFinder.find(); fontAdder.add(systemFontList, fontInfoList); } catch (IOException e) { LogUtil.handleException(log, e, strict); } // classpath font finding ClasspathResource resource = ClasspathResource.getInstance(); for (int i = 0; i < FONT_MIMETYPES.length; i++) { fontAdder.add(resource.listResourcesOfMimeType(FONT_MIMETYPES[i]), fontInfoList); } }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
public void configure(List<EmbedFontInfo> fontInfoList) throws FOPException { Configuration fontsCfg = cfg.getChild("fonts", false); if (fontsCfg != null) { long start = 0; if (log.isDebugEnabled()) { log.debug("Starting font configuration..."); start = System.currentTimeMillis(); } FontAdder fontAdder = new FontAdder(fontManager, fontResolver, listener); // native o/s search (autodetect) configuration boolean autodetectFonts = (fontsCfg.getChild("auto-detect", false) != null); if (autodetectFonts) { FontDetector fontDetector = new FontDetector(fontManager, fontAdder, strict, listener); fontDetector.detect(fontInfoList); } // Add configured directories to FontInfo list addDirectories(fontsCfg, fontAdder, fontInfoList); // Add fonts from configuration to FontInfo list addFonts(fontsCfg, fontManager.getFontCache(), fontInfoList); // Update referenced fonts (fonts which are not to be embedded) fontManager.updateReferencedFonts(fontInfoList); // Renderer-specific referenced fonts Configuration referencedFontsCfg = fontsCfg.getChild("referenced-fonts", false); if (referencedFontsCfg != null) { FontTriplet.Matcher matcher = FontManagerConfigurator.createFontsMatcher( referencedFontsCfg, strict); fontManager.updateReferencedFonts(fontInfoList, matcher); } // Update font cache if it has changed fontManager.saveCache(); if (log.isDebugEnabled()) { log.debug("Finished font configuration in " + (System.currentTimeMillis() - start) + "ms"); } } }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
private void addDirectories(Configuration fontsCfg, FontAdder fontAdder, List<EmbedFontInfo> fontInfoList) throws FOPException { // directory (multiple font) configuration Configuration[] directories = fontsCfg.getChildren("directory"); for (int i = 0; i < directories.length; i++) { boolean recursive = directories[i].getAttributeAsBoolean("recursive", false); String directory = null; try { directory = directories[i].getValue(); } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); continue; } if (directory == null) { LogUtil.handleException(log, new FOPException("directory defined without value"), strict); continue; } // add fonts found in directory FontFileFinder fontFileFinder = new FontFileFinder(recursive ? -1 : 1, listener); List<URL> fontURLList; try { fontURLList = fontFileFinder.find(directory); fontAdder.add(fontURLList, fontInfoList); } catch (IOException e) { LogUtil.handleException(log, e, strict); } } }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
protected void addFonts(Configuration fontsCfg, FontCache fontCache, List<EmbedFontInfo> fontInfoList) throws FOPException { // font file (singular) configuration Configuration[] font = fontsCfg.getChildren("font"); for (int i = 0; i < font.length; i++) { EmbedFontInfo embedFontInfo = getFontInfo( font[i], fontCache); if (embedFontInfo != null) { fontInfoList.add(embedFontInfo); } } }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
protected EmbedFontInfo getFontInfo(Configuration fontCfg, FontCache fontCache) throws FOPException { String metricsUrl = fontCfg.getAttribute("metrics-url", null); String embedUrl = fontCfg.getAttribute("embed-url", null); String subFont = fontCfg.getAttribute("sub-font", null); if (metricsUrl == null && embedUrl == null) { LogUtil.handleError(log, "Font configuration without metric-url or embed-url attribute", strict); return null; } if (strict) { //This section just checks early whether the URIs can be resolved //Stream are immediately closed again since they will never be used anyway if (embedUrl != null) { Source source = fontResolver.resolve(embedUrl); closeSource(source); if (source == null) { LogUtil.handleError(log, "Failed to resolve font with embed-url '" + embedUrl + "'", strict); return null; } } if (metricsUrl != null) { Source source = fontResolver.resolve(metricsUrl); closeSource(source); if (source == null) { LogUtil.handleError(log, "Failed to resolve font with metric-url '" + metricsUrl + "'", strict); return null; } } } Configuration[] tripletCfg = fontCfg.getChildren("font-triplet"); // no font triplet info if (tripletCfg.length == 0) { LogUtil.handleError(log, "font without font-triplet", strict); File fontFile = FontCache.getFileFromUrls(new String[] {embedUrl, metricsUrl}); URL fontURL = null; try { fontURL = fontFile.toURI().toURL(); } catch (MalformedURLException e) { LogUtil.handleException(log, e, strict); } if (fontFile != null) { FontInfoFinder finder = new FontInfoFinder(); finder.setEventListener(listener); EmbedFontInfo[] infos = finder.find(fontURL, fontResolver, fontCache); return infos[0]; //When subFont is set, only one font is returned } else { return null; } } List<FontTriplet> tripletList = new java.util.ArrayList<FontTriplet>(); for (int j = 0; j < tripletCfg.length; j++) { FontTriplet fontTriplet = getFontTriplet(tripletCfg[j]); tripletList.add(fontTriplet); } boolean useKerning = fontCfg.getAttributeAsBoolean("kerning", true); boolean useAdvanced = fontCfg.getAttributeAsBoolean("advanced", true); EncodingMode encodingMode = EncodingMode.getEncodingMode( fontCfg.getAttribute("encoding-mode", EncodingMode.AUTO.getName())); EmbedFontInfo embedFontInfo = new EmbedFontInfo(metricsUrl, useKerning, useAdvanced, tripletList, embedUrl, subFont); embedFontInfo.setEncodingMode(encodingMode); boolean skipCachedFont = false; if (fontCache != null) { if (!fontCache.containsFont(embedFontInfo)) { fontCache.addFont(embedFontInfo); } else { skipCachedFont = true; } } if (log.isDebugEnabled()) { String embedFile = embedFontInfo.getEmbedFile(); log.debug( ( skipCachedFont ? "Skipping (cached) font " : "Adding font " ) + (embedFile != null ? embedFile + ", " : "") + "metric file " + embedFontInfo.getMetricsFile()); for (int j = 0; j < tripletList.size(); ++j) { FontTriplet triplet = tripletList.get(j); log.debug(" Font triplet " + triplet.getName() + ", " + triplet.getStyle() + ", " + triplet.getWeight()); } } return embedFontInfo; }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
private FontTriplet getFontTriplet(Configuration tripletCfg) throws FOPException { try { String name = tripletCfg.getAttribute("name"); if (name == null) { LogUtil.handleError(log, "font-triplet without name", strict); return null; } String weightStr = tripletCfg.getAttribute("weight"); if (weightStr == null) { LogUtil.handleError(log, "font-triplet without weight", strict); return null; } int weight = FontUtil.parseCSS2FontWeight(FontUtil.stripWhiteSpace(weightStr)); String style = tripletCfg.getAttribute("style"); if (style == null) { LogUtil.handleError(log, "font-triplet without style", strict); return null; } else { style = FontUtil.stripWhiteSpace(style); } return FontInfo.createFontKey(name, style, weight); } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); } return null; }
// in src/java/org/apache/fop/render/XMLHandlerConfigurator.java
public void configure(RendererContext context, String ns) throws FOPException { //Optional XML handler configuration Configuration cfg = getRendererConfig(context.getRenderer()); if (cfg != null) { cfg = getHandlerConfig(cfg, ns); if (cfg != null) { context.setProperty(RendererContextConstants.HANDLER_CONFIGURATION, cfg); } } }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
private void configure(Configuration cfg, PDFRenderingUtil pdfUtil) throws FOPException { //PDF filters try { Map filterMap = buildFilterMapFromConfiguration(cfg); if (filterMap != null) { pdfUtil.setFilterMap(filterMap); } } catch (ConfigurationException e) { LogUtil.handleException(log, e, false); } String s = cfg.getChild(PDFConfigurationConstants.PDF_A_MODE, true).getValue(null); if (s != null) { pdfUtil.setAMode(PDFAMode.valueOf(s)); } s = cfg.getChild(PDFConfigurationConstants.PDF_X_MODE, true).getValue(null); if (s != null) { pdfUtil.setXMode(PDFXMode.valueOf(s)); } Configuration encryptionParamsConfig = cfg.getChild(PDFConfigurationConstants.ENCRYPTION_PARAMS, false); if (encryptionParamsConfig != null) { PDFEncryptionParams encryptionParams = pdfUtil.getEncryptionParams(); Configuration ownerPasswordConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.OWNER_PASSWORD, false); if (ownerPasswordConfig != null) { String ownerPassword = ownerPasswordConfig.getValue(null); if (ownerPassword != null) { encryptionParams.setOwnerPassword(ownerPassword); } } Configuration userPasswordConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.USER_PASSWORD, false); if (userPasswordConfig != null) { String userPassword = userPasswordConfig.getValue(null); if (userPassword != null) { encryptionParams.setUserPassword(userPassword); } } Configuration noPrintConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_PRINT, false); if (noPrintConfig != null) { encryptionParams.setAllowPrint(false); } Configuration noCopyContentConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_COPY_CONTENT, false); if (noCopyContentConfig != null) { encryptionParams.setAllowCopyContent(false); } Configuration noEditContentConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_EDIT_CONTENT, false); if (noEditContentConfig != null) { encryptionParams.setAllowEditContent(false); } Configuration noAnnotationsConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_ANNOTATIONS, false); if (noAnnotationsConfig != null) { encryptionParams.setAllowEditAnnotations(false); } Configuration noFillInForms = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_FILLINFORMS, false); if (noFillInForms != null) { encryptionParams.setAllowFillInForms(false); } Configuration noAccessContentConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_ACCESSCONTENT, false); if (noAccessContentConfig != null) { encryptionParams.setAllowAccessContent(false); } Configuration noAssembleDocConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_ASSEMBLEDOC, false); if (noAssembleDocConfig != null) { encryptionParams.setAllowAssembleDocument(false); } Configuration noPrintHqConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_PRINTHQ, false); if (noPrintHqConfig != null) { encryptionParams.setAllowPrintHq(false); } Configuration encryptionLengthConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.ENCRYPTION_LENGTH, false); if (encryptionLengthConfig != null) { int encryptionLength = checkEncryptionLength( Integer.parseInt(encryptionLengthConfig.getValue(null))); encryptionParams.setEncryptionLengthInBits(encryptionLength); } } s = cfg.getChild(PDFConfigurationConstants.KEY_OUTPUT_PROFILE, true).getValue(null); if (s != null) { pdfUtil.setOutputProfileURI(s); } Configuration disableColorSpaceConfig = cfg.getChild( PDFConfigurationConstants.KEY_DISABLE_SRGB_COLORSPACE, false); if (disableColorSpaceConfig != null) { pdfUtil.setDisableSRGBColorSpace( disableColorSpaceConfig.getValueAsBoolean(false)); } setPDFDocVersion(cfg, pdfUtil); }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
private void setPDFDocVersion(Configuration cfg, PDFRenderingUtil pdfUtil) throws FOPException { Configuration pdfVersion = cfg.getChild(PDFConfigurationConstants.PDF_VERSION, false); if (pdfVersion != null) { String version = pdfVersion.getValue(null); if (version != null && version.length() != 0) { try { pdfUtil.setPDFVersion(version); } catch (IllegalArgumentException e) { throw new FOPException(e.getMessage()); } } else { throw new FOPException("The PDF version has not been set."); } } }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { PDFDocumentHandler pdfDocumentHandler = (PDFDocumentHandler)documentHandler; PDFRenderingUtil pdfUtil = pdfDocumentHandler.getPDFUtil(); configure(cfg, pdfUtil); } }
// in src/java/org/apache/fop/render/pdf/extensions/PDFEmbeddedFileElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if (parent.getNameId() != Constants.FO_DECLARATIONS) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfDeclarations"); } }
// in src/java/org/apache/fop/render/pdf/extensions/PDFEmbeddedFileElement.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { PDFEmbeddedFileExtensionAttachment embeddedFile = (PDFEmbeddedFileExtensionAttachment)getExtensionAttachment(); String desc = attlist.getValue("description"); if (desc != null && desc.length() > 0) { embeddedFile.setDesc(desc); } String src = attlist.getValue("src"); src = URISpecification.getURL(src); if (src != null && src.length() > 0) { embeddedFile.setSrc(src); } else { missingPropertyError("src"); } String filename = attlist.getValue("filename"); if (filename == null || filename.length() == 0) { try { URI uri = new URI(src); String path = uri.getPath(); int idx = path.lastIndexOf('/'); if (idx > 0) { filename = path.substring(idx + 1); } else { filename = path; } embeddedFile.setFilename(filename); } catch (URISyntaxException e) { //Filename could not be deduced from URI missingPropertyError("name"); } } embeddedFile.setFilename(filename); }
// in src/java/org/apache/fop/render/RendererFactory.java
public Renderer createRenderer(FOUserAgent userAgent, String outputFormat) throws FOPException { if (userAgent.getDocumentHandlerOverride() != null) { return createRendererForDocumentHandler(userAgent.getDocumentHandlerOverride()); } else if (userAgent.getRendererOverride() != null) { return userAgent.getRendererOverride(); } else { Renderer renderer; if (isRendererPreferred()) { //Try renderer first renderer = tryRendererMaker(userAgent, outputFormat); if (renderer == null) { renderer = tryIFDocumentHandlerMaker(userAgent, outputFormat); } } else { //Try document handler first renderer = tryIFDocumentHandlerMaker(userAgent, outputFormat); if (renderer == null) { renderer = tryRendererMaker(userAgent, outputFormat); } } if (renderer == null) { throw new UnsupportedOperationException( "No renderer for the requested format available: " + outputFormat); } return renderer; } }
// in src/java/org/apache/fop/render/RendererFactory.java
private Renderer tryIFDocumentHandlerMaker(FOUserAgent userAgent, String outputFormat) throws FOPException { AbstractIFDocumentHandlerMaker documentHandlerMaker = getDocumentHandlerMaker(outputFormat); if (documentHandlerMaker != null) { IFDocumentHandler documentHandler = createDocumentHandler( userAgent, outputFormat); return createRendererForDocumentHandler(documentHandler); } else { return null; } }
// in src/java/org/apache/fop/render/RendererFactory.java
private Renderer tryRendererMaker(FOUserAgent userAgent, String outputFormat) throws FOPException { AbstractRendererMaker maker = getRendererMaker(outputFormat); if (maker != null) { Renderer rend = maker.makeRenderer(userAgent); RendererConfigurator configurator = maker.getConfigurator(userAgent); if (configurator != null) { configurator.configure(rend); } return rend; } else { return null; } }
// in src/java/org/apache/fop/render/RendererFactory.java
public FOEventHandler createFOEventHandler(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { if (userAgent.getFOEventHandlerOverride() != null) { return userAgent.getFOEventHandlerOverride(); } else { AbstractFOEventHandlerMaker maker = getFOEventHandlerMaker(outputFormat); if (maker != null) { return maker.makeFOEventHandler(userAgent, out); } else { AbstractRendererMaker rendMaker = getRendererMaker(outputFormat); AbstractIFDocumentHandlerMaker documentHandlerMaker = null; boolean outputStreamMissing = (userAgent.getRendererOverride() == null) && (userAgent.getDocumentHandlerOverride() == null); if (rendMaker == null) { documentHandlerMaker = getDocumentHandlerMaker(outputFormat); if (documentHandlerMaker != null) { outputStreamMissing &= (out == null) && (documentHandlerMaker.needsOutputStream()); } } else { outputStreamMissing &= (out == null) && (rendMaker.needsOutputStream()); } if (userAgent.getRendererOverride() != null || rendMaker != null || userAgent.getDocumentHandlerOverride() != null || documentHandlerMaker != null) { if (outputStreamMissing) { throw new FOPException( "OutputStream has not been set"); } //Found a Renderer so we need to construct an AreaTreeHandler. return new AreaTreeHandler(userAgent, outputFormat, out); } else { throw new UnsupportedOperationException( "Don't know how to handle \"" + outputFormat + "\" as an output format." + " Neither an FOEventHandler, nor a Renderer could be found" + " for this output format."); } } } }
// in src/java/org/apache/fop/render/RendererFactory.java
public IFDocumentHandler createDocumentHandler(FOUserAgent userAgent, String outputFormat) throws FOPException { if (userAgent.getDocumentHandlerOverride() != null) { return userAgent.getDocumentHandlerOverride(); } AbstractIFDocumentHandlerMaker maker = getDocumentHandlerMaker(outputFormat); if (maker == null) { throw new UnsupportedOperationException( "No IF document handler for the requested format available: " + outputFormat); } IFDocumentHandler documentHandler = maker.makeIFDocumentHandler(userAgent); IFDocumentHandlerConfigurator configurator = documentHandler.getConfigurator(); if (configurator != null) { configurator.configure(documentHandler); } return new EventProducingFilter(documentHandler, userAgent); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
Override public void setupFontInfo(FontInfo inFontInfo) throws FOPException { if (mimic != null) { mimic.setupFontInfo(inFontInfo); } else { super.setupFontInfo(inFontInfo); } }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
Override public void renderPage(PageViewport page) throws IOException, FOPException { atts.clear(); addAttribute("bounds", page.getViewArea()); addAttribute("key", page.getKey()); addAttribute("nr", page.getPageNumber()); addAttribute("formatted-nr", page.getPageNumberString()); if (page.getSimplePageMasterName() != null) { addAttribute("simple-page-master-name", page.getSimplePageMasterName()); } if (page.isBlank()) { addAttribute("blank", "true"); } transferForeignObjects(page); startElement("pageViewport", atts); startElement("page"); handlePageExtensionAttachments(page); super.renderPage(page); endElement("page"); endElement("pageViewport"); }
// in src/java/org/apache/fop/render/intermediate/IFUtil.java
public static void setupFonts(IFDocumentHandler documentHandler, FontInfo fontInfo) throws FOPException { if (fontInfo == null) { fontInfo = new FontInfo(); } if (documentHandler instanceof IFSerializer) { IFSerializer serializer = (IFSerializer)documentHandler; if (serializer.getMimickedDocumentHandler() != null) { //Use the mimicked document handler's configurator to set up fonts documentHandler = serializer.getMimickedDocumentHandler(); } } IFDocumentHandlerConfigurator configurator = documentHandler.getConfigurator(); if (configurator != null) { configurator.setupFontInfo(documentHandler, fontInfo); } else { documentHandler.setDefaultFontInfo(fontInfo); } }
// in src/java/org/apache/fop/render/intermediate/IFUtil.java
public static void setupFonts(IFDocumentHandler documentHandler) throws FOPException { setupFonts(documentHandler, null); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
public void setupFontInfo(FontInfo inFontInfo) throws FOPException { if (this.documentHandler == null) { this.documentHandler = createDefaultDocumentHandler(); } IFUtil.setupFonts(this.documentHandler, inFontInfo); this.fontInfo = inFontInfo; }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
public void renderPage(PageViewport page) throws IOException, FOPException { if (log.isTraceEnabled()) { log.trace("renderPage() " + page); } try { pageIndices.put(page.getKey(), new Integer(page.getPageIndex())); Rectangle viewArea = page.getViewArea(); Dimension dim = new Dimension(viewArea.width, viewArea.height); establishForeignAttributes(page.getForeignAttributes()); documentHandler.startPage(page.getPageIndex(), page.getPageNumberString(), page.getSimplePageMasterName(), dim); resetForeignAttributes(); documentHandler.startPageHeader(); //Add page attachments to page header processExtensionAttachments(page); documentHandler.endPageHeader(); this.painter = documentHandler.startPageContent(); super.renderPage(page); this.painter = null; documentHandler.endPageContent(); documentHandler.startPageTrailer(); if (hasDocumentNavigation()) { Iterator iter = this.deferredLinks.iterator(); while (iter.hasNext()) { Link link = (Link)iter.next(); iter.remove(); getDocumentNavigationHandler().renderLink(link); } } documentHandler.endPageTrailer(); establishForeignAttributes(page.getForeignAttributes()); documentHandler.endPage(); resetForeignAttributes(); } catch (IFException e) { handleIFException(e); } }
// in src/java/org/apache/fop/render/PrintRenderer.java
public void setupFontInfo(FontInfo inFontInfo) throws FOPException { this.fontInfo = inFontInfo; FontManager fontManager = userAgent.getFactory().getFontManager(); FontCollection[] fontCollections = new FontCollection[] { new Base14FontCollection(fontManager.isBase14KerningEnabled()), new CustomFontCollection(getFontResolver(), getFontList(), userAgent.isComplexScriptFeaturesEnabled()) }; fontManager.setup(getFontInfo(), fontCollections); }
// in src/java/org/apache/fop/render/txt/TXTRenderer.java
public void renderPage(PageViewport page) throws IOException, FOPException { if (firstPage) { firstPage = false; } else { currentStream.add(pageEnding); } Rectangle2D bounds = page.getViewArea(); double width = bounds.getWidth(); double height = bounds.getHeight(); pageWidth = Helper.ceilPosition((int) width, CHAR_WIDTH); pageHeight = Helper.ceilPosition((int) height, CHAR_HEIGHT + 2 * LINE_LEADING); // init buffers charData = new StringBuffer[pageHeight]; decoData = new StringBuffer[pageHeight]; for (int i = 0; i < pageHeight; i++) { charData[i] = new StringBuffer(); decoData[i] = new StringBuffer(); } bm = new BorderManager(pageWidth, pageHeight, currentState); super.renderPage(page); flushBorderToBuffer(); flushBuffer(); }
// in src/java/org/apache/fop/render/txt/TXTRendererConfigurator.java
public void configure(Renderer renderer) throws FOPException { Configuration cfg = super.getRendererConfig(renderer); if (cfg != null) { TXTRenderer txtRenderer = (TXTRenderer)renderer; txtRenderer.setEncoding(cfg.getChild("encoding", true).getValue(null)); } }
// in src/java/org/apache/fop/render/AbstractRenderer.java
public void renderPage(PageViewport page) throws IOException, FOPException { this.currentPageViewport = page; try { Page p = page.getPage(); renderPageAreas(p); } finally { this.currentPageViewport = null; } }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
private void configure(Configuration cfg, PCLRenderingUtil pclUtil) throws FOPException { String rendering = cfg.getChild("rendering").getValue(null); if (rendering != null) { try { pclUtil.setRenderingMode(PCLRenderingMode.valueOf(rendering)); } catch (IllegalArgumentException e) { throw new FOPException( "Valid values for 'rendering' are 'quality', 'speed' and 'bitmap'." + " Value found: " + rendering); } } String textRendering = cfg.getChild("text-rendering").getValue(null); if ("bitmap".equalsIgnoreCase(textRendering)) { pclUtil.setAllTextAsBitmaps(true); } else if ("auto".equalsIgnoreCase(textRendering)) { pclUtil.setAllTextAsBitmaps(false); } else if (textRendering != null) { throw new FOPException( "Valid values for 'text-rendering' are 'auto' and 'bitmap'. Value found: " + textRendering); } pclUtil.setPJLDisabled(cfg.getChild("disable-pjl").getValueAsBoolean(false)); }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { PCLDocumentHandler pclDocumentHandler = (PCLDocumentHandler)documentHandler; PCLRenderingUtil pclUtil = pclDocumentHandler.getPCLUtil(); configure(cfg, pclUtil); } }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo) throws FOPException { FontManager fontManager = userAgent.getFactory().getFontManager(); final Java2DFontMetrics java2DFontMetrics = new Java2DFontMetrics(); final List fontCollections = new java.util.ArrayList(); fontCollections.add(new Base14FontCollection(java2DFontMetrics)); fontCollections.add(new InstalledFontCollection(java2DFontMetrics)); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { FontResolver fontResolver = new DefaultFontResolver(userAgent); FontEventListener listener = new FontEventAdapter( userAgent.getEventBroadcaster()); List fontList = buildFontList(cfg, fontResolver, listener); fontCollections.add(new ConfiguredFontCollection(fontResolver, fontList, userAgent.isComplexScriptFeaturesEnabled())); } fontManager.setup(fontInfo, (FontCollection[])fontCollections.toArray( new FontCollection[fontCollections.size()])); documentHandler.setFontInfo(fontInfo); }
// in src/java/org/apache/fop/render/rtf/ListAttributesConverter.java
static RtfAttributes convertAttributes(ListBlock fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrib.setTwips(RtfListTable.LIST_INDENT, fobj.getCommonMarginBlock().startIndent); attrib.setTwips(RtfText.LEFT_INDENT_BODY, fobj.getCommonMarginBlock().endIndent); /* * set list table defaults */ //set a simple list type attrib.set(RtfListTable.LIST, "simple"); //set following char as tab attrib.set(RtfListTable.LIST_FOLLOWING_CHAR, 0); return attrib; }
// in src/java/org/apache/fop/render/rtf/TableAttributesConverter.java
static RtfAttributes convertTableAttributes(Table fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrib.setTwips(ITableAttributes.ATTR_ROW_LEFT_INDENT, fobj.getCommonMarginBlock().marginLeft); return attrib; }
// in src/java/org/apache/fop/render/rtf/TableAttributesConverter.java
static RtfAttributes convertTablePartAttributes(TablePart part) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); return attrib; }
// in src/java/org/apache/fop/render/rtf/TableAttributesConverter.java
static RtfAttributes convertCellAttributes(TableCell fobj) throws FOPException { //Property p; //RtfColorTable colorTable = RtfColorTable.getInstance(); FOPRtfAttributes attrib = new FOPRtfAttributes(); //boolean isBorderPresent = false; CommonBorderPaddingBackground border = fobj.getCommonBorderPaddingBackground(); // Cell background color Color color = border.backgroundColor; if (color == null) { //If there is no background-color specified for the cell, //then try to read it from table-row or table-header. CommonBorderPaddingBackground brd = null; if (fobj.getParent() instanceof TableRow) { TableRow parentRow = (TableRow)fobj.getParent(); brd = parentRow.getCommonBorderPaddingBackground(); color = brd.backgroundColor; } else if (fobj.getParent() instanceof TableHeader) { TableHeader parentHeader = (TableHeader)fobj.getParent(); brd = parentHeader.getCommonBorderPaddingBackground(); color = brd.backgroundColor; } if (color == null && fobj.getParent() != null && fobj.getParent().getParent() != null && fobj.getParent().getParent().getParent() instanceof Table) { Table table = (Table)fobj.getParent().getParent().getParent(); brd = table.getCommonBorderPaddingBackground(); color = brd.backgroundColor; } } if ((color != null) && (color.getAlpha() != 0 || color.getRed() != 0 || color.getGreen() != 0 || color.getBlue() != 0)) { attrib.set(ITableAttributes.CELL_COLOR_BACKGROUND, color); } BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.BEFORE, attrib, ITableAttributes.CELL_BORDER_TOP); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.AFTER, attrib, ITableAttributes.CELL_BORDER_BOTTOM); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.START, attrib, ITableAttributes.CELL_BORDER_LEFT); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.END, attrib, ITableAttributes.CELL_BORDER_RIGHT); int padding; boolean reproduceMSWordBug = true; //TODO Make this configurable if (reproduceMSWordBug) { //MS Word has a bug where padding left and top are exchanged padding = border.getPaddingStart(false, null); // TODO do we need a real context here? if (padding != 0) { attrib.setTwips(ITableAttributes.ATTR_CELL_PADDING_TOP, padding); attrib.set(ITableAttributes.ATTR_CELL_U_PADDING_TOP, 3 /*=twips*/); } padding = border.getPaddingBefore(false, null); // TODO do we need a real context here? if (padding != 0) { attrib.setTwips(ITableAttributes.ATTR_CELL_PADDING_LEFT, padding); attrib.set(ITableAttributes.ATTR_CELL_U_PADDING_LEFT, 3 /*=twips*/); } } else { padding = border.getPaddingStart(false, null); // TODO do we need a real context here? if (padding != 0) { attrib.setTwips(ITableAttributes.ATTR_CELL_PADDING_LEFT, padding); attrib.set(ITableAttributes.ATTR_CELL_U_PADDING_LEFT, 3 /*=twips*/); } padding = border.getPaddingBefore(false, null); // TODO do we need a real context here? if (padding != 0) { attrib.setTwips(ITableAttributes.ATTR_CELL_PADDING_TOP, padding); attrib.set(ITableAttributes.ATTR_CELL_U_PADDING_TOP, 3 /*=twips*/); } } padding = border.getPaddingEnd(false, null); // TODO do we need a real context here? if (padding != 0) { attrib.setTwips(ITableAttributes.ATTR_CELL_PADDING_RIGHT, padding); attrib.set(ITableAttributes.ATTR_CELL_U_PADDING_RIGHT, 3 /*=twips*/); } padding = border.getPaddingAfter(false, null); // TODO do we need a real context here? if (padding != 0) { attrib.setTwips(ITableAttributes.ATTR_CELL_PADDING_BOTTOM, padding); attrib.set(ITableAttributes.ATTR_CELL_U_PADDING_BOTTOM, 3 /*=twips*/); } int n = fobj.getNumberColumnsSpanned(); // Column spanning : if (n > 1) { attrib.set(ITableAttributes.COLUMN_SPAN, n); } switch (fobj.getDisplayAlign()) { case Constants.EN_BEFORE: attrib.set(ITableAttributes.ATTR_CELL_VERT_ALIGN_TOP); break; case Constants.EN_CENTER: attrib.set(ITableAttributes.ATTR_CELL_VERT_ALIGN_CENTER); break; case Constants.EN_AFTER: attrib.set(ITableAttributes.ATTR_CELL_VERT_ALIGN_BOTTOM); break; default: //nop } return attrib; }
// in src/java/org/apache/fop/render/rtf/TableAttributesConverter.java
static RtfAttributes convertRowAttributes(TableRow fobj, RtfAttributes rtfatts) throws FOPException { //Property p; //RtfColorTable colorTable = RtfColorTable.getInstance(); RtfAttributes attrib = null; if (rtfatts == null) { attrib = new RtfAttributes(); } else { attrib = rtfatts; } //String attrValue; //boolean isBorderPresent = false; //need to set a default width //check for keep-together row attribute if (fobj.getKeepTogether().getWithinPage().getEnum() == Constants.EN_ALWAYS) { attrib.set(ITableAttributes.ROW_KEEP_TOGETHER); } //Check for keep-with-next row attribute. if (fobj.getKeepWithNext().getWithinPage().getEnum() == Constants.EN_ALWAYS) { attrib.set(ITableAttributes.ROW_KEEP_WITH_NEXT); } //Check for keep-with-previous row attribute. if (fobj.getKeepWithPrevious().getWithinPage().getEnum() == Constants.EN_ALWAYS) { attrib.set(ITableAttributes.ROW_KEEP_WITH_PREVIOUS); } //Check for height row attribute. if (fobj.getHeight().getEnum() != Constants.EN_AUTO) { attrib.set(ITableAttributes.ROW_HEIGHT, fobj.getHeight().getValue() / (1000 / 20)); } /* to write a border to a side of a cell one must write the directional * side (ie. left, right) and the inside value if one needs to be taken * out ie if the cell lies on the edge of a table or not, the offending * value will be taken out by RtfTableRow. This is because you can't * say BORDER_TOP and BORDER_HORIZONTAL if the cell lies at the top of * the table. Similarly using BORDER_BOTTOM and BORDER_HORIZONTAL will * not work if the cell lies at th bottom of the table. The same rules * apply for left right and vertical. * Also, the border type must be written after every control word. Thus * it is implemented that the border type is the value of the border * place. */ CommonBorderPaddingBackground border = fobj.getCommonBorderPaddingBackground(); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.BEFORE, attrib, ITableAttributes.CELL_BORDER_TOP); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.AFTER, attrib, ITableAttributes.CELL_BORDER_BOTTOM); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.START, attrib, ITableAttributes.CELL_BORDER_LEFT); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.END, attrib, ITableAttributes.CELL_BORDER_RIGHT); /* ep = (EnumProperty)fobj.getProperty(Constants.PR_BORDER_TOP_STYLE); if (ep != null && ep.getEnum() != Constants.EN_NONE) { attrib.set(ITableAttributes.ROW_BORDER_TOP, "\\" + convertAttributetoRtf(ep.getEnum())); attrib.set(ITableAttributes.ROW_BORDER_HORIZONTAL, "\\" + convertAttributetoRtf(ep.getEnum())); isBorderPresent = true; } ep = (EnumProperty)fobj.getProperty(Constants.PR_BORDER_BOTTOM_STYLE); if (ep != null && ep.getEnum() != Constants.EN_NONE) { attrib.set(ITableAttributes.ROW_BORDER_BOTTOM, "\\" + convertAttributetoRtf(ep.getEnum())); attrib.set(ITableAttributes.ROW_BORDER_HORIZONTAL, "\\" + convertAttributetoRtf(ep.getEnum())); isBorderPresent = true; } ep = (EnumProperty)fobj.getProperty(Constants.PR_BORDER_LEFT_STYLE); if (ep != null && ep.getEnum() != Constants.EN_NONE) { attrib.set(ITableAttributes.ROW_BORDER_LEFT, "\\" + convertAttributetoRtf(ep.getEnum())); attrib.set(ITableAttributes.ROW_BORDER_VERTICAL, "\\" + convertAttributetoRtf(ep.getEnum())); isBorderPresent = true; } ep = (EnumProperty)fobj.getProperty(Constants.PR_BORDER_RIGHT_STYLE); if (ep != null && ep.getEnum() != Constants.EN_NONE) { attrib.set(ITableAttributes.ROW_BORDER_RIGHT, "\\" + convertAttributetoRtf(ep.getEnum())); attrib.set(ITableAttributes.ROW_BORDER_VERTICAL, "\\" + convertAttributetoRtf(ep.getEnum())); isBorderPresent = true; } //Currently there is only one border width supported in each cell. p = fobj.getProperty(Constants.PR_BORDER_LEFT_WIDTH); if(p == null) { p = fobj.getProperty(Constants.PR_BORDER_RIGHT_WIDTH); } if(p == null) { p = fobj.getProperty(Constants.PR_BORDER_TOP_WIDTH); } if(p == null) { p = fobj.getProperty(Constants.PR_BORDER_BOTTOM_WIDTH); } if (p != null) { LengthProperty lengthprop = (LengthProperty)p; Float f = new Float(lengthprop.getLength().getValue() / 1000f); String sValue = f.toString() + FixedLength.POINT; attrib.set(BorderAttributesConverter.BORDER_WIDTH, (int)FoUnitsConverter.getInstance().convertToTwips(sValue)); } else if (isBorderPresent) { //if not defined, set default border width //note 20 twips = 1 point attrib.set(BorderAttributesConverter.BORDER_WIDTH, (int)FoUnitsConverter.getInstance().convertToTwips("1pt")); } */ return attrib; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public RtfTableCell newTableCellMergedHorizontally (int cellWidth, RtfAttributes attrs) throws IOException, FOPException { highestCell++; // Added by Normand Masse // Inherit attributes from base cell for merge RtfAttributes wAttributes = null; if (attrs != null) { try { wAttributes = (RtfAttributes)attrs.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } } cell = new RtfTableCell(this, writer, cellWidth, wAttributes, highestCell); cell.setHMerge(RtfTableCell.MERGE_WITH_PREVIOUS); return cell; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfText.java
public RtfAttributes getTextContainerAttributes() throws FOPException { if (attrib == null) { return null; } try { return (RtfAttributes)this.attrib.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfAttributes getTextContainerAttributes() throws FOPException { if (attrib == null) { return null; } try { return (RtfAttributes)this.attrib.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public RtfAttributes getTextContainerAttributes() throws FOPException { if (attrib == null) { return null; } try { return (RtfAttributes) this.attrib.clone (); } catch (CloneNotSupportedException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
public RtfTableRow newTableRow(RtfAttributes attrs) throws IOException, FOPException { RtfAttributes attr = null; if (attrib != null) { try { attr = (RtfAttributes) attrib.clone (); } catch (CloneNotSupportedException e) { throw new FOPException(e); } attr.set (attrs); } else { attr = attrs; } if (row != null) { row.close(); } highestRow++; row = new RtfTableRow(this, writer, attr, highestRow); return row; }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
float convertToTwips(String foValue) throws FOPException { foValue = foValue.trim(); // break value into number and units final StringBuffer number = new StringBuffer(); final StringBuffer units = new StringBuffer(); for (int i = 0; i < foValue.length(); i++) { final char c = foValue.charAt(i); if (Character.isDigit(c) || c == '.') { number.append(c); } else { // found the end of the digits units.append(foValue.substring(i).trim()); break; } } return numberToTwips(number.toString(), units.toString()); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
private float numberToTwips(String number, String units) throws FOPException { float result = 0; // convert number to integer try { if (number != null && number.trim().length() > 0) { result = Float.valueOf(number).floatValue(); } } catch (Exception e) { throw new FOPException("number format error: cannot convert '" + number + "' to float value"); } // find conversion factor if (units != null && units.trim().length() > 0) { final Float factor = (Float)TWIP_FACTORS.get(units.toLowerCase()); if (factor == null) { throw new FOPException("conversion factor not found for '" + units + "' units"); } result *= factor.floatValue(); } return result; }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
int convertFontSize(String size) throws FOPException { size = size.trim(); final String sFONTSUFFIX = FixedLength.POINT; if (!size.endsWith(sFONTSUFFIX)) { throw new FOPException("Invalid font size '" + size + "', must end with '" + sFONTSUFFIX + "'"); } float result = 0; size = size.substring(0, size.length() - sFONTSUFFIX.length()); try { result = (Float.valueOf(size).floatValue()); } catch (Exception e) { throw new FOPException("Invalid font size value '" + size + "'"); } // RTF font size units are in half-points return (int)(result * 2.0); }
// in src/java/org/apache/fop/render/rtf/TextAttributesConverter.java
public static RtfAttributes convertAttributes(Block fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrFont(fobj.getCommonFont(), attrib); attrFontColor(fobj.getColor(), attrib); //attrTextDecoration(fobj.getTextDecoration(), attrib); attrBlockBackgroundColor(fobj.getCommonBorderPaddingBackground(), attrib); attrBlockMargin(fobj.getCommonMarginBlock(), attrib); attrBlockTextAlign(fobj.getTextAlign(), attrib); attrBorder(fobj.getCommonBorderPaddingBackground(), attrib, fobj); attrBreak(fobj, attrib); return attrib; }
// in src/java/org/apache/fop/render/rtf/TextAttributesConverter.java
public static RtfAttributes convertBlockContainerAttributes(BlockContainer fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrBackgroundColor(fobj.getCommonBorderPaddingBackground(), attrib); attrBlockMargin(fobj.getCommonMarginBlock(), attrib); //attrBlockDimension(fobj, attrib); attrBorder(fobj.getCommonBorderPaddingBackground(), attrib, fobj); return attrib; }
// in src/java/org/apache/fop/render/rtf/TextAttributesConverter.java
public static RtfAttributes convertCharacterAttributes( FOText fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrFont(fobj.getCommonFont(), attrib); attrFontColor(fobj.getColor(), attrib); attrTextDecoration(fobj.getTextDecoration(), attrib); attrBaseLineShift(fobj.getBaseLineShift(), attrib); return attrib; }
// in src/java/org/apache/fop/render/rtf/TextAttributesConverter.java
public static RtfAttributes convertCharacterAttributes( PageNumber fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrFont(fobj.getCommonFont(), attrib); attrTextDecoration(fobj.getTextDecoration(), attrib); attrBackgroundColor(fobj.getCommonBorderPaddingBackground(), attrib); return attrib; }
// in src/java/org/apache/fop/render/rtf/TextAttributesConverter.java
public static RtfAttributes convertCharacterAttributes( Inline fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrFont(fobj.getCommonFont(), attrib); attrFontColor(fobj.getColor(), attrib); attrBackgroundColor(fobj.getCommonBorderPaddingBackground(), attrib); attrInlineBorder(fobj.getCommonBorderPaddingBackground(), attrib); return attrib; }
// in src/java/org/apache/fop/render/rtf/TextAttributesConverter.java
public static RtfAttributes convertLeaderAttributes(Leader fobj, PercentBaseContext context) throws FOPException { boolean tab = false; FOPRtfAttributes attrib = new FOPRtfAttributes(); attrib.set(RtfText.ATTR_FONT_FAMILY, RtfFontManager.getInstance().getFontNumber(fobj.getCommonFont().getFirstFontFamily())); if (fobj.getLeaderLength() != null) { attrib.set(RtfLeader.LEADER_WIDTH, convertMptToTwips(fobj.getLeaderLength().getMaximum( context).getLength().getValue(context))); if (fobj.getLeaderLength().getMaximum(context) instanceof PercentLength) { if (((PercentLength)fobj.getLeaderLength().getMaximum(context)).getString().equals( "100.0%")) { // Use Tab instead of white spaces attrib.set(RtfLeader.LEADER_USETAB, 1); tab = true; } } } attrFontColor(fobj.getColor(), attrib); if (fobj.getLeaderPatternWidth() != null) { //TODO calculate pattern width not possible for white spaces, because its using //underlines for tab it would work with LEADER_PATTERN_WIDTH (expndtw) } switch(fobj.getLeaderPattern()) { case Constants.EN_DOTS: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_DOTTED); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_DOTTED); } break; case Constants.EN_SPACE: //nothing has to be set for spaces break; case Constants.EN_RULE: //Things like start-indent, space-after, ... not supported? //Leader class does not offer these properties //TODO aggregate them with the leader width or // create a second - blank leader - before if (fobj.getRuleThickness() != null) { //TODO See inside RtfLeader, better calculation for //white spaces would be necessary //attrib.set(RtfLeader.LEADER_RULE_THICKNESS, // fobj.getRuleThickness().getValue(context)); log.warn("RTF: fo:leader rule-thickness not supported"); } switch (fobj.getRuleStyle()) { case Constants.EN_SOLID: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_THICK); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_THICK); } break; case Constants.EN_DASHED: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_MIDDLEDOTTED); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_MIDDLEDOTTED); } break; case Constants.EN_DOTTED: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_DOTTED); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_DOTTED); } break; case Constants.EN_DOUBLE: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_EQUAL); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_EQUAL); } break; case Constants.EN_GROOVE: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_HYPHENS); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_HYPHENS); } break; case Constants.EN_RIDGE: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_UNDERLINE); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_UNDERLINE); } break; default: break; } break; case Constants.EN_USECONTENT: log.warn("RTF: fo:leader use-content not supported"); break; default: break; } if (fobj.getLeaderAlignment() == Constants.EN_REFERENCE_AREA) { log.warn("RTF: fo:leader reference-area not supported"); } return attrib; }
// in src/java/org/apache/fop/render/bitmap/BitmapRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { super.configure(documentHandler); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { AbstractBitmapDocumentHandler bitmapHandler = (AbstractBitmapDocumentHandler)documentHandler; BitmapRenderingSettings settings = bitmapHandler.getSettings(); boolean transparent = cfg.getChild( Java2DRenderer.JAVA2D_TRANSPARENT_PAGE_BACKGROUND).getValueAsBoolean( settings.hasTransparentPageBackground()); if (transparent) { settings.setPageBackgroundColor(null); } else { String background = cfg.getChild("background-color").getValue(null); if (background != null) { settings.setPageBackgroundColor( ColorUtil.parseColorString(this.userAgent, background)); } } boolean antiAliasing = cfg.getChild("anti-aliasing").getValueAsBoolean( settings.isAntiAliasingEnabled()); settings.setAntiAliasing(antiAliasing); String optimization = cfg.getChild("rendering").getValue(null); if ("quality".equalsIgnoreCase(optimization)) { settings.setQualityRendering(true); } else if ("speed".equalsIgnoreCase(optimization)) { settings.setQualityRendering(false); } String color = cfg.getChild("color-mode").getValue(null); if (color != null) { if ("rgba".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_INT_ARGB); } else if ("rgb".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_INT_RGB); } else if ("gray".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_BYTE_GRAY); } else if ("binary".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_BYTE_BINARY); } else if ("bi-level".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_BYTE_BINARY); } else { throw new FOPException("Invalid value for color-mode: " + color); } } } }
// in src/java/org/apache/fop/render/bitmap/BitmapRendererConfigurator.java
public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo) throws FOPException { final FontManager fontManager = userAgent.getFactory().getFontManager(); final Java2DFontMetrics java2DFontMetrics = new Java2DFontMetrics(); final List fontCollections = new java.util.ArrayList(); fontCollections.add(new Base14FontCollection(java2DFontMetrics)); fontCollections.add(new InstalledFontCollection(java2DFontMetrics)); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { FontResolver fontResolver = new DefaultFontResolver(userAgent); FontEventListener listener = new FontEventAdapter( userAgent.getEventBroadcaster()); List fontList = buildFontList(cfg, fontResolver, listener); fontCollections.add(new ConfiguredFontCollection(fontResolver, fontList, userAgent.isComplexScriptFeaturesEnabled())); } fontManager.setup(fontInfo, (FontCollection[])fontCollections.toArray( new FontCollection[fontCollections.size()])); documentHandler.setFontInfo(fontInfo); }
// in src/java/org/apache/fop/render/bitmap/TIFFRendererConfigurator.java
public void configure(Renderer renderer) throws FOPException { Configuration cfg = super.getRendererConfig(renderer); if (cfg != null) { TIFFRenderer tiffRenderer = (TIFFRenderer)renderer; //set compression String name = cfg.getChild("compression").getValue(TIFFConstants.COMPRESSION_PACKBITS); //Some compression formats need a special image format: tiffRenderer.setBufferedImageType(getBufferedImageTypeFor(name)); if (!"NONE".equalsIgnoreCase(name)) { tiffRenderer.getWriterParams().setCompressionMethod(name); } if (log.isInfoEnabled()) { log.info("TIFF compression set to " + name); } } super.configure(renderer); }
// in src/java/org/apache/fop/render/bitmap/TIFFRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { super.configure(documentHandler); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { TIFFDocumentHandler tiffHandler = (TIFFDocumentHandler)documentHandler; BitmapRenderingSettings settings = tiffHandler.getSettings(); //set compression String name = cfg.getChild("compression").getValue(TIFFConstants.COMPRESSION_PACKBITS); //Some compression formats need a special image format: settings.setBufferedImageType(getBufferedImageTypeFor(name)); if (!"NONE".equalsIgnoreCase(name)) { settings.getWriterParams().setCompressionMethod(name); } if (log.isInfoEnabled()) { log.info("TIFF compression set to " + name); } } }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private List<AFPFontInfo> buildFontListFromConfiguration(Configuration cfg, AFPEventProducer eventProducer) throws FOPException, ConfigurationException { Configuration fonts = cfg.getChild("fonts"); FontManager fontManager = this.userAgent.getFactory().getFontManager(); // General matcher FontTriplet.Matcher referencedFontsMatcher = fontManager.getReferencedFontsMatcher(); // Renderer-specific matcher FontTriplet.Matcher localMatcher = null; // Renderer-specific referenced fonts Configuration referencedFontsCfg = fonts.getChild("referenced-fonts", false); if (referencedFontsCfg != null) { localMatcher = FontManagerConfigurator.createFontsMatcher( referencedFontsCfg, this.userAgent.getFactory().validateUserConfigStrictly()); } List<AFPFontInfo> fontList = new java.util.ArrayList<AFPFontInfo>(); Configuration[] font = fonts.getChildren("font"); final String fontPath = null; for (int i = 0; i < font.length; i++) { AFPFontInfo afi = buildFont(font[i], fontPath); if (afi != null) { if (log.isDebugEnabled()) { log.debug("Adding font " + afi.getAFPFont().getFontName()); } List<FontTriplet> fontTriplets = afi.getFontTriplets(); for (int j = 0; j < fontTriplets.size(); ++j) { FontTriplet triplet = fontTriplets.get(j); if (log.isDebugEnabled()) { log.debug(" Font triplet " + triplet.getName() + ", " + triplet.getStyle() + ", " + triplet.getWeight()); } if ((referencedFontsMatcher != null && referencedFontsMatcher.matches(triplet)) || (localMatcher != null && localMatcher.matches(triplet))) { afi.getAFPFont().setEmbeddable(false); break; } } fontList.add(afi); } } return fontList; }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private void configure(AFPCustomizable customizable, Configuration cfg) throws FOPException { // image information Configuration imagesCfg = cfg.getChild("images"); // default to grayscale images String imagesMode = imagesCfg.getAttribute("mode", IMAGES_MODE_GRAYSCALE); if (IMAGES_MODE_COLOR.equals(imagesMode)) { customizable.setColorImages(true); boolean cmyk = imagesCfg.getAttributeAsBoolean("cmyk", false); customizable.setCMYKImagesSupported(cmyk); } else { customizable.setColorImages(false); // default to 8 bits per pixel int bitsPerPixel = imagesCfg.getAttributeAsInteger("bits-per-pixel", 8); customizable.setBitsPerPixel(bitsPerPixel); } String dithering = imagesCfg.getAttribute("dithering-quality", "medium"); float dq = 0.5f; if (dithering.startsWith("min")) { dq = 0.0f; } else if (dithering.startsWith("max")) { dq = 1.0f; } else { try { dq = Float.parseFloat(dithering); } catch (NumberFormatException nfe) { //ignore and leave the default above } } customizable.setDitheringQuality(dq); // native image support boolean nativeImageSupport = imagesCfg.getAttributeAsBoolean("native", false); customizable.setNativeImagesSupported(nativeImageSupport); Configuration jpegConfig = imagesCfg.getChild("jpeg"); boolean allowEmbedding = false; float ieq = 1.0f; if (jpegConfig != null) { allowEmbedding = jpegConfig.getAttributeAsBoolean("allow-embedding", false); String bitmapEncodingQuality = jpegConfig.getAttribute("bitmap-encoding-quality", null); if (bitmapEncodingQuality != null) { try { ieq = Float.parseFloat(bitmapEncodingQuality); } catch (NumberFormatException nfe) { //ignore and leave the default above } } } customizable.canEmbedJpeg(allowEmbedding); customizable.setBitmapEncodingQuality(ieq); //FS11 and FS45 page segment wrapping boolean pSeg = imagesCfg.getAttributeAsBoolean("pseg", false); customizable.setWrapPSeg(pSeg); //FS45 image forcing boolean fs45 = imagesCfg.getAttributeAsBoolean("fs45", false); customizable.setFS45(fs45); // shading (filled rectangles) Configuration shadingCfg = cfg.getChild("shading"); AFPShadingMode shadingMode = AFPShadingMode.valueOf( shadingCfg.getValue(AFPShadingMode.COLOR.getName())); customizable.setShadingMode(shadingMode); // GOCA Support Configuration gocaCfg = cfg.getChild("goca"); boolean gocaEnabled = gocaCfg.getAttributeAsBoolean( "enabled", customizable.isGOCAEnabled()); customizable.setGOCAEnabled(gocaEnabled); String gocaText = gocaCfg.getAttribute( "text", customizable.isStrokeGOCAText() ? "stroke" : "default"); customizable.setStrokeGOCAText("stroke".equalsIgnoreCase(gocaText) || "shapes".equalsIgnoreCase(gocaText)); // renderer resolution Configuration rendererResolutionCfg = cfg.getChild("renderer-resolution", false); if (rendererResolutionCfg != null) { customizable.setResolution(rendererResolutionCfg.getValueAsInteger(240)); } // renderer resolution Configuration lineWidthCorrectionCfg = cfg.getChild("line-width-correction", false); if (lineWidthCorrectionCfg != null) { customizable.setLineWidthCorrection(lineWidthCorrectionCfg .getValueAsFloat(AFPConstants.LINE_WIDTH_CORRECTION)); } // a default external resource group file setting Configuration resourceGroupFileCfg = cfg.getChild("resource-group-file", false); if (resourceGroupFileCfg != null) { String resourceGroupDest = null; try { resourceGroupDest = resourceGroupFileCfg.getValue(); if (resourceGroupDest != null) { File resourceGroupFile = new File(resourceGroupDest); boolean created = resourceGroupFile.createNewFile(); if (created && resourceGroupFile.canWrite()) { customizable.setDefaultResourceGroupFilePath(resourceGroupDest); } else { log.warn("Unable to write to default external resource group file '" + resourceGroupDest + "'"); } } } catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); } catch (IOException ioe) { throw new FOPException("Could not create default external resource group file" , ioe); } } Configuration defaultResourceLevelCfg = cfg.getChild("default-resource-levels", false); if (defaultResourceLevelCfg != null) { AFPResourceLevelDefaults defaults = new AFPResourceLevelDefaults(); String[] types = defaultResourceLevelCfg.getAttributeNames(); for (int i = 0, c = types.length; i < c; i++) { String type = types[i]; try { String level = defaultResourceLevelCfg.getAttribute(type); defaults.setDefaultResourceLevel(type, AFPResourceLevel.valueOf(level)); } catch (IllegalArgumentException iae) { LogUtil.handleException(log, iae, userAgent.getFactory().validateUserConfigStrictly()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); } } customizable.setResourceLevelDefaults(defaults); } }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
Override public void configure(IFDocumentHandler documentHandler) throws FOPException { Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { AFPDocumentHandler afpDocumentHandler = (AFPDocumentHandler) documentHandler; configure(afpDocumentHandler, cfg); } }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
Override public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo) throws FOPException { FontManager fontManager = userAgent.getFactory().getFontManager(); List<AFPFontCollection> fontCollections = new ArrayList<AFPFontCollection>(); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { try { List<AFPFontInfo> fontList = buildFontListFromConfiguration(cfg, eventProducer); fontCollections.add(new AFPFontCollection( userAgent.getEventBroadcaster(), fontList)); } catch (ConfigurationException e) { eventProducer.invalidConfiguration(this, e); LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); } } else { fontCollections.add(new AFPFontCollection(userAgent.getEventBroadcaster(), null)); } fontManager.setup(fontInfo, fontCollections.toArray( new FontCollection[fontCollections.size()])); documentHandler.setFontInfo(fontInfo); }
// in src/java/org/apache/fop/render/afp/extensions/AFPInvokeMediumMapElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if (parent.getNameId() != Constants.FO_PAGE_SEQUENCE && parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfPageSequence"); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageOverlayElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if (AFPElementMapping.INCLUDE_PAGE_OVERLAY.equals(getLocalName())) { if (parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER && parent.getNameId() != Constants.FO_PAGE_SEQUENCE) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfPageSequenceOrSPM"); } } else { if (parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfSPM"); } } }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageOverlayElement.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { super.processNode(elementName, locator, attlist, propertyList); AFPPageOverlay pageOverlay = getPageSetupAttachment(); if (AFPElementMapping.INCLUDE_PAGE_OVERLAY.equals(elementName)) { // convert user specific units to mpts and set the coordinates for the page overlay AFPPaintingState paintingState = new AFPPaintingState(); AFPUnitConverter unitConverter = new AFPUnitConverter(paintingState); int x = (int)unitConverter.mpt2units(UnitConv.convert(attlist.getValue(ATT_X))); int y = (int)unitConverter.mpt2units(UnitConv.convert(attlist.getValue(ATT_Y))); pageOverlay.setX(x); pageOverlay.setY(y); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPIncludeFormMapElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if (parent.getNameId() != Constants.FO_DECLARATIONS) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfDeclarations"); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPIncludeFormMapElement.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { super.processNode(elementName, locator, attlist, propertyList); AFPIncludeFormMap formMap = getFormMapAttachment(); String attr = attlist.getValue(ATT_SRC); if (attr != null && attr.length() > 0) { try { formMap.setSrc(new URI(attr)); } catch (URISyntaxException e) { getFOValidationEventProducer().invalidPropertyValue(this, elementName, ATT_SRC, attr, null, getLocator()); } } else { missingPropertyError(ATT_SRC); } }
// in src/java/org/apache/fop/render/afp/extensions/AbstractAFPExtensionObject.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { getExtensionAttachment(); String attr = attlist.getValue("name"); if (attr != null && attr.length() > 0) { extensionAttachment.setName(attr); } else { throw new FOPException(elementName + " must have a name attribute."); } }
// in src/java/org/apache/fop/render/afp/extensions/AbstractAFPExtensionObject.java
protected void endOfNode() throws FOPException { super.endOfNode(); }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSetupElement.java
Override protected void startOfNode() throws FOPException { super.startOfNode(); if (AFPElementMapping.TAG_LOGICAL_ELEMENT.equals(getLocalName())) { if (parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER && parent.getNameId() != Constants.FO_PAGE_SEQUENCE) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfPageSequenceOrSPM"); } } else { if (parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER && parent.getNameId() != Constants.FO_PAGE_SEQUENCE && parent.getNameId() != Constants.FO_DECLARATIONS) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfSPMorPSorDeclarations"); } } }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSetupElement.java
Override protected void characters(char[] data, int start, int length, PropertyList pList, Locator locator) throws FOPException { StringBuffer sb = new StringBuffer(); AFPPageSetup pageSetup = getPageSetupAttachment(); if (pageSetup.getContent() != null) { sb.append(pageSetup.getContent()); } sb.append(data, start, length); pageSetup.setContent(sb.toString()); }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSetupElement.java
Override public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { super.processNode(elementName, locator, attlist, propertyList); AFPPageSetup pageSetup = getPageSetupAttachment(); if (AFPElementMapping.INCLUDE_PAGE_SEGMENT.equals(elementName)) { String attr = attlist.getValue(ATT_SRC); if (attr != null && attr.length() > 0) { pageSetup.setValue(attr); } else { missingPropertyError(ATT_SRC); } } else if (AFPElementMapping.TAG_LOGICAL_ELEMENT.equals(elementName)) { String attr = attlist.getValue(AFPPageSetup.ATT_VALUE); if (attr != null && attr.length() > 0) { pageSetup.setValue(attr); } else { missingPropertyError(AFPPageSetup.ATT_VALUE); } } String placement = attlist.getValue(AFPPageSetup.ATT_PLACEMENT); if (placement != null && placement.length() > 0) { pageSetup.setPlacement(ExtensionPlacement.fromXMLValue(placement)); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSegmentElement.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { AFPPageSegmentSetup pageSetup = getPageSetupAttachment(); super.processNode(elementName, locator, attlist, propertyList); String attr = attlist.getValue(ATT_RESOURCE_SRC); if (attr != null && attr.length() > 0) { pageSetup.setResourceSrc(attr); } }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public void renderPage(PageViewport pageViewport) throws IOException, FOPException { super.renderPage(pageViewport); if (statusListener != null) { statusListener.notifyPageRendered(); } }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public Dimension getPageImageSize(int pageNum) throws FOPException { Rectangle2D bounds = getPageViewport(pageNum).getViewArea(); pageWidth = (int) Math.round(bounds.getWidth() / 1000f); pageHeight = (int) Math.round(bounds.getHeight() / 1000f); double scaleX = scaleFactor * (UnitConv.IN2MM / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION) / userAgent.getTargetPixelUnitToMillimeter(); double scaleY = scaleFactor * (UnitConv.IN2MM / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION) / userAgent.getTargetPixelUnitToMillimeter(); if (getPageViewport(pageNum).getForeignAttributes() != null) { String scale = (String) getPageViewport(pageNum).getForeignAttributes().get( PageScale.EXT_PAGE_SCALE); Point2D scales = PageScale.getScale(scale); if (scales != null) { scaleX *= scales.getX(); scaleY *= scales.getY(); } } int bitmapWidth = (int) ((pageWidth * scaleX) + 0.5); int bitmapHeight = (int) ((pageHeight * scaleY) + 0.5); return new Dimension(bitmapWidth, bitmapHeight); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java
public double getScaleToFitWindow() throws FOPException { Dimension extents = previewArea.getViewport().getExtentSize(); return getScaleToFit(extents.getWidth() - 2 * BORDER_SPACING, extents.getHeight() - 2 * BORDER_SPACING); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java
public double getScaleToFitWidth() throws FOPException { Dimension extents = previewArea.getViewport().getExtentSize(); return getScaleToFit(extents.getWidth() - 2 * BORDER_SPACING, Double.MAX_VALUE); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java
public double getScaleToFit(double viewWidth, double viewHeight) throws FOPException { PageViewport pageViewport = renderer.getPageViewport(currentPage); Rectangle2D pageSize = pageViewport.getViewArea(); float screenResolution = Toolkit.getDefaultToolkit().getScreenResolution(); float screenFactor = screenResolution / UnitConv.IN2PT; double widthScale = viewWidth / (pageSize.getWidth() / 1000f) / screenFactor; double heightScale = viewHeight / (pageSize.getHeight() / 1000f) / screenFactor; return Math.min(displayMode == CONT_FACING ? widthScale / 2 : widthScale, heightScale); }
// in src/java/org/apache/fop/render/ps/PSRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { PSDocumentHandler psDocumentHandler = (PSDocumentHandler)documentHandler; configure(psDocumentHandler.getPSUtil(), cfg); } }
// in src/java/org/apache/fop/render/ps/extensions/AbstractPSExtensionElement.java
protected void endOfNode() throws FOPException { super.endOfNode(); String s = ((PSExtensionAttachment)getExtensionAttachment()).getContent(); if (s == null || s.length() == 0) { missingChildElementError("#PCDATA"); } }
// in src/java/org/apache/fop/render/ps/extensions/AbstractPSExtensionObject.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { String name = attlist.getValue("name"); if (name != null && name.length() > 0) { setupCode.setName(name); } }
// in src/java/org/apache/fop/render/ps/extensions/AbstractPSExtensionObject.java
protected void endOfNode() throws FOPException { super.endOfNode(); String s = setupCode.getContent(); if (s == null || s.length() == 0) { missingChildElementError("#PCDATA"); } }
// in src/java/org/apache/fop/render/ps/extensions/AbstractPSCommentElement.java
protected void startOfNode() throws FOPException { if (parent.getNameId() != Constants.FO_DECLARATIONS && parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfSPMorDeclarations"); } }
// in src/java/org/apache/fop/render/ps/extensions/PSSetPageDeviceElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if ( !((parent.getNameId() == Constants.FO_DECLARATIONS) || (parent.getNameId() == Constants.FO_SIMPLE_PAGE_MASTER)) ) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfSPMorDeclarations"); } }
// in src/java/org/apache/fop/render/ps/extensions/PSSetPageDeviceElement.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { String name = attlist.getValue("name"); if (name != null && name.length() > 0) { ((PSSetPageDevice)getExtensionAttachment()).setName(name); } }
// in src/java/org/apache/fop/render/ps/extensions/PSPageSetupCodeElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if (parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfSPM"); } }
// in src/java/org/apache/fop/render/ps/extensions/PSSetupCodeElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if (parent.getNameId() != Constants.FO_DECLARATIONS) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfDeclarations"); } }
// in src/java/org/apache/fop/render/java2d/Java2DRendererConfigurator.java
public void configure(Renderer renderer) throws FOPException { Configuration cfg = super.getRendererConfig(renderer); if (cfg != null) { Java2DRenderer java2dRenderer = (Java2DRenderer)renderer; String value = cfg.getChild( Java2DRenderer.JAVA2D_TRANSPARENT_PAGE_BACKGROUND, true).getValue(null); if (value != null) { java2dRenderer.setTransparentPageBackground("true".equalsIgnoreCase(value)); } } super.configure(renderer); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public void renderPage(PageViewport pageViewport) throws IOException, FOPException { try { rememberPage((PageViewport)pageViewport.clone()); } catch (CloneNotSupportedException e) { throw new FOPException(e); } //The clone() call is necessary as we store the page for later. Otherwise, the //RenderPagesModel calls PageViewport.clear() to release memory as early as possible. currentPageNumber++; }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public PageViewport getPageViewport(int pageIndex) throws FOPException { if (pageIndex < 0 || pageIndex >= pageViewportList.size()) { throw new FOPException("Requested page number is out of range: " + pageIndex + "; only " + pageViewportList.size() + " page(s) available."); } return (PageViewport) pageViewportList.get(pageIndex); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public BufferedImage getPageImage(int pageNum) throws FOPException { return getPageImage(getPageViewport(pageNum)); }
// in src/java/org/apache/fop/render/PrintRendererConfigurator.java
public void configure(Renderer renderer) throws FOPException { Configuration cfg = getRendererConfig(renderer); if (cfg == null) { log.trace("no configuration found for " + renderer); return; } PrintRenderer printRenderer = (PrintRenderer)renderer; FontResolver fontResolver = printRenderer.getFontResolver(); FontEventListener listener = new FontEventAdapter( renderer.getUserAgent().getEventBroadcaster()); List<EmbedFontInfo> embedFontInfoList = buildFontList(cfg, fontResolver, listener); printRenderer.addFontList(embedFontInfoList); }
// in src/java/org/apache/fop/render/PrintRendererConfigurator.java
protected List<EmbedFontInfo> buildFontList(Configuration cfg, FontResolver fontResolver, FontEventListener listener) throws FOPException { FopFactory factory = userAgent.getFactory(); FontManager fontManager = factory.getFontManager(); if (fontResolver == null) { //Ensure that we have minimal font resolution capabilities fontResolver = FontManager.createMinimalFontResolver ( userAgent.isComplexScriptFeaturesEnabled() ); } boolean strict = factory.validateUserConfigStrictly(); //Read font configuration FontInfoConfigurator fontInfoConfigurator = new FontInfoConfigurator(cfg, fontManager, fontResolver, listener, strict); List<EmbedFontInfo> fontInfoList = new ArrayList<EmbedFontInfo>(); fontInfoConfigurator.configure(fontInfoList); return fontInfoList; }
// in src/java/org/apache/fop/render/PrintRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { //nop }
// in src/java/org/apache/fop/render/PrintRendererConfigurator.java
public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo) throws FOPException { FontManager fontManager = userAgent.getFactory().getFontManager(); List<FontCollection> fontCollections = new ArrayList<FontCollection>(); fontCollections.add(new Base14FontCollection(fontManager.isBase14KerningEnabled())); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { FontResolver fontResolver = new DefaultFontResolver(userAgent); FontEventListener listener = new FontEventAdapter( userAgent.getEventBroadcaster()); List<EmbedFontInfo> fontList = buildFontList(cfg, fontResolver, listener); fontCollections.add(new CustomFontCollection(fontResolver, fontList, userAgent.isComplexScriptFeaturesEnabled())); } fontManager.setup(fontInfo, (FontCollection[])fontCollections.toArray( new FontCollection[fontCollections.size()])); documentHandler.setFontInfo(fontInfo); }
// in src/java/org/apache/fop/area/AreaTreeHandler.java
protected void setupModel(FOUserAgent userAgent, String outputFormat, OutputStream stream) throws FOPException { if (userAgent.isConserveMemoryPolicyEnabled()) { this.model = new CachedRenderPagesModel(userAgent, outputFormat, fontInfo, stream); } else { this.model = new RenderPagesModel(userAgent, outputFormat, fontInfo, stream); } }
// in src/java/org/apache/fop/util/LogUtil.java
public static void handleError(Log log, String errorStr, boolean strict) throws FOPException { handleException(log, new FOPException(errorStr), strict); }
// in src/java/org/apache/fop/util/LogUtil.java
public static void handleException(Log log, Exception e, boolean strict) throws FOPException { if (strict) { if (e instanceof FOPException) { throw (FOPException)e; } throw new FOPException(e); } log.error(e.getMessage()); }
// in src/java/org/apache/fop/cli/AreaTreeInputHandler.java
public void renderTo(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { FontInfo fontInfo = new FontInfo(); AreaTreeModel treeModel = new RenderPagesModel(userAgent, outputFormat, fontInfo, out); //Iterate over all intermediate files AreaTreeParser parser = new AreaTreeParser(); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(parser.getContentHandler(treeModel, userAgent)); transformTo(res); try { treeModel.endDocument(); } catch (SAXException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/cli/InputHandler.java
public void renderTo(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { FopFactory factory = userAgent.getFactory(); Fop fop; if (out != null) { fop = factory.newFop(outputFormat, userAgent, out); } else { fop = factory.newFop(outputFormat, userAgent); } // if base URL was not explicitly set in FOUserAgent, obtain here if (fop.getUserAgent().getBaseURL() == null && sourcefile != null) { String baseURL = null; try { baseURL = new File(sourcefile.getAbsolutePath()) .getParentFile().toURI().toURL().toExternalForm(); } catch (Exception e) { baseURL = ""; } fop.getUserAgent().setBaseURL(baseURL); } // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); transformTo(res); }
// in src/java/org/apache/fop/cli/InputHandler.java
public void renderTo(FOUserAgent userAgent, String outputFormat) throws FOPException { renderTo(userAgent, outputFormat, null); }
// in src/java/org/apache/fop/cli/InputHandler.java
public void transformTo(OutputStream out) throws FOPException { Result res = new StreamResult(out); transformTo(res); }
// in src/java/org/apache/fop/cli/InputHandler.java
protected void transformTo(Result result) throws FOPException { try { // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer; Source xsltSource = createXSLTSource(); if (xsltSource == null) { // FO Input transformer = factory.newTransformer(); } else { // XML/XSLT input transformer = factory.newTransformer(xsltSource); // Set the value of parameters, if any, defined for stylesheet if (xsltParams != null) { for (int i = 0; i < xsltParams.size(); i += 2) { transformer.setParameter((String) xsltParams.elementAt(i), (String) xsltParams.elementAt(i + 1)); } } if (uriResolver != null) { transformer.setURIResolver(uriResolver); } } transformer.setErrorListener(this); // Create a SAXSource from the input Source file Source src = createMainSource(); // Start XSLT transformation and FOP processing transformer.transform(src, result); } catch (Exception e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
public boolean parse(String[] args) throws FOPException, IOException { boolean optionsParsed = true; try { optionsParsed = parseOptions(args); if (optionsParsed) { if (showConfiguration == Boolean.TRUE) { dumpConfiguration(); } checkSettings(); setUserConfig(); if (flushCache) { flushCache(); } //Factory config is set up, now we can create the user agent foUserAgent = factory.newFOUserAgent(); foUserAgent.getRendererOptions().putAll(renderingOptions); if (targetResolution != 0) { foUserAgent.setTargetResolution(targetResolution); } addXSLTParameter("fop-output-format", getOutputFormat()); addXSLTParameter("fop-version", Version.getVersion()); foUserAgent.setConserveMemoryPolicy(conserveMemoryPolicy); if (!useComplexScriptFeatures) { foUserAgent.setComplexScriptFeaturesEnabled(false); } } else { return false; } } catch (FOPException e) { printUsage(System.err); throw e; } catch (java.io.FileNotFoundException e) { printUsage(System.err); throw e; } inputHandler = createInputHandler(); if (MimeConstants.MIME_FOP_AWT_PREVIEW.equals(outputmode)) { //set the system look&feel for the preview dialog try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println("Couldn't set system look & feel!"); } AWTRenderer renderer = new AWTRenderer(foUserAgent, inputHandler, true, true); foUserAgent.setRendererOverride(renderer); } else if (MimeConstants.MIME_FOP_AREA_TREE.equals(outputmode) && mimicRenderer != null) { // render from FO to Intermediate Format Renderer targetRenderer = foUserAgent.getRendererFactory().createRenderer( foUserAgent, mimicRenderer); XMLRenderer xmlRenderer = new XMLRenderer(foUserAgent); //Tell the XMLRenderer to mimic the target renderer xmlRenderer.mimicRenderer(targetRenderer); //Make sure the prepared XMLRenderer is used foUserAgent.setRendererOverride(xmlRenderer); } else if (MimeConstants.MIME_FOP_IF.equals(outputmode) && mimicRenderer != null) { // render from FO to Intermediate Format IFSerializer serializer = new IFSerializer(); serializer.setContext(new IFContext(foUserAgent)); IFDocumentHandler targetHandler = foUserAgent.getRendererFactory().createDocumentHandler( foUserAgent, mimicRenderer); serializer.mimicDocumentHandler(targetHandler); //Make sure the prepared serializer is used foUserAgent.setDocumentHandlerOverride(serializer); } return true; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private boolean parseOptions(String[] args) throws FOPException { // do not throw an exception for no args if (args.length == 0) { printVersion(); printUsage(System.out); return false; } for (int i = 0; i < args.length; i++) { if (args[i].equals("-x") || args[i].equals("--dump-config")) { showConfiguration = Boolean.TRUE; } else if (args[i].equals("-c")) { i = i + parseConfigurationOption(args, i); } else if (args[i].equals("-l")) { i = i + parseLanguageOption(args, i); } else if (args[i].equals("-s")) { suppressLowLevelAreas = Boolean.TRUE; } else if (args[i].equals("-d")) { setLogOption("debug", "debug"); } else if (args[i].equals("-r")) { factory.setStrictValidation(false); } else if (args[i].equals("-conserve")) { conserveMemoryPolicy = true; } else if (args[i].equals("-flush")) { flushCache = true; } else if (args[i].equals("-cache")) { parseCacheOption(args, i); } else if (args[i].equals("-dpi")) { i = i + parseResolution(args, i); } else if (args[i].equals("-q") || args[i].equals("--quiet")) { setLogOption("quiet", "error"); } else if (args[i].equals("-fo")) { i = i + parseFOInputOption(args, i); } else if (args[i].equals("-xsl")) { i = i + parseXSLInputOption(args, i); } else if (args[i].equals("-xml")) { i = i + parseXMLInputOption(args, i); } else if (args[i].equals("-atin")) { i = i + parseAreaTreeInputOption(args, i); } else if (args[i].equals("-ifin")) { i = i + parseIFInputOption(args, i); } else if (args[i].equals("-imagein")) { i = i + parseImageInputOption(args, i); } else if (args[i].equals("-awt")) { i = i + parseAWTOutputOption(args, i); } else if (args[i].equals("-pdf")) { i = i + parsePDFOutputOption(args, i, null); } else if (args[i].equals("-pdfa1b")) { i = i + parsePDFOutputOption(args, i, "PDF/A-1b"); } else if (args[i].equals("-mif")) { i = i + parseMIFOutputOption(args, i); } else if (args[i].equals("-rtf")) { i = i + parseRTFOutputOption(args, i); } else if (args[i].equals("-tiff")) { i = i + parseTIFFOutputOption(args, i); } else if (args[i].equals("-png")) { i = i + parsePNGOutputOption(args, i); } else if (args[i].equals("-print")) { // show print help if (i + 1 < args.length) { if (args[i + 1].equals("help")) { printUsagePrintOutput(); return false; } } i = i + parsePrintOutputOption(args, i); } else if (args[i].equals("-copies")) { i = i + parseCopiesOption(args, i); } else if (args[i].equals("-pcl")) { i = i + parsePCLOutputOption(args, i); } else if (args[i].equals("-ps")) { i = i + parsePostscriptOutputOption(args, i); } else if (args[i].equals("-txt")) { i = i + parseTextOutputOption(args, i); } else if (args[i].equals("-svg")) { i = i + parseSVGOutputOption(args, i); } else if (args[i].equals("-afp")) { i = i + parseAFPOutputOption(args, i); } else if (args[i].equals("-foout")) { i = i + parseFOOutputOption(args, i); } else if (args[i].equals("-out")) { i = i + parseCustomOutputOption(args, i); } else if (args[i].equals("-at")) { i = i + parseAreaTreeOption(args, i); } else if (args[i].equals("-if")) { i = i + parseIntermediateFormatOption(args, i); } else if (args[i].equals("-a")) { this.renderingOptions.put(Accessibility.ACCESSIBILITY, Boolean.TRUE); } else if (args[i].equals("-v")) { /* verbose mode although users may expect version; currently just print the version */ printVersion(); if (args.length == 1) { return false; } } else if (args[i].equals("-param")) { if (i + 2 < args.length) { String name = args[++i]; String expression = args[++i]; addXSLTParameter(name, expression); } else { throw new FOPException("invalid param usage: use -param <name> <value>"); } } else if (args[i].equals("-catalog")) { useCatalogResolver = true; } else if (args[i].equals("-o")) { i = i + parsePDFOwnerPassword(args, i); } else if (args[i].equals("-u")) { i = i + parsePDFUserPassword(args, i); } else if (args[i].equals("-pdfprofile")) { i = i + parsePDFProfile(args, i); } else if (args[i].equals("-noprint")) { getPDFEncryptionParams().setAllowPrint(false); } else if (args[i].equals("-nocopy")) { getPDFEncryptionParams().setAllowCopyContent(false); } else if (args[i].equals("-noedit")) { getPDFEncryptionParams().setAllowEditContent(false); } else if (args[i].equals("-noannotations")) { getPDFEncryptionParams().setAllowEditAnnotations(false); } else if (args[i].equals("-nocs")) { useComplexScriptFeatures = false; } else if (args[i].equals("-nofillinforms")) { getPDFEncryptionParams().setAllowFillInForms(false); } else if (args[i].equals("-noaccesscontent")) { getPDFEncryptionParams().setAllowAccessContent(false); } else if (args[i].equals("-noassembledoc")) { getPDFEncryptionParams().setAllowAssembleDocument(false); } else if (args[i].equals("-noprinthq")) { getPDFEncryptionParams().setAllowPrintHq(false); } else if (args[i].equals("-version")) { printVersion(); return false; } else if (!isOption(args[i])) { i = i + parseUnknownOption(args, i); } else { printUsage(System.err); System.exit(1); } } return true; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseCacheOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("if you use '-cache', you must specify " + "the name of the font cache file"); } else { factory.getFontManager().setCacheFile(new File(args[i + 1])); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseConfigurationOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("if you use '-c', you must specify " + "the name of the configuration file"); } else { userConfigFile = new File(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseLanguageOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("if you use '-l', you must specify a language"); } else { Locale.setDefault(new Locale(args[i + 1], "")); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseResolution(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException( "if you use '-dpi', you must specify a resolution (dots per inch)"); } else { this.targetResolution = Integer.parseInt(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseFOInputOption(String[] args, int i) throws FOPException { setInputFormat(FO_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the fo file for the '-fo' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { fofile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseXSLInputOption(String[] args, int i) throws FOPException { setInputFormat(XSLT_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the stylesheet " + "file for the '-xsl' option"); } else { xsltfile = new File(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseXMLInputOption(String[] args, int i) throws FOPException { setInputFormat(XSLT_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the input file " + "for the '-xml' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { xmlfile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAWTOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_FOP_AWT_PREVIEW); return 0; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePDFOutputOption(String[] args, int i, String pdfAMode) throws FOPException { setOutputMode(MimeConstants.MIME_PDF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PDF output file"); } else { setOutputFile(args[i + 1]); if (pdfAMode != null) { if (renderingOptions.get("pdf-a-mode") != null) { throw new FOPException("PDF/A mode already set"); } renderingOptions.put("pdf-a-mode", pdfAMode); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseMIFOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_MIF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the MIF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseRTFOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_RTF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the RTF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseTIFFOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_TIFF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the TIFF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePNGOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_PNG); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PNG output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePrintOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_FOP_PRINT); if ((i + 1 < args.length) && (args[i + 1].charAt(0) != '-')) { String arg = args[i + 1]; String[] parts = arg.split(","); for (int j = 0; j < parts.length; j++) { String s = parts[j]; if (s.matches("\\d+")) { renderingOptions.put(PrintRenderer.START_PAGE, new Integer(s)); } else if (s.matches("\\d+-\\d+")) { String[] startend = s.split("-"); renderingOptions.put(PrintRenderer.START_PAGE, new Integer(startend[0])); renderingOptions.put(PrintRenderer.END_PAGE, new Integer(startend[1])); } else { PagesMode mode = PagesMode.byName(s); renderingOptions.put(PrintRenderer.PAGES_MODE, mode); } } return 1; } else { return 0; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseCopiesOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the number of copies"); } else { renderingOptions.put(PrintRenderer.COPIES, new Integer(args[i + 1])); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePCLOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_PCL); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PDF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePostscriptOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_POSTSCRIPT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PostScript output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseTextOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_PLAIN_TEXT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the text output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseSVGOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_SVG); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the SVG output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAFPOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_AFP); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the AFP output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseFOOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_XSL_FO); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the FO output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseCustomOutputOption(String[] args, int i) throws FOPException { String mime = null; if ((i + 1 < args.length) || (args[i + 1].charAt(0) != '-')) { mime = args[i + 1]; if ("list".equals(mime)) { String[] mimes = factory.getRendererFactory().listSupportedMimeTypes(); System.out.println("Supported MIME types:"); for (int j = 0; j < mimes.length; j++) { System.out.println(" " + mimes[j]); } System.exit(0); } } if ((i + 2 >= args.length) || (isOption(args[i + 1])) || (isOption(args[i + 2]))) { throw new FOPException("you must specify the output format and the output file"); } else { setOutputMode(mime); setOutputFile(args[i + 2]); return 2; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseUnknownOption(String[] args, int i) throws FOPException { if (inputmode == NOT_SET) { inputmode = FO_INPUT; String filename = args[i]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { fofile = new File(filename); } } else if (outputmode == null) { outputmode = MimeConstants.MIME_PDF; setOutputFile(args[i]); } else { throw new FOPException("Don't know what to do with " + args[i]); } return 0; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAreaTreeOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_FOP_AREA_TREE); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the area-tree output file"); } else if ((i + 2 == args.length) || (isOption(args[i + 2]))) { // only output file is specified setOutputFile(args[i + 1]); return 1; } else { // mimic format and output file have been specified mimicRenderer = args[i + 1]; setOutputFile(args[i + 2]); return 2; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseIntermediateFormatOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_FOP_IF); if ((i + 1 == args.length) || (args[i + 1].charAt(0) == '-')) { throw new FOPException("you must specify the intermediate format output file"); } else if ((i + 2 == args.length) || (args[i + 2].charAt(0) == '-')) { // only output file is specified setOutputFile(args[i + 1]); return 1; } else { // mimic format and output file have been specified mimicRenderer = args[i + 1]; setOutputFile(args[i + 2]); return 2; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAreaTreeInputOption(String[] args, int i) throws FOPException { setInputFormat(AREATREE_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the Area Tree file for the '-atin' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { areatreefile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseIFInputOption(String[] args, int i) throws FOPException { setInputFormat(IF_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the intermediate file for the '-ifin' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { iffile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseImageInputOption(String[] args, int i) throws FOPException { setInputFormat(IMAGE_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the image file for the '-imagein' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { imagefile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private PDFEncryptionParams getPDFEncryptionParams() throws FOPException { PDFEncryptionParams params = (PDFEncryptionParams)renderingOptions.get( PDFConfigurationConstants.ENCRYPTION_PARAMS); if (params == null) { if (!PDFEncryptionManager.checkAvailableAlgorithms()) { throw new FOPException("PDF encryption requested but it is not available." + " Please make sure MD5 and RC4 algorithms are available."); } params = new PDFEncryptionParams(); renderingOptions.put(PDFConfigurationConstants.ENCRYPTION_PARAMS, params); } return params; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePDFOwnerPassword(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { getPDFEncryptionParams().setOwnerPassword(""); return 0; } else { getPDFEncryptionParams().setOwnerPassword(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePDFUserPassword(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { getPDFEncryptionParams().setUserPassword(""); return 0; } else { getPDFEncryptionParams().setUserPassword(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePDFProfile(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("You must specify a PDF profile"); } else { String profile = args[i + 1]; PDFAMode pdfAMode = PDFAMode.valueOf(profile); if (pdfAMode != null && pdfAMode != PDFAMode.DISABLED) { if (renderingOptions.get("pdf-a-mode") != null) { throw new FOPException("PDF/A mode already set"); } renderingOptions.put("pdf-a-mode", pdfAMode.getName()); return 1; } else { PDFXMode pdfXMode = PDFXMode.valueOf(profile); if (pdfXMode != null && pdfXMode != PDFXMode.DISABLED) { if (renderingOptions.get("pdf-x-mode") != null) { throw new FOPException("PDF/X mode already set"); } renderingOptions.put("pdf-x-mode", pdfXMode.getName()); return 1; } } throw new FOPException("Unsupported PDF profile: " + profile); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setOutputMode(String mime) throws FOPException { if (outputmode == null) { outputmode = mime; } else { throw new FOPException("you can only set one output method"); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setInputFormat(int format) throws FOPException { if (inputmode == NOT_SET || inputmode == format) { inputmode = format; } else { throw new FOPException("Only one input mode can be specified!"); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void checkSettings() throws FOPException, FileNotFoundException { if (inputmode == NOT_SET) { throw new FOPException("No input file specified"); } if (outputmode == null) { throw new FOPException("No output file specified"); } if ((outputmode.equals(MimeConstants.MIME_FOP_AWT_PREVIEW) || outputmode.equals(MimeConstants.MIME_FOP_PRINT)) && outfile != null) { throw new FOPException("Output file may not be specified " + "for AWT or PRINT output"); } if (inputmode == XSLT_INPUT) { // check whether xml *and* xslt file have been set if (xmlfile == null && !this.useStdIn) { throw new FOPException("XML file must be specified for the transform mode"); } if (xsltfile == null) { throw new FOPException("XSLT file must be specified for the transform mode"); } // warning if fofile has been set in xslt mode if (fofile != null) { log.warn("Can't use fo file with transform mode! Ignoring.\n" + "Your input is " + "\n xmlfile: " + xmlfile.getAbsolutePath() + "\nxsltfile: " + xsltfile.getAbsolutePath() + "\n fofile: " + fofile.getAbsolutePath()); } if (xmlfile != null && !xmlfile.exists()) { throw new FileNotFoundException("Error: xml file " + xmlfile.getAbsolutePath() + " not found "); } if (!xsltfile.exists()) { throw new FileNotFoundException("Error: xsl file " + xsltfile.getAbsolutePath() + " not found "); } } else if (inputmode == FO_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (fofile != null && !fofile.exists()) { throw new FileNotFoundException("Error: fo file " + fofile.getAbsolutePath() + " not found "); } } else if (inputmode == AREATREE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Area Tree is used as input!"); } if (areatreefile != null && !areatreefile.exists()) { throw new FileNotFoundException("Error: area tree file " + areatreefile.getAbsolutePath() + " not found "); } } else if (inputmode == IF_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Intermediate Format" + " is used as input!"); } else if (outputmode.equals(MimeConstants.MIME_FOP_IF)) { throw new FOPException( "Intermediate Output is not available if Intermediate Format" + " is used as input!"); } if (iffile != null && !iffile.exists()) { throw new FileNotFoundException("Error: intermediate format file " + iffile.getAbsolutePath() + " not found "); } } else if (inputmode == IMAGE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (imagefile != null && !imagefile.exists()) { throw new FileNotFoundException("Error: image file " + imagefile.getAbsolutePath() + " not found "); } } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setUserConfig() throws FOPException, IOException { if (userConfigFile == null) { return; } try { factory.setUserConfig(userConfigFile); } catch (SAXException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
protected String getOutputFormat() throws FOPException { if (outputmode == null) { throw new FOPException("Renderer has not been set!"); } if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { renderingOptions.put("fineDetail", isCoarseAreaXml()); } return outputmode; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void flushCache() throws FOPException { FontManager fontManager = factory.getFontManager(); File cacheFile = fontManager.getCacheFile(); if (!fontManager.deleteCache()) { System.err.println("Failed to flush the font cache file '" + cacheFile + "'."); System.exit(1); } }
// in src/java/org/apache/fop/cli/IFInputHandler.java
public void renderTo(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { IFDocumentHandler documentHandler = userAgent.getFactory().getRendererFactory().createDocumentHandler( userAgent, outputFormat); try { documentHandler.setResult(new StreamResult(out)); IFUtil.setupFonts(documentHandler); //Create IF parser IFParser parser = new IFParser(); // Resulting SAX events are sent to the parser Result res = new SAXResult(parser.getContentHandler(documentHandler, userAgent)); transformTo(res); } catch (IFException ife) { throw new FOPException(ife); } }
(Domain) PropertyException 85
              
// in src/java/org/apache/fop/fo/properties/TextDecorationMaker.java
Override public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { ListProperty listProp = (ListProperty) super.convertProperty(p, propertyList, fo); List lst = listProp.getList(); boolean none = false; boolean under = false; boolean over = false; boolean through = false; boolean blink = false; int enumValue = -1; for (int i = lst.size(); --i >= 0;) { Property prop = (Property)lst.get(i); if (prop instanceof NCnameProperty) { prop = checkEnumValues(prop.getString()); lst.set(i, prop); } if (prop != null) { enumValue = prop.getEnum(); } switch (enumValue) { case Constants.EN_NONE: if (under | over | through | blink) { throw new PropertyException("Invalid combination of values"); } none = true; break; case Constants.EN_UNDERLINE: case Constants.EN_NO_UNDERLINE: case Constants.EN_OVERLINE: case Constants.EN_NO_OVERLINE: case Constants.EN_LINE_THROUGH: case Constants.EN_NO_LINE_THROUGH: case Constants.EN_BLINK: case Constants.EN_NO_BLINK: if (none) { throw new PropertyException ("'none' specified, no additional values allowed"); } switch (enumValue) { case Constants.EN_UNDERLINE: case Constants.EN_NO_UNDERLINE: if (!under) { under = true; continue; } case Constants.EN_OVERLINE: case Constants.EN_NO_OVERLINE: if (!over) { over = true; continue; } case Constants.EN_LINE_THROUGH: case Constants.EN_NO_LINE_THROUGH: if (!through) { through = true; continue; } case Constants.EN_BLINK: case Constants.EN_NO_BLINK: if (!blink) { blink = true; continue; } default: throw new PropertyException("Invalid combination of values"); } default: throw new PropertyException("Invalid value specified: " + p); } } return listProp; }
// in src/java/org/apache/fop/fo/properties/CommonTextDecoration.java
private static CommonTextDecoration calcTextDecoration(PropertyList pList) throws PropertyException { CommonTextDecoration deco = null; PropertyList parentList = pList.getParentPropertyList(); if (parentList != null) { //Parent is checked first deco = calcTextDecoration(parentList); } //For rules, see XSL 1.0, chapters 5.5.6 and 7.16.4 Property textDecoProp = pList.getExplicit(Constants.PR_TEXT_DECORATION); if (textDecoProp != null) { List list = textDecoProp.getList(); Iterator i = list.iterator(); while (i.hasNext()) { Property prop = (Property)i.next(); int propEnum = prop.getEnum(); FOUserAgent ua = (pList == null) ? null : (pList.getFObj() == null ? null : pList.getFObj().getUserAgent()); if (propEnum == Constants.EN_NONE) { if (deco != null) { deco.decoration = 0; } return deco; } else if (propEnum == Constants.EN_UNDERLINE) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= UNDERLINE; deco.underColor = pList.get(Constants.PR_COLOR).getColor(ua); } else if (propEnum == Constants.EN_NO_UNDERLINE) { if (deco != null) { deco.decoration &= OVERLINE | LINE_THROUGH | BLINK; deco.underColor = pList.get(Constants.PR_COLOR).getColor(ua); } } else if (propEnum == Constants.EN_OVERLINE) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= OVERLINE; deco.overColor = pList.get(Constants.PR_COLOR).getColor(ua); } else if (propEnum == Constants.EN_NO_OVERLINE) { if (deco != null) { deco.decoration &= UNDERLINE | LINE_THROUGH | BLINK; deco.overColor = pList.get(Constants.PR_COLOR).getColor(ua); } } else if (propEnum == Constants.EN_LINE_THROUGH) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= LINE_THROUGH; deco.throughColor = pList.get(Constants.PR_COLOR).getColor(ua); } else if (propEnum == Constants.EN_NO_LINE_THROUGH) { if (deco != null) { deco.decoration &= UNDERLINE | OVERLINE | BLINK; deco.throughColor = pList.get(Constants.PR_COLOR).getColor(ua); } } else if (propEnum == Constants.EN_BLINK) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= BLINK; } else if (propEnum == Constants.EN_NO_BLINK) { if (deco != null) { deco.decoration &= UNDERLINE | OVERLINE | LINE_THROUGH; } } else { throw new PropertyException("Illegal value encountered: " + prop.getString()); } } } return deco; }
// in src/java/org/apache/fop/fo/properties/URIProperty.java
Override public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { Property p = null; //special treament for data: URIs if (value.matches("(?s)^(url\\(('|\")?)?data:.*$")) { p = new URIProperty(value, false); } else { try { URI specifiedURI = new URI(URISpecification.escapeURI(value)); URIProperty xmlBase = (URIProperty)propertyList.get(PR_X_XML_BASE, true, false); if (xmlBase == null) { //xml:base undefined if (this.propId == PR_X_XML_BASE) { //if current property is xml:base, define a new one p = new URIProperty(specifiedURI); p.setSpecifiedValue(value); } else { //otherwise, just store the specified value (for backward compatibility) p = new URIProperty(value, false); } } else { //xml:base defined, so resolve p = new URIProperty(xmlBase.resolvedURI.resolve(specifiedURI)); p.setSpecifiedValue(value); } } catch (URISyntaxException use) { // Let PropertyList propagate the exception throw new PropertyException("Invalid URI specified"); } } return p; }
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { try { FontShorthandProperty newProp = new FontShorthandProperty(); newProp.setSpecifiedValue(value); String specVal = value; Property prop = null; if ("inherit".equals(specVal)) { /* fill the list with the individual properties from the parent */ for (int i = PROP_IDS.length; --i >= 0;) { prop = propertyList.getFromParent(PROP_IDS[i]); newProp.addProperty(prop, i); } } else { /* initialize list with nulls */ for (int pos = PROP_IDS.length; --pos >= 0;) { newProp.addProperty(null, pos); } prop = checkEnumValues(specVal); if (prop == null) { /* not an enum: * value should consist at least of font-size and font-family * separated by a space * mind the possible spaces from quoted font-family names */ int spaceIndex = value.indexOf(' '); int quoteIndex = (value.indexOf('\'') == -1) ? value.indexOf('\"') : value.indexOf('\''); if (spaceIndex == -1 || (quoteIndex != -1 && spaceIndex > quoteIndex)) { /* no spaces or first space appears after the first * single/double quote, so malformed value string */ throw new PropertyException("Invalid property value: " + "font=\"" + value + "\""); } PropertyMaker m = null; int fromIndex = spaceIndex + 1; int toIndex = specVal.length(); /* at least one space that appears before the first * single/double quote, so extract the individual properties */ boolean fontFamilyParsed = false; int commaIndex = value.indexOf(','); while (!fontFamilyParsed) { /* value contains a (list of) possibly quoted * font-family name(s) */ if (commaIndex == -1) { /* no list, just a single name * (or first name in the list) */ if (quoteIndex != -1) { /* a single name, quoted */ fromIndex = quoteIndex; } m = FObj.getPropertyMakerFor(PROP_IDS[1]); prop = m.make(propertyList, specVal.substring(fromIndex), fo); newProp.addProperty(prop, 1); fontFamilyParsed = true; } else { if (quoteIndex != -1 && quoteIndex < commaIndex) { /* a quoted font-family name as first name * in the comma-separated list * fromIndex = index of the first quote */ fromIndex = quoteIndex; quoteIndex = -1; } else { fromIndex = value.lastIndexOf(' ', commaIndex) + 1; } commaIndex = -1; } } toIndex = fromIndex - 1; fromIndex = value.lastIndexOf(' ', toIndex - 1) + 1; value = specVal.substring(fromIndex, toIndex); int slashIndex = value.indexOf('/'); String fontSize = value.substring(0, (slashIndex == -1) ? value.length() : slashIndex); m = FObj.getPropertyMakerFor(PROP_IDS[0]); prop = m.make(propertyList, fontSize, fo); /* need to make sure subsequent call to LineHeightPropertyMaker.make() * doesn't generate the default font-size property... */ propertyList.putExplicit(PROP_IDS[0], prop); newProp.addProperty(prop, 0); if (slashIndex != -1) { /* line-height */ String lineHeight = value.substring(slashIndex + 1); m = FObj.getPropertyMakerFor(PROP_IDS[2]); prop = m.make(propertyList, lineHeight, fo); newProp.addProperty(prop, 2); } if (fromIndex != 0) { toIndex = fromIndex - 1; value = specVal.substring(0, toIndex); fromIndex = 0; spaceIndex = value.indexOf(' '); do { toIndex = (spaceIndex == -1) ? value.length() : spaceIndex; String val = value.substring(fromIndex, toIndex); for (int i = 6; --i >= 3;) { if (newProp.list.get(i) == null) { /* not set */ m = FObj.getPropertyMakerFor(PROP_IDS[i]); val = m.checkValueKeywords(val); prop = m.checkEnumValues(val); if (prop != null) { newProp.addProperty(prop, i); } } } fromIndex = toIndex + 1; spaceIndex = value.indexOf(' ', fromIndex); } while (toIndex != value.length()); } } else { //TODO: implement enum values log.warn("Enum values other than \"inherit\"" + " not yet supported for the font shorthand."); return null; } } if (newProp.list.get(0) == null || newProp.list.get(1) == null) { throw new PropertyException("Invalid property value: " + "font-size and font-family are required for the font shorthand" + "\nfont=\"" + value + "\""); } return newProp; } catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; } }
// in src/java/org/apache/fop/fo/properties/ReferenceOrientationMaker.java
public Property get(int subpropId, PropertyList propertyList, boolean tryInherit, boolean tryDefault) throws PropertyException { Property p = super.get(0, propertyList, tryInherit, tryDefault); int ro = 0; if (p != null) { ro = p.getNumeric().getValue(); } if ((Math.abs(ro) % 90) == 0 && (Math.abs(ro) / 90) <= 3) { return p; } else { throw new PropertyException("Illegal property value: " + "reference-orientation=\"" + ro + "\" " + "on " + propertyList.getFObj().getName()); } }
// in src/java/org/apache/fop/fo/properties/BorderSpacingShorthandParser.java
protected Property convertValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { List lst = property.getList(); if (lst != null) { if (lst.size() == 1) { Property len = (Property)lst.get(0); return new LengthPairProperty(len); } else if (lst.size() == 2) { Property ipd = (Property)lst.get(0); Property bpd = (Property)lst.get(1); return new LengthPairProperty(ipd, bpd); } } throw new PropertyException("list with 1 or 2 length values expected"); }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { try { Property newProp = null; String pvalue = value; if ("inherit".equals(value)) { newProp = propertyList.getFromParent(this.propId & Constants.PROPERTY_MASK); if ((propId & Constants.COMPOUND_MASK) != 0) { newProp = getSubprop(newProp, propId & Constants.COMPOUND_MASK); } if (!isInherited() && LOG.isWarnEnabled()) { /* check whether explicit value is available on the parent * (for inherited properties, an inherited value will always * be available) */ Property parentExplicit = propertyList.getParentPropertyList() .getExplicit(getPropId()); if (parentExplicit == null) { LOG.warn(FOPropertyMapping.getPropertyName(getPropId()) + "=\"inherit\" on " + propertyList.getFObj().getName() + ", but no explicit value found on the parent FO."); } } } else { // Check for keyword shorthand values to be substituted. pvalue = checkValueKeywords(pvalue.trim()); newProp = checkEnumValues(pvalue); } if (newProp == null) { // Override parsePropertyValue in each subclass of Property.Maker newProp = PropertyParser.parse(pvalue, new PropertyInfo(this, propertyList)); } if (newProp != null) { newProp = convertProperty(newProp, propertyList, fo); } if (newProp == null) { throw new PropertyException("No conversion defined " + pvalue); } return newProp; } catch (PropertyException propEx) { if (fo != null) { propEx.setLocator(fo.getLocator()); } propEx.setPropertyName(getName()); throw propEx; } }
// in src/java/org/apache/fop/fo/expr/FromTableColumnFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { FObj fo = pInfo.getPropertyList().getFObj(); /* obtain property Id for the property for which the function is being * evaluated */ int propId = 0; if (args.length == 0) { propId = pInfo.getPropertyMaker().getPropId(); } else { String propName = args[0].getString(); propId = FOPropertyMapping.getPropertyId(propName); } /* make sure we have a correct property id ... */ if (propId != -1) { /* obtain column number for which the function is being evaluated: */ int columnNumber = -1; int span = 0; if (fo.getNameId() != Constants.FO_TABLE_CELL) { // climb up to the nearest cell do { fo = (FObj) fo.getParent(); } while (fo.getNameId() != Constants.FO_TABLE_CELL && fo.getNameId() != Constants.FO_PAGE_SEQUENCE); if (fo.getNameId() == Constants.FO_TABLE_CELL) { //column-number is available on the cell columnNumber = ((TableCell) fo).getColumnNumber(); span = ((TableCell) fo).getNumberColumnsSpanned(); } else { //means no table-cell was found... throw new PropertyException("from-table-column() may only be used on " + "fo:table-cell or its descendants."); } } else { //column-number is only accurately available through the propertyList columnNumber = pInfo.getPropertyList().get(Constants.PR_COLUMN_NUMBER) .getNumeric().getValue(); span = pInfo.getPropertyList().get(Constants.PR_NUMBER_COLUMNS_SPANNED) .getNumeric().getValue(); } /* return the property from the column */ Table t = ((TableFObj) fo).getTable(); List cols = t.getColumns(); ColumnNumberManager columnIndexManager = t.getColumnNumberManager(); if (cols == null) { //no columns defined => no match: return default value return pInfo.getPropertyList().get(propId, false, true); } else { if (columnIndexManager.isColumnNumberUsed(columnNumber)) { //easiest case: exact match return ((TableColumn) cols.get(columnNumber - 1)).getProperty(propId); } else { //no exact match: try all spans... while (--span > 0 && !columnIndexManager.isColumnNumberUsed(++columnNumber)) { //nop: just increment/decrement } if (columnIndexManager.isColumnNumberUsed(columnNumber)) { return ((TableColumn) cols.get(columnNumber - 1)).getProperty(propId); } else { //no match: return default value return pInfo.getPropertyList().get(propId, false, true); } } } } else { throw new PropertyException("Incorrect parameter to from-table-column() function"); } }
// in src/java/org/apache/fop/fo/expr/AbsFunction.java
public Property eval(Property[] args, PropertyInfo propInfo) throws PropertyException { Numeric num = args[0].getNumeric(); if (num == null) { throw new PropertyException("Non numeric operand to abs function"); } // TODO: What if it has relative components (percent, table-col units)? return (Property) NumericOp.abs(num); }
// in src/java/org/apache/fop/fo/expr/LabelEndFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Length distance = pInfo.getPropertyList().get( Constants.PR_PROVISIONAL_DISTANCE_BETWEEN_STARTS).getLength(); Length separation = pInfo.getPropertyList().getNearestSpecified( Constants.PR_PROVISIONAL_LABEL_SEPARATION).getLength(); PropertyList pList = pInfo.getPropertyList(); while (pList != null && !(pList.getFObj() instanceof ListItem)) { pList = pList.getParentPropertyList(); } if (pList == null) { throw new PropertyException("label-end() called from outside an fo:list-item"); } Length startIndent = pList.get(Constants.PR_START_INDENT).getLength(); LengthBase base = new LengthBase(pInfo.getPropertyList(), LengthBase.CONTAINING_REFAREA_WIDTH); PercentLength refWidth = new PercentLength(1.0, base); Numeric labelEnd = distance; labelEnd = NumericOp.addition(labelEnd, startIndent); //TODO add start-intrusion-adjustment labelEnd = NumericOp.subtraction(labelEnd, separation); labelEnd = NumericOp.subtraction(refWidth, labelEnd); return (Property) labelEnd; }
// in src/java/org/apache/fop/fo/expr/BodyStartFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Numeric distance = pInfo.getPropertyList() .get(Constants.PR_PROVISIONAL_DISTANCE_BETWEEN_STARTS).getNumeric(); PropertyList pList = pInfo.getPropertyList(); while (pList != null && !(pList.getFObj() instanceof ListItem)) { pList = pList.getParentPropertyList(); } if (pList == null) { throw new PropertyException("body-start() called from outside an fo:list-item"); } Numeric startIndent = pList.get(Constants.PR_START_INDENT).getNumeric(); return (Property) NumericOp.addition(distance, startIndent); }
// in src/java/org/apache/fop/fo/expr/FromParentFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { String propName = args[0].getString(); if (propName == null) { throw new PropertyException("Incorrect parameter to from-parent function"); } // NOTE: special cases for shorthand property // Should return COMPUTED VALUE /* * For now, this is the same as inherited-property-value(propName) * (The only difference I can see is that this could work for * non-inherited properties too. Perhaps the result is different for * a property line line-height which "inherits specified"??? */ int propId = FOPropertyMapping.getPropertyId(propName); if (propId < 0) { throw new PropertyException( "Unknown property name used with inherited-property-value function: " + propName); } return pInfo.getPropertyList().getFromParent(propId); }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
private Numeric getResolved(PercentBaseContext context) throws PropertyException { switch (operation) { case ADDITION: return NumericOp.addition2(op1, op2, context); case SUBTRACTION: return NumericOp.subtraction2(op1, op2, context); case MULTIPLY: return NumericOp.multiply2(op1, op2, context); case DIVIDE: return NumericOp.divide2(op1, op2, context); case MODULO: return NumericOp.modulo2(op1, op2, context); case NEGATE: return NumericOp.negate2(op1, context); case ABS: return NumericOp.abs2(op1, context); case MAX: return NumericOp.max2(op1, op2, context); case MIN: return NumericOp.min2(op1, op2, context); default: throw new PropertyException("Unknown expr operation " + operation); } }
// in src/java/org/apache/fop/fo/expr/RoundFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number dbl = args[0].getNumber(); if (dbl == null) { throw new PropertyException("Non number operand to round function"); } double n = dbl.doubleValue(); double r = Math.floor(n + 0.5); if (r == 0.0 && n < 0.0) { r = -r; // round(-0.2) returns -0 not 0 } return NumberProperty.getInstance(r); }
// in src/java/org/apache/fop/fo/expr/PropertyTokenizer.java
void next() throws PropertyException { currentTokenValue = null; currentTokenStartIndex = exprIndex; boolean bSawDecimal; while ( true ) { if (exprIndex >= exprLength) { currentToken = TOK_EOF; return; } char c = expr.charAt(exprIndex++); switch (c) { case ' ': case '\t': case '\r': case '\n': currentTokenStartIndex = exprIndex; break; case ',': currentToken = TOK_COMMA; return; case '+': currentToken = TOK_PLUS; return; case '-': currentToken = TOK_MINUS; return; case '(': currentToken = TOK_LPAR; return; case ')': currentToken = TOK_RPAR; return; case '"': case '\'': exprIndex = expr.indexOf(c, exprIndex); if (exprIndex < 0) { exprIndex = currentTokenStartIndex + 1; throw new PropertyException("missing quote"); } currentTokenValue = expr.substring(currentTokenStartIndex + 1, exprIndex++); currentToken = TOK_LITERAL; return; case '*': /* * if (currentMaybeOperator) { * recognizeOperator = false; */ currentToken = TOK_MULTIPLY; /* * } * else * throw new PropertyException("illegal operator *"); */ return; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': scanDigits(); if (exprIndex < exprLength && expr.charAt(exprIndex) == '.') { exprIndex++; bSawDecimal = true; if (exprIndex < exprLength && isDigit(expr.charAt(exprIndex))) { exprIndex++; scanDigits(); } } else { bSawDecimal = false; } if (exprIndex < exprLength && expr.charAt(exprIndex) == '%') { exprIndex++; currentToken = TOK_PERCENT; } else { // Check for possible unit name following number currentUnitLength = exprIndex; scanName(); currentUnitLength = exprIndex - currentUnitLength; currentToken = (currentUnitLength > 0) ? TOK_NUMERIC : (bSawDecimal ? TOK_FLOAT : TOK_INTEGER); } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); return; case '.': nextDecimalPoint(); return; case '#': // Start of color value nextColor(); return; default: --exprIndex; scanName(); if (exprIndex == currentTokenStartIndex) { throw new PropertyException("illegal character"); } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); if (currentTokenValue.equals("mod")) { currentToken = TOK_MOD; return; } else if (currentTokenValue.equals("div")) { currentToken = TOK_DIV; return; } if (followingParen()) { currentToken = TOK_FUNCTION_LPAR; } else { currentToken = TOK_NCNAME; } return; } } }
// in src/java/org/apache/fop/fo/expr/PropertyTokenizer.java
private void nextDecimalPoint() throws PropertyException { if (exprIndex < exprLength && isDigit(expr.charAt(exprIndex))) { ++exprIndex; scanDigits(); if (exprIndex < exprLength && expr.charAt(exprIndex) == '%') { exprIndex++; currentToken = TOK_PERCENT; } else { // Check for possible unit name following number currentUnitLength = exprIndex; scanName(); currentUnitLength = exprIndex - currentUnitLength; currentToken = (currentUnitLength > 0) ? TOK_NUMERIC : TOK_FLOAT; } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); return; } throw new PropertyException("illegal character '.'"); }
// in src/java/org/apache/fop/fo/expr/PropertyTokenizer.java
private void nextColor() throws PropertyException { if (exprIndex < exprLength) { ++exprIndex; scanHexDigits(); int len = exprIndex - currentTokenStartIndex - 1; if (len % 3 == 0) { currentToken = TOK_COLORSPEC; } else { //Actually not a color at all, but an NCNAME starting with "#" scanRestOfName(); currentToken = TOK_NCNAME; } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); return; } else { throw new PropertyException("illegal character '#'"); } }
// in src/java/org/apache/fop/fo/expr/CIELabColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { float red = args[0].getNumber().floatValue(); float green = args[1].getNumber().floatValue(); float blue = args[2].getNumber().floatValue(); /* Verify sRGB replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("sRGB color values out of range. " + "Arguments to cie-lab-color() must be [0..255] or [0%..100%]"); } float l = args[3].getNumber().floatValue(); float a = args[4].getNumber().floatValue(); float b = args[5].getNumber().floatValue(); if (l < 0 || l > 100) { throw new PropertyException("L* value out of range. Valid range: [0..100]"); } if (a < -127 || a > 127 || b < -127 || b > 127) { throw new PropertyException("a* and b* values out of range. Valid range: [-127..+127]"); } StringBuffer sb = new StringBuffer(); sb.append("cie-lab-color(" + red + "," + green + "," + blue + "," + l + "," + a + "," + b + ")"); FOUserAgent ua = (pInfo == null) ? null : (pInfo.getFO() == null ? null : pInfo.getFO().getUserAgent()); return ColorProperty.getInstance(ua, sb.toString()); }
// in src/java/org/apache/fop/fo/expr/FromNearestSpecifiedValueFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { String propName = args[0].getString(); if (propName == null) { throw new PropertyException( "Incorrect parameter to from-nearest-specified-value function"); } // NOTE: special cases for shorthand property // Should return COMPUTED VALUE int propId = FOPropertyMapping.getPropertyId(propName); if (propId < 0) { throw new PropertyException( "Unknown property name used with inherited-property-value function: " + propName); } return pInfo.getPropertyList().getNearestSpecified(propId); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric addition2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Can't subtract Numerics of different dimensions"); } return numeric(op1.getNumericValue(context) + op2.getNumericValue(context), op1.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric subtraction2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Can't subtract Numerics of different dimensions"); } return numeric(op1.getNumericValue(context) - op2.getNumericValue(context), op1.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric max2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Arguments to max() must have same dimensions"); } return op1.getNumericValue(context) > op2.getNumericValue(context) ? op1 : op2; }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric min2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Arguments to min() must have same dimensions"); } return op1.getNumericValue(context) <= op2.getNumericValue(context) ? op1 : op2; }
// in src/java/org/apache/fop/fo/expr/MaxFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Numeric n1 = args[0].getNumeric(); Numeric n2 = args[1].getNumeric(); if (n1 == null || n2 == null) { throw new PropertyException("Non numeric operands to max function"); } return (Property) NumericOp.max(n1, n2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private void expectRpar() throws PropertyException { if (currentToken != TOK_RPAR) { throw new PropertyException("expected )"); } next(); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property parsePrimaryExpr() throws PropertyException { Property prop; if (currentToken == TOK_COMMA) { //Simply skip commas, for example for font-family next(); } switch (currentToken) { case TOK_LPAR: next(); prop = parseAdditiveExpr(); expectRpar(); return prop; case TOK_LITERAL: prop = StringProperty.getInstance(currentTokenValue); break; case TOK_NCNAME: // Interpret this in context of the property or do it later? prop = new NCnameProperty(currentTokenValue); break; case TOK_FLOAT: prop = NumberProperty.getInstance(new Double(currentTokenValue)); break; case TOK_INTEGER: prop = NumberProperty.getInstance(new Integer(currentTokenValue)); break; case TOK_PERCENT: /* * Get the length base value object from the Maker. If null, then * this property can't have % values. Treat it as a real number. */ double pcval = Double.parseDouble( currentTokenValue.substring(0, currentTokenValue.length() - 1)) / 100.0; PercentBase pcBase = this.propInfo.getPercentBase(); if (pcBase != null) { if (pcBase.getDimension() == 0) { prop = NumberProperty.getInstance(pcval * pcBase.getBaseValue()); } else if (pcBase.getDimension() == 1) { if (pcBase instanceof LengthBase) { if (pcval == 0.0) { prop = FixedLength.ZERO_FIXED_LENGTH; break; } //If the base of the percentage is known //and absolute, it can be resolved by the //parser Length base = ((LengthBase)pcBase).getBaseLength(); if (base != null && base.isAbsolute()) { prop = FixedLength.getInstance(pcval * base.getValue()); break; } } prop = new PercentLength(pcval, pcBase); } else { throw new PropertyException("Illegal percent dimension value"); } } else { // WARNING? Interpret as a decimal fraction, eg. 50% = .5 prop = NumberProperty.getInstance(pcval); } break; case TOK_NUMERIC: // A number plus a valid unit name. int numLen = currentTokenValue.length() - currentUnitLength; String unitPart = currentTokenValue.substring(numLen); double numPart = Double.parseDouble(currentTokenValue.substring(0, numLen)); if (RELUNIT.equals(unitPart)) { prop = (Property) NumericOp.multiply( NumberProperty.getInstance(numPart), propInfo.currentFontSize()); } else { if ("px".equals(unitPart)) { //pass the ratio between target-resolution and //the default resolution of 72dpi float resolution = propInfo.getPropertyList().getFObj() .getUserAgent().getSourceResolution(); prop = FixedLength.getInstance( numPart, unitPart, UnitConv.IN2PT / resolution); } else { //use default resolution of 72dpi prop = FixedLength.getInstance(numPart, unitPart); } } break; case TOK_COLORSPEC: prop = ColorProperty.getInstance(propInfo.getUserAgent(), currentTokenValue); break; case TOK_FUNCTION_LPAR: Function function = (Function)FUNCTION_TABLE.get(currentTokenValue); if (function == null) { throw new PropertyException("no such function: " + currentTokenValue); } next(); // Push new function (for function context: getPercentBase()) propInfo.pushFunction(function); prop = function.eval(parseArgs(function), propInfo); propInfo.popFunction(); return prop; default: // TODO: add the token or the expr to the error message. throw new PropertyException("syntax error"); } next(); return prop; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
Property[] parseArgs(Function function) throws PropertyException { int numReq = function.getRequiredArgsCount(); // # required args int numOpt = function.getOptionalArgsCount(); // # optional args boolean hasVar = function.hasVariableArgs(); // has variable args List<Property> args = new java.util.ArrayList<Property>(numReq + numOpt); if (currentToken == TOK_RPAR) { // No args: func() next(); } else { while (true) { Property p = parseAdditiveExpr(); int i = args.size(); if ( ( i < numReq ) || ( ( i - numReq ) < numOpt ) || hasVar ) { args.add ( p ); } else { throw new PropertyException ( "Unexpected function argument at index " + i ); } // ignore extra args if (currentToken != TOK_COMMA) { break; } next(); } expectRpar(); } int numArgs = args.size(); if ( numArgs < numReq ) { throw new PropertyException("Expected " + numReq + " required arguments, but only " + numArgs + " specified"); } else { for ( int i = 0; i < numOpt; i++ ) { if ( args.size() < ( numReq + i + 1 ) ) { args.add ( function.getOptionalArgDefault ( i, propInfo ) ); } } } return (Property[]) args.toArray ( new Property [ args.size() ] ); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalAddition(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in addition"); } return (Property) NumericOp.addition(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalSubtraction(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in subtraction"); } return (Property) NumericOp.subtraction(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalNegate(Numeric op) throws PropertyException { if (op == null) { throw new PropertyException("Non numeric operand to unary minus"); } return (Property) NumericOp.negate(op); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalMultiply(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in multiplication"); } return (Property) NumericOp.multiply(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalDivide(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in division"); } return (Property) NumericOp.divide(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalModulo(Number op1, Number op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non number operand to modulo"); } return NumberProperty.getInstance(op1.doubleValue() % op2.doubleValue()); }
// in src/java/org/apache/fop/fo/expr/MinFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Numeric n1 = args[0].getNumeric(); Numeric n2 = args[1].getNumeric(); if (n1 == null || n2 == null) { throw new PropertyException("Non numeric operands to min function"); } return (Property) NumericOp.min(n1, n2); }
// in src/java/org/apache/fop/fo/expr/FloorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number dbl = args[0].getNumber(); if (dbl == null) { throw new PropertyException("Non number operand to floor function"); } return NumberProperty.getInstance(Math.floor(dbl.doubleValue())); }
// in src/java/org/apache/fop/fo/expr/RGBICCColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { // Map color profile NCNAME to src from declarations/color-profile element String colorProfileName = args[3].getString(); Declarations decls = (pInfo.getFO() != null ? pInfo.getFO().getRoot().getDeclarations() : null); ColorProfile cp = null; if (decls == null) { //function used in a color-specification //on a FO occurring: //a) before the fo:declarations, //b) or in a document without fo:declarations? //=> return the sRGB fallback if (!ColorUtil.isPseudoProfile(colorProfileName)) { Property[] rgbArgs = new Property[3]; System.arraycopy(args, 0, rgbArgs, 0, 3); return new RGBColorFunction().eval(rgbArgs, pInfo); } } else { cp = decls.getColorProfile(colorProfileName); if (cp == null) { if (!ColorUtil.isPseudoProfile(colorProfileName)) { PropertyException pe = new PropertyException("The " + colorProfileName + " color profile was not declared"); pe.setPropertyInfo(pInfo); throw pe; } } } String src = (cp != null ? cp.getSrc() : ""); float red = 0; float green = 0; float blue = 0; red = args[0].getNumber().floatValue(); green = args[1].getNumber().floatValue(); blue = args[2].getNumber().floatValue(); /* Verify rgb replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("Color values out of range. " + "Arguments to rgb-icc() must be [0..255] or [0%..100%]"); } // rgb-icc is replaced with fop-rgb-icc which has an extra fifth argument containing the // color profile src attribute as it is defined in the color-profile declarations element. StringBuffer sb = new StringBuffer(); sb.append("fop-rgb-icc("); sb.append(red / 255f); sb.append(',').append(green / 255f); sb.append(',').append(blue / 255f); for (int ix = 3; ix < args.length; ix++) { if (ix == 3) { sb.append(',').append(colorProfileName); sb.append(',').append(src); } else { sb.append(',').append(args[ix]); } } sb.append(")"); return ColorProperty.getInstance(pInfo.getUserAgent(), sb.toString()); }
// in src/java/org/apache/fop/fo/expr/RGBNamedColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { // Map color profile NCNAME to src from declarations/color-profile element String colorProfileName = args[3].getString(); String colorName = args[4].getString(); Declarations decls = (pInfo.getFO() != null ? pInfo.getFO().getRoot().getDeclarations() : null); ColorProfile cp = null; if (decls != null) { cp = decls.getColorProfile(colorProfileName); } if (cp == null) { PropertyException pe = new PropertyException("The " + colorProfileName + " color profile was not declared"); pe.setPropertyInfo(pInfo); throw pe; } float red = 0; float green = 0; float blue = 0; red = args[0].getNumber().floatValue(); green = args[1].getNumber().floatValue(); blue = args[2].getNumber().floatValue(); /* Verify rgb replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("sRGB color values out of range. " + "Arguments to rgb-named-color() must be [0..255] or [0%..100%]"); } // rgb-named-color is replaced with fop-rgb-named-color which has an extra argument // containing the color profile src attribute as it is defined in the color-profile // declarations element. StringBuffer sb = new StringBuffer(); sb.append("fop-rgb-named-color("); sb.append(red / 255f); sb.append(',').append(green / 255f); sb.append(',').append(blue / 255f); sb.append(',').append(colorProfileName); sb.append(',').append(cp.getSrc()); sb.append(", '").append(colorName).append('\''); sb.append(")"); return ColorProperty.getInstance(pInfo.getUserAgent(), sb.toString()); }
// in src/java/org/apache/fop/fo/expr/CeilingFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number dbl = args[0].getNumber(); if (dbl == null) { throw new PropertyException("Non number operand to ceiling function"); } return NumberProperty.getInstance(Math.ceil(dbl.doubleValue())); }
// in src/java/org/apache/fop/fo/expr/ProportionalColumnWidthFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number d = args[0].getNumber(); if (d == null) { throw new PropertyException("Non numeric operand to " + "proportional-column-width() function."); } PropertyList pList = pInfo.getPropertyList(); if (!"fo:table-column".equals(pList.getFObj().getName())) { throw new PropertyException("proportional-column-width() function " + "may only be used on fo:table-column."); } Table t = (Table) pList.getParentFObj(); if (t.isAutoLayout()) { throw new PropertyException("proportional-column-width() function " + "may only be used when fo:table has " + "table-layout=\"fixed\"."); } return new TableColLength(d.doubleValue(), pInfo.getFO()); }
// in src/java/org/apache/fop/fo/expr/InheritedPropFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { String propName = args[0].getString(); if (propName == null) { throw new PropertyException("Incorrect parameter to inherited-property-value function"); } int propId = FOPropertyMapping.getPropertyId(propName); if (propId < 0) { throw new PropertyException( "Unknown property name used with inherited-property-value function: " + propName); } return pInfo.getPropertyList().getInherited(propId); }
// in src/java/org/apache/fop/util/ColorUtil.java
public static Color parseColorString(FOUserAgent foUserAgent, String value) throws PropertyException { if (value == null) { return null; } Color parsedColor = colorMap.get(value.toLowerCase()); if (parsedColor == null) { if (value.startsWith("#")) { parsedColor = parseWithHash(value); } else if (value.startsWith("rgb(")) { parsedColor = parseAsRGB(value); } else if (value.startsWith("url(")) { throw new PropertyException( "Colors starting with url( are not yet supported!"); } else if (value.startsWith("java.awt.Color")) { parsedColor = parseAsJavaAWTColor(value); } else if (value.startsWith("system-color(")) { parsedColor = parseAsSystemColor(value); } else if (value.startsWith("fop-rgb-icc")) { parsedColor = parseAsFopRgbIcc(foUserAgent, value); } else if (value.startsWith("fop-rgb-named-color")) { parsedColor = parseAsFopRgbNamedColor(foUserAgent, value); } else if (value.startsWith("cie-lab-color")) { parsedColor = parseAsCIELabColor(foUserAgent, value); } else if (value.startsWith("cmyk")) { parsedColor = parseAsCMYK(value); } if (parsedColor == null) { throw new PropertyException("Unknown Color: " + value); } colorMap.put(value, parsedColor); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsSystemColor(String value) throws PropertyException { int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); } else { throw new PropertyException("Unknown color format: " + value + ". Must be system-color(x)"); } return colorMap.get(value); }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsJavaAWTColor(String value) throws PropertyException { float red = 0.0f; float green = 0.0f; float blue = 0.0f; int poss = value.indexOf("["); int pose = value.indexOf("]"); try { if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); String[] args = value.split(","); if (args.length != 3) { throw new PropertyException( "Invalid number of arguments for a java.awt.Color: " + value); } red = Float.parseFloat(args[0].trim().substring(2)) / 255f; green = Float.parseFloat(args[1].trim().substring(2)) / 255f; blue = Float.parseFloat(args[2].trim().substring(2)) / 255f; if ((red < 0.0 || red > 1.0) || (green < 0.0 || green > 1.0) || (blue < 0.0 || blue > 1.0)) { throw new PropertyException("Color values out of range"); } } else { throw new IllegalArgumentException( "Invalid format for a java.awt.Color: " + value); } } catch (RuntimeException re) { throw new PropertyException(re); } return new Color(red, green, blue); }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsRGB(String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); try { String[] args = value.split(","); if (args.length != 3) { throw new PropertyException( "Invalid number of arguments: rgb(" + value + ")"); } float red = parseComponent255(args[0], value); float green = parseComponent255(args[1], value); float blue = parseComponent255(args[2], value); //Convert to ints to synchronize the behaviour with toRGBFunctionCall() int r = (int)(red * 255 + 0.5); int g = (int)(green * 255 + 0.5); int b = (int)(blue * 255 + 0.5); parsedColor = new Color(r, g, b); } catch (RuntimeException re) { //wrap in a PropertyException throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be rgb(r,g,b)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static float parseComponent255(String str, String function) throws PropertyException { float component; str = str.trim(); if (str.endsWith("%")) { component = Float.parseFloat(str.substring(0, str.length() - 1)) / 100f; } else { component = Float.parseFloat(str) / 255f; } if ((component < 0.0 || component > 1.0)) { throw new PropertyException("Color value out of range for " + function + ": " + str + ". Valid range: [0..255] or [0%..100%]"); } return component; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static float parseComponent(String argument, float min, float max, String function) throws PropertyException { float component = Float.parseFloat(argument.trim()); if ((component < min || component > max)) { throw new PropertyException("Color value out of range for " + function + ": " + argument + ". Valid range: [" + min + ".." + max + "]"); } return component; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseWithHash(String value) throws PropertyException { Color parsedColor; try { int len = value.length(); int alpha; if (len == 5 || len == 9) { alpha = Integer.parseInt( value.substring((len == 5) ? 3 : 7), 16); } else { alpha = 0xFF; } int red = 0; int green = 0; int blue = 0; if ((len == 4) || (len == 5)) { //multiply by 0x11 = 17 = 255/15 red = Integer.parseInt(value.substring(1, 2), 16) * 0x11; green = Integer.parseInt(value.substring(2, 3), 16) * 0x11; blue = Integer.parseInt(value.substring(3, 4), 16) * 0X11; } else if ((len == 7) || (len == 9)) { red = Integer.parseInt(value.substring(1, 3), 16); green = Integer.parseInt(value.substring(3, 5), 16); blue = Integer.parseInt(value.substring(5, 7), 16); } else { throw new NumberFormatException(); } parsedColor = new Color(red, green, blue, alpha); } catch (RuntimeException re) { throw new PropertyException("Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsFopRgbIcc(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { String[] args = value.substring(poss + 1, pose).split(","); try { if (args.length < 5) { throw new PropertyException("Too few arguments for rgb-icc() function"); } //Set up fallback sRGB value Color sRGB = parseFallback(args, value); /* Get and verify ICC profile name */ String iccProfileName = args[3].trim(); if (iccProfileName == null || "".equals(iccProfileName)) { throw new PropertyException("ICC profile name missing"); } ColorSpace colorSpace = null; String iccProfileSrc = null; if (isPseudoProfile(iccProfileName)) { if (CMYK_PSEUDO_PROFILE.equalsIgnoreCase(iccProfileName)) { colorSpace = ColorSpaces.getDeviceCMYKColorSpace(); } else if (SEPARATION_PSEUDO_PROFILE.equalsIgnoreCase(iccProfileName)) { colorSpace = new NamedColorSpace(args[5], sRGB, SEPARATION_PSEUDO_PROFILE, null); } else { assert false : "Incomplete implementation"; } } else { /* Get and verify ICC profile source */ iccProfileSrc = args[4].trim(); if (iccProfileSrc == null || "".equals(iccProfileSrc)) { throw new PropertyException("ICC profile source missing"); } iccProfileSrc = unescapeString(iccProfileSrc); } /* ICC profile arguments */ int componentStart = 4; if (colorSpace instanceof NamedColorSpace) { componentStart++; } float[] iccComponents = new float[args.length - componentStart - 1]; for (int ix = componentStart; ++ix < args.length;) { iccComponents[ix - componentStart - 1] = Float.parseFloat(args[ix].trim()); } if (colorSpace instanceof NamedColorSpace && iccComponents.length == 0) { iccComponents = new float[] {1.0f}; //full tint if not specified } /* Ask FOP factory to get ColorSpace for the specified ICC profile source */ if (foUserAgent != null && iccProfileSrc != null) { RenderingIntent renderingIntent = RenderingIntent.AUTO; //TODO connect to fo:color-profile/@rendering-intent colorSpace = foUserAgent.getFactory().getColorSpaceCache().get( iccProfileName, foUserAgent.getBaseURL(), iccProfileSrc, renderingIntent); } if (colorSpace != null) { // ColorSpace is available if (ColorSpaces.isDeviceColorSpace(colorSpace)) { //Device-specific colors are handled differently: //sRGB is the primary color with the CMYK as the alternative Color deviceColor = new Color(colorSpace, iccComponents, 1.0f); float[] rgbComps = sRGB.getRGBColorComponents(null); parsedColor = new ColorWithAlternatives( rgbComps[0], rgbComps[1], rgbComps[2], new Color[] {deviceColor}); } else { parsedColor = new ColorWithFallback( colorSpace, iccComponents, 1.0f, null, sRGB); } } else { // ICC profile could not be loaded - use rgb replacement values */ log.warn("Color profile '" + iccProfileSrc + "' not found. Using sRGB replacement values."); parsedColor = sRGB; } } catch (RuntimeException re) { throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be fop-rgb-icc(r,g,b,NCNAME,src,....)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsFopRgbNamedColor(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { String[] args = value.substring(poss + 1, pose).split(","); try { if (args.length != 6) { throw new PropertyException("rgb-named-color() function must have 6 arguments"); } //Set up fallback sRGB value Color sRGB = parseFallback(args, value); /* Get and verify ICC profile name */ String iccProfileName = args[3].trim(); if (iccProfileName == null || "".equals(iccProfileName)) { throw new PropertyException("ICC profile name missing"); } ICC_ColorSpace colorSpace = null; String iccProfileSrc; if (isPseudoProfile(iccProfileName)) { throw new IllegalArgumentException( "Pseudo-profiles are not allowed with fop-rgb-named-color()"); } else { /* Get and verify ICC profile source */ iccProfileSrc = args[4].trim(); if (iccProfileSrc == null || "".equals(iccProfileSrc)) { throw new PropertyException("ICC profile source missing"); } iccProfileSrc = unescapeString(iccProfileSrc); } // color name String colorName = unescapeString(args[5].trim()); /* Ask FOP factory to get ColorSpace for the specified ICC profile source */ if (foUserAgent != null && iccProfileSrc != null) { RenderingIntent renderingIntent = RenderingIntent.AUTO; //TODO connect to fo:color-profile/@rendering-intent colorSpace = (ICC_ColorSpace)foUserAgent.getFactory().getColorSpaceCache().get( iccProfileName, foUserAgent.getBaseURL(), iccProfileSrc, renderingIntent); } if (colorSpace != null) { ICC_Profile profile = colorSpace.getProfile(); if (NamedColorProfileParser.isNamedColorProfile(profile)) { NamedColorProfileParser parser = new NamedColorProfileParser(); NamedColorProfile ncp = parser.parseProfile(profile, iccProfileName, iccProfileSrc); NamedColorSpace ncs = ncp.getNamedColor(colorName); if (ncs != null) { parsedColor = new ColorWithFallback(ncs, new float[] {1.0f}, 1.0f, null, sRGB); } else { log.warn("Color '" + colorName + "' does not exist in named color profile: " + iccProfileSrc); parsedColor = sRGB; } } else { log.warn("ICC profile is no named color profile: " + iccProfileSrc); parsedColor = sRGB; } } else { // ICC profile could not be loaded - use rgb replacement values */ log.warn("Color profile '" + iccProfileSrc + "' not found. Using sRGB replacement values."); parsedColor = sRGB; } } catch (IOException ioe) { //wrap in a PropertyException throw new PropertyException(ioe); } catch (RuntimeException re) { throw new PropertyException(re); //wrap in a PropertyException } } else { throw new PropertyException("Unknown color format: " + value + ". Must be fop-rgb-named-color(r,g,b,NCNAME,src,color-name)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsCIELabColor(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { try { String[] args = value.substring(poss + 1, pose).split(","); if (args.length != 6) { throw new PropertyException("cie-lab-color() function must have 6 arguments"); } //Set up fallback sRGB value float red = parseComponent255(args[0], value); float green = parseComponent255(args[1], value); float blue = parseComponent255(args[2], value); Color sRGB = new Color(red, green, blue); float l = parseComponent(args[3], 0f, 100f, value); float a = parseComponent(args[4], -127f, 127f, value); float b = parseComponent(args[5], -127f, 127f, value); //Assuming the XSL-FO spec uses the D50 white point CIELabColorSpace cs = ColorSpaces.getCIELabColorSpaceD50(); //use toColor() to have components normalized Color labColor = cs.toColor(l, a, b, 1.0f); //Convert to ColorWithFallback parsedColor = new ColorWithFallback(labColor, sRGB); } catch (RuntimeException re) { throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be cie-lab-color(r,g,b,Lightness,a-value,b-value)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsCMYK(String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); String[] args = value.split(","); try { if (args.length != 4) { throw new PropertyException( "Invalid number of arguments: cmyk(" + value + ")"); } float cyan = parseComponent1(args[0], value); float magenta = parseComponent1(args[1], value); float yellow = parseComponent1(args[2], value); float black = parseComponent1(args[3], value); float[] comps = new float[] {cyan, magenta, yellow, black}; Color cmykColor = DeviceCMYKColorSpace.createCMYKColor(comps); float[] rgbComps = cmykColor.getRGBColorComponents(null); parsedColor = new ColorWithAlternatives(rgbComps[0], rgbComps[1], rgbComps[2], new Color[] {cmykColor}); } catch (RuntimeException re) { throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be cmyk(c,m,y,k)"); } return parsedColor; }
9
              
// in src/java/org/apache/fop/fo/properties/URIProperty.java
catch (URISyntaxException use) { // Let PropertyList propagate the exception throw new PropertyException("Invalid URI specified"); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { //wrap in a PropertyException throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException("Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA"); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (IOException ioe) { //wrap in a PropertyException throw new PropertyException(ioe); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); //wrap in a PropertyException }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
182
              
// in src/java/org/apache/fop/fo/StaticPropertyList.java
public Property get(int propId, boolean bTryInherit, boolean bTryDefault) throws PropertyException { Property p = values[propId]; if (p == null) { p = super.get(propId, bTryInherit, bTryDefault); values[propId] = p; } return p; }
// in src/java/org/apache/fop/fo/properties/PageDimensionMaker.java
public Property get(int subpropId, PropertyList propertyList, boolean tryInherit, boolean tryDefault) throws PropertyException { Property p = super.get(0, propertyList, tryInherit, tryDefault); FObj fo = propertyList.getFObj(); String fallbackValue = (propId == Constants.PR_PAGE_HEIGHT) ? fo.getUserAgent().getPageHeight() : fo.getUserAgent().getPageWidth(); if (p.getEnum() == Constants.EN_INDEFINITE) { int otherId = (propId == Constants.PR_PAGE_HEIGHT) ? Constants.PR_PAGE_WIDTH : Constants.PR_PAGE_HEIGHT; int writingMode = propertyList.get(Constants.PR_WRITING_MODE).getEnum(); int refOrientation = propertyList.get(Constants.PR_REFERENCE_ORIENTATION) .getNumeric().getValue(); if (propertyList.getExplicit(otherId) != null && propertyList.getExplicit(otherId).getEnum() == Constants.EN_INDEFINITE) { //both set to "indefinite": //determine which one of the two defines the dimension //in block-progression-direction, and set the other to //"auto" if ((writingMode != Constants.EN_TB_RL && (refOrientation == 0 || refOrientation == 180 || refOrientation == -180)) || (writingMode == Constants.EN_TB_RL && (refOrientation == 90 || refOrientation == 270 || refOrientation == -270))) { //set page-width to "auto" = use the fallback from FOUserAgent if (propId == Constants.PR_PAGE_WIDTH) { Property.log.warn("Both page-width and page-height set to " + "\"indefinite\". Forcing page-width to \"auto\""); return make(propertyList, fallbackValue, fo); } } else { //set page-height to "auto" = use fallback from FOUserAgent Property.log.warn("Both page-width and page-height set to " + "\"indefinite\". Forcing page-height to \"auto\""); if (propId == Constants.PR_PAGE_HEIGHT) { return make(propertyList, fallbackValue, fo); } } } } else if (p.isAuto()) { return make(propertyList, fallbackValue, fo); } return p; }
// in src/java/org/apache/fop/fo/properties/LengthProperty.java
Override public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof EnumProperty) { return new EnumLength(p); } if (p instanceof LengthProperty) { return p; } if (p instanceof NumberProperty) { //Assume pixels (like in HTML) when there's no unit float resolution = propertyList.getFObj().getUserAgent().getSourceResolution(); return FixedLength.getInstance( p.getNumeric().getNumericValue(), "px", UnitConv.IN2PT / resolution); } Length val = p.getLength(); if (val != null) { return (Property) val; } /* always null ?? */ return convertPropertyDatatype(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/TextDecorationMaker.java
Override public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { ListProperty listProp = (ListProperty) super.convertProperty(p, propertyList, fo); List lst = listProp.getList(); boolean none = false; boolean under = false; boolean over = false; boolean through = false; boolean blink = false; int enumValue = -1; for (int i = lst.size(); --i >= 0;) { Property prop = (Property)lst.get(i); if (prop instanceof NCnameProperty) { prop = checkEnumValues(prop.getString()); lst.set(i, prop); } if (prop != null) { enumValue = prop.getEnum(); } switch (enumValue) { case Constants.EN_NONE: if (under | over | through | blink) { throw new PropertyException("Invalid combination of values"); } none = true; break; case Constants.EN_UNDERLINE: case Constants.EN_NO_UNDERLINE: case Constants.EN_OVERLINE: case Constants.EN_NO_OVERLINE: case Constants.EN_LINE_THROUGH: case Constants.EN_NO_LINE_THROUGH: case Constants.EN_BLINK: case Constants.EN_NO_BLINK: if (none) { throw new PropertyException ("'none' specified, no additional values allowed"); } switch (enumValue) { case Constants.EN_UNDERLINE: case Constants.EN_NO_UNDERLINE: if (!under) { under = true; continue; } case Constants.EN_OVERLINE: case Constants.EN_NO_OVERLINE: if (!over) { over = true; continue; } case Constants.EN_LINE_THROUGH: case Constants.EN_NO_LINE_THROUGH: if (!through) { through = true; continue; } case Constants.EN_BLINK: case Constants.EN_NO_BLINK: if (!blink) { blink = true; continue; } default: throw new PropertyException("Invalid combination of values"); } default: throw new PropertyException("Invalid value specified: " + p); } } return listProp; }
// in src/java/org/apache/fop/fo/properties/ColorProperty.java
Override public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof ColorProperty) { return p; } FObj fobj = (fo == null ? propertyList.getFObj() : fo); FOUserAgent ua = (fobj == null ? null : fobj.getUserAgent()); Color val = p.getColor(ua); if (val != null) { return new ColorProperty(val); } return convertPropertyDatatype(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/ColorProperty.java
public static ColorProperty getInstance(FOUserAgent foUserAgent, String value) throws PropertyException { ColorProperty instance = new ColorProperty( ColorUtil.parseColorString( foUserAgent, value)); return CACHE.fetch(instance); }
// in src/java/org/apache/fop/fo/properties/CommonFont.java
public static CommonFont getInstance(PropertyList pList) throws PropertyException { FontFamilyProperty fontFamily = (FontFamilyProperty) pList.get(Constants.PR_FONT_FAMILY); EnumProperty fontSelectionStrategy = (EnumProperty) pList.get(Constants.PR_FONT_SELECTION_STRATEGY); EnumProperty fontStretch = (EnumProperty) pList.get(Constants.PR_FONT_STRETCH); EnumProperty fontStyle = (EnumProperty) pList.get(Constants.PR_FONT_STYLE); EnumProperty fontVariant = (EnumProperty) pList.get(Constants.PR_FONT_VARIANT); EnumProperty fontWeight = (EnumProperty) pList.get(Constants.PR_FONT_WEIGHT); Numeric fontSizeAdjust = pList.get(Constants.PR_FONT_SIZE_ADJUST).getNumeric(); Length fontSize = pList.get(Constants.PR_FONT_SIZE).getLength(); CommonFont commonFont = new CommonFont(fontFamily, fontSelectionStrategy, fontStretch, fontStyle, fontVariant, fontWeight, fontSize, fontSizeAdjust); return CACHE.fetch(commonFont); }
// in src/java/org/apache/fop/fo/properties/KeepProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof KeepProperty) { return p; } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/FontShorthandParser.java
public Property getValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { int index = -1; Property newProp; switch (propId) { case Constants.PR_FONT_SIZE: index = 0; break; case Constants.PR_FONT_FAMILY: index = 1; break; case Constants.PR_LINE_HEIGHT: index = 2; break; case Constants.PR_FONT_STYLE: index = 3; break; case Constants.PR_FONT_VARIANT: index = 4; break; case Constants.PR_FONT_WEIGHT: index = 5; break; default: //nop } newProp = (Property) property.getList().get(index); return newProp; }
// in src/java/org/apache/fop/fo/properties/CondLengthProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof KeepProperty) { return p; } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/CompoundPropertyMaker.java
public Property get(int subpropertyId, PropertyList propertyList, boolean tryInherit, boolean tryDefault) throws PropertyException { Property p = super.get(subpropertyId, propertyList, tryInherit, tryDefault); if (subpropertyId != 0 && p != null) { p = getSubprop(p, subpropertyId); } return p; }
// in src/java/org/apache/fop/fo/properties/CompoundPropertyMaker.java
protected Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { // Delegate to the subproperty maker to do conversions. p = shorthandMaker.convertProperty(p, propertyList, fo); if (p != null) { Property prop = makeCompound(propertyList, fo); CompoundDatatype pval = (CompoundDatatype) prop.getObject(); for (int i = 0; i < Constants.COMPOUND_COUNT; i++) { PropertyMaker submaker = subproperties[i]; if (submaker != null && submaker.setByShorthand) { pval.setComponent(submaker.getPropId() & Constants.COMPOUND_MASK, p, false); } } return prop; } return null; }
// in src/java/org/apache/fop/fo/properties/CompoundPropertyMaker.java
public Property make(PropertyList propertyList) throws PropertyException { if (defaultValue != null) { return make(propertyList, defaultValue, propertyList.getParentFObj()); } else { return makeCompound(propertyList, propertyList.getParentFObj()); } }
// in src/java/org/apache/fop/fo/properties/CompoundPropertyMaker.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { Property p = super.make(propertyList, value, fo); p = convertProperty(p, propertyList, fo); return p; }
// in src/java/org/apache/fop/fo/properties/CompoundPropertyMaker.java
public Property make(Property baseProperty, int subpropertyId, PropertyList propertyList, String value, FObj fo) throws PropertyException { if (baseProperty == null) { baseProperty = makeCompound(propertyList, fo); } PropertyMaker spMaker = getSubpropMaker(subpropertyId); if (spMaker != null) { Property p = spMaker.make(propertyList, value, fo); if (p != null) { return setSubprop(baseProperty, subpropertyId & Constants.COMPOUND_MASK, p); } } else { //getLogger().error("compound property component " // + partName + " unknown."); } return baseProperty; }
// in src/java/org/apache/fop/fo/properties/CompoundPropertyMaker.java
protected Property makeCompound(PropertyList propertyList, FObj parentFO) throws PropertyException { Property p = makeNewProperty(); CompoundDatatype data = (CompoundDatatype) p.getObject(); for (int i = 0; i < Constants.COMPOUND_COUNT; i++) { PropertyMaker subpropertyMaker = subproperties[i]; if (subpropertyMaker != null) { Property subproperty = subpropertyMaker.make(propertyList); data.setComponent(subpropertyMaker.getPropId() & Constants.COMPOUND_MASK, subproperty, true); } } return p; }
// in src/java/org/apache/fop/fo/properties/SpaceProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof SpaceProperty) { return p; } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/EnumNumber.java
public double getNumericValue(PercentBaseContext context) throws PropertyException { log.error("getNumericValue() called on " + enumProperty + " number"); return 0; }
// in src/java/org/apache/fop/fo/properties/IndentPropertyMaker.java
public Property compute(PropertyList propertyList) throws PropertyException { if (propertyList.getFObj().getUserAgent() .isBreakIndentInheritanceOnReferenceAreaBoundary()) { return computeAlternativeRuleset(propertyList); } else { return computeConforming(propertyList); } }
// in src/java/org/apache/fop/fo/properties/IndentPropertyMaker.java
public Property computeConforming(PropertyList propertyList) throws PropertyException { PropertyList pList = getWMPropertyList(propertyList); if (pList == null) { return null; } // Calculate the values as described in 5.3.2. Numeric padding = getCorresponding(paddingCorresponding, propertyList).getNumeric(); Numeric border = getCorresponding(borderWidthCorresponding, propertyList).getNumeric(); int marginProp = pList.selectFromWritingMode(lrtb, rltb, tbrl, tblr); // Calculate the absolute margin. if (propertyList.getExplicitOrShorthand(marginProp) == null) { Property indent = propertyList.getExplicit(baseMaker.propId); if (indent == null) { //Neither indent nor margin is specified, use inherited return null; } else { //Use explicit indent directly return indent; } } else { //Margin is used Numeric margin = propertyList.get(marginProp).getNumeric(); Numeric v = FixedLength.ZERO_FIXED_LENGTH; if (!propertyList.getFObj().generatesReferenceAreas()) { // The inherited_value_of([start|end]-indent) v = NumericOp.addition(v, propertyList.getInherited(baseMaker.propId).getNumeric()); } // The corresponding absolute margin-[right|left}. v = NumericOp.addition(v, margin); v = NumericOp.addition(v, padding); v = NumericOp.addition(v, border); return (Property) v; } }
// in src/java/org/apache/fop/fo/properties/IndentPropertyMaker.java
public Property computeAlternativeRuleset(PropertyList propertyList) throws PropertyException { PropertyList pList = getWMPropertyList(propertyList); if (pList == null) { return null; } // Calculate the values as described in 5.3.2. Numeric padding = getCorresponding(paddingCorresponding, propertyList).getNumeric(); Numeric border = getCorresponding(borderWidthCorresponding, propertyList).getNumeric(); int marginProp = pList.selectFromWritingMode(lrtb, rltb, tbrl, tblr); //Determine whether the nearest anscestor indent was specified through //start-indent|end-indent or through a margin property. boolean marginNearest = false; PropertyList pl = propertyList.getParentPropertyList(); while (pl != null) { if (pl.getExplicit(baseMaker.propId) != null) { break; } else if (pl.getExplicitOrShorthand(marginProp) != null) { marginNearest = true; break; } pl = pl.getParentPropertyList(); } // Calculate the absolute margin. if (propertyList.getExplicitOrShorthand(marginProp) == null) { Property indent = propertyList.getExplicit(baseMaker.propId); if (indent == null) { //Neither start-indent nor margin is specified, use inherited if (isInherited(propertyList) || !marginNearest) { return null; } else { return FixedLength.ZERO_FIXED_LENGTH; } } else { return indent; } } else { //Margin is used Numeric margin = propertyList.get(marginProp).getNumeric(); Numeric v = FixedLength.ZERO_FIXED_LENGTH; if (isInherited(propertyList)) { // The inherited_value_of([start|end]-indent) v = NumericOp.addition(v, propertyList.getInherited(baseMaker.propId).getNumeric()); } // The corresponding absolute margin-[right|left}. v = NumericOp.addition(v, margin); v = NumericOp.addition(v, padding); v = NumericOp.addition(v, border); return (Property) v; } }
// in src/java/org/apache/fop/fo/properties/IndentPropertyMaker.java
private Property getCorresponding(int[] corresponding, PropertyList propertyList) throws PropertyException { PropertyList pList = getWMPropertyList(propertyList); if (pList != null) { int wmcorr = pList.selectFromWritingMode ( corresponding[0], corresponding[1], corresponding[2], corresponding[3] ); return propertyList.get(wmcorr); } else { return null; } }
// in src/java/org/apache/fop/fo/properties/SpacingPropertyMaker.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p.getEnum() == Constants.EN_NORMAL) { return p; } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/LineHeightPropertyMaker.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { /* if value was specified as a number/length/percentage then * conditionality and precedence components are overridden */ Property p = super.make(propertyList, value, fo); p.getSpace().setConditionality( EnumProperty.getInstance(Constants.EN_RETAIN, "RETAIN"), true); p.getSpace().setPrecedence( EnumProperty.getInstance(Constants.EN_FORCE, "FORCE"), true); return p; }
// in src/java/org/apache/fop/fo/properties/LineHeightPropertyMaker.java
protected Property compute(PropertyList propertyList) throws PropertyException { // recalculate based on last specified value // Climb up propertylist and find last spec'd value Property specProp = propertyList.getNearestSpecified(propId); if (specProp != null) { String specVal = specProp.getSpecifiedValue(); if (specVal != null) { return make(propertyList, specVal, propertyList.getParentFObj()); } } return null; }
// in src/java/org/apache/fop/fo/properties/LineHeightPropertyMaker.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { Numeric numval = p.getNumeric(); if (numval != null && numval.getDimension() == 0) { if (getPercentBase(propertyList) instanceof LengthBase) { Length base = ((LengthBase)getPercentBase(propertyList)).getBaseLength(); if (base != null && base.isAbsolute()) { p = FixedLength.getInstance( numval.getNumericValue() * base.getNumericValue()); } else { p = new PercentLength( numval.getNumericValue(), getPercentBase(propertyList)); } } Property spaceProp = super.convertProperty(p, propertyList, fo); spaceProp.setSpecifiedValue(String.valueOf(numval.getNumericValue())); return spaceProp; } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/ListProperty.java
Override public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof ListProperty) { return p; } else { return new ListProperty(p); } }
// in src/java/org/apache/fop/fo/properties/BackgroundPositionShorthand.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { Property p = super.make(propertyList, value, fo); if (p.getList().size() == 1) { /* only background-position-horizontal specified * through the shorthand, as a length or percentage: * background-position-vertical=50% (see: XSL-FO 1.1 -- 7.31.2) */ PropertyMaker m = FObj.getPropertyMakerFor( Constants.PR_BACKGROUND_POSITION_VERTICAL); p.getList().add(1, m.make(propertyList, "50%", fo)); } return p; }
// in src/java/org/apache/fop/fo/properties/BackgroundPositionShorthand.java
public int getBaseLength(PercentBaseContext context) throws PropertyException { return 0; }
// in src/java/org/apache/fop/fo/properties/BackgroundPositionShorthand.java
public Property getValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { int index = -1; List propList = property.getList(); if (propId == Constants.PR_BACKGROUND_POSITION_HORIZONTAL) { index = 0; } else if (propId == Constants.PR_BACKGROUND_POSITION_VERTICAL) { index = 1; } if (index >= 0) { return maker.convertProperty( (Property) propList.get(index), propertyList, propertyList.getFObj()); } // else: invalid index? shouldn't happen... return null; }
// in src/java/org/apache/fop/fo/properties/CommonTextDecoration.java
public static CommonTextDecoration createFromPropertyList(PropertyList pList) throws PropertyException { return calcTextDecoration(pList); }
// in src/java/org/apache/fop/fo/properties/CommonTextDecoration.java
private static CommonTextDecoration calcTextDecoration(PropertyList pList) throws PropertyException { CommonTextDecoration deco = null; PropertyList parentList = pList.getParentPropertyList(); if (parentList != null) { //Parent is checked first deco = calcTextDecoration(parentList); } //For rules, see XSL 1.0, chapters 5.5.6 and 7.16.4 Property textDecoProp = pList.getExplicit(Constants.PR_TEXT_DECORATION); if (textDecoProp != null) { List list = textDecoProp.getList(); Iterator i = list.iterator(); while (i.hasNext()) { Property prop = (Property)i.next(); int propEnum = prop.getEnum(); FOUserAgent ua = (pList == null) ? null : (pList.getFObj() == null ? null : pList.getFObj().getUserAgent()); if (propEnum == Constants.EN_NONE) { if (deco != null) { deco.decoration = 0; } return deco; } else if (propEnum == Constants.EN_UNDERLINE) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= UNDERLINE; deco.underColor = pList.get(Constants.PR_COLOR).getColor(ua); } else if (propEnum == Constants.EN_NO_UNDERLINE) { if (deco != null) { deco.decoration &= OVERLINE | LINE_THROUGH | BLINK; deco.underColor = pList.get(Constants.PR_COLOR).getColor(ua); } } else if (propEnum == Constants.EN_OVERLINE) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= OVERLINE; deco.overColor = pList.get(Constants.PR_COLOR).getColor(ua); } else if (propEnum == Constants.EN_NO_OVERLINE) { if (deco != null) { deco.decoration &= UNDERLINE | LINE_THROUGH | BLINK; deco.overColor = pList.get(Constants.PR_COLOR).getColor(ua); } } else if (propEnum == Constants.EN_LINE_THROUGH) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= LINE_THROUGH; deco.throughColor = pList.get(Constants.PR_COLOR).getColor(ua); } else if (propEnum == Constants.EN_NO_LINE_THROUGH) { if (deco != null) { deco.decoration &= UNDERLINE | OVERLINE | BLINK; deco.throughColor = pList.get(Constants.PR_COLOR).getColor(ua); } } else if (propEnum == Constants.EN_BLINK) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= BLINK; } else if (propEnum == Constants.EN_NO_BLINK) { if (deco != null) { deco.decoration &= UNDERLINE | OVERLINE | LINE_THROUGH; } } else { throw new PropertyException("Illegal value encountered: " + prop.getString()); } } } return deco; }
// in src/java/org/apache/fop/fo/properties/CommonAccessibility.java
public static CommonAccessibility getInstance(PropertyList propertyList) throws PropertyException { String sourceDocument = propertyList.get(Constants.PR_SOURCE_DOCUMENT).getString(); if ("none".equals(sourceDocument)) { sourceDocument = null; } String role = propertyList.get(Constants.PR_ROLE).getString(); if ("none".equals(role)) { role = null; } if (sourceDocument == null && role == null) { return DEFAULT_INSTANCE; } else { return new CommonAccessibility(sourceDocument, role); } }
// in src/java/org/apache/fop/fo/properties/URIProperty.java
Override public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { Property p = null; //special treament for data: URIs if (value.matches("(?s)^(url\\(('|\")?)?data:.*$")) { p = new URIProperty(value, false); } else { try { URI specifiedURI = new URI(URISpecification.escapeURI(value)); URIProperty xmlBase = (URIProperty)propertyList.get(PR_X_XML_BASE, true, false); if (xmlBase == null) { //xml:base undefined if (this.propId == PR_X_XML_BASE) { //if current property is xml:base, define a new one p = new URIProperty(specifiedURI); p.setSpecifiedValue(value); } else { //otherwise, just store the specified value (for backward compatibility) p = new URIProperty(value, false); } } else { //xml:base defined, so resolve p = new URIProperty(xmlBase.resolvedURI.resolve(specifiedURI)); p.setSpecifiedValue(value); } } catch (URISyntaxException use) { // Let PropertyList propagate the exception throw new PropertyException("Invalid URI specified"); } } return p; }
// in src/java/org/apache/fop/fo/properties/FontWeightPropertyMaker.java
public Property make(PropertyList pList, String value, FObj fo) throws PropertyException { if ("inherit".equals(value)) { return super.make(pList, value, fo); } else { String pValue = checkValueKeywords(value); Property newProp = checkEnumValues(pValue); int enumValue = ( newProp != null ) ? newProp.getEnum() : -1; if (enumValue == Constants.EN_BOLDER || enumValue == Constants.EN_LIGHTER) { /* check for relative enum values, compute in relation to parent */ Property parentProp = pList.getInherited(Constants.PR_FONT_WEIGHT); if (enumValue == Constants.EN_BOLDER) { enumValue = parentProp.getEnum(); switch (enumValue) { case Constants.EN_100: newProp = EnumProperty.getInstance(Constants.EN_200, "200"); break; case Constants.EN_200: newProp = EnumProperty.getInstance(Constants.EN_300, "300"); break; case Constants.EN_300: newProp = EnumProperty.getInstance(Constants.EN_400, "400"); break; case Constants.EN_400: newProp = EnumProperty.getInstance(Constants.EN_500, "500"); break; case Constants.EN_500: newProp = EnumProperty.getInstance(Constants.EN_600, "600"); break; case Constants.EN_600: newProp = EnumProperty.getInstance(Constants.EN_700, "700"); break; case Constants.EN_700: newProp = EnumProperty.getInstance(Constants.EN_800, "800"); break; case Constants.EN_800: case Constants.EN_900: newProp = EnumProperty.getInstance(Constants.EN_900, "900"); break; default: //nop } } else { enumValue = parentProp.getEnum(); switch (enumValue) { case Constants.EN_100: case Constants.EN_200: newProp = EnumProperty.getInstance(Constants.EN_100, "100"); break; case Constants.EN_300: newProp = EnumProperty.getInstance(Constants.EN_200, "200"); break; case Constants.EN_400: newProp = EnumProperty.getInstance(Constants.EN_300, "300"); break; case Constants.EN_500: newProp = EnumProperty.getInstance(Constants.EN_400, "400"); break; case Constants.EN_600: newProp = EnumProperty.getInstance(Constants.EN_500, "500"); break; case Constants.EN_700: newProp = EnumProperty.getInstance(Constants.EN_600, "600"); break; case Constants.EN_800: newProp = EnumProperty.getInstance(Constants.EN_700, "700"); break; case Constants.EN_900: newProp = EnumProperty.getInstance(Constants.EN_800, "800"); break; default: //nop } } } else if (enumValue == -1) { /* neither a keyword, nor an enum * still maybe a valid expression, so send it through the parser... */ newProp = PropertyParser.parse(value, new PropertyInfo(this, pList)); } if (newProp != null) { newProp = convertProperty(newProp, pList, fo); } return newProp; } }
// in src/java/org/apache/fop/fo/properties/EnumProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof EnumProperty) { return p; } else { return super.convertProperty(p, propertyList, fo); } }
// in src/java/org/apache/fop/fo/properties/BorderWidthPropertyMaker.java
public Property get(int subpropId, PropertyList propertyList, boolean bTryInherit, boolean bTryDefault) throws PropertyException { Property p = super.get(subpropId, propertyList, bTryInherit, bTryDefault); // Calculate the values as described in 7.7.20. Property style = propertyList.get(borderStyleId); if (style.getEnum() == Constants.EN_NONE) { return FixedLength.ZERO_FIXED_LENGTH; } return p; }
// in src/java/org/apache/fop/fo/properties/FontStretchPropertyMaker.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { // if it is a relative font stretch value get current parent value and step // up or down accordingly if (p.getEnum() == EN_NARROWER) { return computeNextAbsoluteFontStretch(propertyList.getFromParent(this.getPropId()), -1); } else if (p.getEnum() == EN_WIDER) { return computeNextAbsoluteFontStretch(propertyList.getFromParent(this.getPropId()), 1); } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/TableBorderPrecedence.java
public Property make(PropertyList propertyList) throws PropertyException { FObj fo = propertyList.getFObj(); switch (fo.getNameId()) { case Constants.FO_TABLE: return num6; case Constants.FO_TABLE_CELL: return num5; case Constants.FO_TABLE_COLUMN: return num4; case Constants.FO_TABLE_ROW: return num3; case Constants.FO_TABLE_BODY: return num2; case Constants.FO_TABLE_HEADER: return num1; case Constants.FO_TABLE_FOOTER: return num0; default: return null; } }
// in src/java/org/apache/fop/fo/properties/LengthRangeProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof LengthRangeProperty) { return p; } if (this.propId == PR_BLOCK_PROGRESSION_DIMENSION || this.propId == PR_INLINE_PROGRESSION_DIMENSION) { Length len = p.getLength(); if (len != null) { if (isNegativeLength(len)) { log.warn(FObj.decorateWithContextInfo( "Replaced negative value (" + len + ") for " + getName() + " with 0mpt", fo)); p = FixedLength.ZERO_FIXED_LENGTH; } } } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { try { FontShorthandProperty newProp = new FontShorthandProperty(); newProp.setSpecifiedValue(value); String specVal = value; Property prop = null; if ("inherit".equals(specVal)) { /* fill the list with the individual properties from the parent */ for (int i = PROP_IDS.length; --i >= 0;) { prop = propertyList.getFromParent(PROP_IDS[i]); newProp.addProperty(prop, i); } } else { /* initialize list with nulls */ for (int pos = PROP_IDS.length; --pos >= 0;) { newProp.addProperty(null, pos); } prop = checkEnumValues(specVal); if (prop == null) { /* not an enum: * value should consist at least of font-size and font-family * separated by a space * mind the possible spaces from quoted font-family names */ int spaceIndex = value.indexOf(' '); int quoteIndex = (value.indexOf('\'') == -1) ? value.indexOf('\"') : value.indexOf('\''); if (spaceIndex == -1 || (quoteIndex != -1 && spaceIndex > quoteIndex)) { /* no spaces or first space appears after the first * single/double quote, so malformed value string */ throw new PropertyException("Invalid property value: " + "font=\"" + value + "\""); } PropertyMaker m = null; int fromIndex = spaceIndex + 1; int toIndex = specVal.length(); /* at least one space that appears before the first * single/double quote, so extract the individual properties */ boolean fontFamilyParsed = false; int commaIndex = value.indexOf(','); while (!fontFamilyParsed) { /* value contains a (list of) possibly quoted * font-family name(s) */ if (commaIndex == -1) { /* no list, just a single name * (or first name in the list) */ if (quoteIndex != -1) { /* a single name, quoted */ fromIndex = quoteIndex; } m = FObj.getPropertyMakerFor(PROP_IDS[1]); prop = m.make(propertyList, specVal.substring(fromIndex), fo); newProp.addProperty(prop, 1); fontFamilyParsed = true; } else { if (quoteIndex != -1 && quoteIndex < commaIndex) { /* a quoted font-family name as first name * in the comma-separated list * fromIndex = index of the first quote */ fromIndex = quoteIndex; quoteIndex = -1; } else { fromIndex = value.lastIndexOf(' ', commaIndex) + 1; } commaIndex = -1; } } toIndex = fromIndex - 1; fromIndex = value.lastIndexOf(' ', toIndex - 1) + 1; value = specVal.substring(fromIndex, toIndex); int slashIndex = value.indexOf('/'); String fontSize = value.substring(0, (slashIndex == -1) ? value.length() : slashIndex); m = FObj.getPropertyMakerFor(PROP_IDS[0]); prop = m.make(propertyList, fontSize, fo); /* need to make sure subsequent call to LineHeightPropertyMaker.make() * doesn't generate the default font-size property... */ propertyList.putExplicit(PROP_IDS[0], prop); newProp.addProperty(prop, 0); if (slashIndex != -1) { /* line-height */ String lineHeight = value.substring(slashIndex + 1); m = FObj.getPropertyMakerFor(PROP_IDS[2]); prop = m.make(propertyList, lineHeight, fo); newProp.addProperty(prop, 2); } if (fromIndex != 0) { toIndex = fromIndex - 1; value = specVal.substring(0, toIndex); fromIndex = 0; spaceIndex = value.indexOf(' '); do { toIndex = (spaceIndex == -1) ? value.length() : spaceIndex; String val = value.substring(fromIndex, toIndex); for (int i = 6; --i >= 3;) { if (newProp.list.get(i) == null) { /* not set */ m = FObj.getPropertyMakerFor(PROP_IDS[i]); val = m.checkValueKeywords(val); prop = m.checkEnumValues(val); if (prop != null) { newProp.addProperty(prop, i); } } } fromIndex = toIndex + 1; spaceIndex = value.indexOf(' ', fromIndex); } while (toIndex != value.length()); } } else { //TODO: implement enum values log.warn("Enum values other than \"inherit\"" + " not yet supported for the font shorthand."); return null; } } if (newProp.list.get(0) == null || newProp.list.get(1) == null) { throw new PropertyException("Invalid property value: " + "font-size and font-family are required for the font shorthand" + "\nfont=\"" + value + "\""); } return newProp; } catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; } }
// in src/java/org/apache/fop/fo/properties/GenericShorthandParser.java
public Property getValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { // Check for keyword "inherit" if (property.getList().size() == 1) { String sval = getElement(property, 0).getString(); if (sval != null && sval.equals("inherit")) { return propertyList.getFromParent(propId); } } return convertValueForProperty(propId, property, maker, propertyList); }
// in src/java/org/apache/fop/fo/properties/GenericShorthandParser.java
protected Property convertValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { Property prop = null; // Try each of the stored values in turn Iterator iprop = property.getList().iterator(); while (iprop.hasNext() && prop == null) { Property p = (Property)iprop.next(); prop = maker.convertShorthandProperty(propertyList, p, null); } return prop; }
// in src/java/org/apache/fop/fo/properties/ReferenceOrientationMaker.java
public Property get(int subpropId, PropertyList propertyList, boolean tryInherit, boolean tryDefault) throws PropertyException { Property p = super.get(0, propertyList, tryInherit, tryDefault); int ro = 0; if (p != null) { ro = p.getNumeric().getValue(); } if ((Math.abs(ro) % 90) == 0 && (Math.abs(ro) / 90) <= 3) { return p; } else { throw new PropertyException("Illegal property value: " + "reference-orientation=\"" + ro + "\" " + "on " + propertyList.getFObj().getName()); } }
// in src/java/org/apache/fop/fo/properties/CorrespondingPropertyMaker.java
public Property compute(PropertyList propertyList) throws PropertyException { PropertyList pList = getWMPropertyList(propertyList); if (pList == null) { return null; } int correspondingId = pList.selectFromWritingMode(lrtb, rltb, tbrl, tblr); Property p = propertyList.getExplicitOrShorthand(correspondingId); if (p != null) { FObj parentFO = propertyList.getParentFObj(); p = baseMaker.convertProperty(p, propertyList, parentFO); } return p; }
// in src/java/org/apache/fop/fo/properties/SpacePropertyMaker.java
public Property compute(PropertyList propertyList) throws PropertyException { Property prop = super.compute(propertyList); if (prop != null && prop instanceof SpaceProperty) { ((SpaceProperty)prop).setConditionality( EnumProperty.getInstance(Constants.EN_RETAIN, "RETAIN"), false); } return prop; }
// in src/java/org/apache/fop/fo/properties/CommonHyphenation.java
public static CommonHyphenation getInstance(PropertyList propertyList) throws PropertyException { StringProperty language = (StringProperty) propertyList.get(Constants.PR_LANGUAGE); StringProperty country = (StringProperty) propertyList.get(Constants.PR_COUNTRY); StringProperty script = (StringProperty) propertyList.get(Constants.PR_SCRIPT); EnumProperty hyphenate = (EnumProperty) propertyList.get(Constants.PR_HYPHENATE); CharacterProperty hyphenationCharacter = (CharacterProperty) propertyList.get(Constants.PR_HYPHENATION_CHARACTER); NumberProperty hyphenationPushCharacterCount = (NumberProperty) propertyList.get(Constants.PR_HYPHENATION_PUSH_CHARACTER_COUNT); NumberProperty hyphenationRemainCharacterCount = (NumberProperty) propertyList.get(Constants.PR_HYPHENATION_REMAIN_CHARACTER_COUNT); CommonHyphenation instance = new CommonHyphenation( language, country, script, hyphenate, hyphenationCharacter, hyphenationPushCharacterCount, hyphenationRemainCharacterCount); return CACHE.fetch(instance); }
// in src/java/org/apache/fop/fo/properties/FontSizePropertyMaker.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { Property p = super.make(propertyList, value, fo); if (p instanceof PercentLength) { Property pp = propertyList.getFromParent(this.propId); p = FixedLength.getInstance( pp.getLength().getValue() * ((PercentLength)p).getPercentage() / 100); } return p; }
// in src/java/org/apache/fop/fo/properties/FontSizePropertyMaker.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p.getEnum() == EN_LARGER || p.getEnum() == EN_SMALLER) { // get the corresponding property from parent Property pp = propertyList.getFromParent(this.propId); int baseFontSize = computeClosestAbsoluteFontSize(pp.getLength().getValue()); if (p.getEnum() == EN_LARGER) { return FixedLength.getInstance( Math.round(baseFontSize * FONT_SIZE_GROWTH_FACTOR)); } else { return FixedLength.getInstance( Math.round(baseFontSize / FONT_SIZE_GROWTH_FACTOR)); } } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
public static CommonBorderPaddingBackground getInstance(PropertyList pList) throws PropertyException { CommonBorderPaddingBackground newInstance = new CommonBorderPaddingBackground(pList); CommonBorderPaddingBackground cachedInstance = null; /* if padding-* and background-position-* resolve to absolute lengths * the whole instance can be cached */ if ((newInstance.padding[BEFORE] == null || newInstance.padding[BEFORE].getLength().isAbsolute()) && (newInstance.padding[AFTER] == null || newInstance.padding[AFTER].getLength().isAbsolute()) && (newInstance.padding[START] == null || newInstance.padding[START].getLength().isAbsolute()) && (newInstance.padding[END] == null || newInstance.padding[END].getLength().isAbsolute()) && (newInstance.backgroundPositionHorizontal == null || newInstance.backgroundPositionHorizontal.isAbsolute()) && (newInstance.backgroundPositionVertical == null || newInstance.backgroundPositionVertical.isAbsolute())) { cachedInstance = CACHE.fetch(newInstance); } synchronized (newInstance.backgroundImage.intern()) { /* for non-cached, or not-yet-cached instances, preload the image */ if ((cachedInstance == null || cachedInstance == newInstance) && !("".equals(newInstance.backgroundImage))) { //Additional processing: preload image String uri = URISpecification.getURL(newInstance.backgroundImage); FObj fobj = pList.getFObj(); FOUserAgent userAgent = pList.getFObj().getUserAgent(); ImageManager manager = userAgent.getFactory().getImageManager(); ImageSessionContext sessionContext = userAgent.getImageSessionContext(); ImageInfo info; try { info = manager.getImageInfo(uri, sessionContext); newInstance.backgroundImageInfo = info; } catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageError(fobj, uri, e, fobj.getLocator()); } catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(fobj, uri, fnfe, fobj.getLocator()); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(fobj, uri, ioe, fobj.getLocator()); } }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
private void initBorderInfo(PropertyList pList, int side, int colorProp, int styleProp, int widthProp, int paddingProp) throws PropertyException { padding[side] = pList.get(paddingProp).getCondLength(); // If style = none, force width to 0, don't get Color (spec 7.7.20) int style = pList.get(styleProp).getEnum(); if (style != Constants.EN_NONE) { FOUserAgent ua = pList.getFObj().getUserAgent(); setBorderInfo(BorderInfo.getInstance(style, pList.get(widthProp).getCondLength(), pList.get(colorProp).getColor(ua)), side); } }
// in src/java/org/apache/fop/fo/properties/PageBreakShorthandParser.java
public Property getValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { if (propId == Constants.PR_KEEP_WITH_PREVIOUS || propId == Constants.PR_KEEP_WITH_NEXT || propId == Constants.PR_KEEP_TOGETHER) { if (property.getEnum() == Constants.EN_AVOID) { return maker.make(null, Constants.CP_WITHIN_PAGE, propertyList, "always", propertyList.getFObj()); } } else if (propId == Constants.PR_BREAK_BEFORE || propId == Constants.PR_BREAK_AFTER) { switch (property.getEnum()) { case Constants.EN_ALWAYS: return EnumProperty.getInstance(Constants.EN_PAGE, "PAGE"); case Constants.EN_LEFT: return EnumProperty.getInstance(Constants.EN_EVEN_PAGE, "EVEN_PAGE"); case Constants.EN_RIGHT: return EnumProperty.getInstance(Constants.EN_ODD_PAGE, "ODD_PAGE"); case Constants.EN_AVOID: default: //nop; } } return null; }
// in src/java/org/apache/fop/fo/properties/WhiteSpaceShorthandParser.java
public Property getValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { switch (property.getEnum()) { case Constants.EN_PRE: switch (propId) { case Constants.PR_LINEFEED_TREATMENT: case Constants.PR_WHITE_SPACE_TREATMENT: return EnumProperty.getInstance(Constants.EN_PRESERVE, "PRESERVE"); case Constants.PR_WHITE_SPACE_COLLAPSE: return EnumProperty.getInstance(Constants.EN_FALSE, "FALSE"); case Constants.PR_WRAP_OPTION: return EnumProperty.getInstance(Constants.EN_NO_WRAP, "NO_WRAP"); default: //nop } case Constants.EN_NO_WRAP: if (propId == Constants.PR_WRAP_OPTION) { return EnumProperty.getInstance(Constants.EN_NO_WRAP, "NO_WRAP"); } case Constants.EN_NORMAL: default: //nop } return null; }
// in src/java/org/apache/fop/fo/properties/NumberProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof NumberProperty) { return p; } if (p instanceof EnumProperty) { return EnumNumber.getInstance(p); } Number val = p.getNumber(); if (val != null) { return getInstance(val.doubleValue()); } return convertPropertyDatatype(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/NumberProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof EnumProperty) { return EnumNumber.getInstance(p); } Number val = p.getNumber(); if (val != null) { int i = Math.round(val.floatValue()); if (i <= 0) { i = 1; } return getInstance(i); } return convertPropertyDatatype(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/BorderSpacingShorthandParser.java
protected Property convertValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { List lst = property.getList(); if (lst != null) { if (lst.size() == 1) { Property len = (Property)lst.get(0); return new LengthPairProperty(len); } else if (lst.size() == 2) { Property ipd = (Property)lst.get(0); Property bpd = (Property)lst.get(1); return new LengthPairProperty(ipd, bpd); } } throw new PropertyException("list with 1 or 2 length values expected"); }
// in src/java/org/apache/fop/fo/properties/LengthPairProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof LengthPairProperty) { return p; } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/XMLLangShorthandParser.java
public Property getValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { String shorthandValue = property.getString(); int hyphenIndex = shorthandValue.indexOf(HYPHEN_MINUS); if (propId == Constants.PR_LANGUAGE) { if (hyphenIndex == -1) { /* only language specified; use the whole property */ return property; } else { /* use only the primary tag */ return StringProperty.getInstance( shorthandValue.substring(0, hyphenIndex)); } } else if (propId == Constants.PR_COUNTRY) { if (hyphenIndex != -1) { int nextHyphenIndex = shorthandValue.indexOf(HYPHEN_MINUS, hyphenIndex + 1); if (nextHyphenIndex != -1) { return StringProperty.getInstance( shorthandValue.substring(hyphenIndex + 1, nextHyphenIndex)); } else { return StringProperty.getInstance( shorthandValue.substring(hyphenIndex + 1)); } } } return null; }
// in src/java/org/apache/fop/fo/properties/FontFamilyProperty.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { if ("inherit".equals(value)) { return super.make(propertyList, value, fo); } else { FontFamilyProperty prop = new FontFamilyProperty(); String tmpVal; int startIndex = 0; int commaIndex = value.indexOf(','); int quoteIndex; int aposIndex; char qChar; boolean parsed = false; while (!parsed) { if (commaIndex == -1) { tmpVal = value.substring(startIndex).trim(); parsed = true; } else { tmpVal = value.substring(startIndex, commaIndex).trim(); startIndex = commaIndex + 1; commaIndex = value.indexOf(',', startIndex); } aposIndex = tmpVal.indexOf('\''); quoteIndex = tmpVal.indexOf('\"'); if (aposIndex != -1 || quoteIndex != -1) { qChar = (aposIndex == -1) ? '\"' : '\''; if (tmpVal.lastIndexOf(qChar) != tmpVal.length() - 1) { log.warn("Skipping malformed value for font-family: " + tmpVal + " in \"" + value + "\"."); tmpVal = ""; } else { tmpVal = tmpVal.substring(1, tmpVal.length() - 1); } } if (!"".equals(tmpVal)) { int dblSpaceIndex = tmpVal.indexOf(" "); while (dblSpaceIndex != -1) { tmpVal = tmpVal.substring(0, dblSpaceIndex) + tmpVal.substring(dblSpaceIndex + 1); dblSpaceIndex = tmpVal.indexOf(" "); } prop.addProperty(StringProperty.getInstance(tmpVal)); } } return CACHE.fetch(prop); } }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property findProperty(PropertyList propertyList, boolean tryInherit) throws PropertyException { Property p = null; if (IS_LOG_TRACE_ENABLED) { LOG.trace("PropertyMaker.findProperty: " + FOPropertyMapping.getPropertyName(propId) + ", " + propertyList.getFObj().getName()); } if (corresponding != null && corresponding.isCorrespondingForced(propertyList)) { p = corresponding.compute(propertyList); } else { p = propertyList.getExplicit(propId); if (p == null) { // check for shorthand specification p = getShorthand(propertyList); } if (p == null) { p = this.compute(propertyList); } } if (p == null && tryInherit) { // else inherit (if has parent and is inheritable) PropertyList parentPropertyList = propertyList.getParentPropertyList(); if (parentPropertyList != null && isInherited()) { p = parentPropertyList.get(propId, true, false); } } return p; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property get(int subpropertyId, PropertyList propertyList, boolean tryInherit, boolean tryDefault) throws PropertyException { Property p = findProperty(propertyList, tryInherit); if (p == null && tryDefault) { // default value for this FO! p = make(propertyList); } return p; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public PercentBase getPercentBase(PropertyList pl) throws PropertyException { if (percentBase == -1) { return null; } else { return new LengthBase(pl, percentBase); } }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property make(PropertyList propertyList) throws PropertyException { if (defaultProperty != null) { if (IS_LOG_TRACE_ENABLED) { LOG.trace("PropertyMaker.make: reusing defaultProperty, " + FOPropertyMapping.getPropertyName(propId)); } return defaultProperty; } if (IS_LOG_TRACE_ENABLED) { LOG.trace("PropertyMaker.make: making default property value, " + FOPropertyMapping.getPropertyName(propId) + ", " + propertyList.getFObj().getName()); } Property p = make(propertyList, defaultValue, propertyList.getParentFObj()); if (!contextDep) { defaultProperty = p; } return p; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { try { Property newProp = null; String pvalue = value; if ("inherit".equals(value)) { newProp = propertyList.getFromParent(this.propId & Constants.PROPERTY_MASK); if ((propId & Constants.COMPOUND_MASK) != 0) { newProp = getSubprop(newProp, propId & Constants.COMPOUND_MASK); } if (!isInherited() && LOG.isWarnEnabled()) { /* check whether explicit value is available on the parent * (for inherited properties, an inherited value will always * be available) */ Property parentExplicit = propertyList.getParentPropertyList() .getExplicit(getPropId()); if (parentExplicit == null) { LOG.warn(FOPropertyMapping.getPropertyName(getPropId()) + "=\"inherit\" on " + propertyList.getFObj().getName() + ", but no explicit value found on the parent FO."); } } } else { // Check for keyword shorthand values to be substituted. pvalue = checkValueKeywords(pvalue.trim()); newProp = checkEnumValues(pvalue); } if (newProp == null) { // Override parsePropertyValue in each subclass of Property.Maker newProp = PropertyParser.parse(pvalue, new PropertyInfo(this, propertyList)); } if (newProp != null) { newProp = convertProperty(newProp, propertyList, fo); } if (newProp == null) { throw new PropertyException("No conversion defined " + pvalue); } return newProp; } catch (PropertyException propEx) { if (fo != null) { propEx.setLocator(fo.getLocator()); } propEx.setPropertyName(getName()); throw propEx; } }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property make(Property baseProperty, int subpropertyId, PropertyList propertyList, String value, FObj fo) throws PropertyException { //getLogger().error("compound property component " // + partName + " unknown."); return baseProperty; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property convertShorthandProperty(PropertyList propertyList, Property prop, FObj fo) throws PropertyException { Property pret = convertProperty(prop, propertyList, fo); if (pret == null) { // If value is a name token, may be keyword or Enum String sval = prop.getNCname(); if (sval != null) { //log.debug("Convert shorthand ncname " + sval); pret = checkEnumValues(sval); if (pret == null) { /* Check for keyword shorthand values to be substituted. */ String pvalue = checkValueKeywords(sval); if (!pvalue.equals(sval)) { //log.debug("Convert shorthand keyword" + pvalue); // Substituted a value: must parse it Property p = PropertyParser.parse(pvalue, new PropertyInfo(this, propertyList)); pret = convertProperty(p, propertyList, fo); } } } } if (pret != null) { /* * log.debug("Return shorthand value " + pret.getString() + * " for " + getPropName()); */ } return pret; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
protected Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { return null; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
protected Property convertPropertyDatatype(Property p, PropertyList propertyList, FObj fo) throws PropertyException { return null; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
protected Property compute(PropertyList propertyList) throws PropertyException { if (corresponding != null) { return corresponding.compute(propertyList); } return null; // standard }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property getShorthand(PropertyList propertyList) throws PropertyException { if (shorthands == null) { return null; } Property prop; int n = shorthands.length; for (int i = 0; i < n && shorthands[i] != null; i++) { PropertyMaker shorthand = shorthands[i]; prop = propertyList.getExplicit(shorthand.propId); if (prop != null) { ShorthandParser parser = shorthand.datatypeParser; Property p = parser.getValueForProperty(getPropId(), prop, this, propertyList); if (p != null) { return p; } } } return null; }
// in src/java/org/apache/fop/fo/properties/DimensionPropertyMaker.java
public Property compute(PropertyList propertyList) throws PropertyException { // Based on [width|height] Property p = super.compute(propertyList); if (p == null) { p = baseMaker.make(propertyList); } // Based on min-[width|height] int wmcorr = propertyList.selectFromWritingMode(extraCorresponding[0][0], extraCorresponding[0][1], extraCorresponding[0][2], extraCorresponding[0][3]); Property subprop = propertyList.getExplicitOrShorthand(wmcorr); if (subprop != null) { baseMaker.setSubprop(p, Constants.CP_MINIMUM, subprop); } // Based on max-[width|height] wmcorr = propertyList.selectFromWritingMode(extraCorresponding[1][0], extraCorresponding[1][1], extraCorresponding[1][2], extraCorresponding[1][3]); subprop = propertyList.getExplicitOrShorthand(wmcorr); // TODO: Don't set when NONE. if (subprop != null) { baseMaker.setSubprop(p, Constants.CP_MAXIMUM, subprop); } return p; }
// in src/java/org/apache/fop/fo/properties/BoxPropShorthandParser.java
protected Property convertValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { String name = FOPropertyMapping.getPropertyName(propId); Property p = null; int count = property.getList().size(); if (name.indexOf("-top") >= 0) { p = getElement(property, 0); } else if (name.indexOf("-right") >= 0) { p = getElement(property, count > 1 ? 1 : 0); } else if (name.indexOf("-bottom") >= 0) { p = getElement(property, count > 2 ? 2 : 0); } else if (name.indexOf("-left") >= 0) { p = getElement(property, count > 3 ? 3 : (count > 1 ? 1 : 0)); } // if p not null, try to convert it to a value of the correct type if (p != null) { return maker.convertShorthandProperty(propertyList, p, null); } return p; }
// in src/java/org/apache/fop/fo/PropertyList.java
public Property getExplicitOrShorthand(int propId) throws PropertyException { /* Handle request for one part of a compound property */ Property p = getExplicit(propId); if (p == null) { p = getShorthand(propId); } return p; }
// in src/java/org/apache/fop/fo/PropertyList.java
public Property getInherited(int propId) throws PropertyException { if (isInherited(propId)) { return getFromParent(propId); } else { // return the "initial" value return makeProperty(propId); } }
// in src/java/org/apache/fop/fo/PropertyList.java
public Property get(int propId) throws PropertyException { return get(propId, true, true); }
// in src/java/org/apache/fop/fo/PropertyList.java
public Property get(int propId, boolean bTryInherit, boolean bTryDefault) throws PropertyException { PropertyMaker propertyMaker = findMaker(propId & Constants.PROPERTY_MASK); if (propertyMaker != null) { return propertyMaker.get(propId & Constants.COMPOUND_MASK, this, bTryInherit, bTryDefault); } return null; }
// in src/java/org/apache/fop/fo/PropertyList.java
public Property getNearestSpecified(int propId) throws PropertyException { Property p = null; PropertyList pList = parentPropertyList; while (pList != null) { p = pList.getExplicit(propId); if (p != null) { return p; } else { pList = pList.parentPropertyList; } } // If no explicit value found on any of the ancestor-nodes, // return initial (default) value. return makeProperty(propId); }
// in src/java/org/apache/fop/fo/PropertyList.java
public Property getFromParent(int propId) throws PropertyException { if (parentPropertyList != null) { return parentPropertyList.get(propId); } else { return makeProperty(propId); } }
// in src/java/org/apache/fop/fo/PropertyList.java
private Property findBaseProperty(Attributes attributes, FObj parentFO, int propId, String basePropertyName, PropertyMaker propertyMaker) throws PropertyException { /* If the baseProperty has already been created, return it * e.g. <fo:leader xxxx="120pt" xxxx.maximum="200pt"... /> */ Property baseProperty = getExplicit(propId); if (baseProperty != null) { return baseProperty; } /* Otherwise If it is specified later in this list of Attributes, create it now * e.g. <fo:leader xxxx.maximum="200pt" xxxx="200pt"... /> */ String basePropertyValue = attributes.getValue(basePropertyName); if (basePropertyValue != null && propertyMaker != null) { baseProperty = propertyMaker.make(this, basePropertyValue, parentFO); return baseProperty; } return null; // could not find base property }
// in src/java/org/apache/fop/fo/PropertyList.java
private Property getShorthand(int propId) throws PropertyException { PropertyMaker propertyMaker = findMaker(propId); if (propertyMaker != null) { return propertyMaker.getShorthand(this); } else { //log.error("no Maker for " + propertyName); return null; } }
// in src/java/org/apache/fop/fo/PropertyList.java
private Property makeProperty(int propId) throws PropertyException { PropertyMaker propertyMaker = findMaker(propId); if (propertyMaker != null) { return propertyMaker.make(this); } else { //log.error("property " + propertyName // + " ignored"); } return null; }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonBorderPaddingBackground getBorderPaddingBackgroundProps() throws PropertyException { return CommonBorderPaddingBackground.getInstance(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonHyphenation getHyphenationProps() throws PropertyException { return CommonHyphenation.getInstance(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonMarginBlock getMarginBlockProps() throws PropertyException { return new CommonMarginBlock(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonMarginInline getMarginInlineProps() throws PropertyException { return new CommonMarginInline(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonAural getAuralProps() throws PropertyException { CommonAural props = new CommonAural(this); return props; }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonRelativePosition getRelativePositionProps() throws PropertyException { return new CommonRelativePosition(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonAbsolutePosition getAbsolutePositionProps() throws PropertyException { return new CommonAbsolutePosition(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonFont getFontProps() throws PropertyException { return CommonFont.getInstance(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonTextDecoration getTextDecorationProps() throws PropertyException { return CommonTextDecoration.createFromPropertyList(this); }
// in src/java/org/apache/fop/fo/expr/FromTableColumnFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { FObj fo = pInfo.getPropertyList().getFObj(); /* obtain property Id for the property for which the function is being * evaluated */ int propId = 0; if (args.length == 0) { propId = pInfo.getPropertyMaker().getPropId(); } else { String propName = args[0].getString(); propId = FOPropertyMapping.getPropertyId(propName); } /* make sure we have a correct property id ... */ if (propId != -1) { /* obtain column number for which the function is being evaluated: */ int columnNumber = -1; int span = 0; if (fo.getNameId() != Constants.FO_TABLE_CELL) { // climb up to the nearest cell do { fo = (FObj) fo.getParent(); } while (fo.getNameId() != Constants.FO_TABLE_CELL && fo.getNameId() != Constants.FO_PAGE_SEQUENCE); if (fo.getNameId() == Constants.FO_TABLE_CELL) { //column-number is available on the cell columnNumber = ((TableCell) fo).getColumnNumber(); span = ((TableCell) fo).getNumberColumnsSpanned(); } else { //means no table-cell was found... throw new PropertyException("from-table-column() may only be used on " + "fo:table-cell or its descendants."); } } else { //column-number is only accurately available through the propertyList columnNumber = pInfo.getPropertyList().get(Constants.PR_COLUMN_NUMBER) .getNumeric().getValue(); span = pInfo.getPropertyList().get(Constants.PR_NUMBER_COLUMNS_SPANNED) .getNumeric().getValue(); } /* return the property from the column */ Table t = ((TableFObj) fo).getTable(); List cols = t.getColumns(); ColumnNumberManager columnIndexManager = t.getColumnNumberManager(); if (cols == null) { //no columns defined => no match: return default value return pInfo.getPropertyList().get(propId, false, true); } else { if (columnIndexManager.isColumnNumberUsed(columnNumber)) { //easiest case: exact match return ((TableColumn) cols.get(columnNumber - 1)).getProperty(propId); } else { //no exact match: try all spans... while (--span > 0 && !columnIndexManager.isColumnNumberUsed(++columnNumber)) { //nop: just increment/decrement } if (columnIndexManager.isColumnNumberUsed(columnNumber)) { return ((TableColumn) cols.get(columnNumber - 1)).getProperty(propId); } else { //no match: return default value return pInfo.getPropertyList().get(propId, false, true); } } } } else { throw new PropertyException("Incorrect parameter to from-table-column() function"); } }
// in src/java/org/apache/fop/fo/expr/AbsFunction.java
public Property eval(Property[] args, PropertyInfo propInfo) throws PropertyException { Numeric num = args[0].getNumeric(); if (num == null) { throw new PropertyException("Non numeric operand to abs function"); } // TODO: What if it has relative components (percent, table-col units)? return (Property) NumericOp.abs(num); }
// in src/java/org/apache/fop/fo/expr/PropertyInfo.java
public PercentBase getPercentBase() throws PropertyException { PercentBase pcbase = getFunctionPercentBase(); return (pcbase != null) ? pcbase : maker.getPercentBase(plist); }
// in src/java/org/apache/fop/fo/expr/PropertyInfo.java
public Length currentFontSize() throws PropertyException { return plist.get(Constants.PR_FONT_SIZE).getLength(); }
// in src/java/org/apache/fop/fo/expr/LabelEndFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Length distance = pInfo.getPropertyList().get( Constants.PR_PROVISIONAL_DISTANCE_BETWEEN_STARTS).getLength(); Length separation = pInfo.getPropertyList().getNearestSpecified( Constants.PR_PROVISIONAL_LABEL_SEPARATION).getLength(); PropertyList pList = pInfo.getPropertyList(); while (pList != null && !(pList.getFObj() instanceof ListItem)) { pList = pList.getParentPropertyList(); } if (pList == null) { throw new PropertyException("label-end() called from outside an fo:list-item"); } Length startIndent = pList.get(Constants.PR_START_INDENT).getLength(); LengthBase base = new LengthBase(pInfo.getPropertyList(), LengthBase.CONTAINING_REFAREA_WIDTH); PercentLength refWidth = new PercentLength(1.0, base); Numeric labelEnd = distance; labelEnd = NumericOp.addition(labelEnd, startIndent); //TODO add start-intrusion-adjustment labelEnd = NumericOp.subtraction(labelEnd, separation); labelEnd = NumericOp.subtraction(refWidth, labelEnd); return (Property) labelEnd; }
// in src/java/org/apache/fop/fo/expr/BodyStartFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Numeric distance = pInfo.getPropertyList() .get(Constants.PR_PROVISIONAL_DISTANCE_BETWEEN_STARTS).getNumeric(); PropertyList pList = pInfo.getPropertyList(); while (pList != null && !(pList.getFObj() instanceof ListItem)) { pList = pList.getParentPropertyList(); } if (pList == null) { throw new PropertyException("body-start() called from outside an fo:list-item"); } Numeric startIndent = pList.get(Constants.PR_START_INDENT).getNumeric(); return (Property) NumericOp.addition(distance, startIndent); }
// in src/java/org/apache/fop/fo/expr/FromParentFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { String propName = args[0].getString(); if (propName == null) { throw new PropertyException("Incorrect parameter to from-parent function"); } // NOTE: special cases for shorthand property // Should return COMPUTED VALUE /* * For now, this is the same as inherited-property-value(propName) * (The only difference I can see is that this could work for * non-inherited properties too. Perhaps the result is different for * a property line line-height which "inherits specified"??? */ int propId = FOPropertyMapping.getPropertyId(propName); if (propId < 0) { throw new PropertyException( "Unknown property name used with inherited-property-value function: " + propName); } return pInfo.getPropertyList().getFromParent(propId); }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
private Numeric getResolved(PercentBaseContext context) throws PropertyException { switch (operation) { case ADDITION: return NumericOp.addition2(op1, op2, context); case SUBTRACTION: return NumericOp.subtraction2(op1, op2, context); case MULTIPLY: return NumericOp.multiply2(op1, op2, context); case DIVIDE: return NumericOp.divide2(op1, op2, context); case MODULO: return NumericOp.modulo2(op1, op2, context); case NEGATE: return NumericOp.negate2(op1, context); case ABS: return NumericOp.abs2(op1, context); case MAX: return NumericOp.max2(op1, op2, context); case MIN: return NumericOp.min2(op1, op2, context); default: throw new PropertyException("Unknown expr operation " + operation); } }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
public double getNumericValue() throws PropertyException { return getResolved(null).getNumericValue(null); }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
public double getNumericValue(PercentBaseContext context) throws PropertyException { return getResolved(context).getNumericValue(context); }
// in src/java/org/apache/fop/fo/expr/RoundFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number dbl = args[0].getNumber(); if (dbl == null) { throw new PropertyException("Non number operand to round function"); } double n = dbl.doubleValue(); double r = Math.floor(n + 0.5); if (r == 0.0 && n < 0.0) { r = -r; // round(-0.2) returns -0 not 0 } return NumberProperty.getInstance(r); }
// in src/java/org/apache/fop/fo/expr/RGBColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { return ColorProperty.getInstance(pInfo.getUserAgent(), "rgb(" + args[0] + "," + args[1] + "," + args[2] + ")"); }
// in src/java/org/apache/fop/fo/expr/FunctionBase.java
public Property getOptionalArgDefault(int index, PropertyInfo pi) throws PropertyException { if ( index >= getOptionalArgsCount() ) { PropertyException e = new PropertyException ( new IndexOutOfBoundsException ( "illegal optional argument index" ) ); e.setPropertyInfo ( pi ); throw e; } else { return null; } }
// in src/java/org/apache/fop/fo/expr/PropertyTokenizer.java
void next() throws PropertyException { currentTokenValue = null; currentTokenStartIndex = exprIndex; boolean bSawDecimal; while ( true ) { if (exprIndex >= exprLength) { currentToken = TOK_EOF; return; } char c = expr.charAt(exprIndex++); switch (c) { case ' ': case '\t': case '\r': case '\n': currentTokenStartIndex = exprIndex; break; case ',': currentToken = TOK_COMMA; return; case '+': currentToken = TOK_PLUS; return; case '-': currentToken = TOK_MINUS; return; case '(': currentToken = TOK_LPAR; return; case ')': currentToken = TOK_RPAR; return; case '"': case '\'': exprIndex = expr.indexOf(c, exprIndex); if (exprIndex < 0) { exprIndex = currentTokenStartIndex + 1; throw new PropertyException("missing quote"); } currentTokenValue = expr.substring(currentTokenStartIndex + 1, exprIndex++); currentToken = TOK_LITERAL; return; case '*': /* * if (currentMaybeOperator) { * recognizeOperator = false; */ currentToken = TOK_MULTIPLY; /* * } * else * throw new PropertyException("illegal operator *"); */ return; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': scanDigits(); if (exprIndex < exprLength && expr.charAt(exprIndex) == '.') { exprIndex++; bSawDecimal = true; if (exprIndex < exprLength && isDigit(expr.charAt(exprIndex))) { exprIndex++; scanDigits(); } } else { bSawDecimal = false; } if (exprIndex < exprLength && expr.charAt(exprIndex) == '%') { exprIndex++; currentToken = TOK_PERCENT; } else { // Check for possible unit name following number currentUnitLength = exprIndex; scanName(); currentUnitLength = exprIndex - currentUnitLength; currentToken = (currentUnitLength > 0) ? TOK_NUMERIC : (bSawDecimal ? TOK_FLOAT : TOK_INTEGER); } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); return; case '.': nextDecimalPoint(); return; case '#': // Start of color value nextColor(); return; default: --exprIndex; scanName(); if (exprIndex == currentTokenStartIndex) { throw new PropertyException("illegal character"); } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); if (currentTokenValue.equals("mod")) { currentToken = TOK_MOD; return; } else if (currentTokenValue.equals("div")) { currentToken = TOK_DIV; return; } if (followingParen()) { currentToken = TOK_FUNCTION_LPAR; } else { currentToken = TOK_NCNAME; } return; } } }
// in src/java/org/apache/fop/fo/expr/PropertyTokenizer.java
private void nextDecimalPoint() throws PropertyException { if (exprIndex < exprLength && isDigit(expr.charAt(exprIndex))) { ++exprIndex; scanDigits(); if (exprIndex < exprLength && expr.charAt(exprIndex) == '%') { exprIndex++; currentToken = TOK_PERCENT; } else { // Check for possible unit name following number currentUnitLength = exprIndex; scanName(); currentUnitLength = exprIndex - currentUnitLength; currentToken = (currentUnitLength > 0) ? TOK_NUMERIC : TOK_FLOAT; } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); return; } throw new PropertyException("illegal character '.'"); }
// in src/java/org/apache/fop/fo/expr/PropertyTokenizer.java
private void nextColor() throws PropertyException { if (exprIndex < exprLength) { ++exprIndex; scanHexDigits(); int len = exprIndex - currentTokenStartIndex - 1; if (len % 3 == 0) { currentToken = TOK_COLORSPEC; } else { //Actually not a color at all, but an NCNAME starting with "#" scanRestOfName(); currentToken = TOK_NCNAME; } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); return; } else { throw new PropertyException("illegal character '#'"); } }
// in src/java/org/apache/fop/fo/expr/CIELabColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { float red = args[0].getNumber().floatValue(); float green = args[1].getNumber().floatValue(); float blue = args[2].getNumber().floatValue(); /* Verify sRGB replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("sRGB color values out of range. " + "Arguments to cie-lab-color() must be [0..255] or [0%..100%]"); } float l = args[3].getNumber().floatValue(); float a = args[4].getNumber().floatValue(); float b = args[5].getNumber().floatValue(); if (l < 0 || l > 100) { throw new PropertyException("L* value out of range. Valid range: [0..100]"); } if (a < -127 || a > 127 || b < -127 || b > 127) { throw new PropertyException("a* and b* values out of range. Valid range: [-127..+127]"); } StringBuffer sb = new StringBuffer(); sb.append("cie-lab-color(" + red + "," + green + "," + blue + "," + l + "," + a + "," + b + ")"); FOUserAgent ua = (pInfo == null) ? null : (pInfo.getFO() == null ? null : pInfo.getFO().getUserAgent()); return ColorProperty.getInstance(ua, sb.toString()); }
// in src/java/org/apache/fop/fo/expr/FromNearestSpecifiedValueFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { String propName = args[0].getString(); if (propName == null) { throw new PropertyException( "Incorrect parameter to from-nearest-specified-value function"); } // NOTE: special cases for shorthand property // Should return COMPUTED VALUE int propId = FOPropertyMapping.getPropertyId(propName); if (propId < 0) { throw new PropertyException( "Unknown property name used with inherited-property-value function: " + propName); } return pInfo.getPropertyList().getNearestSpecified(propId); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric addition(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return addition2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.ADDITION, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric addition2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Can't subtract Numerics of different dimensions"); } return numeric(op1.getNumericValue(context) + op2.getNumericValue(context), op1.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric subtraction(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return subtraction2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.SUBTRACTION, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric subtraction2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Can't subtract Numerics of different dimensions"); } return numeric(op1.getNumericValue(context) - op2.getNumericValue(context), op1.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric multiply(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return multiply2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.MULTIPLY, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric multiply2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { return numeric(op1.getNumericValue(context) * op2.getNumericValue(context), op1.getDimension() + op2.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric divide(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return divide2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.DIVIDE, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric divide2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { return numeric(op1.getNumericValue(context) / op2.getNumericValue(context), op1.getDimension() - op2.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric modulo(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return modulo2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.MODULO, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric modulo2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { return numeric(op1.getNumericValue(context) % op2.getNumericValue(context), op1.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric abs(Numeric op) throws PropertyException { if (op.isAbsolute()) { return abs2(op, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.ABS, op); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric abs2(Numeric op, PercentBaseContext context) throws PropertyException { return numeric(Math.abs(op.getNumericValue(context)), op.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric negate(Numeric op) throws PropertyException { if (op.isAbsolute()) { return negate2(op, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.NEGATE, op); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric negate2(Numeric op, PercentBaseContext context) throws PropertyException { return numeric(-op.getNumericValue(context), op.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric max(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return max2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.MAX, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric max2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Arguments to max() must have same dimensions"); } return op1.getNumericValue(context) > op2.getNumericValue(context) ? op1 : op2; }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric min(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return min2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.MIN, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric min2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Arguments to min() must have same dimensions"); } return op1.getNumericValue(context) <= op2.getNumericValue(context) ? op1 : op2; }
// in src/java/org/apache/fop/fo/expr/MaxFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Numeric n1 = args[0].getNumeric(); Numeric n2 = args[1].getNumeric(); if (n1 == null || n2 == null) { throw new PropertyException("Non numeric operands to max function"); } return (Property) NumericOp.max(n1, n2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
public static Property parse(String expr, PropertyInfo propInfo) throws PropertyException { try { return new PropertyParser(expr, propInfo).parseProperty(); } catch (PropertyException exc) { exc.setPropertyInfo(propInfo); throw exc; } }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property parseProperty() throws PropertyException { next(); if (currentToken == TOK_EOF) { // if prop value is empty string, force to StringProperty return StringProperty.getInstance(""); } ListProperty propList = null; while (true) { Property prop = parseAdditiveExpr(); if (currentToken == TOK_EOF) { if (propList != null) { propList.addProperty(prop); return propList; } else { return prop; } } else { if (propList == null) { propList = new ListProperty(prop); } else { propList.addProperty(prop); } } // throw new PropertyException("unexpected token"); } // return prop; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property parseAdditiveExpr() throws PropertyException { // Evaluate and put result on the operand stack Property prop = parseMultiplicativeExpr(); loop: while (true) { switch (currentToken) { case TOK_PLUS: next(); prop = evalAddition(prop.getNumeric(), parseMultiplicativeExpr().getNumeric()); break; case TOK_MINUS: next(); prop = evalSubtraction(prop.getNumeric(), parseMultiplicativeExpr().getNumeric()); break; default: break loop; } } return prop; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property parseMultiplicativeExpr() throws PropertyException { Property prop = parseUnaryExpr(); loop: while (true) { switch (currentToken) { case TOK_DIV: next(); prop = evalDivide(prop.getNumeric(), parseUnaryExpr().getNumeric()); break; case TOK_MOD: next(); prop = evalModulo(prop.getNumber(), parseUnaryExpr().getNumber()); break; case TOK_MULTIPLY: next(); prop = evalMultiply(prop.getNumeric(), parseUnaryExpr().getNumeric()); break; default: break loop; } } return prop; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property parseUnaryExpr() throws PropertyException { if (currentToken == TOK_MINUS) { next(); return evalNegate(parseUnaryExpr().getNumeric()); } return parsePrimaryExpr(); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private void expectRpar() throws PropertyException { if (currentToken != TOK_RPAR) { throw new PropertyException("expected )"); } next(); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property parsePrimaryExpr() throws PropertyException { Property prop; if (currentToken == TOK_COMMA) { //Simply skip commas, for example for font-family next(); } switch (currentToken) { case TOK_LPAR: next(); prop = parseAdditiveExpr(); expectRpar(); return prop; case TOK_LITERAL: prop = StringProperty.getInstance(currentTokenValue); break; case TOK_NCNAME: // Interpret this in context of the property or do it later? prop = new NCnameProperty(currentTokenValue); break; case TOK_FLOAT: prop = NumberProperty.getInstance(new Double(currentTokenValue)); break; case TOK_INTEGER: prop = NumberProperty.getInstance(new Integer(currentTokenValue)); break; case TOK_PERCENT: /* * Get the length base value object from the Maker. If null, then * this property can't have % values. Treat it as a real number. */ double pcval = Double.parseDouble( currentTokenValue.substring(0, currentTokenValue.length() - 1)) / 100.0; PercentBase pcBase = this.propInfo.getPercentBase(); if (pcBase != null) { if (pcBase.getDimension() == 0) { prop = NumberProperty.getInstance(pcval * pcBase.getBaseValue()); } else if (pcBase.getDimension() == 1) { if (pcBase instanceof LengthBase) { if (pcval == 0.0) { prop = FixedLength.ZERO_FIXED_LENGTH; break; } //If the base of the percentage is known //and absolute, it can be resolved by the //parser Length base = ((LengthBase)pcBase).getBaseLength(); if (base != null && base.isAbsolute()) { prop = FixedLength.getInstance(pcval * base.getValue()); break; } } prop = new PercentLength(pcval, pcBase); } else { throw new PropertyException("Illegal percent dimension value"); } } else { // WARNING? Interpret as a decimal fraction, eg. 50% = .5 prop = NumberProperty.getInstance(pcval); } break; case TOK_NUMERIC: // A number plus a valid unit name. int numLen = currentTokenValue.length() - currentUnitLength; String unitPart = currentTokenValue.substring(numLen); double numPart = Double.parseDouble(currentTokenValue.substring(0, numLen)); if (RELUNIT.equals(unitPart)) { prop = (Property) NumericOp.multiply( NumberProperty.getInstance(numPart), propInfo.currentFontSize()); } else { if ("px".equals(unitPart)) { //pass the ratio between target-resolution and //the default resolution of 72dpi float resolution = propInfo.getPropertyList().getFObj() .getUserAgent().getSourceResolution(); prop = FixedLength.getInstance( numPart, unitPart, UnitConv.IN2PT / resolution); } else { //use default resolution of 72dpi prop = FixedLength.getInstance(numPart, unitPart); } } break; case TOK_COLORSPEC: prop = ColorProperty.getInstance(propInfo.getUserAgent(), currentTokenValue); break; case TOK_FUNCTION_LPAR: Function function = (Function)FUNCTION_TABLE.get(currentTokenValue); if (function == null) { throw new PropertyException("no such function: " + currentTokenValue); } next(); // Push new function (for function context: getPercentBase()) propInfo.pushFunction(function); prop = function.eval(parseArgs(function), propInfo); propInfo.popFunction(); return prop; default: // TODO: add the token or the expr to the error message. throw new PropertyException("syntax error"); } next(); return prop; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
Property[] parseArgs(Function function) throws PropertyException { int numReq = function.getRequiredArgsCount(); // # required args int numOpt = function.getOptionalArgsCount(); // # optional args boolean hasVar = function.hasVariableArgs(); // has variable args List<Property> args = new java.util.ArrayList<Property>(numReq + numOpt); if (currentToken == TOK_RPAR) { // No args: func() next(); } else { while (true) { Property p = parseAdditiveExpr(); int i = args.size(); if ( ( i < numReq ) || ( ( i - numReq ) < numOpt ) || hasVar ) { args.add ( p ); } else { throw new PropertyException ( "Unexpected function argument at index " + i ); } // ignore extra args if (currentToken != TOK_COMMA) { break; } next(); } expectRpar(); } int numArgs = args.size(); if ( numArgs < numReq ) { throw new PropertyException("Expected " + numReq + " required arguments, but only " + numArgs + " specified"); } else { for ( int i = 0; i < numOpt; i++ ) { if ( args.size() < ( numReq + i + 1 ) ) { args.add ( function.getOptionalArgDefault ( i, propInfo ) ); } } } return (Property[]) args.toArray ( new Property [ args.size() ] ); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalAddition(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in addition"); } return (Property) NumericOp.addition(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalSubtraction(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in subtraction"); } return (Property) NumericOp.subtraction(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalNegate(Numeric op) throws PropertyException { if (op == null) { throw new PropertyException("Non numeric operand to unary minus"); } return (Property) NumericOp.negate(op); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalMultiply(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in multiplication"); } return (Property) NumericOp.multiply(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalDivide(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in division"); } return (Property) NumericOp.divide(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalModulo(Number op1, Number op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non number operand to modulo"); } return NumberProperty.getInstance(op1.doubleValue() % op2.doubleValue()); }
// in src/java/org/apache/fop/fo/expr/MinFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Numeric n1 = args[0].getNumeric(); Numeric n2 = args[1].getNumeric(); if (n1 == null || n2 == null) { throw new PropertyException("Non numeric operands to min function"); } return (Property) NumericOp.min(n1, n2); }
// in src/java/org/apache/fop/fo/expr/FloorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number dbl = args[0].getNumber(); if (dbl == null) { throw new PropertyException("Non number operand to floor function"); } return NumberProperty.getInstance(Math.floor(dbl.doubleValue())); }
// in src/java/org/apache/fop/fo/expr/CMYKColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { StringBuffer sb = new StringBuffer(); sb.append("cmyk(" + args[0] + "," + args[1] + "," + args[2] + "," + args[3] + ")"); FOUserAgent ua = (pInfo == null) ? null : (pInfo.getFO() == null ? null : pInfo.getFO().getUserAgent()); return ColorProperty.getInstance(ua, sb.toString()); }
// in src/java/org/apache/fop/fo/expr/SystemColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { FOUserAgent ua = (pInfo == null) ? null : (pInfo.getFO() == null ? null : pInfo.getFO().getUserAgent()); return ColorProperty.getInstance(ua, "system-color(" + args[0] + ")"); }
// in src/java/org/apache/fop/fo/expr/RGBICCColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { // Map color profile NCNAME to src from declarations/color-profile element String colorProfileName = args[3].getString(); Declarations decls = (pInfo.getFO() != null ? pInfo.getFO().getRoot().getDeclarations() : null); ColorProfile cp = null; if (decls == null) { //function used in a color-specification //on a FO occurring: //a) before the fo:declarations, //b) or in a document without fo:declarations? //=> return the sRGB fallback if (!ColorUtil.isPseudoProfile(colorProfileName)) { Property[] rgbArgs = new Property[3]; System.arraycopy(args, 0, rgbArgs, 0, 3); return new RGBColorFunction().eval(rgbArgs, pInfo); } } else { cp = decls.getColorProfile(colorProfileName); if (cp == null) { if (!ColorUtil.isPseudoProfile(colorProfileName)) { PropertyException pe = new PropertyException("The " + colorProfileName + " color profile was not declared"); pe.setPropertyInfo(pInfo); throw pe; } } } String src = (cp != null ? cp.getSrc() : ""); float red = 0; float green = 0; float blue = 0; red = args[0].getNumber().floatValue(); green = args[1].getNumber().floatValue(); blue = args[2].getNumber().floatValue(); /* Verify rgb replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("Color values out of range. " + "Arguments to rgb-icc() must be [0..255] or [0%..100%]"); } // rgb-icc is replaced with fop-rgb-icc which has an extra fifth argument containing the // color profile src attribute as it is defined in the color-profile declarations element. StringBuffer sb = new StringBuffer(); sb.append("fop-rgb-icc("); sb.append(red / 255f); sb.append(',').append(green / 255f); sb.append(',').append(blue / 255f); for (int ix = 3; ix < args.length; ix++) { if (ix == 3) { sb.append(',').append(colorProfileName); sb.append(',').append(src); } else { sb.append(',').append(args[ix]); } } sb.append(")"); return ColorProperty.getInstance(pInfo.getUserAgent(), sb.toString()); }
// in src/java/org/apache/fop/fo/expr/RGBICCColorFunction.java
public int getBaseLength(PercentBaseContext context) throws PropertyException { return 0; }
// in src/java/org/apache/fop/fo/expr/RGBNamedColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { // Map color profile NCNAME to src from declarations/color-profile element String colorProfileName = args[3].getString(); String colorName = args[4].getString(); Declarations decls = (pInfo.getFO() != null ? pInfo.getFO().getRoot().getDeclarations() : null); ColorProfile cp = null; if (decls != null) { cp = decls.getColorProfile(colorProfileName); } if (cp == null) { PropertyException pe = new PropertyException("The " + colorProfileName + " color profile was not declared"); pe.setPropertyInfo(pInfo); throw pe; } float red = 0; float green = 0; float blue = 0; red = args[0].getNumber().floatValue(); green = args[1].getNumber().floatValue(); blue = args[2].getNumber().floatValue(); /* Verify rgb replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("sRGB color values out of range. " + "Arguments to rgb-named-color() must be [0..255] or [0%..100%]"); } // rgb-named-color is replaced with fop-rgb-named-color which has an extra argument // containing the color profile src attribute as it is defined in the color-profile // declarations element. StringBuffer sb = new StringBuffer(); sb.append("fop-rgb-named-color("); sb.append(red / 255f); sb.append(',').append(green / 255f); sb.append(',').append(blue / 255f); sb.append(',').append(colorProfileName); sb.append(',').append(cp.getSrc()); sb.append(", '").append(colorName).append('\''); sb.append(")"); return ColorProperty.getInstance(pInfo.getUserAgent(), sb.toString()); }
// in src/java/org/apache/fop/fo/expr/RGBNamedColorFunction.java
public int getBaseLength(PercentBaseContext context) throws PropertyException { return 0; }
// in src/java/org/apache/fop/fo/expr/CeilingFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number dbl = args[0].getNumber(); if (dbl == null) { throw new PropertyException("Non number operand to ceiling function"); } return NumberProperty.getInstance(Math.ceil(dbl.doubleValue())); }
// in src/java/org/apache/fop/fo/expr/ProportionalColumnWidthFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number d = args[0].getNumber(); if (d == null) { throw new PropertyException("Non numeric operand to " + "proportional-column-width() function."); } PropertyList pList = pInfo.getPropertyList(); if (!"fo:table-column".equals(pList.getFObj().getName())) { throw new PropertyException("proportional-column-width() function " + "may only be used on fo:table-column."); } Table t = (Table) pList.getParentFObj(); if (t.isAutoLayout()) { throw new PropertyException("proportional-column-width() function " + "may only be used when fo:table has " + "table-layout=\"fixed\"."); } return new TableColLength(d.doubleValue(), pInfo.getFO()); }
// in src/java/org/apache/fop/fo/expr/ProportionalColumnWidthFunction.java
public int getBaseLength(PercentBaseContext context) throws PropertyException { return 0; }
// in src/java/org/apache/fop/fo/expr/InheritedPropFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { String propName = args[0].getString(); if (propName == null) { throw new PropertyException("Incorrect parameter to inherited-property-value function"); } int propId = FOPropertyMapping.getPropertyId(propName); if (propId < 0) { throw new PropertyException( "Unknown property name used with inherited-property-value function: " + propName); } return pInfo.getPropertyList().getInherited(propId); }
// in src/java/org/apache/fop/fo/flow/table/TableColumn.java
public Property getProperty(int propId) throws PropertyException { return this.pList.get(propId); }
// in src/java/org/apache/fop/fo/flow/table/TableFObj.java
public Property make(PropertyList propertyList) throws PropertyException { FObj fo = propertyList.getFObj(); return NumberProperty.getInstance(((ColumnNumberManagerHolder) fo.getParent()) .getColumnNumberManager().getCurrentColumnNumber()); }
// in src/java/org/apache/fop/fo/flow/table/TableFObj.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { Property p = super.make(propertyList, value, fo); int columnIndex = p.getNumeric().getValue(); int colSpan = propertyList.get(Constants.PR_NUMBER_COLUMNS_SPANNED) .getNumeric().getValue(); // only check whether the column-number is occupied in case it was // specified on a fo:table-cell or fo:table-column int foId = propertyList.getFObj().getNameId(); if (foId == FO_TABLE_COLUMN || foId == FO_TABLE_CELL) { ColumnNumberManagerHolder parent = (ColumnNumberManagerHolder) propertyList.getParentFObj(); ColumnNumberManager columnIndexManager = parent.getColumnNumberManager(); int lastIndex = columnIndex - 1 + colSpan; for (int i = columnIndex; i <= lastIndex; ++i) { if (columnIndexManager.isColumnNumberUsed(i)) { /* if column-number is already in use by another * cell/column => error! */ TableEventProducer eventProducer = TableEventProducer.Provider.get( fo.getUserAgent().getEventBroadcaster()); eventProducer.cellOverlap( this, propertyList.getFObj().getName(), i, propertyList.getFObj().getLocator()); } } } return p; }
// in src/java/org/apache/fop/fo/flow/table/TableFObj.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof EnumProperty) { return EnumNumber.getInstance(p); } Number val = p.getNumber(); if (val != null) { int i = Math.round(val.floatValue()); int foId = propertyList.getFObj().getNameId(); if (i <= 0) { if (foId == FO_TABLE_CELL || foId == FO_TABLE_COLUMN) { ColumnNumberManagerHolder parent = (ColumnNumberManagerHolder) propertyList.getParentFObj(); ColumnNumberManager columnIndexManager = parent.getColumnNumberManager(); i = columnIndexManager.getCurrentColumnNumber(); } else { /* very exceptional case: * negative column-number specified on * a FO that is not a fo:table-cell or fo:table-column */ i = 1; } TableEventProducer eventProducer = TableEventProducer.Provider.get( fo.getUserAgent().getEventBroadcaster()); eventProducer.forceNextColumnNumber(this, propertyList.getFObj().getName(), val, i, propertyList.getFObj().getLocator()); } return NumberProperty.getInstance(i); } return convertPropertyDatatype(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/FOPropertyMapping.java
private void createBorderPaddingBackgroundProperties() { // CSOK: MethodLength PropertyMaker m; BorderWidthPropertyMaker bwm; CorrespondingPropertyMaker corr; // background-attachment m = new EnumProperty.Maker(PR_BACKGROUND_ATTACHMENT); m.setInherited(false); m.addEnum("scroll", getEnumProperty(EN_SCROLL, "SCROLL")); m.addEnum("fixed", getEnumProperty(EN_FIXED, "FIXED")); m.setDefault("scroll"); addPropertyMaker("background-attachment", m); // background-color m = new ColorProperty.Maker(PR_BACKGROUND_COLOR) { protected Property convertPropertyDatatype( Property p, PropertyList propertyList, FObj fo) throws PropertyException { String nameval = p.getNCname(); if (nameval != null) { FObj fobj = (fo == null ? propertyList.getFObj() : fo); FOUserAgent ua = (fobj == null ? null : fobj.getUserAgent()); return ColorProperty.getInstance(ua, nameval); } return super.convertPropertyDatatype(p, propertyList, fo); } }; m.useGeneric(genericColor); m.setInherited(false); m.setDefault("transparent"); addPropertyMaker("background-color", m); // background-image m = new StringProperty.Maker(PR_BACKGROUND_IMAGE); m.setInherited(false); m.setDefault("none"); addPropertyMaker("background-image", m); // background-repeat m = new EnumProperty.Maker(PR_BACKGROUND_REPEAT); m.setInherited(false); m.addEnum("repeat", getEnumProperty(EN_REPEAT, "REPEAT")); m.addEnum("repeat-x", getEnumProperty(EN_REPEATX, "REPEATX")); m.addEnum("repeat-y", getEnumProperty(EN_REPEATY, "REPEATY")); m.addEnum("no-repeat", getEnumProperty(EN_NOREPEAT, "NOREPEAT")); m.setDefault("repeat"); addPropertyMaker("background-repeat", m); // background-position-horizontal m = new LengthProperty.Maker(PR_BACKGROUND_POSITION_HORIZONTAL); m.setInherited(false); m.setDefault("0pt"); m.addKeyword("left", "0pt"); m.addKeyword("center", "50%"); m.addKeyword("right", "100%"); m.setPercentBase(LengthBase.IMAGE_BACKGROUND_POSITION_HORIZONTAL); m.addShorthand(generics[PR_BACKGROUND_POSITION]); addPropertyMaker("background-position-horizontal", m); // background-position-vertical m = new LengthProperty.Maker(PR_BACKGROUND_POSITION_VERTICAL); m.setInherited(false); m.setDefault("0pt"); m.addKeyword("top", "0pt"); m.addKeyword("center", "50%"); m.addKeyword("bottom", "100%"); m.setPercentBase(LengthBase.IMAGE_BACKGROUND_POSITION_VERTICAL); m.addShorthand(generics[PR_BACKGROUND_POSITION]); addPropertyMaker("background-position-vertical", m); // border-before-color m = new ColorProperty.Maker(PR_BORDER_BEFORE_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_TOP_COLOR, PR_BORDER_TOP_COLOR, PR_BORDER_RIGHT_COLOR, PR_BORDER_LEFT_COLOR); corr.setRelative(true); addPropertyMaker("border-before-color", m); // border-before-style m = new EnumProperty.Maker(PR_BORDER_BEFORE_STYLE); m.useGeneric(genericBorderStyle); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_TOP_STYLE, PR_BORDER_TOP_STYLE, PR_BORDER_RIGHT_STYLE, PR_BORDER_LEFT_STYLE); corr.setRelative(true); addPropertyMaker("border-before-style", m); // border-before-width m = new CondLengthProperty.Maker(PR_BORDER_BEFORE_WIDTH); m.useGeneric(genericCondBorderWidth); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_TOP_WIDTH, PR_BORDER_TOP_WIDTH, PR_BORDER_RIGHT_WIDTH, PR_BORDER_LEFT_WIDTH); corr.setRelative(true); addPropertyMaker("border-before-width", m); // border-after-color m = new ColorProperty.Maker(PR_BORDER_AFTER_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_BOTTOM_COLOR, PR_BORDER_BOTTOM_COLOR, PR_BORDER_LEFT_COLOR, PR_BORDER_RIGHT_COLOR); corr.setRelative(true); addPropertyMaker("border-after-color", m); // border-after-style m = new EnumProperty.Maker(PR_BORDER_AFTER_STYLE); m.useGeneric(genericBorderStyle); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_BOTTOM_STYLE, PR_BORDER_BOTTOM_STYLE, PR_BORDER_LEFT_STYLE, PR_BORDER_RIGHT_STYLE); corr.setRelative(true); addPropertyMaker("border-after-style", m); // border-after-width m = new CondLengthProperty.Maker(PR_BORDER_AFTER_WIDTH); m.useGeneric(genericCondBorderWidth); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_BOTTOM_WIDTH, PR_BORDER_BOTTOM_WIDTH, PR_BORDER_LEFT_WIDTH, PR_BORDER_LEFT_WIDTH); corr.setRelative(true); addPropertyMaker("border-after-width", m); // border-start-color m = new ColorProperty.Maker(PR_BORDER_START_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_LEFT_COLOR, PR_BORDER_RIGHT_COLOR, PR_BORDER_TOP_COLOR, PR_BORDER_TOP_COLOR); corr.setRelative(true); addPropertyMaker("border-start-color", m); // border-start-style m = new EnumProperty.Maker(PR_BORDER_START_STYLE); m.useGeneric(genericBorderStyle); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_LEFT_STYLE, PR_BORDER_RIGHT_STYLE, PR_BORDER_TOP_STYLE, PR_BORDER_TOP_STYLE); corr.setRelative(true); addPropertyMaker("border-start-style", m); // border-start-width m = new CondLengthProperty.Maker(PR_BORDER_START_WIDTH); m.useGeneric(genericCondBorderWidth); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_LEFT_WIDTH, PR_BORDER_RIGHT_WIDTH, PR_BORDER_TOP_WIDTH, PR_BORDER_TOP_WIDTH); corr.setRelative(true); addPropertyMaker("border-start-width", m); // border-end-color m = new ColorProperty.Maker(PR_BORDER_END_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_RIGHT_COLOR, PR_BORDER_LEFT_COLOR, PR_BORDER_BOTTOM_COLOR, PR_BORDER_BOTTOM_COLOR); corr.setRelative(true); addPropertyMaker("border-end-color", m); // border-end-style m = new EnumProperty.Maker(PR_BORDER_END_STYLE); m.useGeneric(genericBorderStyle); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_RIGHT_STYLE, PR_BORDER_LEFT_STYLE, PR_BORDER_BOTTOM_STYLE, PR_BORDER_BOTTOM_STYLE); corr.setRelative(true); addPropertyMaker("border-end-style", m); // border-end-width m = new CondLengthProperty.Maker(PR_BORDER_END_WIDTH); m.useGeneric(genericCondBorderWidth); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_RIGHT_WIDTH, PR_BORDER_LEFT_WIDTH, PR_BORDER_BOTTOM_WIDTH, PR_BORDER_BOTTOM_WIDTH); corr.setRelative(true); addPropertyMaker("border-end-width", m); // border-top-color m = new ColorProperty.Maker(PR_BORDER_TOP_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); m.addShorthand(generics[PR_BORDER_TOP]); m.addShorthand(generics[PR_BORDER_COLOR]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_BEFORE_COLOR, PR_BORDER_BEFORE_COLOR, PR_BORDER_START_COLOR, PR_BORDER_START_COLOR); addPropertyMaker("border-top-color", m); // border-top-style m = new EnumProperty.Maker(PR_BORDER_TOP_STYLE); m.useGeneric(genericBorderStyle); m.addShorthand(generics[PR_BORDER_TOP]); m.addShorthand(generics[PR_BORDER_STYLE]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_BEFORE_STYLE, PR_BORDER_BEFORE_STYLE, PR_BORDER_START_STYLE, PR_BORDER_START_STYLE); addPropertyMaker("border-top-style", m); // border-top-width bwm = new BorderWidthPropertyMaker(PR_BORDER_TOP_WIDTH); bwm.useGeneric(genericBorderWidth); bwm.setBorderStyleId(PR_BORDER_TOP_STYLE); bwm.addShorthand(generics[PR_BORDER_TOP]); bwm.addShorthand(generics[PR_BORDER_WIDTH]); bwm.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(bwm); corr.setCorresponding(PR_BORDER_BEFORE_WIDTH, PR_BORDER_BEFORE_WIDTH, PR_BORDER_START_WIDTH, PR_BORDER_START_WIDTH); addPropertyMaker("border-top-width", bwm); // border-bottom-color m = new ColorProperty.Maker(PR_BORDER_BOTTOM_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); m.addShorthand(generics[PR_BORDER_BOTTOM]); m.addShorthand(generics[PR_BORDER_COLOR]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_AFTER_COLOR, PR_BORDER_AFTER_COLOR, PR_BORDER_END_COLOR, PR_BORDER_END_COLOR); addPropertyMaker("border-bottom-color", m); // border-bottom-style m = new EnumProperty.Maker(PR_BORDER_BOTTOM_STYLE); m.useGeneric(genericBorderStyle); m.addShorthand(generics[PR_BORDER_BOTTOM]); m.addShorthand(generics[PR_BORDER_STYLE]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_AFTER_STYLE, PR_BORDER_AFTER_STYLE, PR_BORDER_END_STYLE, PR_BORDER_END_STYLE); addPropertyMaker("border-bottom-style", m); // border-bottom-width bwm = new BorderWidthPropertyMaker(PR_BORDER_BOTTOM_WIDTH); bwm.useGeneric(genericBorderWidth); bwm.setBorderStyleId(PR_BORDER_BOTTOM_STYLE); bwm.addShorthand(generics[PR_BORDER_BOTTOM]); bwm.addShorthand(generics[PR_BORDER_WIDTH]); bwm.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(bwm); corr.setCorresponding(PR_BORDER_AFTER_WIDTH, PR_BORDER_AFTER_WIDTH, PR_BORDER_END_WIDTH, PR_BORDER_END_WIDTH); addPropertyMaker("border-bottom-width", bwm); // border-left-color m = new ColorProperty.Maker(PR_BORDER_LEFT_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); m.addShorthand(generics[PR_BORDER_LEFT]); m.addShorthand(generics[PR_BORDER_COLOR]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_START_COLOR, PR_BORDER_END_COLOR, PR_BORDER_AFTER_COLOR, PR_BORDER_BEFORE_COLOR); addPropertyMaker("border-left-color", m); // border-left-style m = new EnumProperty.Maker(PR_BORDER_LEFT_STYLE); m.useGeneric(genericBorderStyle); m.addShorthand(generics[PR_BORDER_LEFT]); m.addShorthand(generics[PR_BORDER_STYLE]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_START_STYLE, PR_BORDER_END_STYLE, PR_BORDER_AFTER_STYLE, PR_BORDER_BEFORE_STYLE); addPropertyMaker("border-left-style", m); // border-left-width bwm = new BorderWidthPropertyMaker(PR_BORDER_LEFT_WIDTH); bwm.useGeneric(genericBorderWidth); bwm.setBorderStyleId(PR_BORDER_LEFT_STYLE); bwm.addShorthand(generics[PR_BORDER_LEFT]); bwm.addShorthand(generics[PR_BORDER_WIDTH]); bwm.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(bwm); corr.setCorresponding(PR_BORDER_START_WIDTH, PR_BORDER_END_WIDTH, PR_BORDER_AFTER_WIDTH, PR_BORDER_BEFORE_WIDTH); addPropertyMaker("border-left-width", bwm); // border-right-color m = new ColorProperty.Maker(PR_BORDER_RIGHT_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); m.addShorthand(generics[PR_BORDER_RIGHT]); m.addShorthand(generics[PR_BORDER_COLOR]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_END_COLOR, PR_BORDER_START_COLOR, PR_BORDER_BEFORE_COLOR, PR_BORDER_AFTER_COLOR); addPropertyMaker("border-right-color", m); // border-right-style m = new EnumProperty.Maker(PR_BORDER_RIGHT_STYLE); m.useGeneric(genericBorderStyle); m.addShorthand(generics[PR_BORDER_RIGHT]); m.addShorthand(generics[PR_BORDER_STYLE]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_END_STYLE, PR_BORDER_START_STYLE, PR_BORDER_BEFORE_STYLE, PR_BORDER_AFTER_STYLE); addPropertyMaker("border-right-style", m); // border-right-width bwm = new BorderWidthPropertyMaker(PR_BORDER_RIGHT_WIDTH); bwm.useGeneric(genericBorderWidth); bwm.setBorderStyleId(PR_BORDER_RIGHT_STYLE); bwm.addShorthand(generics[PR_BORDER_RIGHT]); bwm.addShorthand(generics[PR_BORDER_WIDTH]); bwm.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(bwm); corr.setCorresponding(PR_BORDER_END_WIDTH, PR_BORDER_START_WIDTH, PR_BORDER_BEFORE_WIDTH, PR_BORDER_AFTER_WIDTH); addPropertyMaker("border-right-width", bwm); // padding-before m = new CondLengthProperty.Maker(PR_PADDING_BEFORE); m.useGeneric(genericCondPadding); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_TOP, PR_PADDING_TOP, PR_PADDING_RIGHT, PR_PADDING_LEFT); corr.setRelative(true); addPropertyMaker("padding-before", m); // padding-after m = new CondLengthProperty.Maker(PR_PADDING_AFTER); m.useGeneric(genericCondPadding); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_BOTTOM, PR_PADDING_BOTTOM, PR_PADDING_LEFT, PR_PADDING_RIGHT); corr.setRelative(true); addPropertyMaker("padding-after", m); // padding-start m = new CondLengthProperty.Maker(PR_PADDING_START); m.useGeneric(genericCondPadding); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_LEFT, PR_PADDING_RIGHT, PR_PADDING_TOP, PR_PADDING_TOP); corr.setRelative(true); addPropertyMaker("padding-start", m); // padding-end m = new CondLengthProperty.Maker(PR_PADDING_END); m.useGeneric(genericCondPadding); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_RIGHT, PR_PADDING_LEFT, PR_PADDING_BOTTOM, PR_PADDING_BOTTOM); corr.setRelative(true); addPropertyMaker("padding-end", m); // padding-top m = new LengthProperty.Maker(PR_PADDING_TOP); m.useGeneric(genericPadding); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_BEFORE, PR_PADDING_BEFORE, PR_PADDING_START, PR_PADDING_START); addPropertyMaker("padding-top", m); // padding-bottom m = new LengthProperty.Maker(PR_PADDING_BOTTOM); m.useGeneric(genericPadding); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_AFTER, PR_PADDING_AFTER, PR_PADDING_END, PR_PADDING_END); addPropertyMaker("padding-bottom", m); // padding-left m = new LengthProperty.Maker(PR_PADDING_LEFT); m.useGeneric(genericPadding); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_START, PR_PADDING_END, PR_PADDING_AFTER, PR_PADDING_BEFORE); addPropertyMaker("padding-left", m); // padding-right m = new LengthProperty.Maker(PR_PADDING_RIGHT); m.useGeneric(genericPadding); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_END, PR_PADDING_START, PR_PADDING_BEFORE, PR_PADDING_AFTER); addPropertyMaker("padding-right", m); }
// in src/java/org/apache/fop/fo/FOPropertyMapping.java
protected Property convertPropertyDatatype( Property p, PropertyList propertyList, FObj fo) throws PropertyException { String nameval = p.getNCname(); if (nameval != null) { FObj fobj = (fo == null ? propertyList.getFObj() : fo); FOUserAgent ua = (fobj == null ? null : fobj.getUserAgent()); return ColorProperty.getInstance(ua, nameval); } return super.convertPropertyDatatype(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/FOPropertyMapping.java
private void createBlockAndLineProperties() { // CSOK: MethodLength PropertyMaker m; // hyphenation-keep m = new EnumProperty.Maker(PR_HYPHENATION_KEEP); m.setInherited(true); m.addEnum("auto", getEnumProperty(EN_AUTO, "AUTO")); m.addEnum("column", getEnumProperty(EN_COLUMN, "COLUMN")); m.addEnum("page", getEnumProperty(EN_PAGE, "PAGE")); m.setDefault("auto"); addPropertyMaker("hyphenation-keep", m); // hyphenation-ladder-count m = new NumberProperty.Maker(PR_HYPHENATION_LADDER_COUNT); m.setInherited(true); m.addEnum("no-limit", getEnumProperty(EN_NO_LIMIT, "NO_LIMIT")); m.setDefault("no-limit"); addPropertyMaker("hyphenation-ladder-count", m); // last-line-end-indent m = new LengthProperty.Maker(PR_LAST_LINE_END_INDENT); m.setInherited(true); m.setDefault("0pt"); m.setPercentBase(LengthBase.CONTAINING_BLOCK_WIDTH); addPropertyMaker("last-line-end-indent", m); // line-height m = new LineHeightPropertyMaker(PR_LINE_HEIGHT); m.useGeneric(genericSpace); m.setInherited(true); m.addKeyword("normal", "1.2"); m.setPercentBase(LengthBase.FONTSIZE); m.setDefault("normal", true); m.addShorthand(generics[PR_FONT]); addPropertyMaker("line-height", m); // line-height-shift-adjustment m = new EnumProperty.Maker(PR_LINE_HEIGHT_SHIFT_ADJUSTMENT); m.setInherited(true); m.addEnum("consider-shifts", getEnumProperty(EN_CONSIDER_SHIFTS, "CONSIDER_SHIFTS")); m.addEnum("disregard-shifts", getEnumProperty(EN_DISREGARD_SHIFTS, "DISREGARD_SHIFTS")); m.setDefault("consider-shifts"); addPropertyMaker("line-height-shift-adjustment", m); // line-stacking-strategy m = new EnumProperty.Maker(PR_LINE_STACKING_STRATEGY); m.setInherited(true); m.addEnum("line-height", getEnumProperty(EN_LINE_HEIGHT, "LINE_HEIGHT")); m.addEnum("font-height", getEnumProperty(EN_FONT_HEIGHT, "FONT_HEIGHT")); m.addEnum("max-height", getEnumProperty(EN_MAX_HEIGHT, "MAX_HEIGHT")); m.setDefault("max-height"); addPropertyMaker("line-stacking-strategy", m); // linefeed-treatment m = new EnumProperty.Maker(PR_LINEFEED_TREATMENT); m.setInherited(true); m.addEnum("ignore", getEnumProperty(EN_IGNORE, "IGNORE")); m.addEnum("preserve", getEnumProperty(EN_PRESERVE, "PRESERVE")); m.addEnum("treat-as-space", getEnumProperty(EN_TREAT_AS_SPACE, "TREAT_AS_SPACE")); m.addEnum("treat-as-zero-width-space", getEnumProperty(EN_TREAT_AS_ZERO_WIDTH_SPACE, "TREAT_AS_ZERO_WIDTH_SPACE")); m.setDefault("treat-as-space"); m.addShorthand(generics[PR_WHITE_SPACE]); addPropertyMaker("linefeed-treatment", m); // white-space-treatment m = new EnumProperty.Maker(PR_WHITE_SPACE_TREATMENT); m.setInherited(true); m.addEnum("ignore", getEnumProperty(EN_IGNORE, "IGNORE")); m.addEnum("preserve", getEnumProperty(EN_PRESERVE, "PRESERVE")); m.addEnum("ignore-if-before-linefeed", getEnumProperty(EN_IGNORE_IF_BEFORE_LINEFEED, "IGNORE_IF_BEFORE_LINEFEED")); m.addEnum("ignore-if-after-linefeed", getEnumProperty(EN_IGNORE_IF_AFTER_LINEFEED, "IGNORE_IF_AFTER_LINEFEED")); m.addEnum("ignore-if-surrounding-linefeed", getEnumProperty(EN_IGNORE_IF_SURROUNDING_LINEFEED, "IGNORE_IF_SURROUNDING_LINEFEED")); m.setDefault("ignore-if-surrounding-linefeed"); m.addShorthand(generics[PR_WHITE_SPACE]); addPropertyMaker("white-space-treatment", m); // text-align TODO: make it a StringProperty with enums. m = new EnumProperty.Maker(PR_TEXT_ALIGN) { public Property get(int subpropId, PropertyList propertyList, boolean bTryInherit, boolean bTryDefault) throws PropertyException { Property p = super.get(subpropId, propertyList, bTryInherit, bTryDefault); if ( p != null ) { int pv = p.getEnum(); if ( ( pv == EN_LEFT ) || ( pv == EN_RIGHT ) ) { p = calcWritingModeDependent ( pv, propertyList.get(Constants.PR_WRITING_MODE).getEnum() ); } } return p; } }; m.setInherited(true); m.addEnum("center", getEnumProperty(EN_CENTER, "CENTER")); m.addEnum("end", getEnumProperty(EN_END, "END")); m.addEnum("start", getEnumProperty(EN_START, "START")); m.addEnum("justify", getEnumProperty(EN_JUSTIFY, "JUSTIFY")); // [GA] must defer writing-mode relative mapping of left/right m.addEnum("left", getEnumProperty(EN_LEFT, "LEFT")); m.addEnum("right", getEnumProperty(EN_RIGHT, "RIGHT")); // [GA] inside and outside are not correctly implemented by the following mapping m.addEnum("inside", getEnumProperty(EN_START, "START")); m.addEnum("outside", getEnumProperty(EN_END, "END")); m.setDefault("start"); addPropertyMaker("text-align", m); // text-align-last m = new EnumProperty.Maker(PR_TEXT_ALIGN_LAST) { public Property get(int subpropId, PropertyList propertyList, boolean bTryInherit, boolean bTryDefault) throws PropertyException { Property p = super.get(subpropId, propertyList, bTryInherit, bTryDefault); if (p != null && p.getEnum() == EN_RELATIVE) { //The default may have been returned, so check inherited value p = propertyList.getNearestSpecified(PR_TEXT_ALIGN_LAST); if (p.getEnum() == EN_RELATIVE) { return calcRelative(propertyList); } } return p; } private Property calcRelative(PropertyList propertyList) throws PropertyException { Property corresponding = propertyList.get(PR_TEXT_ALIGN); if (corresponding == null) { return null; } int correspondingValue = corresponding.getEnum(); if (correspondingValue == EN_JUSTIFY) { return getEnumProperty(EN_START, "START"); } else if (correspondingValue == EN_END) { return getEnumProperty(EN_END, "END"); } else if (correspondingValue == EN_START) { return getEnumProperty(EN_START, "START"); } else if (correspondingValue == EN_CENTER) { return getEnumProperty(EN_CENTER, "CENTER"); } else if (correspondingValue == EN_LEFT) { return calcWritingModeDependent ( EN_LEFT, propertyList.get(Constants.PR_WRITING_MODE).getEnum() ); } else if (correspondingValue == EN_RIGHT) { return calcWritingModeDependent ( EN_RIGHT, propertyList.get(Constants.PR_WRITING_MODE).getEnum() ); } else { return null; } } }; m.setInherited(false); //Actually it's "true" but the special PropertyMaker compensates // Note: both 'end', 'right' and 'outside' are mapped to END // both 'start', 'left' and 'inside' are mapped to START m.addEnum("relative", getEnumProperty(EN_RELATIVE, "RELATIVE")); m.addEnum("center", getEnumProperty(EN_CENTER, "CENTER")); m.addEnum("end", getEnumProperty(EN_END, "END")); m.addEnum("right", getEnumProperty(EN_END, "END")); m.addEnum("start", getEnumProperty(EN_START, "START")); m.addEnum("left", getEnumProperty(EN_START, "START")); m.addEnum("justify", getEnumProperty(EN_JUSTIFY, "JUSTIFY")); m.addEnum("inside", getEnumProperty(EN_START, "START")); m.addEnum("outside", getEnumProperty(EN_END, "END")); m.setDefault("relative", true); addPropertyMaker("text-align-last", m); // text-indent m = new LengthProperty.Maker(PR_TEXT_INDENT); m.setInherited(true); m.setDefault("0pt"); m.setPercentBase(LengthBase.CONTAINING_BLOCK_WIDTH); addPropertyMaker("text-indent", m); // white-space-collapse m = new EnumProperty.Maker(PR_WHITE_SPACE_COLLAPSE); m.useGeneric(genericBoolean); m.setInherited(true); m.setDefault("true"); m.addShorthand(generics[PR_WHITE_SPACE]); addPropertyMaker("white-space-collapse", m); // wrap-option m = new EnumProperty.Maker(PR_WRAP_OPTION); m.setInherited(true); m.addEnum("wrap", getEnumProperty(EN_WRAP, "WRAP")); m.addEnum("no-wrap", getEnumProperty(EN_NO_WRAP, "NO_WRAP")); m.setDefault("wrap"); m.addShorthand(generics[PR_WHITE_SPACE]); addPropertyMaker("wrap-option", m); }
// in src/java/org/apache/fop/fo/FOPropertyMapping.java
public Property get(int subpropId, PropertyList propertyList, boolean bTryInherit, boolean bTryDefault) throws PropertyException { Property p = super.get(subpropId, propertyList, bTryInherit, bTryDefault); if ( p != null ) { int pv = p.getEnum(); if ( ( pv == EN_LEFT ) || ( pv == EN_RIGHT ) ) { p = calcWritingModeDependent ( pv, propertyList.get(Constants.PR_WRITING_MODE).getEnum() ); } } return p; }
// in src/java/org/apache/fop/fo/FOPropertyMapping.java
public Property get(int subpropId, PropertyList propertyList, boolean bTryInherit, boolean bTryDefault) throws PropertyException { Property p = super.get(subpropId, propertyList, bTryInherit, bTryDefault); if (p != null && p.getEnum() == EN_RELATIVE) { //The default may have been returned, so check inherited value p = propertyList.getNearestSpecified(PR_TEXT_ALIGN_LAST); if (p.getEnum() == EN_RELATIVE) { return calcRelative(propertyList); } } return p; }
// in src/java/org/apache/fop/fo/FOPropertyMapping.java
private Property calcRelative(PropertyList propertyList) throws PropertyException { Property corresponding = propertyList.get(PR_TEXT_ALIGN); if (corresponding == null) { return null; } int correspondingValue = corresponding.getEnum(); if (correspondingValue == EN_JUSTIFY) { return getEnumProperty(EN_START, "START"); } else if (correspondingValue == EN_END) { return getEnumProperty(EN_END, "END"); } else if (correspondingValue == EN_START) { return getEnumProperty(EN_START, "START"); } else if (correspondingValue == EN_CENTER) { return getEnumProperty(EN_CENTER, "CENTER"); } else if (correspondingValue == EN_LEFT) { return calcWritingModeDependent ( EN_LEFT, propertyList.get(Constants.PR_WRITING_MODE).getEnum() ); } else if (correspondingValue == EN_RIGHT) { return calcWritingModeDependent ( EN_RIGHT, propertyList.get(Constants.PR_WRITING_MODE).getEnum() ); } else { return null; } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
private Color getAttributeAsColor(Attributes attributes, String name) throws PropertyException { String s = attributes.getValue(name); if (s == null) { return null; } else { return ColorUtil.parseColorString(userAgent, s); } }
// in src/java/org/apache/fop/datatypes/LengthBase.java
public int getBaseLength(PercentBaseContext context) throws PropertyException { int baseLen = 0; if (context != null) { if (baseType == FONTSIZE || baseType == INH_FONTSIZE) { return baseLength.getValue(context); } baseLen = context.getBaseLength(baseType, fobj); } else { log.error("getBaseLength called without context"); } return baseLen; }
// in src/java/org/apache/fop/util/ColorUtil.java
public static Color parseColorString(FOUserAgent foUserAgent, String value) throws PropertyException { if (value == null) { return null; } Color parsedColor = colorMap.get(value.toLowerCase()); if (parsedColor == null) { if (value.startsWith("#")) { parsedColor = parseWithHash(value); } else if (value.startsWith("rgb(")) { parsedColor = parseAsRGB(value); } else if (value.startsWith("url(")) { throw new PropertyException( "Colors starting with url( are not yet supported!"); } else if (value.startsWith("java.awt.Color")) { parsedColor = parseAsJavaAWTColor(value); } else if (value.startsWith("system-color(")) { parsedColor = parseAsSystemColor(value); } else if (value.startsWith("fop-rgb-icc")) { parsedColor = parseAsFopRgbIcc(foUserAgent, value); } else if (value.startsWith("fop-rgb-named-color")) { parsedColor = parseAsFopRgbNamedColor(foUserAgent, value); } else if (value.startsWith("cie-lab-color")) { parsedColor = parseAsCIELabColor(foUserAgent, value); } else if (value.startsWith("cmyk")) { parsedColor = parseAsCMYK(value); } if (parsedColor == null) { throw new PropertyException("Unknown Color: " + value); } colorMap.put(value, parsedColor); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsSystemColor(String value) throws PropertyException { int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); } else { throw new PropertyException("Unknown color format: " + value + ". Must be system-color(x)"); } return colorMap.get(value); }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsJavaAWTColor(String value) throws PropertyException { float red = 0.0f; float green = 0.0f; float blue = 0.0f; int poss = value.indexOf("["); int pose = value.indexOf("]"); try { if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); String[] args = value.split(","); if (args.length != 3) { throw new PropertyException( "Invalid number of arguments for a java.awt.Color: " + value); } red = Float.parseFloat(args[0].trim().substring(2)) / 255f; green = Float.parseFloat(args[1].trim().substring(2)) / 255f; blue = Float.parseFloat(args[2].trim().substring(2)) / 255f; if ((red < 0.0 || red > 1.0) || (green < 0.0 || green > 1.0) || (blue < 0.0 || blue > 1.0)) { throw new PropertyException("Color values out of range"); } } else { throw new IllegalArgumentException( "Invalid format for a java.awt.Color: " + value); } } catch (RuntimeException re) { throw new PropertyException(re); } return new Color(red, green, blue); }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsRGB(String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); try { String[] args = value.split(","); if (args.length != 3) { throw new PropertyException( "Invalid number of arguments: rgb(" + value + ")"); } float red = parseComponent255(args[0], value); float green = parseComponent255(args[1], value); float blue = parseComponent255(args[2], value); //Convert to ints to synchronize the behaviour with toRGBFunctionCall() int r = (int)(red * 255 + 0.5); int g = (int)(green * 255 + 0.5); int b = (int)(blue * 255 + 0.5); parsedColor = new Color(r, g, b); } catch (RuntimeException re) { //wrap in a PropertyException throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be rgb(r,g,b)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static float parseComponent255(String str, String function) throws PropertyException { float component; str = str.trim(); if (str.endsWith("%")) { component = Float.parseFloat(str.substring(0, str.length() - 1)) / 100f; } else { component = Float.parseFloat(str) / 255f; } if ((component < 0.0 || component > 1.0)) { throw new PropertyException("Color value out of range for " + function + ": " + str + ". Valid range: [0..255] or [0%..100%]"); } return component; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static float parseComponent1(String argument, String function) throws PropertyException { return parseComponent(argument, 0f, 1f, function); }
// in src/java/org/apache/fop/util/ColorUtil.java
private static float parseComponent(String argument, float min, float max, String function) throws PropertyException { float component = Float.parseFloat(argument.trim()); if ((component < min || component > max)) { throw new PropertyException("Color value out of range for " + function + ": " + argument + ". Valid range: [" + min + ".." + max + "]"); } return component; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseFallback(String[] args, String value) throws PropertyException { float red = parseComponent1(args[0], value); float green = parseComponent1(args[1], value); float blue = parseComponent1(args[2], value); //Sun's classlib rounds differently with this constructor than when converting to sRGB //via CIE XYZ. Color sRGB = new Color(red, green, blue); return sRGB; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseWithHash(String value) throws PropertyException { Color parsedColor; try { int len = value.length(); int alpha; if (len == 5 || len == 9) { alpha = Integer.parseInt( value.substring((len == 5) ? 3 : 7), 16); } else { alpha = 0xFF; } int red = 0; int green = 0; int blue = 0; if ((len == 4) || (len == 5)) { //multiply by 0x11 = 17 = 255/15 red = Integer.parseInt(value.substring(1, 2), 16) * 0x11; green = Integer.parseInt(value.substring(2, 3), 16) * 0x11; blue = Integer.parseInt(value.substring(3, 4), 16) * 0X11; } else if ((len == 7) || (len == 9)) { red = Integer.parseInt(value.substring(1, 3), 16); green = Integer.parseInt(value.substring(3, 5), 16); blue = Integer.parseInt(value.substring(5, 7), 16); } else { throw new NumberFormatException(); } parsedColor = new Color(red, green, blue, alpha); } catch (RuntimeException re) { throw new PropertyException("Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsFopRgbIcc(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { String[] args = value.substring(poss + 1, pose).split(","); try { if (args.length < 5) { throw new PropertyException("Too few arguments for rgb-icc() function"); } //Set up fallback sRGB value Color sRGB = parseFallback(args, value); /* Get and verify ICC profile name */ String iccProfileName = args[3].trim(); if (iccProfileName == null || "".equals(iccProfileName)) { throw new PropertyException("ICC profile name missing"); } ColorSpace colorSpace = null; String iccProfileSrc = null; if (isPseudoProfile(iccProfileName)) { if (CMYK_PSEUDO_PROFILE.equalsIgnoreCase(iccProfileName)) { colorSpace = ColorSpaces.getDeviceCMYKColorSpace(); } else if (SEPARATION_PSEUDO_PROFILE.equalsIgnoreCase(iccProfileName)) { colorSpace = new NamedColorSpace(args[5], sRGB, SEPARATION_PSEUDO_PROFILE, null); } else { assert false : "Incomplete implementation"; } } else { /* Get and verify ICC profile source */ iccProfileSrc = args[4].trim(); if (iccProfileSrc == null || "".equals(iccProfileSrc)) { throw new PropertyException("ICC profile source missing"); } iccProfileSrc = unescapeString(iccProfileSrc); } /* ICC profile arguments */ int componentStart = 4; if (colorSpace instanceof NamedColorSpace) { componentStart++; } float[] iccComponents = new float[args.length - componentStart - 1]; for (int ix = componentStart; ++ix < args.length;) { iccComponents[ix - componentStart - 1] = Float.parseFloat(args[ix].trim()); } if (colorSpace instanceof NamedColorSpace && iccComponents.length == 0) { iccComponents = new float[] {1.0f}; //full tint if not specified } /* Ask FOP factory to get ColorSpace for the specified ICC profile source */ if (foUserAgent != null && iccProfileSrc != null) { RenderingIntent renderingIntent = RenderingIntent.AUTO; //TODO connect to fo:color-profile/@rendering-intent colorSpace = foUserAgent.getFactory().getColorSpaceCache().get( iccProfileName, foUserAgent.getBaseURL(), iccProfileSrc, renderingIntent); } if (colorSpace != null) { // ColorSpace is available if (ColorSpaces.isDeviceColorSpace(colorSpace)) { //Device-specific colors are handled differently: //sRGB is the primary color with the CMYK as the alternative Color deviceColor = new Color(colorSpace, iccComponents, 1.0f); float[] rgbComps = sRGB.getRGBColorComponents(null); parsedColor = new ColorWithAlternatives( rgbComps[0], rgbComps[1], rgbComps[2], new Color[] {deviceColor}); } else { parsedColor = new ColorWithFallback( colorSpace, iccComponents, 1.0f, null, sRGB); } } else { // ICC profile could not be loaded - use rgb replacement values */ log.warn("Color profile '" + iccProfileSrc + "' not found. Using sRGB replacement values."); parsedColor = sRGB; } } catch (RuntimeException re) { throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be fop-rgb-icc(r,g,b,NCNAME,src,....)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsFopRgbNamedColor(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { String[] args = value.substring(poss + 1, pose).split(","); try { if (args.length != 6) { throw new PropertyException("rgb-named-color() function must have 6 arguments"); } //Set up fallback sRGB value Color sRGB = parseFallback(args, value); /* Get and verify ICC profile name */ String iccProfileName = args[3].trim(); if (iccProfileName == null || "".equals(iccProfileName)) { throw new PropertyException("ICC profile name missing"); } ICC_ColorSpace colorSpace = null; String iccProfileSrc; if (isPseudoProfile(iccProfileName)) { throw new IllegalArgumentException( "Pseudo-profiles are not allowed with fop-rgb-named-color()"); } else { /* Get and verify ICC profile source */ iccProfileSrc = args[4].trim(); if (iccProfileSrc == null || "".equals(iccProfileSrc)) { throw new PropertyException("ICC profile source missing"); } iccProfileSrc = unescapeString(iccProfileSrc); } // color name String colorName = unescapeString(args[5].trim()); /* Ask FOP factory to get ColorSpace for the specified ICC profile source */ if (foUserAgent != null && iccProfileSrc != null) { RenderingIntent renderingIntent = RenderingIntent.AUTO; //TODO connect to fo:color-profile/@rendering-intent colorSpace = (ICC_ColorSpace)foUserAgent.getFactory().getColorSpaceCache().get( iccProfileName, foUserAgent.getBaseURL(), iccProfileSrc, renderingIntent); } if (colorSpace != null) { ICC_Profile profile = colorSpace.getProfile(); if (NamedColorProfileParser.isNamedColorProfile(profile)) { NamedColorProfileParser parser = new NamedColorProfileParser(); NamedColorProfile ncp = parser.parseProfile(profile, iccProfileName, iccProfileSrc); NamedColorSpace ncs = ncp.getNamedColor(colorName); if (ncs != null) { parsedColor = new ColorWithFallback(ncs, new float[] {1.0f}, 1.0f, null, sRGB); } else { log.warn("Color '" + colorName + "' does not exist in named color profile: " + iccProfileSrc); parsedColor = sRGB; } } else { log.warn("ICC profile is no named color profile: " + iccProfileSrc); parsedColor = sRGB; } } else { // ICC profile could not be loaded - use rgb replacement values */ log.warn("Color profile '" + iccProfileSrc + "' not found. Using sRGB replacement values."); parsedColor = sRGB; } } catch (IOException ioe) { //wrap in a PropertyException throw new PropertyException(ioe); } catch (RuntimeException re) { throw new PropertyException(re); //wrap in a PropertyException } } else { throw new PropertyException("Unknown color format: " + value + ". Must be fop-rgb-named-color(r,g,b,NCNAME,src,color-name)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsCIELabColor(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { try { String[] args = value.substring(poss + 1, pose).split(","); if (args.length != 6) { throw new PropertyException("cie-lab-color() function must have 6 arguments"); } //Set up fallback sRGB value float red = parseComponent255(args[0], value); float green = parseComponent255(args[1], value); float blue = parseComponent255(args[2], value); Color sRGB = new Color(red, green, blue); float l = parseComponent(args[3], 0f, 100f, value); float a = parseComponent(args[4], -127f, 127f, value); float b = parseComponent(args[5], -127f, 127f, value); //Assuming the XSL-FO spec uses the D50 white point CIELabColorSpace cs = ColorSpaces.getCIELabColorSpaceD50(); //use toColor() to have components normalized Color labColor = cs.toColor(l, a, b, 1.0f); //Convert to ColorWithFallback parsedColor = new ColorWithFallback(labColor, sRGB); } catch (RuntimeException re) { throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be cie-lab-color(r,g,b,Lightness,a-value,b-value)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsCMYK(String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); String[] args = value.split(","); try { if (args.length != 4) { throw new PropertyException( "Invalid number of arguments: cmyk(" + value + ")"); } float cyan = parseComponent1(args[0], value); float magenta = parseComponent1(args[1], value); float yellow = parseComponent1(args[2], value); float black = parseComponent1(args[3], value); float[] comps = new float[] {cyan, magenta, yellow, black}; Color cmykColor = DeviceCMYKColorSpace.createCMYKColor(comps); float[] rgbComps = cmykColor.getRGBColorComponents(null); parsedColor = new ColorWithAlternatives(rgbComps[0], rgbComps[1], rgbComps[2], new Color[] {cmykColor}); } catch (RuntimeException re) { throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be cmyk(c,m,y,k)"); } return parsedColor; }
(Lib) RuntimeException 85
              
// in src/java/org/apache/fop/apps/FOURIResolver.java
protected void applyHttpBasicAuthentication(URLConnection connection, String username, String password) { String combined = username + ":" + password; try { ByteArrayOutputStream baout = new ByteArrayOutputStream(combined .length() * 2); Base64EncodeStream base64 = new Base64EncodeStream(baout); // TODO Not sure what charset/encoding can be used with basic // authentication base64.write(combined.getBytes("UTF-8")); base64.close(); connection.setRequestProperty("Authorization", "Basic " + new String(baout.toByteArray(), "UTF-8")); } catch (IOException e) { // won't happen. We're operating in-memory. throw new RuntimeException( "Error during base64 encodation of username/password"); } }
// in src/java/org/apache/fop/pdf/PDFStream.java
private void setUp() { try { data = StreamCacheFactory.getInstance().createStreamCache(); this.streamWriter = new OutputStreamWriter( getBufferOutputStream(), PDFDocument.ENCODING); //Buffer to minimize calls to the converter this.streamWriter = new java.io.BufferedWriter(this.streamWriter); } catch (IOException e) { throw new RuntimeException(e); } }
// in src/java/org/apache/fop/pdf/PDFICCBasedColorSpace.java
public static PDFICCStream setupsRGBColorProfile(PDFDocument pdfDoc) { ICC_Profile profile; PDFICCStream sRGBProfile = pdfDoc.getFactory().makePDFICCStream(); InputStream in = PDFDocument.class.getResourceAsStream("sRGB Color Space Profile.icm"); if (in != null) { try { profile = ColorProfileUtil.getICC_Profile(in); } catch (IOException ioe) { throw new RuntimeException( "Unexpected IOException loading the sRGB profile: " + ioe.getMessage()); } finally { IOUtils.closeQuietly(in); } } else { // Fallback: Use the sRGB profile from the JRE (about 140KB) profile = ColorProfileUtil.getICC_Profile(ColorSpace.CS_sRGB); } sRGBProfile.setColorSpace(profile, null); return sRGBProfile; }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
private String determineExtension(String outputFormat) { for (int i = 0; i < EXTENSIONS.length; i++) { if (EXTENSIONS[i][0].equals(outputFormat)) { String ext = EXTENSIONS[i][1]; if (ext == null) { throw new RuntimeException("Output format '" + outputFormat + "' does not produce a file."); } else { return ext; } } } return ".unk"; //unknown }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public void addSubpropMaker(PropertyMaker subproperty) { throw new RuntimeException("Unable to add subproperties " + getClass()); }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public PropertyMaker getSubpropMaker(int subpropertyId) { throw new RuntimeException("Unable to add subproperties"); }
// in src/java/org/apache/fop/fo/flow/Leader.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); }
// in src/java/org/apache/fop/fo/ElementMapping.java
public static DOMImplementation getDefaultDOMImplementation() { DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); fact.setNamespaceAware(true); fact.setValidating(false); try { return fact.newDocumentBuilder().getDOMImplementation(); } catch (ParserConfigurationException e) { throw new RuntimeException( "Cannot return default DOM implementation: " + e.getMessage()); } }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
private DOMImplementation getDOMImplementation(String ver) { //TODO It would be great if Batik provided this method as static helper method. if (ver == null || ver.length() == 0 || ver.equals("1.0") || ver.equals("1.1")) { return SVGDOMImplementation.getDOMImplementation(); } else if (ver.equals("1.2")) { try { Class clazz = Class.forName( "org.apache.batik.dom.svg12.SVG12DOMImplementation"); return (DOMImplementation)clazz.getMethod( "getDOMImplementation", (Class[])null).invoke(null, (Object[])null); } catch (Exception e) { return SVGDOMImplementation.getDOMImplementation(); } } throw new RuntimeException("Unsupport SVG version '" + ver + "'"); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
static XMLReader createParser() { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); return factory.newSAXParser().getXMLReader(); } catch (Exception e) { throw new RuntimeException("Couldn't create XMLReader: " + e.getMessage()); } }
// in src/java/org/apache/fop/svg/NativeTextPainter.java
Override protected void paintTextRuns(List textRuns, Graphics2D g2d) { if (log.isTraceEnabled()) { log.trace("paintTextRuns: count = " + textRuns.size()); } if (!isSupported(g2d)) { super.paintTextRuns(textRuns, g2d); return; } for (int i = 0; i < textRuns.size(); i++) { TextRun textRun = (TextRun)textRuns.get(i); try { paintTextRun(textRun, g2d); } catch (IOException ioe) { //No other possibility than to use a RuntimeException throw new RuntimeException(ioe); } } }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
public void displayError(String message) { try { getErrorHandler().error(new TranscoderException(message)); } catch (TranscoderException ex) { throw new RuntimeException(); } }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
public void displayError(Exception e) { try { getErrorHandler().error(new TranscoderException(e)); } catch (TranscoderException ex) { throw new RuntimeException(); } }
// in src/java/org/apache/fop/fonts/LazyFont.java
private void load(boolean fail) { if (!isMetricsLoaded) { try { if (metricsFileName != null) { /**@todo Possible thread problem here */ FontReader reader = null; if (resolver != null) { Source source = resolver.resolve(metricsFileName); if (source == null) { String err = "Cannot load font: failed to create Source from metrics file " + metricsFileName; if (fail) { throw new RuntimeException(err); } else { log.error(err); } return; } InputStream in = null; if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null && source.getSystemId() != null) { in = new java.net.URL(source.getSystemId()).openStream(); } if (in == null) { String err = "Cannot load font: After URI resolution, the returned" + " Source object does not contain an InputStream" + " or a valid URL (system identifier) for metrics file: " + metricsFileName; if (fail) { throw new RuntimeException(err); } else { log.error(err); } return; } InputSource src = new InputSource(in); src.setSystemId(source.getSystemId()); reader = new FontReader(src); } else { reader = new FontReader(new InputSource( new URL(metricsFileName).openStream())); } reader.setKerningEnabled(useKerning); reader.setAdvancedEnabled(useAdvanced); if (this.embedded) { reader.setFontEmbedPath(fontEmbedPath); } reader.setResolver(resolver); realFont = reader.getFont(); } else { if (fontEmbedPath == null) { throw new RuntimeException("Cannot load font. No font URIs available."); } realFont = FontLoader.loadFont(fontEmbedPath, this.subFontName, this.embedded, this.encodingMode, useKerning, useAdvanced, resolver); } if (realFont instanceof FontDescriptor) { realFontDescriptor = (FontDescriptor) realFont; } } catch (FOPException fopex) { log.error("Failed to read font metrics file " + metricsFileName, fopex); if (fail) { throw new RuntimeException(fopex.getMessage()); } } catch (IOException ioex) { log.error("Failed to read font metrics file " + metricsFileName, ioex); if (fail) { throw new RuntimeException(ioex.getMessage()); } } realFont.setEventListener(this.eventListener); isMetricsLoaded = true; } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
protected void setValue(Object target, Class<?> argType, Object value) { Class<?> c = target.getClass(); try { Method mth = c.getMethod(method, argType); mth.invoke(target, value); } catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { Boolean b = getBooleanValue(line, startpos); Object target = getContextObject(stack); Class<?> c = target.getClass(); try { Method mth = c.getMethod(method, boolean.class); mth.invoke(target, b); } catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } }
// in src/java/org/apache/fop/fonts/truetype/TTFFontLoader.java
private void buildFont(TTFFile ttf, String ttcFontName) { if (ttf.isCFF()) { throw new UnsupportedOperationException( "OpenType fonts with CFF data are not supported, yet"); } boolean isCid = this.embedded; if (this.encodingMode == EncodingMode.SINGLE_BYTE) { isCid = false; } if (isCid) { multiFont = new MultiByteFont(); returnFont = multiFont; multiFont.setTTCName(ttcFontName); } else { singleFont = new SingleByteFont(); returnFont = singleFont; } returnFont.setResolver(resolver); returnFont.setFontName(ttf.getPostScriptName()); returnFont.setFullName(ttf.getFullName()); returnFont.setFamilyNames(ttf.getFamilyNames()); returnFont.setFontSubFamilyName(ttf.getSubFamilyName()); returnFont.setCapHeight(ttf.getCapHeight()); returnFont.setXHeight(ttf.getXHeight()); returnFont.setAscender(ttf.getLowerCaseAscent()); returnFont.setDescender(ttf.getLowerCaseDescent()); returnFont.setFontBBox(ttf.getFontBBox()); returnFont.setFlags(ttf.getFlags()); returnFont.setStemV(Integer.parseInt(ttf.getStemV())); //not used for TTF returnFont.setItalicAngle(Integer.parseInt(ttf.getItalicAngle())); returnFont.setMissingWidth(0); returnFont.setWeight(ttf.getWeightClass()); if (isCid) { multiFont.setCIDType(CIDFontType.CIDTYPE2); int[] wx = ttf.getWidths(); multiFont.setWidthArray(wx); List entries = ttf.getCMaps(); BFEntry[] bfentries = new BFEntry[entries.size()]; int pos = 0; Iterator iter = ttf.getCMaps().listIterator(); while (iter.hasNext()) { TTFCmapEntry ce = (TTFCmapEntry)iter.next(); bfentries[pos] = new BFEntry(ce.getUnicodeStart(), ce.getUnicodeEnd(), ce.getGlyphStartIndex()); pos++; } multiFont.setBFEntries(bfentries); } else { singleFont.setFontType(FontType.TRUETYPE); singleFont.setEncoding(ttf.getCharSetName()); returnFont.setFirstChar(ttf.getFirstChar()); returnFont.setLastChar(ttf.getLastChar()); copyWidthsSingleByte(ttf); } if (useKerning) { copyKerning(ttf, isCid); } if (useAdvanced) { copyAdvanced(ttf); } if (this.embedded) { if (ttf.isEmbeddable()) { returnFont.setEmbedFileName(this.fontFileURI); } else { String msg = "The font " + this.fontFileURI + " is not embeddable due to a" + " licensing restriction."; throw new RuntimeException(msg); } } }
// in src/java/org/apache/fop/render/print/PrintRenderer.java
private void initializePrinterJob() { if (this.printerJob == null) { printerJob = PrinterJob.getPrinterJob(); printerJob.setJobName("FOP Document"); printerJob.setCopies(copies); if (System.getProperty("dialog") != null) { if (!printerJob.printDialog()) { throw new RuntimeException( "Printing cancelled by operator"); } } printerJob.setPageable(this); } }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
protected void handleSAXException(SAXException saxe) { throw new RuntimeException(saxe.getMessage()); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { if (this.handler == null) { SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); try { TransformerHandler transformerHandler = factory.newTransformerHandler(); setContentHandler(transformerHandler); StreamResult res = new StreamResult(outputStream); transformerHandler.setResult(res); } catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); } this.out = outputStream; } try { handler.startDocument(); } catch (SAXException saxe) { handleSAXException(saxe); } }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
Override public void startRenderer(OutputStream outputStream) throws IOException { log.debug("Rendering areas to Area Tree XML"); if (this.handler == null) { SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); try { TransformerHandler transformerHandler = factory.newTransformerHandler(); this.handler = transformerHandler; StreamResult res = new StreamResult(outputStream); transformerHandler.setResult(res); } catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); } this.out = outputStream; } try { handler.startDocument(); } catch (SAXException saxe) { handleSAXException(saxe); } if (userAgent.getProducer() != null) { comment("Produced by " + userAgent.getProducer()); } atts.clear(); addAttribute("version", VERSION); startElement("areaTree", atts); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void setDocumentLocale(Locale locale) { AttributesImpl atts = new AttributesImpl(); atts.addAttribute(XML_NAMESPACE, "lang", "xml:lang", XMLUtil.CDATA, LanguageTags.toLanguageTag(locale)); try { handler.startElement(EL_LOCALE, atts); handler.endElement(EL_LOCALE); } catch (SAXException e) { throw new RuntimeException("Unable to create the " + EL_LOCALE + " element.", e); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
private void handleIFException(IFException ife) { if (ife.getCause() instanceof SAXException) { throw new RuntimeException(ife.getCause()); } else { throw new RuntimeException(ife); } }
// in src/java/org/apache/fop/render/txt/TXTStream.java
public void add(String str) { if (!doOutput) { return; } try { byte[] buff = str.getBytes(encoding); out.write(buff); } catch (IOException e) { throw new RuntimeException(e.toString()); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void paint(Graphics2D g2d, Rectangle2D area) { g2d.translate(-rect.x, -rect.y); Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state); try { painter.drawBorderRect(rect, top, bottom, left, right); } catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting borders", e); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void paint(Graphics2D g2d, Rectangle2D area) { g2d.translate(-boundingBox.x, -boundingBox.y); Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state); try { painter.drawLine(start, end, width, color, style); } catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting a line", e); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void paint(Graphics2D g2d, Rectangle2D area) { if (DEBUG) { g2d.setBackground(Color.LIGHT_GRAY); g2d.clearRect(0, 0, (int)area.getWidth(), (int)area.getHeight()); } g2d.translate(-x, -y + baselineOffset); if (DEBUG) { Rectangle rect = new Rectangle(x, y - maxAscent, 3000, maxAscent); g2d.draw(rect); rect = new Rectangle(x, y - ascent, 2000, ascent); g2d.draw(rect); rect = new Rectangle(x, y, 1000, -descent); g2d.draw(rect); } Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state); try { painter.drawText(x, y, letterSpacing, wordSpacing, dp, text); } catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting text", e); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startFlow(Flow fl) { if (bDefer) { return; } try { log.debug("starting flow: " + fl.getFlowName()); boolean handled = false; Region regionBody = pagemaster.getRegion(Constants.FO_REGION_BODY); Region regionBefore = pagemaster.getRegion(Constants.FO_REGION_BEFORE); Region regionAfter = pagemaster.getRegion(Constants.FO_REGION_AFTER); if (fl.getFlowName().equals(regionBody.getRegionName())) { // if there is no header in current page-sequence but there has been // a header in a previous page-sequence, insert an empty header. if (bPrevHeaderSpecified && !bHeaderSpecified) { RtfAttributes attr = new RtfAttributes(); attr.set(RtfBefore.HEADER); final IRtfBeforeContainer contBefore = (IRtfBeforeContainer)builderContext.getContainer (IRtfBeforeContainer.class, true, this); contBefore.newBefore(attr); } // if there is no footer in current page-sequence but there has been // a footer in a previous page-sequence, insert an empty footer. if (bPrevFooterSpecified && !bFooterSpecified) { RtfAttributes attr = new RtfAttributes(); attr.set(RtfAfter.FOOTER); final IRtfAfterContainer contAfter = (IRtfAfterContainer)builderContext.getContainer (IRtfAfterContainer.class, true, this); contAfter.newAfter(attr); } handled = true; } else if (regionBefore != null && fl.getFlowName().equals(regionBefore.getRegionName())) { bHeaderSpecified = true; bPrevHeaderSpecified = true; final IRtfBeforeContainer c = (IRtfBeforeContainer)builderContext.getContainer( IRtfBeforeContainer.class, true, this); RtfAttributes beforeAttributes = ((RtfElement)c).getRtfAttributes(); if (beforeAttributes == null) { beforeAttributes = new RtfAttributes(); } beforeAttributes.set(RtfBefore.HEADER); RtfBefore before = c.newBefore(beforeAttributes); builderContext.pushContainer(before); handled = true; } else if (regionAfter != null && fl.getFlowName().equals(regionAfter.getRegionName())) { bFooterSpecified = true; bPrevFooterSpecified = true; final IRtfAfterContainer c = (IRtfAfterContainer)builderContext.getContainer( IRtfAfterContainer.class, true, this); RtfAttributes afterAttributes = ((RtfElement)c).getRtfAttributes(); if (afterAttributes == null) { afterAttributes = new RtfAttributes(); } afterAttributes.set(RtfAfter.FOOTER); RtfAfter after = c.newAfter(afterAttributes); builderContext.pushContainer(after); handled = true; } if (!handled) { log.warn("A " + fl.getLocalName() + " has been skipped: " + fl.getFlowName()); } } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endFlow(Flow fl) { if (bDefer) { return; } try { Region regionBody = pagemaster.getRegion(Constants.FO_REGION_BODY); Region regionBefore = pagemaster.getRegion(Constants.FO_REGION_BEFORE); Region regionAfter = pagemaster.getRegion(Constants.FO_REGION_AFTER); if (fl.getFlowName().equals(regionBody.getRegionName())) { //just do nothing } else if (regionBefore != null && fl.getFlowName().equals(regionBefore.getRegionName())) { builderContext.popContainer(); } else if (regionAfter != null && fl.getFlowName().equals(regionAfter.getRegionName())) { builderContext.popContainer(); } } catch (Exception e) { log.error("endFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startBlock(Block bl) { if (bDefer) { return; } try { RtfAttributes rtfAttr = TextAttributesConverter.convertAttributes(bl); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addParagraphBreak(); textrun.pushBlockAttributes(rtfAttr); textrun.addBookmark(bl.getId()); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endBlock(Block bl) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); RtfParagraphBreak par = textrun.addParagraphBreak(); RtfTableCell cellParent = (RtfTableCell)textrun.getParentOfClass(RtfTableCell.class); if (cellParent != null && par != null) { int iDepth = cellParent.findChildren(textrun); cellParent.setLastParagraph(par, iDepth); } int breakValue = toRtfBreakValue(bl.getBreakAfter()); textrun.popBlockAttributes(breakValue); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startBlockContainer(BlockContainer blc) { if (bDefer) { return; } try { RtfAttributes rtfAttr = TextAttributesConverter.convertBlockContainerAttributes(blc); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addParagraphBreak(); textrun.pushBlockAttributes(rtfAttr); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endBlockContainer(BlockContainer bl) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addParagraphBreak(); int breakValue = toRtfBreakValue(bl.getBreakAfter()); textrun.popBlockAttributes(breakValue); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startTable(Table tbl) { if (bDefer) { return; } // create an RtfTable in the current table container TableContext tableContext = new TableContext(builderContext); try { final IRtfTableContainer tc = (IRtfTableContainer)builderContext.getContainer( IRtfTableContainer.class, true, null); RtfAttributes atts = TableAttributesConverter.convertTableAttributes(tbl); RtfTable table = tc.newTable(atts, tableContext); table.setNestedTableDepth(nestedTableDepth); nestedTableDepth++; CommonBorderPaddingBackground border = tbl.getCommonBorderPaddingBackground(); RtfAttributes borderAttributes = new RtfAttributes(); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.BEFORE, borderAttributes, ITableAttributes.CELL_BORDER_TOP); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.AFTER, borderAttributes, ITableAttributes.CELL_BORDER_BOTTOM); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.START, borderAttributes, ITableAttributes.CELL_BORDER_LEFT); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.END, borderAttributes, ITableAttributes.CELL_BORDER_RIGHT); table.setBorderAttributes(borderAttributes); builderContext.pushContainer(table); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startTable:" + e.getMessage()); throw new RuntimeException(e.getMessage()); } builderContext.pushTableContext(tableContext); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startColumn(TableColumn tc) { if (bDefer) { return; } try { int iWidth = tc.getColumnWidth().getValue(percentManager); percentManager.setDimension(tc, iWidth); //convert to twips Float width = new Float(FoUnitsConverter.getInstance().convertMptToTwips(iWidth)); builderContext.getTableContext().setNextColumnWidth(width); builderContext.getTableContext().setNextColumnRowSpanning( new Integer(0), null); builderContext.getTableContext().setNextFirstSpanningCol(false); } catch (Exception e) { log.error("startColumn: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startInline(Inline inl) { if (bDefer) { return; } try { RtfAttributes rtfAttr = TextAttributesConverter.convertCharacterAttributes(inl); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.pushInlineAttributes(rtfAttr); textrun.addBookmark(inl.getId()); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (FOPException fe) { log.error("startInline:" + fe.getMessage()); throw new RuntimeException(fe.getMessage()); } catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endInline(Inline inl) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.popInlineAttributes(); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
private void startPart(TablePart part) { if (bDefer) { return; } try { RtfAttributes atts = TableAttributesConverter.convertTablePartAttributes(part); RtfTable tbl = (RtfTable)builderContext.getContainer(RtfTable.class, true, this); tbl.setHeaderAttribs(atts); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
private void endPart(TablePart tb) { if (bDefer) { return; } try { RtfTable tbl = (RtfTable)builderContext.getContainer(RtfTable.class, true, this); tbl.setHeaderAttribs(null); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("endPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startRow(TableRow tr) { if (bDefer) { return; } try { // create an RtfTableRow in the current RtfTable final RtfTable tbl = (RtfTable)builderContext.getContainer(RtfTable.class, true, null); RtfAttributes atts = TableAttributesConverter.convertRowAttributes(tr, tbl.getHeaderAttribs()); if (tr.getParent() instanceof TableHeader) { atts.set(ITableAttributes.ATTR_HEADER); } builderContext.pushContainer(tbl.newTableRow(atts)); // reset column iteration index to correctly access column widths builderContext.getTableContext().selectFirstColumn(); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endRow(TableRow tr) { if (bDefer) { return; } try { TableContext tctx = builderContext.getTableContext(); final RtfTableRow row = (RtfTableRow)builderContext.getContainer(RtfTableRow.class, true, null); //while the current column is in row-spanning, act as if //a vertical merged cell would have been specified. while (tctx.getNumberOfColumns() > tctx.getColumnIndex() && tctx.getColumnRowSpanningNumber().intValue() > 0) { RtfTableCell vCell = row.newTableCellMergedVertically( (int)tctx.getColumnWidth(), tctx.getColumnRowSpanningAttrs()); if (!tctx.getFirstSpanningCol()) { vCell.setHMerge(RtfTableCell.MERGE_WITH_PREVIOUS); } tctx.selectNextColumn(); } } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("endRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } builderContext.popContainer(); builderContext.getTableContext().decreaseRowSpannings(); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startCell(TableCell tc) { if (bDefer) { return; } try { TableContext tctx = builderContext.getTableContext(); final RtfTableRow row = (RtfTableRow)builderContext.getContainer(RtfTableRow.class, true, null); int numberRowsSpanned = tc.getNumberRowsSpanned(); int numberColumnsSpanned = tc.getNumberColumnsSpanned(); //while the current column is in row-spanning, act as if //a vertical merged cell would have been specified. while (tctx.getNumberOfColumns() > tctx.getColumnIndex() && tctx.getColumnRowSpanningNumber().intValue() > 0) { RtfTableCell vCell = row.newTableCellMergedVertically( (int)tctx.getColumnWidth(), tctx.getColumnRowSpanningAttrs()); if (!tctx.getFirstSpanningCol()) { vCell.setHMerge(RtfTableCell.MERGE_WITH_PREVIOUS); } tctx.selectNextColumn(); } //get the width of the currently started cell float width = tctx.getColumnWidth(); // create an RtfTableCell in the current RtfTableRow RtfAttributes atts = TableAttributesConverter.convertCellAttributes(tc); RtfTableCell cell = row.newTableCell((int)width, atts); //process number-rows-spanned attribute if (numberRowsSpanned > 1) { // Start vertical merge cell.setVMerge(RtfTableCell.MERGE_START); // set the number of rows spanned tctx.setCurrentColumnRowSpanning(new Integer(numberRowsSpanned), cell.getRtfAttributes()); } else { tctx.setCurrentColumnRowSpanning( new Integer(numberRowsSpanned), null); } //process number-columns-spanned attribute if (numberColumnsSpanned > 0) { // Get the number of columns spanned tctx.setCurrentFirstSpanningCol(true); // We widthdraw one cell because the first cell is already created // (it's the current cell) ! for (int i = 0; i < numberColumnsSpanned - 1; ++i) { tctx.selectNextColumn(); //aggregate width for further elements width += tctx.getColumnWidth(); tctx.setCurrentFirstSpanningCol(false); RtfTableCell hCell = row.newTableCellMergedHorizontally( 0, null); if (numberRowsSpanned > 1) { // Start vertical merge hCell.setVMerge(RtfTableCell.MERGE_START); // set the number of rows spanned tctx.setCurrentColumnRowSpanning( new Integer(numberRowsSpanned), cell.getRtfAttributes()); } else { tctx.setCurrentColumnRowSpanning( new Integer(numberRowsSpanned), cell.getRtfAttributes()); } } } //save width of the cell, convert from twips to mpt percentManager.setDimension(tc, (int)width * 50); builderContext.pushContainer(cell); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endCell(TableCell tc) { if (bDefer) { return; } try { RtfTableCell cell = (RtfTableCell)builderContext.getContainer(RtfTableCell.class, false, this); cell.finish(); } catch (Exception e) { log.error("endCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } builderContext.popContainer(); builderContext.getTableContext().selectNextColumn(); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startList(ListBlock lb) { if (bDefer) { return; } try { // create an RtfList in the current list container final IRtfListContainer c = (IRtfListContainer)builderContext.getContainer( IRtfListContainer.class, true, this); final RtfList newList = c.newList( ListAttributesConverter.convertAttributes(lb)); builderContext.pushContainer(newList); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (FOPException fe) { log.error("startList: " + fe.getMessage()); throw new RuntimeException(fe.getMessage()); } catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startListItem(ListItem li) { if (bDefer) { return; } // create an RtfListItem in the current RtfList try { RtfList list = (RtfList)builderContext.getContainer( RtfList.class, true, this); /** * If the current list already contains a list item, then close the * list and open a new one, so every single list item gets its own * list. This allows every item to have a different list label. * If all the items would be in the same list, they had all the * same label. */ //TODO: do this only, if the labels content <> previous labels content if (list.getChildCount() > 0) { this.endListBody(null); this.endList((ListBlock) li.getParent()); this.startList((ListBlock) li.getParent()); this.startListBody(null); list = (RtfList)builderContext.getContainer( RtfList.class, true, this); } builderContext.pushContainer(list.newListItem()); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startListLabel(ListItemLabel listItemLabel) { if (bDefer) { return; } try { RtfListItem item = (RtfListItem)builderContext.getContainer(RtfListItem.class, true, this); RtfListItemLabel label = item.new RtfListItemLabel(item); builderContext.pushContainer(label); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startLink(BasicLink basicLink) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); RtfHyperLink link = textrun.addHyperlink(new RtfAttributes()); if (basicLink.hasExternalDestination()) { link.setExternalURL(basicLink.getExternalDestination()); } else { link.setInternalURL(basicLink.getInternalDestination()); } builderContext.pushContainer(link); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startLink: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startFootnote(Footnote footnote) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); RtfFootnote rtfFootnote = textrun.addFootnote(); builderContext.pushContainer(rtfFootnote); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startFootnote: " + e.getMessage()); throw new RuntimeException("Exception: " + e); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startFootnoteBody(FootnoteBody body) { if (bDefer) { return; } try { RtfFootnote rtfFootnote = (RtfFootnote)builderContext.getContainer( RtfFootnote.class, true, this); rtfFootnote.startBody(); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endFootnoteBody(FootnoteBody body) { if (bDefer) { return; } try { RtfFootnote rtfFootnote = (RtfFootnote)builderContext.getContainer( RtfFootnote.class, true, this); rtfFootnote.endBody(); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("endFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startLeader(Leader l) { if (bDefer) { return; } try { percentManager.setDimension(l); RtfAttributes rtfAttr = TextAttributesConverter.convertLeaderAttributes( l, percentManager); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addLeader(rtfAttr); } catch (IOException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } catch (FOPException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void text(FOText text, CharSequence characters) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); RtfAttributes rtfAttr = TextAttributesConverter.convertCharacterAttributes(text); textrun.pushInlineAttributes(rtfAttr); textrun.addString(characters.toString()); textrun.popInlineAttributes(); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("characters:" + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startPageNumber(PageNumber pagenum) { if (bDefer) { return; } try { RtfAttributes rtfAttr = TextAttributesConverter.convertCharacterAttributes( pagenum); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addPageNumber(rtfAttr); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startPageNumberCitation(PageNumberCitation l) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addPageNumberCitation(l.getRefId()); } catch (Exception e) { log.error("startPageNumberCitation: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startPageNumberCitationLast(PageNumberCitationLast l) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addPageNumberCitation(l.getRefId()); } catch (RtfException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } catch (IOException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
private void rewritePostScriptFile() throws IOException { log.debug("Processing PostScript resources..."); long startTime = System.currentTimeMillis(); ResourceTracker resTracker = gen.getResourceTracker(); InputStream in = new java.io.FileInputStream(this.tempFile); in = new java.io.BufferedInputStream(in); try { try { ResourceHandler handler = new ResourceHandler(getUserAgent(), this.fontInfo, resTracker, this.formResources); handler.process(in, this.outputStream, this.currentPageNumber, this.documentBoundingBox); this.outputStream.flush(); } catch (DSCException e) { throw new RuntimeException(e.getMessage()); } } finally { IOUtils.closeQuietly(in); if (!this.tempFile.delete()) { this.tempFile.deleteOnExit(); log.warn("Could not delete temporary file: " + this.tempFile); } } if (log.isDebugEnabled()) { long duration = System.currentTimeMillis() - startTime; log.debug("Resource Processing complete in " + duration + " ms."); } }
// in src/java/org/apache/fop/afp/svg/AFPTextHandler.java
private int registerPageFont(AFPPageFonts pageFonts, String internalFontName, int fontSize) { AFPFont afpFont = (AFPFont)fontInfo.getFonts().get(internalFontName); // register if necessary AFPFontAttributes afpFontAttributes = pageFonts.registerFont( internalFontName, afpFont, fontSize ); if (afpFont.isEmbeddable()) { try { final CharacterSet charSet = afpFont.getCharacterSet(fontSize); this.resourceManager.embedFont(afpFont, charSet); } catch (IOException ioe) { throw new RuntimeException("Error while embedding font resources", ioe); } } return afpFontAttributes.getFontReference(); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
private void handleUnexpectedIOError(IOException ioe) { //"Unexpected" since we're currently dealing with ByteArrayOutputStreams here. throw new RuntimeException("Unexpected I/O error: " + ioe.getMessage(), ioe); }
// in src/java/org/apache/fop/events/EventExceptionManager.java
public static void throwException(Event event, String exceptionClass) throws Throwable { if (exceptionClass != null) { ExceptionFactory factory = (ExceptionFactory)EXCEPTION_FACTORIES.get(exceptionClass); if (factory != null) { throw factory.createException(event); } else { throw new IllegalArgumentException( "No such ExceptionFactory available: " + exceptionClass); } } else { String msg = EventFormatter.format(event); //Get original exception as cause if it is given as one of the parameters Throwable t = null; Iterator<Object> iter = event.getParams().values().iterator(); while (iter.hasNext()) { Object o = iter.next(); if (o instanceof Throwable) { t = (Throwable)o; break; } } if (t != null) { throw new RuntimeException(msg, t); } else { throw new RuntimeException(msg); } } }
// in src/java/org/apache/fop/area/CTM.java
public static CTM getCTMandRelDims(int absRefOrient, WritingMode writingMode, Rectangle2D absVPrect, FODimension reldims) { int width; int height; // We will use the absolute reference-orientation to set up the CTM. // The value here is relative to its ancestor reference area. if (absRefOrient % 180 == 0) { width = (int) absVPrect.getWidth(); height = (int) absVPrect.getHeight(); } else { // invert width and height since top left are rotated by 90 (cl or ccl) height = (int) absVPrect.getWidth(); width = (int) absVPrect.getHeight(); } /* Set up the CTM for the content of this reference area. * This will transform region content coordinates in * writing-mode relative into absolute page-relative * which will then be translated based on the position of * the region viewport. * (Note: scrolling between region vp and ref area when * doing online content!) */ CTM ctm = new CTM(absVPrect.getX(), absVPrect.getY()); // First transform for rotation if (absRefOrient != 0) { // Rotation implies translation to keep the drawing area in the // first quadrant. Note: rotation is counter-clockwise switch (absRefOrient) { case 90: case -270: ctm = ctm.translate(0, width); // width = absVPrect.height break; case 180: case -180: ctm = ctm.translate(width, height); break; case 270: case -90: ctm = ctm.translate(height, 0); // height = absVPrect.width break; default: throw new RuntimeException(); } ctm = ctm.rotate(absRefOrient); } /* Since we've already put adjusted width and height values for the * top and left positions implied by the reference-orientation, we * can set ipd and bpd appropriately based on the writing mode. */ switch ( writingMode.getEnumValue() ) { case EN_TB_LR: case EN_TB_RL: reldims.ipd = height; reldims.bpd = width; break; case EN_LR_TB: case EN_RL_TB: default: reldims.ipd = width; reldims.bpd = height; break; } // Set a rectangle to be the writing-mode relative version??? // Now transform for writing mode return ctm.multiply(CTM.getWMctm(writingMode, reldims.ipd, reldims.bpd)); }
// in src/java/org/apache/fop/area/LineArea.java
public void handleIPDVariation(int ipdVariation) { int si = getStartIndent(); int ei = getEndIndent(); switch (adjustingInfo.lineAlignment) { case EN_START: // adjust end indent addTrait(Trait.END_INDENT, ei - ipdVariation); break; case EN_CENTER: // adjust start and end indents addTrait(Trait.START_INDENT, si - ipdVariation / 2); addTrait(Trait.END_INDENT, ei - ipdVariation / 2); break; case EN_END: // adjust start indent addTrait(Trait.START_INDENT, si - ipdVariation); break; case EN_JUSTIFY: // compute variation factor adjustingInfo.variationFactor *= (float) (adjustingInfo.difference - ipdVariation) / adjustingInfo.difference; adjustingInfo.difference -= ipdVariation; // if the LineArea has already been added to the area tree, // call finalize(); otherwise, wait for the LineLM to call it if (adjustingInfo.bAddedToAreaTree) { finish(); } break; default: throw new RuntimeException(); } }
// in src/java/org/apache/fop/area/RenderPagesModel.java
Override public void handleOffDocumentItem(OffDocumentItem oDI) { switch(oDI.getWhenToProcess()) { case OffDocumentItem.IMMEDIATELY: renderer.processOffDocumentItem(oDI); break; case OffDocumentItem.AFTER_PAGE: pendingODI.add(oDI); break; case OffDocumentItem.END_OF_DOC: endDocODI.add(oDI); break; default: throw new RuntimeException(); } }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
public void startPageSequence(Locale locale, String role) { try { AttributesImpl attributes = new AttributesImpl(); if (role != null) { attributes.addAttribute("", "type", "type", XMLConstants.CDATA, role); } contentHandler.startPrefixMapping( InternalElementMapping.STANDARD_PREFIX, InternalElementMapping.URI); contentHandler.startPrefixMapping( ExtensionElementMapping.STANDARD_PREFIX, ExtensionElementMapping.URI); contentHandler.startElement(IFConstants.NAMESPACE, IFConstants.EL_STRUCTURE_TREE, IFConstants.EL_STRUCTURE_TREE, attributes); } catch (SAXException e) { throw new RuntimeException(e); } }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
public void endPageSequence() { try { contentHandler.endElement(IFConstants.NAMESPACE, IFConstants.EL_STRUCTURE_TREE, IFConstants.EL_STRUCTURE_TREE); contentHandler.endPrefixMapping( ExtensionElementMapping.STANDARD_PREFIX); contentHandler.endPrefixMapping( InternalElementMapping.STANDARD_PREFIX); } catch (SAXException e) { throw new RuntimeException(e); } }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
public StructureTreeElement startNode(String name, Attributes attributes) { try { if (name.equals("#PCDATA")) { name = "marked-content"; contentHandler.startElement(IFConstants.NAMESPACE, name, name, attributes); } else { contentHandler.startElement(FOElementMapping.URI, name, FOElementMapping.STANDARD_PREFIX + ":" + name, attributes); } return null; } catch (SAXException e) { throw new RuntimeException(e); } }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
public void endNode(String name) { try { contentHandler.endElement(FOElementMapping.URI, name, FOElementMapping.STANDARD_PREFIX + ":" + name); } catch (SAXException e) { throw new RuntimeException(e); } }
// in src/java/org/apache/fop/layoutmgr/KnuthElement.java
public int getPenalty() { throw new RuntimeException("Element is not a penalty"); }
// in src/java/org/apache/fop/layoutmgr/KnuthElement.java
public int getStretch() { throw new RuntimeException("Element is not a glue"); }
// in src/java/org/apache/fop/layoutmgr/KnuthElement.java
public int getShrink() { throw new RuntimeException("Element is not a glue"); }
// in src/java/org/apache/fop/cli/Main.java
public static URL[] getJARList() throws MalformedURLException { String fopHome = System.getProperty("fop.home"); File baseDir; if (fopHome != null) { baseDir = new File(fopHome).getAbsoluteFile(); } else { baseDir = new File(".").getAbsoluteFile().getParentFile(); } File buildDir; if ("build".equals(baseDir.getName())) { buildDir = baseDir; baseDir = baseDir.getParentFile(); } else { buildDir = new File(baseDir, "build"); } File fopJar = new File(buildDir, "fop.jar"); if (!fopJar.exists()) { fopJar = new File(baseDir, "fop.jar"); } if (!fopJar.exists()) { throw new RuntimeException("fop.jar not found in directory: " + baseDir.getAbsolutePath() + " (or below)"); } List jars = new java.util.ArrayList(); jars.add(fopJar.toURI().toURL()); File[] files; FileFilter filter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".jar"); } }; File libDir = new File(baseDir, "lib"); if (!libDir.exists()) { libDir = baseDir; } files = libDir.listFiles(filter); if (files != null) { for (int i = 0, size = files.length; i < size; i++) { jars.add(files[i].toURI().toURL()); } } String optionalLib = System.getProperty("fop.optional.lib"); if (optionalLib != null) { files = new File(optionalLib).listFiles(filter); if (files != null) { for (int i = 0, size = files.length; i < size; i++) { jars.add(files[i].toURI().toURL()); } } } URL[] urls = (URL[])jars.toArray(new URL[jars.size()]); /* for (int i = 0, c = urls.length; i < c; i++) { System.out.println(urls[i]); }*/ return urls; }
62
              
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (IOException e) { // won't happen. We're operating in-memory. throw new RuntimeException( "Error during base64 encodation of username/password"); }
// in src/java/org/apache/fop/pdf/PDFStream.java
catch (IOException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/pdf/PDFICCBasedColorSpace.java
catch (IOException ioe) { throw new RuntimeException( "Unexpected IOException loading the sRGB profile: " + ioe.getMessage()); }
// in src/java/org/apache/fop/fo/ElementMapping.java
catch (ParserConfigurationException e) { throw new RuntimeException( "Cannot return default DOM implementation: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (Exception e) { throw new RuntimeException("Couldn't create XMLReader: " + e.getMessage()); }
// in src/java/org/apache/fop/svg/NativeTextPainter.java
catch (IOException ioe) { //No other possibility than to use a RuntimeException throw new RuntimeException(ioe); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (FOPException fopex) { log.error("Failed to read font metrics file " + metricsFileName, fopex); if (fail) { throw new RuntimeException(fopex.getMessage()); } }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (IOException ioex) { log.error("Failed to read font metrics file " + metricsFileName, ioex); if (fail) { throw new RuntimeException(ioex.getMessage()); } }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
catch (java.io.UnsupportedEncodingException e) { throw new RuntimeException("Incompatible VM. It doesn't support the US-ASCII encoding"); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new RuntimeException("Unable to create the " + EL_LOCALE + " element.", e); }
// in src/java/org/apache/fop/render/txt/TXTStream.java
catch (IOException e) { throw new RuntimeException(e.toString()); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting borders", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting a line", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting text", e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startTable:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startColumn: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startInline:" + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startList: " + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startLink: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnote: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("characters:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumberCitation: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (RtfException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (DSCException e) { throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/afp/svg/AFPTextHandler.java
catch (IOException ioe) { throw new RuntimeException("Error while embedding font resources", ioe); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
0
(Lib) IOException 46
              
// in src/sandbox/org/apache/fop/render/svg/SVGDataUrlImageHandler.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { SVGRenderingContext svgContext = (SVGRenderingContext)context; ImageRawStream raw = (ImageRawStream)image; InputStream in = raw.createInputStream(); try { ContentHandler handler = svgContext.getContentHandler(); String url = DataURLUtil.createDataURL(in, raw.getMimeType()); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, IFConstants.XLINK_HREF, url); atts.addAttribute("", "x", "x", CDATA, Integer.toString(pos.x)); atts.addAttribute("", "y", "y", CDATA, Integer.toString(pos.y)); atts.addAttribute("", "width", "width", CDATA, Integer.toString(pos.width)); atts.addAttribute("", "height", "height", CDATA, Integer.toString(pos.height)); try { handler.startElement(NAMESPACE, "image", "image", atts); handler.endElement(NAMESPACE, "image", "image"); } catch (SAXException e) { throw new IOException(e.getMessage()); } } finally { IOUtils.closeQuietly(in); } }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
public void handleImage(RenderingContext context, Image image, final Rectangle pos) throws IOException { SVGRenderingContext svgContext = (SVGRenderingContext)context; ImageXMLDOM svg = (ImageXMLDOM)image; ContentHandler handler = svgContext.getContentHandler(); AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "x", "x", CDATA, SVGUtil.formatMptToPt(pos.x)); atts.addAttribute("", "y", "y", CDATA, SVGUtil.formatMptToPt(pos.y)); atts.addAttribute("", "width", "width", CDATA, SVGUtil.formatMptToPt(pos.width)); atts.addAttribute("", "height", "height", CDATA, SVGUtil.formatMptToPt(pos.height)); try { Document doc = (Document)svg.getDocument(); Element svgEl = (Element)doc.getDocumentElement(); if (svgEl.getAttribute("viewBox").length() == 0) { log.warn("SVG doesn't have a viewBox. The result might not be scaled correctly!"); } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource src = new DOMSource(svg.getDocument()); SAXResult res = new SAXResult(new DelegatingFragmentContentHandler(handler) { private boolean topLevelSVGFound = false; private void setAttribute(AttributesImpl atts, String localName, String value) { int index; index = atts.getIndex("", localName); if (index < 0) { atts.addAttribute("", localName, localName, CDATA, value); } else { atts.setAttribute(index, "", localName, localName, CDATA, value); } } public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { if (!topLevelSVGFound && SVG_ELEMENT.getNamespaceURI().equals(uri) && SVG_ELEMENT.getLocalName().equals(localName)) { topLevelSVGFound = true; AttributesImpl modAtts = new AttributesImpl(atts); setAttribute(modAtts, "x", SVGUtil.formatMptToPt(pos.x)); setAttribute(modAtts, "y", SVGUtil.formatMptToPt(pos.y)); setAttribute(modAtts, "width", SVGUtil.formatMptToPt(pos.width)); setAttribute(modAtts, "height", SVGUtil.formatMptToPt(pos.height)); super.startElement(uri, localName, name, modAtts); } else { super.startElement(uri, localName, name, atts); } } }); transformer.transform(src, res); } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
protected void outputRawStreamData(OutputStream out) throws IOException { try { XMPSerializer.writeXMPPacket(xmpMetadata, out, this.readOnly); } catch (TransformerConfigurationException tce) { throw new IOException("Error setting up Transformer for XMP stream serialization: " + tce.getMessage()); } catch (SAXException saxe) { throw new IOException("Error while serializing XMP stream: " + saxe.getMessage()); } }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceTable.java
private void outputXref() throws IOException { pdf.append("xref\n0 "); pdf.append(objectReferences.size() + 1); pdf.append("\n0000000000 65535 f \n"); for (Long objectReference : objectReferences) { final String padding = "0000000000"; String s = String.valueOf(objectReference); if (s.length() > 10) { throw new IOException("PDF file too large." + " PDF 1.4 cannot grow beyond approx. 9.3GB."); } String loc = padding.substring(s.length()) + s; pdf.append(loc).append(" 00000 n \n"); } }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static InputStream openFontUri(FontResolver resolver, String uri) throws IOException, MalformedURLException { InputStream in = null; if (resolver != null) { Source source = resolver.resolve(uri); if (source == null) { String err = "Cannot load font: failed to create Source for font file " + uri; throw new IOException(err); } if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null && source.getSystemId() != null) { in = new java.net.URL(source.getSystemId()).openStream(); } if (in == null) { String err = "Cannot load font: failed to create InputStream from" + " Source for font file " + uri; throw new IOException(err); } } else { in = new URL(uri).openStream(); } return in; }
// in src/java/org/apache/fop/fonts/CustomFont.java
public Source getEmbedFileSource() throws IOException { Source result = null; if (resolver != null && embedFileName != null) { result = resolver.resolve(embedFileName); if (result == null) { throw new IOException("Unable to resolve Source '" + embedFileName + "' for embedded font"); } } return result; }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
private void parsePCFormat(PFBData pfb, DataInputStream din) throws IOException { int segmentHead; int segmentType; int bytesRead; //Read first segment segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); //Read int len1 = swapInteger(din.readInt()); byte[] headerSegment = new byte[len1]; din.readFully(headerSegment); pfb.setHeaderSegment(headerSegment); //Read second segment segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); int len2 = swapInteger(din.readInt()); byte[] encryptedSegment = new byte[len2]; din.readFully(encryptedSegment); pfb.setEncryptedSegment(encryptedSegment); //Read third segment segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); int len3 = swapInteger(din.readInt()); byte[] trailerSegment = new byte[len3]; din.readFully(trailerSegment); pfb.setTrailerSegment(trailerSegment); //Read EOF indicator segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); if (segmentType != 3) { throw new IOException("Expected segment type 3, but found: " + segmentType); } }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
public void load(InputStream inStream) throws IOException { byte[] pfmBytes = IOUtils.toByteArray(inStream); InputStream bufin = inStream; bufin = new ByteArrayInputStream(pfmBytes); PFMInputStream in = new PFMInputStream(bufin); bufin.mark(512); short sh1 = in.readByte(); short sh2 = in.readByte(); if (sh1 == 128 && sh2 == 1) { //Found the first section header of a PFB file! throw new IOException("Cannot parse PFM file. You probably specified the PFB file" + " of a Type 1 font as parameter instead of the PFM."); } bufin.reset(); byte[] b = new byte[16]; bufin.read(b); if (new String(b, "US-ASCII").equalsIgnoreCase("StartFontMetrics")) { //Found the header of a AFM file! throw new IOException("Cannot parse PFM file. You probably specified the AFM file" + " of a Type 1 font as parameter instead of the PFM."); } bufin.reset(); final int version = in.readShort(); if (version != 256) { log.warn("PFM version expected to be '256' but got '" + version + "'." + " Please make sure you specify the PFM as parameter" + " and not the PFB or the AFM."); } //final long filesize = in.readInt(); bufin.reset(); loadHeader(in); loadExtension(in); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { int endpos = findValue(line, startpos); double version = Double.parseDouble(line.substring(startpos, endpos)); if (version < 2) { throw new IOException( "AFM version must be at least 2.0 but it is " + version + "!"); } AFMFile afm = new AFMFile(); stack.push(afm); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { if (getBooleanValue(line, startpos).booleanValue()) { throw new IOException("Only base fonts are currently supported!"); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { if (getBooleanValue(line, startpos).booleanValue()) { throw new IOException("CID fonts are currently not supported!"); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { if (!(stack.pop() instanceof AFMWritingDirectionMetrics)) { throw new IOException("AFM format error: nesting incorrect"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
public boolean readFont(FontFileReader in, String name) throws IOException { /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(in, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(in); readFontHeader(in); getNumGlyphs(in); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(in); readHorizontalMetrics(in); initAnsiWidths(); readPostScript(in); readOS2(in); determineAscDesc(); if (!isCFF) { readIndexToLocation(in); readGlyf(in); } readName(in); boolean pcltFound = readPCLT(in); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(in); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); if ( useKerning ) { readKerning(in); } // Read advanced typographic tables. if ( useAdvanced ) { try { OTFAdvancedTypographicTableReader atr = new OTFAdvancedTypographicTableReader ( this, in ); atr.readAll(); this.advancedTableReader = atr; } catch ( AdvancedTypographicTableFormatException e ) { log.warn ( "Encountered format constraint violation in advanced (typographic) table (AT) " + "in font '" + getFullName() + "', ignoring AT data: " + e.getMessage() ); } } guessVerticalMetricsFromGlyphBBox(); return true; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected final void readIndexToLocation(FontFileReader in) throws IOException { if (!seekTab(in, "loca", 0)) { throw new IOException("'loca' table not found, happens when the font file doesn't" + " contain TrueType outlines (trying to read an OpenType CFF font maybe?)"); } for (int i = 0; i < numberOfGlyphs; i++) { mtxTab[i].setOffset(locaFormat == 1 ? in.readTTFULong() : (in.readTTFUShort() << 1)); } lastLoca = (locaFormat == 1 ? in.readTTFULong() : (in.readTTFUShort() << 1)); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private void readGlyf(FontFileReader in) throws IOException { TTFDirTabEntry dirTab = getDirectoryEntry ( "glyf" ); if (dirTab == null) { throw new IOException("glyf table not found, cannot continue"); } for (int i = 0; i < (numberOfGlyphs - 1); i++) { if (mtxTab[i].getOffset() != mtxTab[i + 1].getOffset()) { in.seekSet(dirTab.getOffset() + mtxTab[i].getOffset()); in.skip(2); final int[] bbox = { in.readTTFShort(), in.readTTFShort(), in.readTTFShort(), in.readTTFShort()}; mtxTab[i].setBoundingBox(bbox); } else { mtxTab[i].setBoundingBox(mtxTab[0].getBoundingBox()); } } long n = dirTab.getOffset(); for (int i = 0; i < numberOfGlyphs; i++) { if ((i + 1) >= mtxTab.length || mtxTab[i].getOffset() != mtxTab[i + 1].getOffset()) { in.seekSet(n + mtxTab[i].getOffset()); in.skip(2); final int[] bbox = { in.readTTFShort(), in.readTTFShort(), in.readTTFShort(), in.readTTFShort()}; mtxTab[i].setBoundingBox(bbox); } else { /**@todo Verify that this is correct, looks like a copy/paste bug (jm)*/ final int bbox0 = mtxTab[0].getBoundingBox()[0]; final int[] bbox = {bbox0, bbox0, bbox0, bbox0}; mtxTab[i].setBoundingBox(bbox); /* Original code mtxTab[i].bbox[0] = mtxTab[0].bbox[0]; mtxTab[i].bbox[1] = mtxTab[0].bbox[0]; mtxTab[i].bbox[2] = mtxTab[0].bbox[0]; mtxTab[i].bbox[3] = mtxTab[0].bbox[0]; */ } if (log.isTraceEnabled()) { log.trace(mtxTab[i].toString(this)); } } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private Integer unicodeToGlyph(int unicodeIndex) throws IOException { final Integer result = (Integer) unicodeToGlyphMap.get(new Integer(unicodeIndex)); if (result == null) { throw new IOException( "Glyph index not found for unicode value " + unicodeIndex); } return result; }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createMaxp(FontFileReader in, int size) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("maxp"); if (entry != null) { pad4(); seekTab(in, "maxp", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); writeUShort(currentPos + 4, size); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(maxpDirOffset, checksum); writeULong(maxpDirOffset + 4, currentPos); writeULong(maxpDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); } else { throw new IOException("Can't find maxp table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createHhea(FontFileReader in, int size) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("hhea"); if (entry != null) { pad4(); seekTab(in, "hhea", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); writeUShort((int)entry.getLength() + currentPos - 2, size); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(hheaDirOffset, checksum); writeULong(hheaDirOffset + 4, currentPos); writeULong(hheaDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); } else { throw new IOException("Can't find hhea table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createHead(FontFileReader in) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("head"); if (entry != null) { pad4(); seekTab(in, "head", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); checkSumAdjustmentOffset = currentPos + 8; output[currentPos + 8] = 0; // Set checkSumAdjustment to 0 output[currentPos + 9] = 0; output[currentPos + 10] = 0; output[currentPos + 11] = 0; output[currentPos + 50] = 0; // long locaformat output[currentPos + 51] = 1; // long locaformat int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(headDirOffset, checksum); writeULong(headDirOffset + 4, currentPos); writeULong(headDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); } else { throw new IOException("Can't find head table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createGlyf(FontFileReader in, Map glyphs) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("glyf"); int size = 0; int start = 0; int endOffset = 0; // Store this as the last loca if (entry != null) { pad4(); start = currentPos; /* Loca table must be in order by glyph index, so build * an array first and then write the glyph info and * location offset. */ int[] origIndexes = new int[glyphs.size()]; Iterator e = glyphs.keySet().iterator(); while (e.hasNext()) { Integer origIndex = (Integer)e.next(); Integer subsetIndex = (Integer)glyphs.get(origIndex); origIndexes[subsetIndex.intValue()] = origIndex.intValue(); } for (int i = 0; i < origIndexes.length; i++) { int glyphLength = 0; int nextOffset = 0; int origGlyphIndex = origIndexes[i]; if (origGlyphIndex >= (mtxTab.length - 1)) { nextOffset = (int)lastLoca; } else { nextOffset = (int)mtxTab[origGlyphIndex + 1].getOffset(); } glyphLength = nextOffset - (int)mtxTab[origGlyphIndex].getOffset(); // Copy glyph System.arraycopy( in.getBytes((int)entry.getOffset() + (int)mtxTab[origGlyphIndex].getOffset(), glyphLength), 0, output, currentPos, glyphLength); // Update loca table writeULong(locaOffset + i * 4, currentPos - start); if ((currentPos - start + glyphLength) > endOffset) { endOffset = (currentPos - start + glyphLength); } currentPos += glyphLength; realSize += glyphLength; } size = currentPos - start; int checksum = getCheckSum(start, size); writeULong(glyfDirOffset, checksum); writeULong(glyfDirOffset + 4, start); writeULong(glyfDirOffset + 8, size); currentPos += 12; realSize += 12; // Update loca checksum and last loca index writeULong(locaOffset + glyphs.size() * 4, endOffset); checksum = getCheckSum(locaOffset, glyphs.size() * 4 + 4); writeULong(locaDirOffset, checksum); } else { throw new IOException("Can't find glyf table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createHmtx(FontFileReader in, Map glyphs) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("hmtx"); int longHorMetricSize = glyphs.size() * 2; int leftSideBearingSize = glyphs.size() * 2; int hmtxSize = longHorMetricSize + leftSideBearingSize; if (entry != null) { pad4(); //int offset = (int)entry.offset; Iterator e = glyphs.keySet().iterator(); while (e.hasNext()) { Integer origIndex = (Integer)e.next(); Integer subsetIndex = (Integer)glyphs.get(origIndex); writeUShort(currentPos + subsetIndex.intValue() * 4, mtxTab[origIndex.intValue()].getWx()); writeUShort(currentPos + subsetIndex.intValue() * 4 + 2, mtxTab[origIndex.intValue()].getLsb()); } int checksum = getCheckSum(currentPos, hmtxSize); writeULong(hmtxDirOffset, checksum); writeULong(hmtxDirOffset + 4, currentPos); writeULong(hmtxDirOffset + 8, hmtxSize); currentPos += hmtxSize; realSize += hmtxSize; } else { throw new IOException("Can't find hmtx table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
public byte[] readFont(FontFileReader in, String name, Map<Integer, Integer> glyphs) throws IOException { //Check if TrueType collection, and that the name exists in the collection if (!checkTTC(in, name)) { throw new IOException("Failed to read font"); } //Copy the Map as we're going to modify it Map<Integer, Integer> subsetGlyphs = new java.util.HashMap<Integer, Integer>(glyphs); output = new byte[in.getFileSize()]; readDirTabs(in); readFontHeader(in); getNumGlyphs(in); readHorizontalHeader(in); readHorizontalMetrics(in); readIndexToLocation(in); scanGlyphs(in, subsetGlyphs); createDirectory(); // Create the TrueType header and directory createHead(in); createHhea(in, subsetGlyphs.size()); // Create the hhea table createHmtx(in, subsetGlyphs); // Create hmtx table createMaxp(in, subsetGlyphs.size()); // copy the maxp table boolean optionalTableFound; optionalTableFound = createCvt(in); // copy the cvt table if (!optionalTableFound) { // cvt is optional (used in TrueType fonts only) log.debug("TrueType: ctv table not present. Skipped."); } optionalTableFound = createFpgm(in); // copy fpgm table if (!optionalTableFound) { // fpgm is optional (used in TrueType fonts only) log.debug("TrueType: fpgm table not present. Skipped."); } optionalTableFound = createPrep(in); // copy prep table if (!optionalTableFound) { // prep is optional (used in TrueType fonts only) log.debug("TrueType: prep table not present. Skipped."); } createLoca(subsetGlyphs.size()); // create empty loca table createGlyf(in, subsetGlyphs); //create glyf table and update loca table pad4(); createCheckSumAdjustment(); byte[] ret = new byte[realSize]; System.arraycopy(output, 0, ret, 0, realSize); return ret; }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void scanGlyphs(FontFileReader in, Map<Integer, Integer> subsetGlyphs) throws IOException { TTFDirTabEntry glyfTableInfo = (TTFDirTabEntry) dirTabs.get("glyf"); if (glyfTableInfo == null) { throw new IOException("Glyf table could not be found"); } GlyfTable glyfTable = new GlyfTable(in, mtxTab, glyfTableInfo, subsetGlyphs); glyfTable.populateGlyphsWithComposites(); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public byte[] getBytes(int offset, int length) throws IOException { if ((offset + length) > fsize) { throw new java.io.IOException("Reached EOF"); } byte[] ret = new byte[length]; System.arraycopy(file, offset, ret, 0, length); return ret; }
// in src/java/org/apache/fop/fonts/truetype/TTFFontLoader.java
private void read(String ttcFontName) throws IOException { InputStream in = openFontUri(resolver, this.fontFileURI); try { TTFFile ttf = new TTFFile(useKerning, useAdvanced); FontFileReader reader = new FontFileReader(in); boolean supported = ttf.readFont(reader, ttcFontName); if (!supported) { throw new IOException("TrueType font is not supported: " + fontFileURI); } buildFont(ttf, ttcFontName); loaded = true; } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/render/print/PrintRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); try { printerJob.print(); } catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); } clearViewportList(); }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addDefaultOutputProfile() throws IOException { if (this.outputProfile != null) { return; } ICC_Profile profile; InputStream in = null; if (this.outputProfileURI != null) { this.outputProfile = pdfDoc.getFactory().makePDFICCStream(); Source src = getUserAgent().resolveURI(this.outputProfileURI); if (src == null) { throw new IOException("Output profile not found: " + this.outputProfileURI); } if (src instanceof StreamSource) { in = ((StreamSource)src).getInputStream(); } else { in = new URL(src.getSystemId()).openStream(); } try { profile = ColorProfileUtil.getICC_Profile(in); } finally { IOUtils.closeQuietly(in); } this.outputProfile.setColorSpace(profile, null); } else { //Fall back to sRGB profile outputProfile = sRGBColorSpace.getICCStream(); } }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PCLRenderingContext pclContext = (PCLRenderingContext)context; ImageGraphics2D imageG2D = (ImageGraphics2D)image; Dimension imageDim = imageG2D.getSize().getDimensionMpt(); PCLGenerator gen = pclContext.getPCLGenerator(); Point2D transPoint = pclContext.transformedPoint(pos.x, pos.y); gen.setCursorPos(transPoint.getX(), transPoint.getY()); boolean painted = false; ByteArrayOutputStream baout = new ByteArrayOutputStream(); PCLGenerator tempGen = new PCLGenerator(baout, gen.getMaximumBitmapResolution()); tempGen.setDitheringQuality(gen.getDitheringQuality()); try { GraphicContext ctx = (GraphicContext)pclContext.getGraphicContext().clone(); AffineTransform prepareHPGL2 = new AffineTransform(); prepareHPGL2.scale(0.001, 0.001); ctx.setTransform(prepareHPGL2); PCLGraphics2D graphics = new PCLGraphics2D(tempGen); graphics.setGraphicContext(ctx); graphics.setClippingDisabled(false /*pclContext.isClippingDisabled()*/); Rectangle2D area = new Rectangle2D.Double( 0.0, 0.0, imageDim.getWidth(), imageDim.getHeight()); imageG2D.getGraphics2DImagePainter().paint(graphics, area); //If we arrive here, the graphic is natively paintable, so write the graphic gen.writeCommand("*c" + gen.formatDouble4(pos.width / 100f) + "x" + gen.formatDouble4(pos.height / 100f) + "Y"); gen.writeCommand("*c0T"); gen.enterHPGL2Mode(false); gen.writeText("\nIN;"); gen.writeText("SP1;"); //One Plotter unit is 0.025mm! double scale = imageDim.getWidth() / UnitConv.mm2pt(imageDim.getWidth() * 0.025); gen.writeText("SC0," + gen.formatDouble4(scale) + ",0,-" + gen.formatDouble4(scale) + ",2;"); gen.writeText("IR0,100,0,100;"); gen.writeText("PU;PA0,0;\n"); baout.writeTo(gen.getOutputStream()); //Buffer is written to output stream gen.writeText("\n"); gen.enterPCLMode(false); painted = true; } catch (UnsupportedOperationException uoe) { log.debug( "Cannot paint graphic natively. Falling back to bitmap painting. Reason: " + uoe.getMessage()); } if (!painted) { //Fallback solution: Paint to a BufferedImage FOUserAgent ua = context.getUserAgent(); ImageManager imageManager = ua.getFactory().getImageManager(); ImageRendered imgRend; try { imgRend = (ImageRendered)imageManager.convertImage( imageG2D, new ImageFlavor[] {ImageFlavor.RENDERED_IMAGE}/*, hints*/); } catch (ImageException e) { throw new IOException( "Image conversion error while converting the image to a bitmap" + " as a fallback measure: " + e.getMessage()); } gen.paintBitmap(imgRend.getRenderedImage(), new Dimension(pos.width, pos.height), pclContext.isSourceTransparencyEnabled()); } }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
public void processEvent(DSCEvent event, DSCParser parser) throws IOException, DSCException { if (event.isDSCComment() && event instanceof DSCCommentIncludeResource) { DSCCommentIncludeResource include = (DSCCommentIncludeResource)event; PSResource res = include.getResource(); if (res.getType().equals(PSResource.TYPE_FORM)) { if (inlineFormResources.containsValue(res)) { PSImageFormResource form = (PSImageFormResource) inlineFormResources.get(res); //Create an inline form //Wrap in save/restore pair to release memory gen.writeln("save"); generateFormForImage(gen, form); boolean execformFound = false; DSCEvent next = parser.nextEvent(); if (next.isLine()) { PostScriptLine line = next.asLine(); if (line.getLine().endsWith(" execform")) { line.generate(gen); execformFound = true; } } if (!execformFound) { throw new IOException( "Expected a PostScript line in the form: <form> execform"); } gen.writeln("restore"); } else { //Do nothing } parser.next(); } } }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
private CharacterSet processFont(String characterSetName, String codePageName, String encoding, CharacterSetType charsetType, ResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException { // check for cached version of the characterset String descriptor = characterSetName + "_" + encoding + "_" + codePageName; CharacterSet characterSet = (CharacterSet) characterSetsCache.get(descriptor); if (characterSet != null) { return characterSet; } // characterset not in the cache, so recreating characterSet = new CharacterSet(codePageName, encoding, charsetType, characterSetName, accessor, eventProducer); InputStream inputStream = null; try { /** * Get the code page which contains the character mapping * information to map the unicode character id to the graphic * chracter global identifier. */ Map<String, String> codePage; synchronized (codePagesCache) { codePage = codePagesCache.get(codePageName); if (codePage == null) { codePage = loadCodePage(codePageName, encoding, accessor, eventProducer); codePagesCache.put(codePageName, codePage); } } inputStream = openInputStream(accessor, characterSetName, eventProducer); StructuredFieldReader structuredFieldReader = new StructuredFieldReader(inputStream); // Process D3A689 Font Descriptor FontDescriptor fontDescriptor = processFontDescriptor(structuredFieldReader); characterSet.setNominalVerticalSize(fontDescriptor.getNominalFontSizeInMillipoints()); // Process D3A789 Font Control FontControl fontControl = processFontControl(structuredFieldReader); if (fontControl != null) { //process D3AE89 Font Orientation CharacterSetOrientation[] characterSetOrientations = processFontOrientation(structuredFieldReader); double metricNormalizationFactor; if (fontControl.isRelative()) { metricNormalizationFactor = 1; } else { int dpi = fontControl.getDpi(); metricNormalizationFactor = 1000.0d * 72000.0d / fontDescriptor.getNominalFontSizeInMillipoints() / dpi; } //process D3AC89 Font Position processFontPosition(structuredFieldReader, characterSetOrientations, metricNormalizationFactor); //process D38C89 Font Index (per orientation) for (int i = 0; i < characterSetOrientations.length; i++) { processFontIndex(structuredFieldReader, characterSetOrientations[i], codePage, metricNormalizationFactor); characterSet.addCharacterSetOrientation(characterSetOrientations[i]); } } else { throw new IOException("Missing D3AE89 Font Control structured field."); } } finally { closeInputStream(inputStream); } characterSetsCache.put(descriptor, characterSet); return characterSet; }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void createIncludedResource(String resourceName, ResourceAccessor accessor, byte resourceObjectType) throws IOException { URI uri; try { uri = new URI(resourceName.trim()); } catch (URISyntaxException e) { throw new IOException("Could not create URI from resource name: " + resourceName + " (" + e.getMessage() + ")"); } createIncludedResource(resourceName, uri, accessor, resourceObjectType); }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
public static void copyNamedResource(String name, final InputStream in, final OutputStream out) throws IOException { final MODCAParser parser = new MODCAParser(in); Collection<String> resourceNames = new java.util.HashSet<String>(); //Find matching "Begin" field final UnparsedStructuredField fieldBegin; while (true) { final UnparsedStructuredField field = parser.readNextStructuredField(); if (field == null) { throw new IOException("Requested resource '" + name + "' not found. Encountered resource names: " + resourceNames); } if (field.getSfTypeCode() != TYPE_CODE_BEGIN) { //0xA8=Begin continue; //Not a "Begin" field } final String resourceName = getResourceName(field); resourceNames.add(resourceName); if (resourceName.equals(name)) { if (LOG.isDebugEnabled()) { LOG.debug("Start of requested structured field found:\n" + field); } fieldBegin = field; break; //Name doesn't match } } //Decide whether the resource file has to be wrapped in a resource object boolean wrapInResource; if (fieldBegin.getSfCategoryCode() == Category.PAGE_SEGMENT) { //A naked page segment must be wrapped in a resource object wrapInResource = true; } else if (fieldBegin.getSfCategoryCode() == Category.NAME_RESOURCE) { //A resource object can be copied directly wrapInResource = false; } else { throw new IOException("Cannot handle resource: " + fieldBegin); } //Copy structured fields (wrapped or as is) if (wrapInResource) { ResourceObject resourceObject = new ResourceObject(name) { protected void writeContent(OutputStream os) throws IOException { copyNamedStructuredFields(name, fieldBegin, parser, out); } }; resourceObject.setType(ResourceObject.TYPE_PAGE_SEGMENT); resourceObject.writeToStream(out); } else { copyNamedStructuredFields(name, fieldBegin, parser, out); } }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
private static void copyNamedStructuredFields(final String name, UnparsedStructuredField fieldBegin, MODCAParser parser, OutputStream out) throws IOException { UnparsedStructuredField field = fieldBegin; while (true) { if (field == null) { throw new IOException("Ending structured field not found for resource " + name); } out.write(MODCAParser.CARRIAGE_CONTROL_CHAR); field.writeTo(out); if (field.getSfTypeCode() == TYPE_CODE_END && fieldBegin.getSfCategoryCode() == field.getSfCategoryCode() && name.equals(getResourceName(field))) { break; } field = parser.readNextStructuredField(); } }
// in src/java/org/apache/fop/events/model/EventModel.java
private void writeXMLizable(XMLizable object, File outputFile) throws IOException { //These two approaches do not seem to work in all environments: //Result res = new StreamResult(outputFile); //Result res = new StreamResult(outputFile.toURI().toURL().toExternalForm()); //With an old Xalan version: file:/C:/.... --> file:\C:\..... OutputStream out = new java.io.FileOutputStream(outputFile); out = new java.io.BufferedOutputStream(out); Result res = new StreamResult(out); try { SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler handler = tFactory.newTransformerHandler(); Transformer transformer = handler.getTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); handler.setResult(res); handler.startDocument(); object.toSAX(handler); handler.endDocument(); } catch (TransformerConfigurationException e) { throw new IOException(e.getMessage()); } catch (TransformerFactoryConfigurationError e) { throw new IOException(e.getMessage()); } catch (SAXException e) { throw new IOException(e.getMessage()); } finally { IOUtils.closeQuietly(out); } }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
protected void updateTranslationFile(File modelFile) throws IOException { try { boolean resultExists = getTranslationFile().exists(); SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); //Generate fresh generated translation file as template Source src = new StreamSource(modelFile.toURI().toURL().toExternalForm()); StreamSource xslt1 = new StreamSource( getClass().getResourceAsStream(MODEL2TRANSLATION)); if (xslt1.getInputStream() == null) { throw new FileNotFoundException(MODEL2TRANSLATION + " not found"); } DOMResult domres = new DOMResult(); Transformer transformer = tFactory.newTransformer(xslt1); transformer.transform(src, domres); final Node generated = domres.getNode(); Node sourceDocument; if (resultExists) { //Load existing translation file into memory (because we overwrite it later) src = new StreamSource(getTranslationFile().toURI().toURL().toExternalForm()); domres = new DOMResult(); transformer = tFactory.newTransformer(); transformer.transform(src, domres); sourceDocument = domres.getNode(); } else { //Simply use generated as source document sourceDocument = generated; } //Generate translation file (with potentially new translations) src = new DOMSource(sourceDocument); //The following triggers a bug in older Xalan versions //Result res = new StreamResult(getTranslationFile()); OutputStream out = new java.io.FileOutputStream(getTranslationFile()); out = new java.io.BufferedOutputStream(out); Result res = new StreamResult(out); try { StreamSource xslt2 = new StreamSource( getClass().getResourceAsStream(MERGETRANSLATION)); if (xslt2.getInputStream() == null) { throw new FileNotFoundException(MERGETRANSLATION + " not found"); } transformer = tFactory.newTransformer(xslt2); transformer.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { if ("my:dom".equals(href)) { return new DOMSource(generated); } return null; } }); if (resultExists) { transformer.setParameter("generated-url", "my:dom"); } transformer.transform(src, res); if (resultExists) { log("Translation file updated: " + getTranslationFile()); } else { log("Translation file generated: " + getTranslationFile()); } } finally { IOUtils.closeQuietly(out); } } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
12
              
// in src/sandbox/org/apache/fop/render/svg/SVGDataUrlImageHandler.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (TransformerConfigurationException tce) { throw new IOException("Error setting up Transformer for XMP stream serialization: " + tce.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (SAXException saxe) { throw new IOException("Error while serializing XMP stream: " + saxe.getMessage()); }
// in src/java/org/apache/fop/render/print/PrintRenderer.java
catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
catch (ImageException e) { throw new IOException( "Image conversion error while converting the image to a bitmap" + " as a fallback measure: " + e.getMessage()); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
catch (URISyntaxException e) { throw new IOException("Could not create URI from resource name: " + resourceName + " (" + e.getMessage() + ")"); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerConfigurationException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerFactoryConfigurationError e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (TransformerException e) { throw new IOException("Error while parsing XML resource bundle: " + e.getMessage()); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
1022
              
// in src/sandbox/org/apache/fop/render/svg/SVGRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { this.firstOutputStream = outputStream; this.multiFileUtil = new MultiFileRenderingUtil(SVG_FILE_EXTENSION, getUserAgent().getOutputFile()); super.startRenderer(this.firstOutputStream); }
// in src/sandbox/org/apache/fop/render/svg/SVGRenderer.java
public void renderPage(PageViewport pageViewport) throws IOException { log.debug("Rendering page: " + pageViewport.getPageNumberString()); // Get a DOMImplementation DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); // Create an instance of org.w3c.dom.Document this.document = domImpl.createDocument(null, "svg", null); // Create an SVGGeneratorContext to customize SVG generation SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(this.document); ctx.setComment("Generated by " + userAgent.getProducer() + " with Batik SVG Generator"); ctx.setEmbeddedFontsOn(true); // Create an instance of the SVG Generator this.svgGenerator = new SVGGraphics2D(ctx, true); Rectangle2D viewArea = pageViewport.getViewArea(); Dimension dim = new Dimension(); dim.setSize(viewArea.getWidth() / 1000, viewArea.getHeight() / 1000); this.svgGenerator.setSVGCanvasSize(dim); AffineTransform at = this.svgGenerator.getTransform(); this.state = new Java2DGraphicsState(this.svgGenerator, this.fontInfo, at); try { //super.renderPage(pageViewport); renderPageAreas(pageViewport.getPage()); } finally { this.state = null; } writeSVGFile(pageViewport.getPageIndex()); this.svgGenerator = null; this.document = null; }
// in src/sandbox/org/apache/fop/render/svg/SVGRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); // Cleaning clearViewportList(); log.debug("SVG generation complete."); }
// in src/sandbox/org/apache/fop/render/svg/SVGRenderer.java
private void writeSVGFile(int pageNumber) throws IOException { log.debug("Writing out SVG file..."); // Finally, stream out SVG to the standard output using UTF-8 // character to byte encoding boolean useCSS = true; // we want to use CSS style attribute OutputStream out = getCurrentOutputStream(pageNumber); if (out == null) { log.warn("No filename information available." + " Stopping early after the first page."); return; } try { Writer writer = new java.io.OutputStreamWriter(out, "UTF-8"); this.svgGenerator.stream(writer, useCSS); } finally { if (out != this.firstOutputStream) { IOUtils.closeQuietly(out); } else { out.flush(); } } }
// in src/sandbox/org/apache/fop/render/svg/SVGRenderer.java
protected OutputStream getCurrentOutputStream(int pageNumber) throws IOException { if (pageNumber == 0) { return firstOutputStream; } else { return multiFileUtil.createOutputStream(pageNumber); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDataUrlImageHandler.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { SVGRenderingContext svgContext = (SVGRenderingContext)context; ImageRawStream raw = (ImageRawStream)image; InputStream in = raw.createInputStream(); try { ContentHandler handler = svgContext.getContentHandler(); String url = DataURLUtil.createDataURL(in, raw.getMimeType()); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, IFConstants.XLINK_HREF, url); atts.addAttribute("", "x", "x", CDATA, Integer.toString(pos.x)); atts.addAttribute("", "y", "y", CDATA, Integer.toString(pos.y)); atts.addAttribute("", "width", "width", CDATA, Integer.toString(pos.width)); atts.addAttribute("", "height", "height", CDATA, Integer.toString(pos.height)); try { handler.startElement(NAMESPACE, "image", "image", atts); handler.endElement(NAMESPACE, "image", "image"); } catch (SAXException e) { throw new IOException(e.getMessage()); } } finally { IOUtils.closeQuietly(in); } }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
public void handleImage(RenderingContext context, Image image, final Rectangle pos) throws IOException { SVGRenderingContext svgContext = (SVGRenderingContext)context; ImageXMLDOM svg = (ImageXMLDOM)image; ContentHandler handler = svgContext.getContentHandler(); AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "x", "x", CDATA, SVGUtil.formatMptToPt(pos.x)); atts.addAttribute("", "y", "y", CDATA, SVGUtil.formatMptToPt(pos.y)); atts.addAttribute("", "width", "width", CDATA, SVGUtil.formatMptToPt(pos.width)); atts.addAttribute("", "height", "height", CDATA, SVGUtil.formatMptToPt(pos.height)); try { Document doc = (Document)svg.getDocument(); Element svgEl = (Element)doc.getDocumentElement(); if (svgEl.getAttribute("viewBox").length() == 0) { log.warn("SVG doesn't have a viewBox. The result might not be scaled correctly!"); } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource src = new DOMSource(svg.getDocument()); SAXResult res = new SAXResult(new DelegatingFragmentContentHandler(handler) { private boolean topLevelSVGFound = false; private void setAttribute(AttributesImpl atts, String localName, String value) { int index; index = atts.getIndex("", localName); if (index < 0) { atts.addAttribute("", localName, localName, CDATA, value); } else { atts.setAttribute(index, "", localName, localName, CDATA, value); } } public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { if (!topLevelSVGFound && SVG_ELEMENT.getNamespaceURI().equals(uri) && SVG_ELEMENT.getLocalName().equals(localName)) { topLevelSVGFound = true; AttributesImpl modAtts = new AttributesImpl(atts); setAttribute(modAtts, "x", SVGUtil.formatMptToPt(pos.x)); setAttribute(modAtts, "y", SVGUtil.formatMptToPt(pos.y)); setAttribute(modAtts, "width", SVGUtil.formatMptToPt(pos.width)); setAttribute(modAtts, "height", SVGUtil.formatMptToPt(pos.height)); super.startElement(uri, localName, name, modAtts); } else { super.startElement(uri, localName, name, atts); } } }); transformer.transform(src, res); } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
// in src/sandbox/org/apache/fop/render/mif/MIFFile.java
public void output(OutputStream os) throws IOException { if (finished) { return; } if (!started) { os.write(("<MIFFile 5.00> # Generated by FOP\n"/* + getVersion()*/).getBytes()); started = true; } boolean done = true; for (Iterator iter = valueElements.iterator(); iter.hasNext();) { MIFElement el = (MIFElement)iter.next(); boolean d = el.output(os, 0); if (d) { iter.remove(); } else { done = false; break; } } if (done && finish) { os.write(("# end of MIFFile").getBytes()); } }
// in src/sandbox/org/apache/fop/render/mif/MIFElement.java
public boolean output(OutputStream os, int indent) throws IOException { if (finished) { return true; } if (valueElements == null && valueStr == null) { return false; } String indentStr = ""; for (int c = 0; c < indent; c++) { indentStr += " "; } if (!started) { os.write((indentStr + "<" + name).getBytes()); if (valueElements != null) { os.write(("\n").getBytes()); } started = true; } if (valueElements != null) { boolean done = true; for (Iterator iter = valueElements.iterator(); iter.hasNext();) { MIFElement el = (MIFElement)iter.next(); boolean d = el.output(os, indent + 1); if (d) { iter.remove(); } else { done = false; break; } } if (!finish || !done) { return false; } os.write((indentStr + "> # end of " + name + "\n").getBytes()); } else { os.write((" " + valueStr + ">\n").getBytes()); } finished = true; return true; }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setUserConfig(File userConfigFile) throws SAXException, IOException { config.setUserConfig(userConfigFile); }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setUserConfig(String uri) throws SAXException, IOException { config.setUserConfig(uri); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(File userConfigFile) throws SAXException, IOException { try { DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); setUserConfig(cfgBuilder.buildFromFile(userConfigFile)); } catch (ConfigurationException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(String uri) throws SAXException, IOException { try { DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); setUserConfig(cfgBuilder.build(uri)); } catch (ConfigurationException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
public OutputStream applyFilter(OutputStream out) throws IOException { byte[] key = createEncryptionKey(streamNumber, streamGeneration); Cipher cipher = initCipher(key); return new CipherOutputStream(out, cipher); }
// in src/java/org/apache/fop/pdf/PDFCMap.java
public int output(OutputStream stream) throws IOException { CMapBuilder builder = createCMapBuilder(getBufferWriter()); builder.writeCMap(); return super.output(stream); }
// in src/java/org/apache/fop/pdf/PDFObject.java
public int output(OutputStream stream) throws IOException { byte[] pdf = this.toPDF(); stream.write(pdf); return pdf.length; }
// in src/java/org/apache/fop/pdf/PDFObject.java
public void outputInline(OutputStream out, Writer writer) throws IOException { throw new UnsupportedOperationException("Don't use anymore: " + getClass().getName()); }
// in src/java/org/apache/fop/pdf/PDFObject.java
public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { if (hasObjectNumber()) { textBuffer.append(referencePDF()); } else { PDFDocument.flushTextBuffer(textBuffer, out); output(out); } }
// in src/java/org/apache/fop/pdf/PDFObject.java
protected void encodeBinaryToHexString(byte[] data, OutputStream out) throws IOException { out.write('<'); if (getDocumentSafely().isEncryptionActive()) { data = getDocument().getEncryption().encrypt(data, this); } String hex = PDFText.toHex(data, false); byte[] encoded = hex.getBytes("US-ASCII"); out.write(encoded); out.write('>'); }
// in src/java/org/apache/fop/pdf/PDFObject.java
protected void formatObject(Object obj, OutputStream out, StringBuilder textBuffer) throws IOException { if (obj == null) { textBuffer.append("null"); } else if (obj instanceof PDFWritable) { ((PDFWritable)obj).outputInline(out, textBuffer); } else if (obj instanceof Number) { if (obj instanceof Double || obj instanceof Float) { textBuffer.append(PDFNumber.doubleOut(((Number)obj).doubleValue())); } else { textBuffer.append(obj.toString()); } } else if (obj instanceof Boolean) { textBuffer.append(obj.toString()); } else if (obj instanceof byte[]) { PDFDocument.flushTextBuffer(textBuffer, out); encodeBinaryToHexString((byte[])obj, out); } else { PDFDocument.flushTextBuffer(textBuffer, out); out.write(encodeText(obj.toString())); } }
// in src/java/org/apache/fop/pdf/PDFFormXObject.java
public void setData(byte[] data) throws IOException { this.contents.setData(data); }
// in src/java/org/apache/fop/pdf/PDFFormXObject.java
protected void outputRawStreamData(OutputStream out) throws IOException { contents.outputRawStreamData(out); }
// in src/java/org/apache/fop/pdf/PDFFormXObject.java
public int output(OutputStream stream) throws IOException { final int len = super.output(stream); //Now that the data has been written, it can be discarded. this.contents = null; return len; }
// in src/java/org/apache/fop/pdf/PDFRoot.java
public int output(OutputStream stream) throws IOException { getDocument().getProfile().verifyTaggedPDF(); return super.output(stream); }
// in src/java/org/apache/fop/pdf/ASCII85Filter.java
public OutputStream applyFilter(OutputStream out) throws IOException { if (isApplied()) { return out; } else { return new ASCII85OutputStream(out); } }
// in src/java/org/apache/fop/pdf/PDFRectangle.java
public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { format(textBuffer); }
// in src/java/org/apache/fop/pdf/PDFPattern.java
public int output(OutputStream stream) throws IOException { int vectorSize = 0; int tempInt = 0; byte[] buffer; StringBuffer p = new StringBuffer(64); p.append("<< \n/Type /Pattern \n"); if (this.resources != null) { p.append("/Resources " + this.resources.referencePDF() + " \n"); } p.append("/PatternType " + this.patternType + " \n"); PDFStream pdfStream = null; StreamCache encodedStream = null; if (this.patternType == 1) { p.append("/PaintType " + this.paintType + " \n"); p.append("/TilingType " + this.tilingType + " \n"); if (this.bBox != null) { vectorSize = this.bBox.size(); p.append("/BBox [ "); for (tempInt = 0; tempInt < vectorSize; tempInt++) { p.append(PDFNumber.doubleOut((Double)this.bBox.get(tempInt))); p.append(" "); } p.append("] \n"); } p.append("/XStep " + PDFNumber.doubleOut(new Double(this.xStep)) + " \n"); p.append("/YStep " + PDFNumber.doubleOut(new Double(this.yStep)) + " \n"); if (this.matrix != null) { vectorSize = this.matrix.size(); p.append("/Matrix [ "); for (tempInt = 0; tempInt < vectorSize; tempInt++) { p.append(PDFNumber.doubleOut( ((Double)this.matrix.get(tempInt)).doubleValue(), 8)); p.append(" "); } p.append("] \n"); } if (this.xUID != null) { vectorSize = this.xUID.size(); p.append("/XUID [ "); for (tempInt = 0; tempInt < vectorSize; tempInt++) { p.append(((Integer)this.xUID.get(tempInt)) + " "); } p.append("] \n"); } // don't forget the length of the stream. if (this.patternDataStream != null) { pdfStream = new PDFStream(); pdfStream.setDocument(getDocumentSafely()); pdfStream.add(this.patternDataStream.toString()); pdfStream.getFilterList().addDefaultFilters( getDocument().getFilterMap(), PDFFilterList.CONTENT_FILTER); encodedStream = pdfStream.encodeStream(); p.append(pdfStream.getFilterList().buildFilterDictEntries()); p.append("/Length " + (encodedStream.getSize() + 1) + " \n"); } } else { // if (this.patternType ==2) // Smooth Shading... if (this.shading != null) { p.append("/Shading " + this.shading.referencePDF() + " \n"); } if (this.xUID != null) { vectorSize = this.xUID.size(); p.append("/XUID [ "); for (tempInt = 0; tempInt < vectorSize; tempInt++) { p.append(((Integer)this.xUID.get(tempInt)) + " "); } p.append("] \n"); } if (this.extGState != null) { p.append("/ExtGState " + this.extGState + " \n"); } if (this.matrix != null) { vectorSize = this.matrix.size(); p.append("/Matrix [ "); for (tempInt = 0; tempInt < vectorSize; tempInt++) { p.append(PDFNumber.doubleOut( ((Double)this.matrix.get(tempInt)).doubleValue(), 8)); p.append(" "); } p.append("] \n"); } } // end of if patterntype =1...else 2. p.append(">> \n"); buffer = encode(p.toString()); int length = buffer.length; stream.write(buffer); // stream representing the function if (pdfStream != null) { length += pdfStream.outputStreamData(encodedStream, stream); } return length; }
// in src/java/org/apache/fop/pdf/FlateFilter.java
public OutputStream applyFilter(OutputStream out) throws IOException { if (isApplied()) { return out; } else { return new FlateEncodeOutputStream(out); } }
// in src/java/org/apache/fop/pdf/PDFEmbeddedFiles.java
protected void writeDictionary(OutputStream out, StringBuilder textBuffer) throws IOException { sortNames(); //Sort the names before writing them out super.writeDictionary(out, textBuffer); }
// in src/java/org/apache/fop/pdf/PDFStream.java
private void flush() throws IOException { this.streamWriter.flush(); }
// in src/java/org/apache/fop/pdf/PDFStream.java
public OutputStream getBufferOutputStream() throws IOException { if (this.streamWriter != null) { flush(); //Just to be sure } return this.data.getOutputStream(); }
// in src/java/org/apache/fop/pdf/PDFStream.java
public void setData(byte[] data) throws IOException { this.data.clear(); this.data.write(data); }
// in src/java/org/apache/fop/pdf/PDFStream.java
protected int getSizeHint() throws IOException { flush(); return data.getSize(); }
// in src/java/org/apache/fop/pdf/PDFStream.java
protected void outputRawStreamData(OutputStream out) throws IOException { flush(); data.outputContents(out); }
// in src/java/org/apache/fop/pdf/PDFStream.java
public int output(OutputStream stream) throws IOException { final int len = super.output(stream); //Now that the data has been written, it can be discarded. this.data = null; return len; }
// in src/java/org/apache/fop/pdf/PDFICCStream.java
Override public int output(java.io.OutputStream stream) throws java.io.IOException { int length = super.output(stream); this.cp = null; //Free ICC stream when it's not used anymore return length; }
// in src/java/org/apache/fop/pdf/PDFICCStream.java
Override protected void outputRawStreamData(OutputStream out) throws IOException { cp.write(out); }
// in src/java/org/apache/fop/pdf/PDFFont.java
public int output(OutputStream stream) throws IOException { validate(); return super.output(stream); }
// in src/java/org/apache/fop/pdf/ObjectStream.java
Override protected void outputRawStreamData(OutputStream out) throws IOException { int currentOffset = 0; StringBuilder offsetsPart = new StringBuilder(); ByteArrayOutputStream streamContent = new ByteArrayOutputStream(); for (CompressedObject object : objects) { offsetsPart.append(object.getObjectNumber()) .append(' ') .append(currentOffset) .append('\n'); currentOffset += object.output(streamContent); } byte[] offsets = PDFDocument.encode(offsetsPart.toString()); firstObjectOffset = offsets.length; out.write(offsets); streamContent.writeTo(out); }
// in src/java/org/apache/fop/pdf/PDFStructElem.java
Override protected void writeDictionary(OutputStream out, StringBuilder textBuffer) throws IOException { attachKids(); super.writeDictionary(out, textBuffer); }
// in src/java/org/apache/fop/pdf/PDFStructElem.java
Override public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { if (kids != null) { assert kids.size() > 0; for (int i = 0; i < kids.size(); i++) { if (i > 0) { textBuffer.append(' '); } Object obj = kids.get(i); formatObject(obj, out, textBuffer); } } }
// in src/java/org/apache/fop/pdf/PDFDestination.java
Override public int output(OutputStream stream) throws IOException { CountingOutputStream cout = new CountingOutputStream(stream); StringBuilder textBuffer = new StringBuilder(64); formatObject(getIDRef(), cout, textBuffer); textBuffer.append(' '); formatObject(goToReference, cout, textBuffer); PDFDocument.flushTextBuffer(textBuffer, cout); return cout.getCount(); }
// in src/java/org/apache/fop/pdf/PDFResources.java
Override public int output(OutputStream stream) throws IOException { populateDictionary(); return super.output(stream); }
// in src/java/org/apache/fop/pdf/StreamCacheFactory.java
public StreamCache createStreamCache() throws IOException { if (this.cacheToFile) { return new TempFileStreamCache(); } else { return new InMemoryStreamCache(); } }
// in src/java/org/apache/fop/pdf/StreamCacheFactory.java
public StreamCache createStreamCache(int hintSize) throws IOException { if (this.cacheToFile) { return new TempFileStreamCache(); } else { return new InMemoryStreamCache(hintSize); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public static void flushTextBuffer(StringBuilder textBuffer, OutputStream out) throws IOException { out.write(encode(textBuffer.toString())); textBuffer.setLength(0); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void output(OutputStream stream) throws IOException { //Write out objects until the list is empty. This approach (used with a //LinkedList) allows for output() methods to create and register objects //on the fly even during serialization. while (this.objects.size() > 0) { PDFObject object = this.objects.remove(0); streamIndirectObject(object, stream); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
private void streamIndirectObject(PDFObject o, OutputStream stream) throws IOException { recordObjectOffset(o); this.position += outputIndirectObject(o, stream); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
private void streamIndirectObjects(Collection<? extends PDFObject> objects, OutputStream stream) throws IOException { for (PDFObject o : objects) { streamIndirectObject(o, stream); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public static int outputIndirectObject(PDFObject object, OutputStream stream) throws IOException { if (!object.hasObjectNumber()) { throw new IllegalArgumentException("Not an indirect object"); } byte[] obj = encode(object.getObjectID()); stream.write(obj); int length = object.output(stream); byte[] endobj = encode("\nendobj\n"); stream.write(endobj); return obj.length + length + endobj.length; }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void outputHeader(OutputStream stream) throws IOException { this.position = 0; getProfile().verifyPDFVersion(); byte[] pdf = encode("%PDF-" + getPDFVersionString() + "\n"); stream.write(pdf); this.position += pdf.length; // output a binary comment as recommended by the PDF spec (3.4.1) byte[] bin = { (byte)'%', (byte)0xAA, (byte)0xAB, (byte)0xAC, (byte)0xAD, (byte)'\n' }; stream.write(bin); this.position += bin.length; }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void outputTrailer(OutputStream stream) throws IOException { createDestinations(); output(stream); outputTrailerObjectsAndXref(stream); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
private void outputTrailerObjectsAndXref(OutputStream stream) throws IOException { TrailerOutputHelper trailerOutputHelper = mayCompressStructureTreeElements() ? new CompressedTrailerOutputHelper() : new UncompressedTrailerOutputHelper(); if (structureTreeElements != null) { trailerOutputHelper.outputStructureTreeElements(stream); } streamIndirectObjects(trailerObjects, stream); TrailerDictionary trailerDictionary = createTrailerDictionary(); long startxref = trailerOutputHelper.outputCrossReferenceObject(stream, trailerDictionary); String trailer = "startxref\n" + startxref + "\n%%EOF\n"; stream.write(encode(trailer)); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void outputStructureTreeElements(OutputStream stream) throws IOException { streamIndirectObjects(structureTreeElements, stream); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public long outputCrossReferenceObject(OutputStream stream, TrailerDictionary trailerDictionary) throws IOException { new CrossReferenceTable(trailerDictionary, position, indirectObjectOffsets).output(stream); return position; }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void outputStructureTreeElements(OutputStream stream) throws IOException { assert structureTreeElements.size() > 0; structureTreeObjectStreams = new ObjectStreamManager(PDFDocument.this); for (PDFStructElem structElem : structureTreeElements) { structureTreeObjectStreams.add(structElem); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public long outputCrossReferenceObject(OutputStream stream, TrailerDictionary trailerDictionary) throws IOException { // Outputting the object streams should not have created new indirect objects assert objects.isEmpty(); new CrossReferenceStream(PDFDocument.this, ++objectcount, trailerDictionary, position, indirectObjectOffsets, structureTreeObjectStreams.getCompressedObjectReferences()) .output(stream); return position; }
// in src/java/org/apache/fop/pdf/PDFNumsArray.java
Override public int output(OutputStream stream) throws IOException { CountingOutputStream cout = new CountingOutputStream(stream); StringBuilder textBuffer = new StringBuilder(64); textBuffer.append('['); boolean first = true; for (Map.Entry<Integer, Object> entry : this.map.entrySet()) { if (!first) { textBuffer.append(" "); } first = false; formatObject(entry.getKey(), cout, textBuffer); textBuffer.append(" "); formatObject(entry.getValue(), cout, textBuffer); } textBuffer.append(']'); PDFDocument.flushTextBuffer(textBuffer, cout); return cout.getCount(); }
// in src/java/org/apache/fop/pdf/PDFNull.java
public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { textBuffer.append(toString()); }
// in src/java/org/apache/fop/pdf/ASCIIHexFilter.java
public OutputStream applyFilter(OutputStream out) throws IOException { if (isApplied()) { return out; } else { return new ASCIIHexOutputStream(out); } }
// in src/java/org/apache/fop/pdf/PDFToUnicodeCMap.java
public void writeCMap() throws IOException { writeCIDInit(); writeCIDSystemInfo("Adobe", "UCS", 0); writeName("Adobe-Identity-UCS"); writeType("2"); writeCodeSpaceRange(singleByte); writeBFEntries(); writeWrapUp(); }
// in src/java/org/apache/fop/pdf/PDFToUnicodeCMap.java
protected void writeBFEntries() throws IOException { if (unicodeCharMap != null) { writeBFCharEntries(unicodeCharMap); writeBFRangeEntries(unicodeCharMap); } }
// in src/java/org/apache/fop/pdf/PDFToUnicodeCMap.java
protected void writeBFCharEntries(char[] charArray) throws IOException { int totalEntries = 0; for (int i = 0; i < charArray.length; i++) { if (!partOfRange(charArray, i)) { totalEntries++; } } if (totalEntries < 1) { return; } int remainingEntries = totalEntries; int charIndex = 0; do { /* Limited to 100 entries in each section */ int entriesThisSection = Math.min(remainingEntries, 100); writer.write(entriesThisSection + " beginbfchar\n"); for (int i = 0; i < entriesThisSection; i++) { /* Go to the next char not in a range */ while (partOfRange(charArray, charIndex)) { charIndex++; } writer.write("<" + padCharIndex(charIndex) + "> "); writer.write("<" + padHexString(Integer.toHexString(charArray[charIndex]), 4) + ">\n"); charIndex++; } remainingEntries -= entriesThisSection; writer.write("endbfchar\n"); } while (remainingEntries > 0); }
// in src/java/org/apache/fop/pdf/PDFToUnicodeCMap.java
protected void writeBFRangeEntries(char[] charArray) throws IOException { int totalEntries = 0; for (int i = 0; i < charArray.length; i++) { if (startOfRange(charArray, i)) { totalEntries++; } } if (totalEntries < 1) { return; } int remainingEntries = totalEntries; int charIndex = 0; do { /* Limited to 100 entries in each section */ int entriesThisSection = Math.min(remainingEntries, 100); writer.write(entriesThisSection + " beginbfrange\n"); for (int i = 0; i < entriesThisSection; i++) { /* Go to the next start of a range */ while (!startOfRange(charArray, charIndex)) { charIndex++; } writer.write("<" + padCharIndex(charIndex) + "> "); writer.write("<" + padCharIndex(endOfRange(charArray, charIndex)) + "> "); writer.write("<" + padHexString(Integer.toHexString(charArray[charIndex]), 4) + ">\n"); charIndex++; } remainingEntries -= entriesThisSection; writer.write("endbfrange\n"); } while (remainingEntries > 0); }
// in src/java/org/apache/fop/pdf/PDFTTFStream.java
protected int getSizeHint() throws IOException { if (this.ttfData != null) { return ttfData.length; } else { return 0; //no hint available } }
// in src/java/org/apache/fop/pdf/PDFTTFStream.java
public int output(java.io.OutputStream stream) throws java.io.IOException { if (log.isDebugEnabled()) { log.debug("Writing " + origLength + " bytes of TTF font data"); } int length = super.output(stream); log.debug("Embedded TrueType/OpenType font"); return length; }
// in src/java/org/apache/fop/pdf/PDFTTFStream.java
protected void outputRawStreamData(OutputStream out) throws IOException { out.write(this.ttfData); }
// in src/java/org/apache/fop/pdf/PDFTTFStream.java
public void setData(byte[] data, int size) throws IOException { this.ttfData = new byte[size]; System.arraycopy(data, 0, this.ttfData, 0, size); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
public void writeCMap() throws IOException { writePreStream(); writeStreamComments(); writeCIDInit(); writeCIDSystemInfo(); writeVersion("1"); writeType("1"); writeName(name); writeCodeSpaceRange(); writeCIDRange(); writeBFEntries(); writeWrapUp(); writeStreamAfterComments(); writeUseCMap(); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writePreStream() throws IOException { // writer.write("/Type /CMap\n"); // writer.write(sysInfo.toPDFString()); // writer.write("/CMapName /" + name + EOL); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeStreamComments() throws IOException { writer.write("%!PS-Adobe-3.0 Resource-CMap\n"); writer.write("%%DocumentNeededResources: ProcSet (CIDInit)\n"); writer.write("%%IncludeResource: ProcSet (CIDInit)\n"); writer.write("%%BeginResource: CMap (" + name + ")\n"); writer.write("%%EndComments\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeCIDInit() throws IOException { writer.write("/CIDInit /ProcSet findresource begin\n"); writer.write("12 dict begin\n"); writer.write("begincmap\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeCIDSystemInfo(String registry, String ordering, int supplement) throws IOException { writer.write("/CIDSystemInfo 3 dict dup begin\n"); writer.write(" /Registry ("); writer.write(registry); writer.write(") def\n"); writer.write(" /Ordering ("); writer.write(ordering); writer.write(") def\n"); writer.write(" /Supplement "); writer.write(Integer.toString(supplement)); writer.write(" def\n"); writer.write("end def\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeCIDSystemInfo() throws IOException { writeCIDSystemInfo("Adobe", "Identity", 0); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeVersion(String version) throws IOException { writer.write("/CMapVersion "); writer.write(version); writer.write(" def\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeType(String type) throws IOException { writer.write("/CMapType "); writer.write(type); writer.write(" def\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeName(String name) throws IOException { writer.write("/CMapName /"); writer.write(name); writer.write(" def\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeCodeSpaceRange() throws IOException { writeCodeSpaceRange(false); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeCodeSpaceRange(boolean singleByte) throws IOException { writer.write("1 begincodespacerange\n"); if (singleByte) { writer.write("<00> <FF>\n"); } else { writer.write("<0000> <FFFF>\n"); } writer.write("endcodespacerange\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeCIDRange() throws IOException { writer.write("1 begincidrange\n"); writer.write("<0000> <FFFF> 0\n"); writer.write("endcidrange\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeBFEntries() throws IOException { // writer.write("1 beginbfrange\n"); // writer.write("<0020> <0100> <0000>\n"); // writer.write("endbfrange\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeWrapUp() throws IOException { writer.write("endcmap\n"); writer.write("CMapName currentdict /CMap defineresource pop\n"); writer.write("end\n"); writer.write("end\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeStreamAfterComments() throws IOException { writer.write("%%EndResource\n"); writer.write("%%EOF\n"); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
public int output(java.io.OutputStream stream) throws java.io.IOException { int length = super.output(stream); this.xmpMetadata = null; //Release DOM when it's not used anymore return length; }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
protected void outputRawStreamData(OutputStream out) throws IOException { try { XMPSerializer.writeXMPPacket(xmpMetadata, out, this.readOnly); } catch (TransformerConfigurationException tce) { throw new IOException("Error setting up Transformer for XMP stream serialization: " + tce.getMessage()); } catch (SAXException saxe) { throw new IOException("Error while serializing XMP stream: " + saxe.getMessage()); } }
// in src/java/org/apache/fop/pdf/AlphaRasterImage.java
public void outputContents(OutputStream out) throws IOException { int w = getWidth(); int h = getHeight(); //Check Raster int nbands = alpha.getNumBands(); if (nbands != 1) { throw new UnsupportedOperationException( "Expected only one band/component for the alpha channel"); } //...and write the Raster line by line with a reusable buffer int dataType = alpha.getDataBuffer().getDataType(); if (dataType == DataBuffer.TYPE_BYTE) { byte[] line = new byte[nbands * w]; for (int y = 0; y < h; y++) { alpha.getDataElements(0, y, w, 1, line); out.write(line); } } else if (dataType == DataBuffer.TYPE_USHORT) { short[] sline = new short[nbands * w]; byte[] line = new byte[nbands * w]; for (int y = 0; y < h; y++) { alpha.getDataElements(0, y, w, 1, sline); for (int i = 0; i < w; i++) { //this compresses a 16-bit alpha channel to 8 bits! //we probably don't ever need a 16-bit channel line[i] = (byte)(sline[i] >> 8); } out.write(line); } } else if (dataType == DataBuffer.TYPE_INT) { //Is there an better way to get a 8bit raster from a TYPE_INT raster? int shift = 24; SampleModel sampleModel = alpha.getSampleModel(); if (sampleModel instanceof SinglePixelPackedSampleModel) { SinglePixelPackedSampleModel m = (SinglePixelPackedSampleModel)sampleModel; shift = m.getBitOffsets()[0]; } int[] iline = new int[nbands * w]; byte[] line = new byte[nbands * w]; for (int y = 0; y < h; y++) { alpha.getDataElements(0, y, w, 1, iline); for (int i = 0; i < w; i++) { line[i] = (byte)(iline[i] >> shift); } out.write(line); } } else { throw new UnsupportedOperationException("Unsupported DataBuffer type: " + alpha.getDataBuffer().getClass().getName()); } }
// in src/java/org/apache/fop/pdf/TempFileStreamCache.java
public OutputStream getOutputStream() throws IOException { if (output == null) { output = new java.io.BufferedOutputStream( new java.io.FileOutputStream(tempFile)); } return output; }
// in src/java/org/apache/fop/pdf/TempFileStreamCache.java
public void write(byte[] data) throws IOException { getOutputStream().write(data); }
// in src/java/org/apache/fop/pdf/TempFileStreamCache.java
public int outputContents(OutputStream out) throws IOException { if (output == null) { return 0; } output.close(); output = null; // don't need a buffer because copy() is buffered InputStream input = new java.io.FileInputStream(tempFile); try { return IOUtils.copy(input, out); } finally { IOUtils.closeQuietly(input); } }
// in src/java/org/apache/fop/pdf/TempFileStreamCache.java
public int getSize() throws IOException { if (output != null) { output.flush(); } return (int) tempFile.length(); }
// in src/java/org/apache/fop/pdf/TempFileStreamCache.java
public void clear() throws IOException { if (output != null) { output.close(); output = null; } if (tempFile.exists()) { tempFile.delete(); } }
// in src/java/org/apache/fop/pdf/PDFXObject.java
protected int getSizeHint() throws IOException { return 0; }
// in src/java/org/apache/fop/pdf/PDFFilterList.java
public OutputStream applyFilters(OutputStream stream) throws IOException { OutputStream out = stream; if (!isDisableAllFilters()) { for (int count = filters.size() - 1; count >= 0; count--) { PDFFilter filter = (PDFFilter)filters.get(count); out = filter.applyFilter(out); } } return out; }
// in src/java/org/apache/fop/pdf/PDFImageXObject.java
public int output(OutputStream stream) throws IOException { int length = super.output(stream); // let it gc // this object is retained as a reference to inserting // the same image but the image data is no longer needed pdfimage = null; return length; }
// in src/java/org/apache/fop/pdf/PDFImageXObject.java
protected void outputRawStreamData(OutputStream out) throws IOException { pdfimage.outputContents(out); }
// in src/java/org/apache/fop/pdf/PDFImageXObject.java
protected int getSizeHint() throws IOException { return 0; }
// in src/java/org/apache/fop/pdf/AbstractPDFStream.java
protected int outputStreamData(StreamCache encodedStream, OutputStream out) throws IOException { int length = 0; byte[] p = encode("stream\n"); out.write(p); length += p.length; encodedStream.outputContents(out); length += encodedStream.getSize(); p = encode("\nendstream"); out.write(p); length += p.length; return length; }
// in src/java/org/apache/fop/pdf/AbstractPDFStream.java
protected StreamCache encodeStream() throws IOException { //Allocate a temporary buffer to find out the size of the encoded stream final StreamCache encodedStream = StreamCacheFactory.getInstance() .createStreamCache(getSizeHint()); OutputStream filteredOutput = getFilterList().applyFilters(encodedStream.getOutputStream()); outputRawStreamData(filteredOutput); filteredOutput.flush(); filteredOutput.close(); return encodedStream; }
// in src/java/org/apache/fop/pdf/AbstractPDFStream.java
protected int encodeAndWriteStream(OutputStream out, PDFNumber refLength) throws IOException { int bytesWritten = 0; //Stream header byte[] buf = encode("stream\n"); out.write(buf); bytesWritten += buf.length; //Stream contents CloseBlockerOutputStream cbout = new CloseBlockerOutputStream(out); CountingOutputStream cout = new CountingOutputStream(cbout); OutputStream filteredOutput = getFilterList().applyFilters(cout); outputRawStreamData(filteredOutput); filteredOutput.close(); refLength.setNumber(Integer.valueOf(cout.getCount())); bytesWritten += cout.getCount(); //Stream trailer buf = encode("\nendstream"); out.write(buf); bytesWritten += buf.length; return bytesWritten; }
// in src/java/org/apache/fop/pdf/AbstractPDFStream.java
Override public int output(OutputStream stream) throws IOException { setupFilterList(); CountingOutputStream cout = new CountingOutputStream(stream); StringBuilder textBuffer = new StringBuilder(64); StreamCache encodedStream = null; PDFNumber refLength = null; final Object lengthEntry; if (encodeOnTheFly) { refLength = new PDFNumber(); getDocumentSafely().registerObject(refLength); lengthEntry = refLength; } else { encodedStream = encodeStream(); lengthEntry = Integer.valueOf(encodedStream.getSize() + 1); } populateStreamDict(lengthEntry); dictionary.writeDictionary(cout, textBuffer); //Send encoded stream to target OutputStream PDFDocument.flushTextBuffer(textBuffer, cout); if (encodedStream == null) { encodeAndWriteStream(cout, refLength); } else { outputStreamData(encodedStream, cout); encodedStream.clear(); //Encoded stream can now be discarded } PDFDocument.flushTextBuffer(textBuffer, cout); return cout.getCount(); }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceStream.java
public void output(OutputStream stream) throws IOException { populateDictionary(); PDFStream helperStream = new PDFStream(trailerDictionary.getDictionary(), false) { @Override protected void setupFilterList() { PDFFilterList filterList = getFilterList(); assert !filterList.isInitialized(); filterList.addDefaultFilters(document.getFilterMap(), getDefaultFilterName()); } }; helperStream.setObjectNumber(objectNumber); helperStream.setDocument(document); ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(byteArray); addFreeEntryForObject0(data); for (ObjectReference objectReference : objectReferences) { assert objectReference != null; objectReference.output(data); } new UncompressedObjectReference(startxref).output(data); data.close(); helperStream.setData(byteArray.toByteArray()); PDFDocument.outputIndirectObject(helperStream, stream); }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceStream.java
private void populateDictionary() throws IOException { int objectCount = objectReferences.size() + 1; PDFDictionary dictionary = trailerDictionary.getDictionary(); dictionary.put("/Type", XREF); dictionary.put("/Size", objectCount + 1); dictionary.put("/W", new PDFArray(1, 8, 2)); }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceStream.java
private void addFreeEntryForObject0(DataOutputStream data) throws IOException { data.write(new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xff, (byte) 0xff}); }
// in src/java/org/apache/fop/pdf/xref/UncompressedObjectReference.java
public void output(DataOutputStream out) throws IOException { out.write(1); out.writeLong(offset); out.write(0); out.write(0); }
// in src/java/org/apache/fop/pdf/xref/CompressedObjectReference.java
public void output(DataOutputStream out) throws IOException { out.write(2); out.writeLong(objectStreamNumber); out.write(0); out.write(index); }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceTable.java
public void output(OutputStream stream) throws IOException { outputXref(); writeTrailer(stream); }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceTable.java
private void outputXref() throws IOException { pdf.append("xref\n0 "); pdf.append(objectReferences.size() + 1); pdf.append("\n0000000000 65535 f \n"); for (Long objectReference : objectReferences) { final String padding = "0000000000"; String s = String.valueOf(objectReference); if (s.length() > 10) { throw new IOException("PDF file too large." + " PDF 1.4 cannot grow beyond approx. 9.3GB."); } String loc = padding.substring(s.length()) + s; pdf.append(loc).append(" 00000 n \n"); } }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceTable.java
private void writeTrailer(OutputStream stream) throws IOException { pdf.append("trailer\n"); stream.write(PDFDocument.encode(pdf.toString())); PDFDictionary dictionary = trailerDictionary.getDictionary(); dictionary.put("/Size", objectReferences.size() + 1); dictionary.output(stream); }
// in src/java/org/apache/fop/pdf/xref/TrailerDictionary.java
public TrailerDictionary setFileID(byte[] originalFileID, byte[] updatedFileID) { // TODO this is ugly! Used to circumvent the fact that the file ID will be // encrypted if directly stored as a byte array class FileID implements PDFWritable { private final byte[] fileID; FileID(byte[] id) { fileID = id; } public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { PDFDocument.flushTextBuffer(textBuffer, out); String hex = PDFText.toHex(fileID, true); byte[] encoded = hex.getBytes("US-ASCII"); out.write(encoded); } } PDFArray fileID = new PDFArray(new FileID(originalFileID), new FileID(updatedFileID)); dictionary.put("/ID", fileID); return this; }
// in src/java/org/apache/fop/pdf/xref/TrailerDictionary.java
public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { PDFDocument.flushTextBuffer(textBuffer, out); String hex = PDFText.toHex(fileID, true); byte[] encoded = hex.getBytes("US-ASCII"); out.write(encoded); }
// in src/java/org/apache/fop/pdf/PDFDictionary.java
Override public int output(OutputStream stream) throws IOException { CountingOutputStream cout = new CountingOutputStream(stream); StringBuilder textBuffer = new StringBuilder(64); writeDictionary(cout, textBuffer); PDFDocument.flushTextBuffer(textBuffer, cout); return cout.getCount(); }
// in src/java/org/apache/fop/pdf/PDFDictionary.java
protected void writeDictionary(OutputStream out, StringBuilder textBuffer) throws IOException { textBuffer.append("<<"); boolean compact = (this.order.size() <= 2); for (String key : this.order) { if (compact) { textBuffer.append(' '); } else { textBuffer.append("\n "); } textBuffer.append(PDFName.escapeName(key)); textBuffer.append(' '); Object obj = this.entries.get(key); formatObject(obj, out, textBuffer); } if (compact) { textBuffer.append(' '); } else { textBuffer.append('\n'); } textBuffer.append(">>\n"); }
// in src/java/org/apache/fop/pdf/BitmapImage.java
public void outputContents(OutputStream out) throws IOException { out.write(bitmaps); }
// in src/java/org/apache/fop/pdf/PDFT1Stream.java
protected int getSizeHint() throws IOException { if (this.pfb != null) { return pfb.getLength(); } else { return 0; //no hint available } }
// in src/java/org/apache/fop/pdf/PDFT1Stream.java
public int output(java.io.OutputStream stream) throws java.io.IOException { if (pfb == null) { throw new IllegalStateException("pfb must not be null at this point"); } if (log.isDebugEnabled()) { log.debug("Writing " + pfb.getLength() + " bytes of Type 1 font data"); } int length = super.output(stream); log.debug("Embedded Type1 font"); return length; }
// in src/java/org/apache/fop/pdf/PDFT1Stream.java
protected void outputRawStreamData(OutputStream out) throws IOException { this.pfb.outputAllParts(out); }
// in src/java/org/apache/fop/pdf/PDFT1Stream.java
public void setData(PFBData pfb) throws IOException { this.pfb = pfb; }
// in src/java/org/apache/fop/pdf/InMemoryStreamCache.java
public OutputStream getOutputStream() throws IOException { if (output == null) { if (this.hintSize <= 0) { output = new ByteArrayOutputStream(512); } else { output = new ByteArrayOutputStream(this.hintSize); } } return output; }
// in src/java/org/apache/fop/pdf/InMemoryStreamCache.java
public void write(byte[] data) throws IOException { getOutputStream().write(data); }
// in src/java/org/apache/fop/pdf/InMemoryStreamCache.java
public int outputContents(OutputStream out) throws IOException { if (output == null) { return 0; } output.writeTo(out); return output.size(); }
// in src/java/org/apache/fop/pdf/InMemoryStreamCache.java
public int getSize() throws IOException { if (output == null) { return 0; } else { return output.size(); } }
// in src/java/org/apache/fop/pdf/InMemoryStreamCache.java
public void clear() throws IOException { if (output != null) { output.close(); output = null; } }
// in src/java/org/apache/fop/pdf/PDFArray.java
Override public int output(OutputStream stream) throws IOException { CountingOutputStream cout = new CountingOutputStream(stream); StringBuilder textBuffer = new StringBuilder(64); textBuffer.append('['); for (int i = 0; i < values.size(); i++) { if (i > 0) { textBuffer.append(' '); } Object obj = this.values.get(i); formatObject(obj, cout, textBuffer); } textBuffer.append(']'); PDFDocument.flushTextBuffer(textBuffer, cout); return cout.getCount(); }
// in src/java/org/apache/fop/pdf/NullFilter.java
public OutputStream applyFilter(OutputStream out) throws IOException { return out; //No active filtering, NullFilter does nothing }
// in src/java/org/apache/fop/pdf/PDFName.java
Override public int output(OutputStream stream) throws IOException { CountingOutputStream cout = new CountingOutputStream(stream); StringBuilder textBuffer = new StringBuilder(64); textBuffer.append(toString()); PDFDocument.flushTextBuffer(textBuffer, cout); return cout.getCount(); }
// in src/java/org/apache/fop/pdf/PDFName.java
Override public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { if (hasObjectNumber()) { textBuffer.append(referencePDF()); } else { textBuffer.append(toString()); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void prepare() throws SAXException, IOException { if (this.configFile != null) { fopFactory.setUserConfig(this.configFile); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void generateXML(SortedMap fontFamilies, File outFile, String singleFamily) throws TransformerConfigurationException, SAXException, IOException { SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler handler; if (this.mode == GENERATE_XML) { handler = tFactory.newTransformerHandler(); } else { URL url = getClass().getResource("fonts2fo.xsl"); if (url == null) { throw new FileNotFoundException("Did not find resource: fonts2fo.xsl"); } handler = tFactory.newTransformerHandler(new StreamSource(url.toExternalForm())); } if (singleFamily != null) { Transformer transformer = handler.getTransformer(); transformer.setParameter("single-family", singleFamily); } OutputStream out = new java.io.FileOutputStream(outFile); out = new java.io.BufferedOutputStream(out); if (this.mode == GENERATE_RENDERED) { handler.setResult(new SAXResult(getFOPContentHandler(out))); } else { handler.setResult(new StreamResult(out)); } try { GenerationHelperContentHandler helper = new GenerationHelperContentHandler( handler, null); FontListSerializer serializer = new FontListSerializer(); serializer.generateSAX(fontFamilies, singleFamily, helper); } finally { IOUtils.closeQuietly(out); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void writeToConsole(SortedMap fontFamilies) throws TransformerConfigurationException, SAXException, IOException { Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String firstFamilyName = (String)entry.getKey(); System.out.println(firstFamilyName + ":"); List list = (List)entry.getValue(); Iterator fonts = list.iterator(); while (fonts.hasNext()) { FontSpec f = (FontSpec)fonts.next(); System.out.println(" " + f.getKey() + " " + f.getFamilyNames()); Iterator triplets = f.getTriplets().iterator(); while (triplets.hasNext()) { FontTriplet triplet = (FontTriplet)triplets.next(); System.out.println(" " + triplet.toString()); } } } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void writeOutput(SortedMap fontFamilies) throws TransformerConfigurationException, SAXException, IOException { if (this.outputFile.isDirectory()) { System.out.println("Creating one file for each family..."); Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String familyName = (String)entry.getKey(); System.out.println("Creating output file for " + familyName + "..."); String filename; switch(this.mode) { case GENERATE_RENDERED: filename = familyName + ".pdf"; break; case GENERATE_FO: filename = familyName + ".fo"; break; case GENERATE_XML: filename = familyName + ".xml"; break; default: throw new IllegalStateException("Unsupported mode"); } File outFile = new File(this.outputFile, filename); generateXML(fontFamilies, outFile, familyName); } } else { System.out.println("Creating output file..."); generateXML(fontFamilies, this.outputFile, this.singleFamilyFilter); } System.out.println(this.outputFile + " written."); }
// in src/java/org/apache/fop/tools/anttasks/FileCompare.java
public static boolean compareFiles(File f1, File f2) throws IOException { return (compareFileSize(f1, f2) && compareBytes(f1, f2)); }
// in src/java/org/apache/fop/tools/anttasks/FileCompare.java
private static boolean compareBytes(File file1, File file2) throws IOException { BufferedInputStream file1Input = new BufferedInputStream(new java.io.FileInputStream(file1)); BufferedInputStream file2Input = new BufferedInputStream(new java.io.FileInputStream(file2)); int charact1 = 0; int charact2 = 0; while (charact1 != -1) { if (charact1 == charact2) { charact1 = file1Input.read(); charact2 = file2Input.read(); } else { return false; } } return true; }
// in src/java/org/apache/fop/servlet/FopPrintServlet.java
protected void render(Source src, Transformer transformer, HttpServletResponse response) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_FOP_PRINT, foUserAgent); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer.transform(src, res); //Return the result reportOK(response); }
// in src/java/org/apache/fop/servlet/FopPrintServlet.java
private void reportOK(HttpServletResponse response) throws IOException { String sMsg = "<html><title>Success</title>\n" + "<body><h1>FopPrintServlet: </h1>" + "<h3>The requested data was printed to the default printer.</h3></body></html>"; response.setContentType("text/html"); response.setContentLength(sMsg.length()); PrintWriter out = response.getWriter(); out.println(sMsg); out.flush(); }
// in src/java/org/apache/fop/servlet/FopServlet.java
private void sendPDF(byte[] content, HttpServletResponse response) throws IOException { //Send the result back to the client response.setContentType("application/pdf"); response.setContentLength(content.length); response.getOutputStream().write(content); response.getOutputStream().flush(); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void renderFO(String fo, HttpServletResponse response) throws FOPException, TransformerException, IOException { //Setup source Source foSrc = convertString2Source(fo); //Setup the identity transformation Transformer transformer = this.transFactory.newTransformer(); transformer.setURIResolver(this.uriResolver); //Start transformation and rendering process render(foSrc, transformer, response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void renderXML(String xml, String xslt, HttpServletResponse response) throws FOPException, TransformerException, IOException { //Setup sources Source xmlSrc = convertString2Source(xml); Source xsltSrc = convertString2Source(xslt); //Setup the XSL transformation Transformer transformer = this.transFactory.newTransformer(xsltSrc); transformer.setURIResolver(this.uriResolver); //Start transformation and rendering process render(xmlSrc, transformer, response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void render(Source src, Transformer transformer, HttpServletResponse response) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(); //Setup output ByteArrayOutputStream out = new ByteArrayOutputStream(); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer.transform(src, res); //Return the result sendPDF(out.toByteArray(), response); }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java
public void setupDocument(OutputStream stream, int width, int height) throws IOException { this.width = width; this.height = height; pdfDoc.outputHeader(stream); setOutputStream(stream); }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java
protected void startPage() throws IOException { if (pdfContext.isPagePending()) { throw new IllegalStateException("Close page first before starting another"); } //Start page paintingState = new PDFPaintingState(); if (this.initialTransform == null) { //Save initial transformation matrix this.initialTransform = getTransform(); this.initialClip = getClip(); } else { //Reset transformation matrix setTransform(this.initialTransform); setClip(this.initialClip); } currentFontName = ""; currentFontSize = 0; if (currentStream == null) { currentStream = new StringWriter(); } PDFResources pdfResources = this.pdfDoc.getResources(); PDFPage page = this.pdfDoc.getFactory().makePage(pdfResources, width, height); resourceContext = page; pdfContext.setCurrentPage(page); pageRef = page.referencePDF(); currentStream.write("q\n"); AffineTransform at = new AffineTransform(1.0, 0.0, 0.0, -1.0, 0.0, height); currentStream.write("1 0 0 -1 0 " + height + " cm\n"); if (svgWidth != 0) { double scaleX = width / svgWidth; double scaleY = height / svgHeight; at.scale(scaleX, scaleY); currentStream.write("" + PDFNumber.doubleOut(scaleX) + " 0 0 " + PDFNumber.doubleOut(scaleY) + " 0 0 cm\n"); } if (deviceDPI != NORMAL_PDF_RESOLUTION) { double s = NORMAL_PDF_RESOLUTION / deviceDPI; at.scale(s, s); currentStream.write("" + PDFNumber.doubleOut(s) + " 0 0 " + PDFNumber.doubleOut(s) + " 0 0 cm\n"); scale(1 / s, 1 / s); } // Remember the transform we installed. paintingState.concatenate(at); pdfContext.increasePageCount(); }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java
public void finish() throws IOException { // restorePDFState(); closePage(); if (fontInfo != null) { pdfDoc.getResources().addFonts(pdfDoc, fontInfo); } this.pdfDoc.output(outputStream); pdfDoc.outputTrailer(outputStream); outputStream.flush(); }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
public TTFFile loadTTF(String fileName, String fontName, boolean useKerning, boolean useAdvanced) throws IOException { TTFFile ttfFile = new TTFFile(useKerning, useAdvanced); log.info("Reading " + fileName + "..."); FontFileReader reader = new FontFileReader(fileName); boolean supported = ttfFile.readFont(reader, fontName); if (!supported) { return null; } log.info("Font Family: " + ttfFile.getFamilyNames()); if (ttfFile.isCFF()) { throw new UnsupportedOperationException( "OpenType fonts with CFF data are not supported, yet"); } return ttfFile; }
// in src/java/org/apache/fop/fonts/apps/PFMReader.java
public PFMFile loadPFM(String filename) throws IOException { log.info("Reading " + filename + "..."); log.info(""); InputStream in = new java.io.FileInputStream(filename); try { PFMFile pfm = new PFMFile(); pfm.load(in); return pfm; } finally { in.close(); } }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static CustomFont loadFont(File fontFile, String subFontName, boolean embedded, EncodingMode encodingMode, FontResolver resolver) throws IOException { return loadFont(fontFile.toURI().toURL(), subFontName, embedded, encodingMode, resolver); }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static CustomFont loadFont(URL fontUrl, String subFontName, boolean embedded, EncodingMode encodingMode, FontResolver resolver) throws IOException { return loadFont(fontUrl.toExternalForm(), subFontName, embedded, encodingMode, true, true, resolver); }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static CustomFont loadFont(String fontFileURI, String subFontName, boolean embedded, EncodingMode encodingMode, boolean useKerning, boolean useAdvanced, FontResolver resolver) throws IOException { fontFileURI = fontFileURI.trim(); boolean type1 = isType1(fontFileURI); FontLoader loader; if (type1) { if (encodingMode == EncodingMode.CID) { throw new IllegalArgumentException( "CID encoding mode not supported for Type 1 fonts"); } loader = new Type1FontLoader(fontFileURI, embedded, useKerning, resolver); } else { loader = new TTFFontLoader(fontFileURI, subFontName, embedded, encodingMode, useKerning, useAdvanced, resolver); } return loader.getFont(); }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static InputStream openFontUri(FontResolver resolver, String uri) throws IOException, MalformedURLException { InputStream in = null; if (resolver != null) { Source source = resolver.resolve(uri); if (source == null) { String err = "Cannot load font: failed to create Source for font file " + uri; throw new IOException(err); } if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null && source.getSystemId() != null) { in = new java.net.URL(source.getSystemId()).openStream(); } if (in == null) { String err = "Cannot load font: failed to create InputStream from" + " Source for font file " + uri; throw new IOException(err); } } else { in = new URL(uri).openStream(); } return in; }
// in src/java/org/apache/fop/fonts/FontLoader.java
public CustomFont getFont() throws IOException { if (!loaded) { read(); } return this.returnFont; }
// in src/java/org/apache/fop/fonts/CustomFont.java
public Source getEmbedFileSource() throws IOException { Source result = null; if (resolver != null && embedFileName != null) { result = resolver.resolve(embedFileName); if (result == null) { throw new IOException("Unable to resolve Source '" + embedFileName + "' for embedded font"); } } return result; }
// in src/java/org/apache/fop/fonts/EmbedFontInfo.java
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); this.embedded = true; }
// in src/java/org/apache/fop/fonts/autodetect/WindowsFontDirFinder.java
private String getWinDir(String osName) throws IOException { Process process = null; Runtime runtime = Runtime.getRuntime(); if (osName.startsWith("Windows 9")) { process = runtime.exec("command.com /c echo %windir%"); } else { process = runtime.exec("cmd.exe /c echo %windir%"); } BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); return bufferedReader.readLine(); }
// in src/java/org/apache/fop/fonts/autodetect/FontFileFinder.java
public List<URL> find() throws IOException { final FontDirFinder fontDirFinder; final String osName = System.getProperty("os.name"); if (osName.startsWith("Windows")) { fontDirFinder = new WindowsFontDirFinder(); } else { if (osName.startsWith("Mac")) { fontDirFinder = new MacFontDirFinder(); } else { fontDirFinder = new UnixFontDirFinder(); } } List<File> fontDirs = fontDirFinder.find(); List<URL> results = new java.util.ArrayList<URL>(); for (File dir : fontDirs) { super.walk(dir, results); } return results; }
// in src/java/org/apache/fop/fonts/autodetect/FontFileFinder.java
public List<URL> find(String dir) throws IOException { List<URL> results = new java.util.ArrayList<URL>(); File directory = new File(dir); if (!directory.isDirectory()) { eventListener.fontDirectoryNotFound(this, dir); } else { super.walk(directory, results); } return results; }
// in src/java/org/apache/fop/fonts/type1/PFBData.java
public void outputAllParts(OutputStream out) throws IOException { out.write(this.headerSegment); out.write(this.encryptedSegment); out.write(this.trailerSegment); }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
Override protected void read() throws IOException { AFMFile afm = null; PFMFile pfm = null; InputStream afmIn = null; String afmUri = null; for (int i = 0; i < AFM_EXTENSIONS.length; i++) { try { afmUri = this.fontFileURI.substring(0, this.fontFileURI.length() - 4) + AFM_EXTENSIONS[i]; afmIn = openFontUri(resolver, afmUri); if (afmIn != null) { break; } } catch (IOException ioe) { // Ignore, AFM probably not available under the URI } } if (afmIn != null) { try { AFMParser afmParser = new AFMParser(); afm = afmParser.parse(afmIn, afmUri); } finally { IOUtils.closeQuietly(afmIn); } } String pfmUri = getPFMURI(this.fontFileURI); InputStream pfmIn = null; try { pfmIn = openFontUri(resolver, pfmUri); } catch (IOException ioe) { // Ignore, PFM probably not available under the URI } if (pfmIn != null) { try { pfm = new PFMFile(); pfm.load(pfmIn); } catch (IOException ioe) { if (afm == null) { // Ignore the exception if we have a valid PFM. PFM is only the fallback. throw ioe; } } finally { IOUtils.closeQuietly(pfmIn); } } if (afm == null && pfm == null) { throw new java.io.FileNotFoundException( "Neither an AFM nor a PFM file was found for " + this.fontFileURI); } buildFont(afm, pfm); this.loaded = true; }
// in src/java/org/apache/fop/fonts/type1/PFMInputStream.java
public short readByte() throws IOException { short s = datain.readByte(); // Now, we've got to trick Java into forgetting the sign int s1 = (((s & 0xF0) >>> 4) << 4) + (s & 0x0F); return (short)s1; }
// in src/java/org/apache/fop/fonts/type1/PFMInputStream.java
public int readShort() throws IOException { int i = datain.readShort(); // Change byte order int high = (i & 0xFF00) >>> 8; int low = (i & 0x00FF) << 8; return low + high; }
// in src/java/org/apache/fop/fonts/type1/PFMInputStream.java
public long readInt() throws IOException { int i = datain.readInt(); // Change byte order int i1 = (i & 0xFF000000) >>> 24; int i2 = (i & 0x00FF0000) >>> 8; int i3 = (i & 0x0000FF00) << 8; int i4 = (i & 0x000000FF) << 24; return i1 + i2 + i3 + i4; }
// in src/java/org/apache/fop/fonts/type1/PFMInputStream.java
public String readString() throws IOException { InputStreamReader reader = new InputStreamReader(in, "ISO-8859-1"); StringBuffer buf = new StringBuffer(); int ch = reader.read(); while (ch > 0) { buf.append((char)ch); ch = reader.read(); } if (ch == -1) { throw new EOFException("Unexpected end of stream reached"); } return buf.toString(); }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
public PFBData parsePFB(java.net.URL url) throws IOException { InputStream in = url.openStream(); try { return parsePFB(in); } finally { in.close(); } }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
public PFBData parsePFB(java.io.File pfbFile) throws IOException { InputStream in = new java.io.FileInputStream(pfbFile); try { return parsePFB(in); } finally { in.close(); } }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
public PFBData parsePFB(InputStream in) throws IOException { PFBData pfb = new PFBData(); BufferedInputStream bin = new BufferedInputStream(in); DataInputStream din = new DataInputStream(bin); din.mark(32); int firstByte = din.readUnsignedByte(); din.reset(); if (firstByte == 128) { pfb.setPFBFormat(PFBData.PFB_PC); parsePCFormat(pfb, din); } else { pfb.setPFBFormat(PFBData.PFB_RAW); parseRAWFormat(pfb, bin); } return pfb; }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
private void parsePCFormat(PFBData pfb, DataInputStream din) throws IOException { int segmentHead; int segmentType; int bytesRead; //Read first segment segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); //Read int len1 = swapInteger(din.readInt()); byte[] headerSegment = new byte[len1]; din.readFully(headerSegment); pfb.setHeaderSegment(headerSegment); //Read second segment segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); int len2 = swapInteger(din.readInt()); byte[] encryptedSegment = new byte[len2]; din.readFully(encryptedSegment); pfb.setEncryptedSegment(encryptedSegment); //Read third segment segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); int len3 = swapInteger(din.readInt()); byte[] trailerSegment = new byte[len3]; din.readFully(trailerSegment); pfb.setTrailerSegment(trailerSegment); //Read EOF indicator segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); if (segmentType != 3) { throw new IOException("Expected segment type 3, but found: " + segmentType); } }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
private void parseRAWFormat(PFBData pfb, BufferedInputStream bin) throws IOException { calcLengths(pfb, IOUtils.toByteArray(bin)); }
// in src/java/org/apache/fop/fonts/type1/CharMetricsHandler.java
AFMCharMetrics parse(String line, Stack<Object> stack, String afmFileName) throws IOException { AFMCharMetrics chm = new AFMCharMetrics(); stack.push(chm); String[] metrics = SPLIT_REGEX.split(line); for (String metric : metrics) { Matcher matcher = METRICS_REGEX.matcher(metric); if (matcher.matches()) { String operator = matcher.group(1); String operands = matcher.group(2); ValueHandler handler = valueParsers.get(operator); if (handler != null) { handler.parse(operands, 0, stack); } } } stack.pop(); return chm; }
// in src/java/org/apache/fop/fonts/type1/CharMetricsHandler.java
AFMCharMetrics parse(String line, Stack<Object> stack, String afmFileName) throws IOException { AFMCharMetrics chm = defaultHandler.parse(line, stack, afmFileName); NamedCharacter namedChar = chm.getCharacter(); if (namedChar != null) { int codePoint = AdobeStandardEncoding.getAdobeCodePoint(namedChar.getName()); if (chm.getCharCode() != codePoint) { LOG.info(afmFileName + ": named character '" + namedChar.getName() + "'" + " has an incorrect code point: " + chm.getCharCode() + ". Changed to " + codePoint); chm.setCharCode(codePoint); } } return chm; }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
public void load(InputStream inStream) throws IOException { byte[] pfmBytes = IOUtils.toByteArray(inStream); InputStream bufin = inStream; bufin = new ByteArrayInputStream(pfmBytes); PFMInputStream in = new PFMInputStream(bufin); bufin.mark(512); short sh1 = in.readByte(); short sh2 = in.readByte(); if (sh1 == 128 && sh2 == 1) { //Found the first section header of a PFB file! throw new IOException("Cannot parse PFM file. You probably specified the PFB file" + " of a Type 1 font as parameter instead of the PFM."); } bufin.reset(); byte[] b = new byte[16]; bufin.read(b); if (new String(b, "US-ASCII").equalsIgnoreCase("StartFontMetrics")) { //Found the header of a AFM file! throw new IOException("Cannot parse PFM file. You probably specified the AFM file" + " of a Type 1 font as parameter instead of the PFM."); } bufin.reset(); final int version = in.readShort(); if (version != 256) { log.warn("PFM version expected to be '256' but got '" + version + "'." + " Please make sure you specify the PFM as parameter" + " and not the PFB or the AFM."); } //final long filesize = in.readInt(); bufin.reset(); loadHeader(in); loadExtension(in); }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
private void loadHeader(PFMInputStream inStream) throws IOException { inStream.skip(80); dfItalic = inStream.readByte(); inStream.skip(2); dfWeight = inStream.readShort(); dfCharSet = inStream.readByte(); inStream.skip(4); dfPitchAndFamily = inStream.readByte(); dfAvgWidth = inStream.readShort(); dfMaxWidth = inStream.readShort(); dfFirstChar = inStream.readByte(); dfLastChar = inStream.readByte(); inStream.skip(8); long faceOffset = inStream.readInt(); inStream.reset(); inStream.skip(faceOffset); windowsName = inStream.readString(); inStream.reset(); inStream.skip(117); }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
private void loadExtension(PFMInputStream inStream) throws IOException { final int size = inStream.readShort(); if (size != 30) { log.warn("Size of extension block was expected to be " + "30 bytes, but was " + size + " bytes."); } final long extMetricsOffset = inStream.readInt(); final long extentTableOffset = inStream.readInt(); inStream.skip(4); //Skip dfOriginTable final long kernPairOffset = inStream.readInt(); inStream.skip(4); //Skip dfTrackKernTable long driverInfoOffset = inStream.readInt(); if (kernPairOffset > 0) { inStream.reset(); inStream.skip(kernPairOffset); loadKernPairs(inStream); } inStream.reset(); inStream.skip(driverInfoOffset); postscriptName = inStream.readString(); if (extMetricsOffset != 0) { inStream.reset(); inStream.skip(extMetricsOffset); loadExtMetrics(inStream); } if (extentTableOffset != 0) { inStream.reset(); inStream.skip(extentTableOffset); loadExtentTable(inStream); } }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
private void loadKernPairs(PFMInputStream inStream) throws IOException { int i = inStream.readShort(); if (log.isTraceEnabled()) { log.trace(i + " kerning pairs"); } while (i > 0) { int g1 = (int)inStream.readByte(); i--; int g2 = (int)inStream.readByte(); int adj = inStream.readShort(); if (adj > 0x8000) { adj = -(0x10000 - adj); } if (log.isTraceEnabled()) { log.trace("Char no: (" + g1 + ", " + g2 + ") kern: " + adj); final String glyph1 = Glyphs.TEX8R_GLYPH_NAMES[g1]; final String glyph2 = Glyphs.TEX8R_GLYPH_NAMES[g2]; log.trace("glyphs: " + glyph1 + ", " + glyph2); } Map adjTab = (Map)kerningTab.get(new Integer(g1)); if (adjTab == null) { adjTab = new java.util.HashMap(); } adjTab.put(new Integer(g2), new Integer(adj)); kerningTab.put(new Integer(g1), adjTab); } }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
private void loadExtMetrics(PFMInputStream inStream) throws IOException { final int size = inStream.readShort(); if (size != 52) { log.warn("Size of extension block was expected to be " + "52 bytes, but was " + size + " bytes."); } inStream.skip(12); //Skip etmPointSize, etmOrientation, etmMasterHeight, //etmMinScale, etmMaxScale, emtMasterUnits etmCapHeight = inStream.readShort(); etmXHeight = inStream.readShort(); etmLowerCaseAscent = inStream.readShort(); etmLowerCaseDescent = -(inStream.readShort()); //Ignore the rest of the values }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
private void loadExtentTable(PFMInputStream inStream) throws IOException { extentTable = new int[dfLastChar - dfFirstChar + 1]; dfMinWidth = dfMaxWidth; for (short i = dfFirstChar; i <= dfLastChar; i++) { extentTable[i - dfFirstChar] = inStream.readShort(); if (extentTable[i - dfFirstChar] < dfMinWidth) { dfMinWidth = extentTable[i - dfFirstChar]; } } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public AFMFile parse(InputStream in, String afmFileName) throws IOException { Reader reader = new java.io.InputStreamReader(in, "US-ASCII"); try { return parse(new BufferedReader(reader), afmFileName); } finally { IOUtils.closeQuietly(reader); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public AFMFile parse(BufferedReader reader, String afmFileName) throws IOException { Stack<Object> stack = new Stack<Object>(); int parseMode = PARSE_NORMAL; while (true) { String line = reader.readLine(); if (line == null) { break; } String key = null; switch (parseMode) { case PARSE_NORMAL: key = parseLine(line, stack); break; case PARSE_CHAR_METRICS: key = parseCharMetrics(line, stack, afmFileName); break; default: throw new IllegalStateException("Invalid parse mode"); } Integer newParseMode = PARSE_MODE_CHANGES.get(key); if (newParseMode != null) { parseMode = newParseMode.intValue(); } } return (AFMFile)stack.pop(); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
private String parseLine(String line, Stack<Object> stack) throws IOException { int startpos = 0; //Find key startpos = skipToNonWhiteSpace(line, startpos); int endpos = skipToWhiteSpace(line, startpos); String key = line.substring(startpos, endpos); //Parse value startpos = skipToNonWhiteSpace(line, endpos); ValueHandler vp = VALUE_PARSERS.get(key); if (vp != null) { vp.parse(line, startpos, stack); } return key; }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
private String parseCharMetrics(String line, Stack<Object> stack, String afmFileName) throws IOException { String trimmedLine = line.trim(); if (END_CHAR_METRICS.equals(trimmedLine)) { return trimmedLine; } AFMFile afm = (AFMFile) stack.peek(); String encoding = afm.getEncodingScheme(); CharMetricsHandler charMetricsHandler = CharMetricsHandler.getHandler(VALUE_PARSERS, encoding); AFMCharMetrics chm = charMetricsHandler.parse(trimmedLine, stack, afmFileName); afm.addCharMetrics(chm); return null; }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { int endpos = findValue(line, startpos); double version = Double.parseDouble(line.substring(startpos, endpos)); if (version < 2) { throw new IOException( "AFM version must be at least 2.0 but it is " + version + "!"); } AFMFile afm = new AFMFile(); stack.push(afm); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { String s = getStringValue(line, startpos); Object obj = stack.peek(); setValue(obj, String.class, s); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { NamedCharacter ch = new NamedCharacter(getStringValue(line, startpos)); Object obj = stack.peek(); setValue(obj, NamedCharacter.class, ch); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { Number num = getNumberValue(line, startpos); setValue(getContextObject(stack), Number.class, num); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { int value = getIntegerValue(line, startpos); setValue(getContextObject(stack), int.class, new Integer(value)); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { double value = getDoubleValue(line, startpos); setValue(getContextObject(stack), double.class, new Double(value)); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { double value = getDoubleValue(line, startpos); setValue(getContextObject(stack), double.class, new Double(value)); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { Boolean b = getBooleanValue(line, startpos); Object target = getContextObject(stack); Class<?> c = target.getClass(); try { Method mth = c.getMethod(method, boolean.class); mth.invoke(target, b); } catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { Rectangle rect = parseBBox(line, startpos); AFMFile afm = (AFMFile)stack.peek(); afm.setFontBBox(rect); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { Rectangle rect = parseBBox(line, startpos); AFMCharMetrics metrics = (AFMCharMetrics)stack.peek(); metrics.setBBox(rect); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { if (getBooleanValue(line, startpos).booleanValue()) { throw new IOException("Only base fonts are currently supported!"); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { if (getBooleanValue(line, startpos).booleanValue()) { throw new IOException("CID fonts are currently not supported!"); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack stack) throws IOException { log.warn("Support for '" + key + "' has not been implemented, yet!" + " Some font data in the AFM file will be ignored."); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { int index = getIntegerValue(line, startpos); AFMWritingDirectionMetrics wdm = new AFMWritingDirectionMetrics(); AFMFile afm = (AFMFile)stack.peek(); afm.setWritingDirectionMetrics(index, wdm); stack.push(wdm); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { if (!(stack.pop() instanceof AFMWritingDirectionMetrics)) { throw new IOException("AFM format error: nesting incorrect"); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { AFMFile afm = (AFMFile)stack.peek(); int endpos; endpos = findValue(line, startpos); String name1 = line.substring(startpos, endpos); startpos = skipToNonWhiteSpace(line, endpos); endpos = findValue(line, startpos); String name2 = line.substring(startpos, endpos); startpos = skipToNonWhiteSpace(line, endpos); endpos = findValue(line, startpos); double kx = Double.parseDouble(line.substring(startpos, endpos)); startpos = skipToNonWhiteSpace(line, endpos); afm.addXKerning(name1, name2, kx); }
// in src/java/org/apache/fop/fonts/truetype/TTFDirTabEntry.java
public String read(FontFileReader in) throws IOException { tag[0] = in.readTTFByte(); tag[1] = in.readTTFByte(); tag[2] = in.readTTFByte(); tag[3] = in.readTTFByte(); in.skip(4); // Skip checksum offset = in.readTTFULong(); length = in.readTTFULong(); String tagStr = new String(tag, "ISO-8859-1"); return tagStr; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
public boolean seekTab(FontFileReader in, String name, long offset) throws IOException { TTFDirTabEntry dt = getDirectoryEntry ( name ); if (dt == null) { log.error("Dirtab " + name + " not found."); return false; } else { in.seekSet(dt.getOffset() + offset); this.currentDirTab = dt; } return true; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private boolean readCMAP(FontFileReader in) throws IOException { unicodeMappings = new java.util.TreeSet(); seekTab(in, "cmap", 2); int numCMap = in.readTTFUShort(); // Number of cmap subtables long cmapUniOffset = 0; long symbolMapOffset = 0; if (log.isDebugEnabled()) { log.debug(numCMap + " cmap tables"); } //Read offset for all tables. We are only interested in the unicode table for (int i = 0; i < numCMap; i++) { int cmapPID = in.readTTFUShort(); int cmapEID = in.readTTFUShort(); long cmapOffset = in.readTTFULong(); if (log.isDebugEnabled()) { log.debug("Platform ID: " + cmapPID + " Encoding: " + cmapEID); } if (cmapPID == 3 && cmapEID == 1) { cmapUniOffset = cmapOffset; } if (cmapPID == 3 && cmapEID == 0) { symbolMapOffset = cmapOffset; } } if (cmapUniOffset > 0) { return readUnicodeCmap(in, cmapUniOffset, 1); } else if (symbolMapOffset > 0) { return readUnicodeCmap(in, symbolMapOffset, 0); } else { log.fatal("Unsupported TrueType font: No Unicode or Symbol cmap table" + " not present. Aborting"); return false; } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private boolean readUnicodeCmap // CSOK: MethodLength (FontFileReader in, long cmapUniOffset, int encodingID) throws IOException { //Read CMAP table and correct mtxTab.index int mtxPtr = 0; // Read unicode cmap seekTab(in, "cmap", cmapUniOffset); int cmapFormat = in.readTTFUShort(); /*int cmap_length =*/ in.readTTFUShort(); //skip cmap length if (log.isDebugEnabled()) { log.debug("CMAP format: " + cmapFormat); } if (cmapFormat == 4) { in.skip(2); // Skip version number int cmapSegCountX2 = in.readTTFUShort(); int cmapSearchRange = in.readTTFUShort(); int cmapEntrySelector = in.readTTFUShort(); int cmapRangeShift = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug("segCountX2 : " + cmapSegCountX2); log.debug("searchRange : " + cmapSearchRange); log.debug("entrySelector: " + cmapEntrySelector); log.debug("rangeShift : " + cmapRangeShift); } int[] cmapEndCounts = new int[cmapSegCountX2 / 2]; int[] cmapStartCounts = new int[cmapSegCountX2 / 2]; int[] cmapDeltas = new int[cmapSegCountX2 / 2]; int[] cmapRangeOffsets = new int[cmapSegCountX2 / 2]; for (int i = 0; i < (cmapSegCountX2 / 2); i++) { cmapEndCounts[i] = in.readTTFUShort(); } in.skip(2); // Skip reservedPad for (int i = 0; i < (cmapSegCountX2 / 2); i++) { cmapStartCounts[i] = in.readTTFUShort(); } for (int i = 0; i < (cmapSegCountX2 / 2); i++) { cmapDeltas[i] = in.readTTFShort(); } //int startRangeOffset = in.getCurrentPos(); for (int i = 0; i < (cmapSegCountX2 / 2); i++) { cmapRangeOffsets[i] = in.readTTFUShort(); } int glyphIdArrayOffset = in.getCurrentPos(); BitSet eightBitGlyphs = new BitSet(256); // Insert the unicode id for the glyphs in mtxTab // and fill in the cmaps ArrayList for (int i = 0; i < cmapStartCounts.length; i++) { if (log.isTraceEnabled()) { log.trace(i + ": " + cmapStartCounts[i] + " - " + cmapEndCounts[i]); } if (log.isDebugEnabled()) { if (isInPrivateUseArea(cmapStartCounts[i], cmapEndCounts[i])) { log.debug("Font contains glyphs in the Unicode private use area: " + Integer.toHexString(cmapStartCounts[i]) + " - " + Integer.toHexString(cmapEndCounts[i])); } } for (int j = cmapStartCounts[i]; j <= cmapEndCounts[i]; j++) { // Update lastChar if (j < 256 && j > lastChar) { lastChar = (short)j; } if (j < 256) { eightBitGlyphs.set(j); } if (mtxPtr < mtxTab.length) { int glyphIdx; // the last character 65535 = .notdef // may have a range offset if (cmapRangeOffsets[i] != 0 && j != 65535) { int glyphOffset = glyphIdArrayOffset + ((cmapRangeOffsets[i] / 2) + (j - cmapStartCounts[i]) + (i) - cmapSegCountX2 / 2) * 2; in.seekSet(glyphOffset); glyphIdx = (in.readTTFUShort() + cmapDeltas[i]) & 0xffff; unicodeMappings.add(new UnicodeMapping(glyphIdx, j)); mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j)); // Also add winAnsiWidth List v = (List)ansiIndex.get(new Integer(j)); if (v != null) { Iterator e = v.listIterator(); while (e.hasNext()) { Integer aIdx = (Integer)e.next(); ansiWidth[aIdx.intValue()] = mtxTab[glyphIdx].getWx(); if (log.isTraceEnabled()) { log.trace("Added width " + mtxTab[glyphIdx].getWx() + " uni: " + j + " ansi: " + aIdx.intValue()); } } } if (log.isTraceEnabled()) { log.trace("Idx: " + glyphIdx + " Delta: " + cmapDeltas[i] + " Unicode: " + j + " name: " + mtxTab[glyphIdx].getName()); } } else { glyphIdx = (j + cmapDeltas[i]) & 0xffff; if (glyphIdx < mtxTab.length) { mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j)); } else { log.debug("Glyph " + glyphIdx + " out of range: " + mtxTab.length); } unicodeMappings.add(new UnicodeMapping(glyphIdx, j)); if (glyphIdx < mtxTab.length) { mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j)); } else { log.debug("Glyph " + glyphIdx + " out of range: " + mtxTab.length); } // Also add winAnsiWidth List v = (List)ansiIndex.get(new Integer(j)); if (v != null) { Iterator e = v.listIterator(); while (e.hasNext()) { Integer aIdx = (Integer)e.next(); ansiWidth[aIdx.intValue()] = mtxTab[glyphIdx].getWx(); } } //getLogger().debug("IIdx: " + // mtxPtr + // " Delta: " + cmap_deltas[i] + // " Unicode: " + j + // " name: " + // mtxTab[(j+cmap_deltas[i]) & 0xffff].name); } if (glyphIdx < mtxTab.length) { if (mtxTab[glyphIdx].getUnicodeIndex().size() < 2) { mtxPtr++; } } } } } } else { log.error("Cmap format not supported: " + cmapFormat); return false; } return true; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
public void readFont(FontFileReader in) throws IOException { readFont(in, (String)null); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
public boolean readFont(FontFileReader in, String name) throws IOException { /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(in, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(in); readFontHeader(in); getNumGlyphs(in); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(in); readHorizontalMetrics(in); initAnsiWidths(); readPostScript(in); readOS2(in); determineAscDesc(); if (!isCFF) { readIndexToLocation(in); readGlyf(in); } readName(in); boolean pcltFound = readPCLT(in); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(in); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); if ( useKerning ) { readKerning(in); } // Read advanced typographic tables. if ( useAdvanced ) { try { OTFAdvancedTypographicTableReader atr = new OTFAdvancedTypographicTableReader ( this, in ); atr.readAll(); this.advancedTableReader = atr; } catch ( AdvancedTypographicTableFormatException e ) { log.warn ( "Encountered format constraint violation in advanced (typographic) table (AT) " + "in font '" + getFullName() + "', ignoring AT data: " + e.getMessage() ); } } guessVerticalMetricsFromGlyphBBox(); return true; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected void readDirTabs(FontFileReader in) throws IOException { int sfntVersion = in.readTTFLong(); // TTF_FIXED_SIZE (4 bytes) switch (sfntVersion) { case 0x10000: log.debug("sfnt version: OpenType 1.0"); break; case 0x4F54544F: //"OTTO" this.isCFF = true; log.debug("sfnt version: OpenType with CFF data"); break; case 0x74727565: //"true" log.debug("sfnt version: Apple TrueType"); break; case 0x74797031: //"typ1" log.debug("sfnt version: Apple Type 1 housed in sfnt wrapper"); break; default: log.debug("Unknown sfnt version: " + Integer.toHexString(sfntVersion)); break; } int ntabs = in.readTTFUShort(); in.skip(6); // 3xTTF_USHORT_SIZE dirTabs = new java.util.HashMap(); TTFDirTabEntry[] pd = new TTFDirTabEntry[ntabs]; log.debug("Reading " + ntabs + " dir tables"); for (int i = 0; i < ntabs; i++) { pd[i] = new TTFDirTabEntry(); dirTabs.put(pd[i].read(in), pd[i]); } log.debug("dir tables: " + dirTabs.keySet()); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected void readFontHeader(FontFileReader in) throws IOException { seekTab(in, "head", 2 * 4 + 2 * 4); int flags = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug("flags: " + flags + " - " + Integer.toString(flags, 2)); } upem = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug("unit per em: " + upem); } in.skip(16); fontBBox1 = in.readTTFShort(); fontBBox2 = in.readTTFShort(); fontBBox3 = in.readTTFShort(); fontBBox4 = in.readTTFShort(); if (log.isDebugEnabled()) { log.debug("font bbox: xMin=" + fontBBox1 + " yMin=" + fontBBox2 + " xMax=" + fontBBox3 + " yMax=" + fontBBox4); } in.skip(2 + 2 + 2); locaFormat = in.readTTFShort(); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected void getNumGlyphs(FontFileReader in) throws IOException { seekTab(in, "maxp", 4); numberOfGlyphs = in.readTTFUShort(); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected void readHorizontalHeader(FontFileReader in) throws IOException { seekTab(in, "hhea", 4); hheaAscender = in.readTTFShort(); hheaDescender = in.readTTFShort(); in.skip(2 + 2 + 3 * 2 + 8 * 2); nhmtx = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug("hhea.Ascender: " + formatUnitsForDebug(hheaAscender)); log.debug("hhea.Descender: " + formatUnitsForDebug(hheaDescender)); log.debug("Number of horizontal metrics: " + nhmtx); } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected void readHorizontalMetrics(FontFileReader in) throws IOException { seekTab(in, "hmtx", 0); int mtxSize = Math.max(numberOfGlyphs, nhmtx); mtxTab = new TTFMtxEntry[mtxSize]; if (log.isTraceEnabled()) { log.trace("*** Widths array: \n"); } for (int i = 0; i < mtxSize; i++) { mtxTab[i] = new TTFMtxEntry(); } for (int i = 0; i < nhmtx; i++) { mtxTab[i].setWx(in.readTTFUShort()); mtxTab[i].setLsb(in.readTTFUShort()); if (log.isTraceEnabled()) { log.trace(" width[" + i + "] = " + convertTTFUnit2PDFUnit(mtxTab[i].getWx()) + ";"); } } if (nhmtx < mtxSize) { // Fill in the missing widths int lastWidth = mtxTab[nhmtx - 1].getWx(); for (int i = nhmtx; i < mtxSize; i++) { mtxTab[i].setWx(lastWidth); mtxTab[i].setLsb(in.readTTFUShort()); } } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private void readPostScript(FontFileReader in) throws IOException { seekTab(in, "post", 0); postFormat = in.readTTFLong(); italicAngle = in.readTTFULong(); underlinePosition = in.readTTFShort(); underlineThickness = in.readTTFShort(); isFixedPitch = in.readTTFULong(); //Skip memory usage values in.skip(4 * 4); log.debug("PostScript format: 0x" + Integer.toHexString(postFormat)); switch (postFormat) { case 0x00010000: log.debug("PostScript format 1"); for (int i = 0; i < Glyphs.MAC_GLYPH_NAMES.length; i++) { mtxTab[i].setName(Glyphs.MAC_GLYPH_NAMES[i]); } break; case 0x00020000: log.debug("PostScript format 2"); int numGlyphStrings = 0; // Read Number of Glyphs int l = in.readTTFUShort(); // Read indexes for (int i = 0; i < l; i++) { mtxTab[i].setIndex(in.readTTFUShort()); if (mtxTab[i].getIndex() > 257) { //Index is not in the Macintosh standard set numGlyphStrings++; } if (log.isTraceEnabled()) { log.trace("PostScript index: " + mtxTab[i].getIndexAsString()); } } // firstChar=minIndex; String[] psGlyphsBuffer = new String[numGlyphStrings]; if (log.isDebugEnabled()) { log.debug("Reading " + numGlyphStrings + " glyphnames, that are not in the standard Macintosh" + " set. Total number of glyphs=" + l); } for (int i = 0; i < psGlyphsBuffer.length; i++) { psGlyphsBuffer[i] = in.readTTFString(in.readTTFUByte()); } //Set glyph names for (int i = 0; i < l; i++) { if (mtxTab[i].getIndex() < NMACGLYPHS) { mtxTab[i].setName(Glyphs.MAC_GLYPH_NAMES[mtxTab[i].getIndex()]); } else { if (!mtxTab[i].isIndexReserved()) { int k = mtxTab[i].getIndex() - NMACGLYPHS; if (log.isTraceEnabled()) { log.trace(k + " i=" + i + " mtx=" + mtxTab.length + " ps=" + psGlyphsBuffer.length); } mtxTab[i].setName(psGlyphsBuffer[k]); } } } break; case 0x00030000: // PostScript format 3 contains no glyph names log.debug("PostScript format 3"); break; default: log.error("Unknown PostScript format: " + postFormat); } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private void readOS2(FontFileReader in) throws IOException { // Check if font is embeddable TTFDirTabEntry os2Entry = getDirectoryEntry ( "OS/2" ); if (os2Entry != null) { seekTab(in, "OS/2", 0); int version = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug("OS/2 table: version=" + version + ", offset=" + os2Entry.getOffset() + ", len=" + os2Entry.getLength()); } in.skip(2); //xAvgCharWidth this.usWeightClass = in.readTTFUShort(); // usWidthClass in.skip(2); int fsType = in.readTTFUShort(); if (fsType == 2) { isEmbeddable = false; } else { isEmbeddable = true; } in.skip(11 * 2); in.skip(10); //panose array in.skip(4 * 4); //unicode ranges in.skip(4); in.skip(3 * 2); int v; os2Ascender = in.readTTFShort(); //sTypoAscender os2Descender = in.readTTFShort(); //sTypoDescender if (log.isDebugEnabled()) { log.debug("sTypoAscender: " + os2Ascender + " -> internal " + convertTTFUnit2PDFUnit(os2Ascender)); log.debug("sTypoDescender: " + os2Descender + " -> internal " + convertTTFUnit2PDFUnit(os2Descender)); } v = in.readTTFShort(); //sTypoLineGap if (log.isDebugEnabled()) { log.debug("sTypoLineGap: " + v); } v = in.readTTFUShort(); //usWinAscent if (log.isDebugEnabled()) { log.debug("usWinAscent: " + formatUnitsForDebug(v)); } v = in.readTTFUShort(); //usWinDescent if (log.isDebugEnabled()) { log.debug("usWinDescent: " + formatUnitsForDebug(v)); } //version 1 OS/2 table might end here if (os2Entry.getLength() >= 78 + (2 * 4) + (2 * 2)) { in.skip(2 * 4); this.os2xHeight = in.readTTFShort(); //sxHeight this.os2CapHeight = in.readTTFShort(); //sCapHeight if (log.isDebugEnabled()) { log.debug("sxHeight: " + this.os2xHeight); log.debug("sCapHeight: " + this.os2CapHeight); } } } else { isEmbeddable = true; } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected final void readIndexToLocation(FontFileReader in) throws IOException { if (!seekTab(in, "loca", 0)) { throw new IOException("'loca' table not found, happens when the font file doesn't" + " contain TrueType outlines (trying to read an OpenType CFF font maybe?)"); } for (int i = 0; i < numberOfGlyphs; i++) { mtxTab[i].setOffset(locaFormat == 1 ? in.readTTFULong() : (in.readTTFUShort() << 1)); } lastLoca = (locaFormat == 1 ? in.readTTFULong() : (in.readTTFUShort() << 1)); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private void readGlyf(FontFileReader in) throws IOException { TTFDirTabEntry dirTab = getDirectoryEntry ( "glyf" ); if (dirTab == null) { throw new IOException("glyf table not found, cannot continue"); } for (int i = 0; i < (numberOfGlyphs - 1); i++) { if (mtxTab[i].getOffset() != mtxTab[i + 1].getOffset()) { in.seekSet(dirTab.getOffset() + mtxTab[i].getOffset()); in.skip(2); final int[] bbox = { in.readTTFShort(), in.readTTFShort(), in.readTTFShort(), in.readTTFShort()}; mtxTab[i].setBoundingBox(bbox); } else { mtxTab[i].setBoundingBox(mtxTab[0].getBoundingBox()); } } long n = dirTab.getOffset(); for (int i = 0; i < numberOfGlyphs; i++) { if ((i + 1) >= mtxTab.length || mtxTab[i].getOffset() != mtxTab[i + 1].getOffset()) { in.seekSet(n + mtxTab[i].getOffset()); in.skip(2); final int[] bbox = { in.readTTFShort(), in.readTTFShort(), in.readTTFShort(), in.readTTFShort()}; mtxTab[i].setBoundingBox(bbox); } else { /**@todo Verify that this is correct, looks like a copy/paste bug (jm)*/ final int bbox0 = mtxTab[0].getBoundingBox()[0]; final int[] bbox = {bbox0, bbox0, bbox0, bbox0}; mtxTab[i].setBoundingBox(bbox); /* Original code mtxTab[i].bbox[0] = mtxTab[0].bbox[0]; mtxTab[i].bbox[1] = mtxTab[0].bbox[0]; mtxTab[i].bbox[2] = mtxTab[0].bbox[0]; mtxTab[i].bbox[3] = mtxTab[0].bbox[0]; */ } if (log.isTraceEnabled()) { log.trace(mtxTab[i].toString(this)); } } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private void readName(FontFileReader in) throws IOException { seekTab(in, "name", 2); int i = in.getCurrentPos(); int n = in.readTTFUShort(); int j = in.readTTFUShort() + i - 2; i += 2 * 2; while (n-- > 0) { // getLogger().debug("Iteration: " + n); in.seekSet(i); final int platformID = in.readTTFUShort(); final int encodingID = in.readTTFUShort(); final int languageID = in.readTTFUShort(); int k = in.readTTFUShort(); int l = in.readTTFUShort(); if (((platformID == 1 || platformID == 3) && (encodingID == 0 || encodingID == 1))) { in.seekSet(j + in.readTTFUShort()); String txt; if (platformID == 3) { txt = in.readTTFString(l, encodingID); } else { txt = in.readTTFString(l); } if (log.isDebugEnabled()) { log.debug(platformID + " " + encodingID + " " + languageID + " " + k + " " + txt); } switch (k) { case 0: if (notice.length() == 0) { notice = txt; } break; case 1: //Font Family Name case 16: //Preferred Family familyNames.add(txt); break; case 2: if (subFamilyName.length() == 0) { subFamilyName = txt; } break; case 4: if (fullName.length() == 0 || (platformID == 3 && languageID == 1033)) { fullName = txt; } break; case 6: if (postScriptName.length() == 0) { postScriptName = txt; } break; default: break; } } i += 6 * 2; } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private boolean readPCLT(FontFileReader in) throws IOException { TTFDirTabEntry dirTab = getDirectoryEntry ( "PCLT" ); if (dirTab != null) { in.seekSet(dirTab.getOffset() + 4 + 4 + 2); xHeight = in.readTTFUShort(); log.debug("xHeight from PCLT: " + formatUnitsForDebug(xHeight)); in.skip(2 * 2); capHeight = in.readTTFUShort(); log.debug("capHeight from PCLT: " + formatUnitsForDebug(capHeight)); in.skip(2 + 16 + 8 + 6 + 1 + 1); int serifStyle = in.readTTFUByte(); serifStyle = serifStyle >> 6; serifStyle = serifStyle & 3; if (serifStyle == 1) { hasSerifs = false; } else { hasSerifs = true; } return true; } else { return false; } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private void readKerning(FontFileReader in) throws IOException { // Read kerning kerningTab = new java.util.HashMap(); ansiKerningTab = new java.util.HashMap(); TTFDirTabEntry dirTab = getDirectoryEntry ( "kern" ); if (dirTab != null) { seekTab(in, "kern", 2); for (int n = in.readTTFUShort(); n > 0; n--) { in.skip(2 * 2); int k = in.readTTFUShort(); if (!((k & 1) != 0) || (k & 2) != 0 || (k & 4) != 0) { return; } if ((k >> 8) != 0) { continue; } k = in.readTTFUShort(); in.skip(3 * 2); while (k-- > 0) { int i = in.readTTFUShort(); int j = in.readTTFUShort(); int kpx = in.readTTFShort(); if (kpx != 0) { // CID kerning table entry, using unicode indexes final Integer iObj = glyphToUnicode(i); final Integer u2 = glyphToUnicode(j); if (iObj == null) { // happens for many fonts (Ubuntu font set), // stray entries in the kerning table?? log.debug("Ignoring kerning pair because no Unicode index was" + " found for the first glyph " + i); } else if (u2 == null) { log.debug("Ignoring kerning pair because Unicode index was" + " found for the second glyph " + i); } else { Map adjTab = kerningTab.get(iObj); if (adjTab == null) { adjTab = new java.util.HashMap(); } adjTab.put(u2, new Integer(convertTTFUnit2PDFUnit(kpx))); kerningTab.put(iObj, adjTab); } } } } // Create winAnsiEncoded kerning table from kerningTab // (could probably be simplified, for now we remap back to CID indexes and // then to winAnsi) Iterator ae = kerningTab.keySet().iterator(); while (ae.hasNext()) { Integer unicodeKey1 = (Integer)ae.next(); Integer cidKey1 = unicodeToGlyph(unicodeKey1.intValue()); Map<Integer, Integer> akpx = new java.util.HashMap(); Map ckpx = kerningTab.get(unicodeKey1); Iterator aee = ckpx.keySet().iterator(); while (aee.hasNext()) { Integer unicodeKey2 = (Integer)aee.next(); Integer cidKey2 = unicodeToGlyph(unicodeKey2.intValue()); Integer kern = (Integer)ckpx.get(unicodeKey2); Iterator uniMap = mtxTab[cidKey2.intValue()].getUnicodeIndex().listIterator(); while (uniMap.hasNext()) { Integer unicodeKey = (Integer)uniMap.next(); Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue()); for (int u = 0; u < ansiKeys.length; u++) { akpx.put(ansiKeys[u], kern); } } } if (akpx.size() > 0) { Iterator uniMap = mtxTab[cidKey1.intValue()].getUnicodeIndex().listIterator(); while (uniMap.hasNext()) { Integer unicodeKey = (Integer)uniMap.next(); Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue()); for (int u = 0; u < ansiKeys.length; u++) { ansiKerningTab.put(ansiKeys[u], akpx); } } } } } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected final boolean checkTTC(FontFileReader in, String name) throws IOException { String tag = in.readTTFString(4); if ("ttcf".equals(tag)) { // This is a TrueType Collection in.skip(4); // Read directory offsets int numDirectories = (int)in.readTTFULong(); // int numDirectories=in.readTTFUShort(); long[] dirOffsets = new long[numDirectories]; for (int i = 0; i < numDirectories; i++) { dirOffsets[i] = in.readTTFULong(); } log.info("This is a TrueType collection file with " + numDirectories + " fonts"); log.info("Containing the following fonts: "); // Read all the directories and name tables to check // If the font exists - this is a bit ugly, but... boolean found = false; // Iterate through all name tables even if font // Is found, just to show all the names long dirTabOffset = 0; for (int i = 0; (i < numDirectories); i++) { in.seekSet(dirOffsets[i]); readDirTabs(in); readName(in); if (fullName.equals(name)) { found = true; dirTabOffset = dirOffsets[i]; log.info(fullName + " <-- selected"); } else { log.info(fullName); } // Reset names notice = ""; fullName = ""; familyNames.clear(); postScriptName = ""; subFamilyName = ""; } in.seekSet(dirTabOffset); return found; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
public final List<String> getTTCnames(FontFileReader in) throws IOException { List<String> fontNames = new java.util.ArrayList<String>(); String tag = in.readTTFString(4); if ("ttcf".equals(tag)) { // This is a TrueType Collection in.skip(4); // Read directory offsets int numDirectories = (int)in.readTTFULong(); long[] dirOffsets = new long[numDirectories]; for (int i = 0; i < numDirectories; i++) { dirOffsets[i] = in.readTTFULong(); } log.info("This is a TrueType collection file with " + numDirectories + " fonts"); log.info("Containing the following fonts: "); for (int i = 0; (i < numDirectories); i++) { in.seekSet(dirOffsets[i]); readDirTabs(in); readName(in); log.info(fullName); fontNames.add(fullName); // Reset names notice = ""; fullName = ""; familyNames.clear(); postScriptName = ""; subFamilyName = ""; } in.seekSet(0); return fontNames; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private Integer unicodeToGlyph(int unicodeIndex) throws IOException { final Integer result = (Integer) unicodeToGlyphMap.get(new Integer(unicodeIndex)); if (result == null) { throw new IOException( "Glyph index not found for unicode value " + unicodeIndex); } return result; }
// in src/java/org/apache/fop/fonts/truetype/GlyfTable.java
void populateGlyphsWithComposites() throws IOException { for (int indexInOriginal : subset.keySet()) { scanGlyphsRecursively(indexInOriginal); } addAllComposedGlyphsToSubset(); for (int compositeGlyph : compositeGlyphs) { long offset = tableOffset + mtxTab[compositeGlyph].getOffset() + 10; if (!remappedComposites.contains(offset)) { remapComposite(offset); } } }
// in src/java/org/apache/fop/fonts/truetype/GlyfTable.java
private void scanGlyphsRecursively(int indexInOriginal) throws IOException { if (!subset.containsKey(indexInOriginal)) { composedGlyphs.add(indexInOriginal); } if (isComposite(indexInOriginal)) { compositeGlyphs.add(indexInOriginal); Set<Integer> composedGlyphs = retrieveComposedGlyphs(indexInOriginal); for (Integer composedGlyph : composedGlyphs) { scanGlyphsRecursively(composedGlyph); } } }
// in src/java/org/apache/fop/fonts/truetype/GlyfTable.java
private void remapComposite(long glyphOffset) throws IOException { long currentGlyphOffset = glyphOffset; remappedComposites.add(currentGlyphOffset); int flags = 0; do { flags = in.readTTFUShort(currentGlyphOffset); int glyphIndex = in.readTTFUShort(currentGlyphOffset + 2); Integer indexInSubset = subset.get(glyphIndex); assert indexInSubset != null; /* * TODO: this should not be done here!! We're writing to the stream we're reading from, * this is asking for trouble! What should happen is when the glyph data is copied from * subset, the remapping should be done there. So the original stream is left untouched. */ in.writeTTFUShort(currentGlyphOffset + 2, indexInSubset); currentGlyphOffset += 4 + GlyfFlags.getOffsetToNextComposedGlyf(flags); } while (GlyfFlags.hasMoreComposites(flags)); }
// in src/java/org/apache/fop/fonts/truetype/GlyfTable.java
private boolean isComposite(int indexInOriginal) throws IOException { int numberOfContours = in.readTTFShort(tableOffset + mtxTab[indexInOriginal].getOffset()); return numberOfContours < 0; }
// in src/java/org/apache/fop/fonts/truetype/GlyfTable.java
private Set<Integer> retrieveComposedGlyphs(int indexInOriginal) throws IOException { Set<Integer> composedGlyphs = new HashSet<Integer>(); long offset = tableOffset + mtxTab[indexInOriginal].getOffset() + 10; int flags = 0; do { flags = in.readTTFUShort(offset); composedGlyphs.add(in.readTTFUShort(offset + 2)); offset += 4 + GlyfFlags.getOffsetToNextComposedGlyf(flags); } while (GlyfFlags.hasMoreComposites(flags)); return composedGlyphs; }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private boolean createCvt(FontFileReader in) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("cvt "); if (entry != null) { pad4(); seekTab(in, "cvt ", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(cvtDirOffset, checksum); writeULong(cvtDirOffset + 4, currentPos); writeULong(cvtDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); return true; } else { return false; //throw new IOException("Can't find cvt table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private boolean createFpgm(FontFileReader in) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("fpgm"); if (entry != null) { pad4(); seekTab(in, "fpgm", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(fpgmDirOffset, checksum); writeULong(fpgmDirOffset + 4, currentPos); writeULong(fpgmDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); return true; } else { return false; } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createLoca(int size) throws IOException { pad4(); locaOffset = currentPos; writeULong(locaDirOffset + 4, currentPos); writeULong(locaDirOffset + 8, size * 4 + 4); currentPos += size * 4 + 4; realSize += size * 4 + 4; }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createMaxp(FontFileReader in, int size) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("maxp"); if (entry != null) { pad4(); seekTab(in, "maxp", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); writeUShort(currentPos + 4, size); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(maxpDirOffset, checksum); writeULong(maxpDirOffset + 4, currentPos); writeULong(maxpDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); } else { throw new IOException("Can't find maxp table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private boolean createPrep(FontFileReader in) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("prep"); if (entry != null) { pad4(); seekTab(in, "prep", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(prepDirOffset, checksum); writeULong(prepDirOffset + 4, currentPos); writeULong(prepDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); return true; } else { return false; } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createHhea(FontFileReader in, int size) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("hhea"); if (entry != null) { pad4(); seekTab(in, "hhea", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); writeUShort((int)entry.getLength() + currentPos - 2, size); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(hheaDirOffset, checksum); writeULong(hheaDirOffset + 4, currentPos); writeULong(hheaDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); } else { throw new IOException("Can't find hhea table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createHead(FontFileReader in) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("head"); if (entry != null) { pad4(); seekTab(in, "head", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); checkSumAdjustmentOffset = currentPos + 8; output[currentPos + 8] = 0; // Set checkSumAdjustment to 0 output[currentPos + 9] = 0; output[currentPos + 10] = 0; output[currentPos + 11] = 0; output[currentPos + 50] = 0; // long locaformat output[currentPos + 51] = 1; // long locaformat int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(headDirOffset, checksum); writeULong(headDirOffset + 4, currentPos); writeULong(headDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); } else { throw new IOException("Can't find head table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createGlyf(FontFileReader in, Map glyphs) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("glyf"); int size = 0; int start = 0; int endOffset = 0; // Store this as the last loca if (entry != null) { pad4(); start = currentPos; /* Loca table must be in order by glyph index, so build * an array first and then write the glyph info and * location offset. */ int[] origIndexes = new int[glyphs.size()]; Iterator e = glyphs.keySet().iterator(); while (e.hasNext()) { Integer origIndex = (Integer)e.next(); Integer subsetIndex = (Integer)glyphs.get(origIndex); origIndexes[subsetIndex.intValue()] = origIndex.intValue(); } for (int i = 0; i < origIndexes.length; i++) { int glyphLength = 0; int nextOffset = 0; int origGlyphIndex = origIndexes[i]; if (origGlyphIndex >= (mtxTab.length - 1)) { nextOffset = (int)lastLoca; } else { nextOffset = (int)mtxTab[origGlyphIndex + 1].getOffset(); } glyphLength = nextOffset - (int)mtxTab[origGlyphIndex].getOffset(); // Copy glyph System.arraycopy( in.getBytes((int)entry.getOffset() + (int)mtxTab[origGlyphIndex].getOffset(), glyphLength), 0, output, currentPos, glyphLength); // Update loca table writeULong(locaOffset + i * 4, currentPos - start); if ((currentPos - start + glyphLength) > endOffset) { endOffset = (currentPos - start + glyphLength); } currentPos += glyphLength; realSize += glyphLength; } size = currentPos - start; int checksum = getCheckSum(start, size); writeULong(glyfDirOffset, checksum); writeULong(glyfDirOffset + 4, start); writeULong(glyfDirOffset + 8, size); currentPos += 12; realSize += 12; // Update loca checksum and last loca index writeULong(locaOffset + glyphs.size() * 4, endOffset); checksum = getCheckSum(locaOffset, glyphs.size() * 4 + 4); writeULong(locaDirOffset, checksum); } else { throw new IOException("Can't find glyf table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createHmtx(FontFileReader in, Map glyphs) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("hmtx"); int longHorMetricSize = glyphs.size() * 2; int leftSideBearingSize = glyphs.size() * 2; int hmtxSize = longHorMetricSize + leftSideBearingSize; if (entry != null) { pad4(); //int offset = (int)entry.offset; Iterator e = glyphs.keySet().iterator(); while (e.hasNext()) { Integer origIndex = (Integer)e.next(); Integer subsetIndex = (Integer)glyphs.get(origIndex); writeUShort(currentPos + subsetIndex.intValue() * 4, mtxTab[origIndex.intValue()].getWx()); writeUShort(currentPos + subsetIndex.intValue() * 4 + 2, mtxTab[origIndex.intValue()].getLsb()); } int checksum = getCheckSum(currentPos, hmtxSize); writeULong(hmtxDirOffset, checksum); writeULong(hmtxDirOffset + 4, currentPos); writeULong(hmtxDirOffset + 8, hmtxSize); currentPos += hmtxSize; realSize += hmtxSize; } else { throw new IOException("Can't find hmtx table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
public byte[] readFont(FontFileReader in, String name, Map<Integer, Integer> glyphs) throws IOException { //Check if TrueType collection, and that the name exists in the collection if (!checkTTC(in, name)) { throw new IOException("Failed to read font"); } //Copy the Map as we're going to modify it Map<Integer, Integer> subsetGlyphs = new java.util.HashMap<Integer, Integer>(glyphs); output = new byte[in.getFileSize()]; readDirTabs(in); readFontHeader(in); getNumGlyphs(in); readHorizontalHeader(in); readHorizontalMetrics(in); readIndexToLocation(in); scanGlyphs(in, subsetGlyphs); createDirectory(); // Create the TrueType header and directory createHead(in); createHhea(in, subsetGlyphs.size()); // Create the hhea table createHmtx(in, subsetGlyphs); // Create hmtx table createMaxp(in, subsetGlyphs.size()); // copy the maxp table boolean optionalTableFound; optionalTableFound = createCvt(in); // copy the cvt table if (!optionalTableFound) { // cvt is optional (used in TrueType fonts only) log.debug("TrueType: ctv table not present. Skipped."); } optionalTableFound = createFpgm(in); // copy fpgm table if (!optionalTableFound) { // fpgm is optional (used in TrueType fonts only) log.debug("TrueType: fpgm table not present. Skipped."); } optionalTableFound = createPrep(in); // copy prep table if (!optionalTableFound) { // prep is optional (used in TrueType fonts only) log.debug("TrueType: prep table not present. Skipped."); } createLoca(subsetGlyphs.size()); // create empty loca table createGlyf(in, subsetGlyphs); //create glyf table and update loca table pad4(); createCheckSumAdjustment(); byte[] ret = new byte[realSize]; System.arraycopy(output, 0, ret, 0, realSize); return ret; }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void scanGlyphs(FontFileReader in, Map<Integer, Integer> subsetGlyphs) throws IOException { TTFDirTabEntry glyfTableInfo = (TTFDirTabEntry) dirTabs.get("glyf"); if (glyfTableInfo == null) { throw new IOException("Glyf table could not be found"); } GlyfTable glyfTable = new GlyfTable(in, mtxTab, glyfTableInfo, subsetGlyphs); glyfTable.populateGlyphsWithComposites(); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
private void init(InputStream in) throws java.io.IOException { this.file = IOUtils.toByteArray(in); this.fsize = this.file.length; this.current = 0; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public void seekSet(long offset) throws IOException { if (offset > fsize || offset < 0) { throw new java.io.EOFException("Reached EOF, file size=" + fsize + " offset=" + offset); } current = (int)offset; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public void seekAdd(long add) throws IOException { seekSet(current + add); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public void skip(long add) throws IOException { seekAdd(add); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public byte read() throws IOException { if (current >= fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } final byte ret = file[current++]; return ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final byte readTTFByte() throws IOException { return read(); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final int readTTFUByte() throws IOException { final byte buf = read(); if (buf < 0) { return (int)(256 + buf); } else { return (int)buf; } }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final short readTTFShort() throws IOException { final int ret = (readTTFUByte() << 8) + readTTFUByte(); final short sret = (short)ret; return sret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final int readTTFUShort() throws IOException { final int ret = (readTTFUByte() << 8) + readTTFUByte(); return (int)ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final void writeTTFUShort(long pos, int val) throws IOException { if ((pos + 2) > fsize) { throw new java.io.EOFException("Reached EOF"); } final byte b1 = (byte)((val >> 8) & 0xff); final byte b2 = (byte)(val & 0xff); final int fileIndex = (int) pos; file[fileIndex] = b1; file[fileIndex + 1] = b2; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final short readTTFShort(long pos) throws IOException { final long cp = getCurrentPos(); seekSet(pos); final short ret = readTTFShort(); seekSet(cp); return ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final int readTTFUShort(long pos) throws IOException { long cp = getCurrentPos(); seekSet(pos); int ret = readTTFUShort(); seekSet(cp); return ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final int readTTFLong() throws IOException { long ret = readTTFUByte(); // << 8; ret = (ret << 8) + readTTFUByte(); ret = (ret << 8) + readTTFUByte(); ret = (ret << 8) + readTTFUByte(); return (int)ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final long readTTFULong() throws IOException { long ret = readTTFUByte(); ret = (ret << 8) + readTTFUByte(); ret = (ret << 8) + readTTFUByte(); ret = (ret << 8) + readTTFUByte(); return ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final String readTTFString() throws IOException { int i = current; while (file[i++] != 0) { if (i > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } } byte[] tmp = new byte[i - current]; System.arraycopy(file, current, tmp, 0, i - current); return new String(tmp, "ISO-8859-1"); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final String readTTFString(int len) throws IOException { if ((len + current) > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } byte[] tmp = new byte[len]; System.arraycopy(file, current, tmp, 0, len); current += len; final String encoding; if ((tmp.length > 0) && (tmp[0] == 0)) { encoding = "UTF-16BE"; } else { encoding = "ISO-8859-1"; } return new String(tmp, encoding); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final String readTTFString(int len, int encodingID) throws IOException { if ((len + current) > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } byte[] tmp = new byte[len]; System.arraycopy(file, current, tmp, 0, len); current += len; final String encoding; encoding = "UTF-16BE"; //Use this for all known encoding IDs for now return new String(tmp, encoding); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public byte[] getBytes(int offset, int length) throws IOException { if ((offset + length) > fsize) { throw new java.io.IOException("Reached EOF"); } byte[] ret = new byte[length]; System.arraycopy(file, offset, ret, 0, length); return ret; }
// in src/java/org/apache/fop/fonts/truetype/TTFFontLoader.java
Override protected void read() throws IOException { read(this.subFontName); }
// in src/java/org/apache/fop/fonts/truetype/TTFFontLoader.java
private void read(String ttcFontName) throws IOException { InputStream in = openFontUri(resolver, this.fontFileURI); try { TTFFile ttf = new TTFFile(useKerning, useAdvanced); FontFileReader reader = new FontFileReader(in); boolean supported = ttf.readFont(reader, ttcFontName); if (!supported) { throw new IOException("TrueType font is not supported: " + fontFileURI); } buildFont(ttf, ttcFontName); loaded = true; } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/render/print/PrintRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); try { printerJob.print(); } catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); } clearViewportList(); }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); if (endNumber == -1) { // was not set on command line endNumber = getNumberOfPages(); } }
// in src/java/org/apache/fop/render/pdf/ImageRenderedAdapter.java
public void outputContents(OutputStream out) throws IOException { long start = System.currentTimeMillis(); encodingHelper.encode(out); long duration = System.currentTimeMillis() - start; if (log.isDebugEnabled()) { log.debug("Image encoding took " + duration + "ms"); } }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addsRGBColorSpace() throws IOException { if (disableSRGBColorSpace) { if (this.pdfAMode != PDFAMode.DISABLED || this.pdfXMode != PDFXMode.DISABLED || this.outputProfileURI != null) { throw new IllegalStateException("It is not possible to disable the sRGB color" + " space if PDF/A or PDF/X functionality is enabled or an" + " output profile is set!"); } } else { if (this.sRGBColorSpace != null) { return; } //Map sRGB as default RGB profile for DeviceRGB this.sRGBColorSpace = PDFICCBasedColorSpace.setupsRGBAsDefaultRGBColorSpace(pdfDoc); } }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addDefaultOutputProfile() throws IOException { if (this.outputProfile != null) { return; } ICC_Profile profile; InputStream in = null; if (this.outputProfileURI != null) { this.outputProfile = pdfDoc.getFactory().makePDFICCStream(); Source src = getUserAgent().resolveURI(this.outputProfileURI); if (src == null) { throw new IOException("Output profile not found: " + this.outputProfileURI); } if (src instanceof StreamSource) { in = ((StreamSource)src).getInputStream(); } else { in = new URL(src.getSystemId()).openStream(); } try { profile = ColorProfileUtil.getICC_Profile(in); } finally { IOUtils.closeQuietly(in); } this.outputProfile.setColorSpace(profile, null); } else { //Fall back to sRGB profile outputProfile = sRGBColorSpace.getICCStream(); } }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addPDFA1OutputIntent() throws IOException { addDefaultOutputProfile(); String desc = ColorProfileUtil.getICCProfileDescription(this.outputProfile.getICCProfile()); PDFOutputIntent outputIntent = pdfDoc.getFactory().makeOutputIntent(); outputIntent.setSubtype(PDFOutputIntent.GTS_PDFA1); outputIntent.setDestOutputProfile(this.outputProfile); outputIntent.setOutputConditionIdentifier(desc); outputIntent.setInfo(outputIntent.getOutputConditionIdentifier()); pdfDoc.getRoot().addOutputIntent(outputIntent); }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addPDFXOutputIntent() throws IOException { addDefaultOutputProfile(); String desc = ColorProfileUtil.getICCProfileDescription(this.outputProfile.getICCProfile()); int deviceClass = this.outputProfile.getICCProfile().getProfileClass(); if (deviceClass != ICC_Profile.CLASS_OUTPUT) { throw new PDFConformanceException(pdfDoc.getProfile().getPDFXMode() + " requires that" + " the DestOutputProfile be an Output Device Profile. " + desc + " does not match that requirement."); } PDFOutputIntent outputIntent = pdfDoc.getFactory().makeOutputIntent(); outputIntent.setSubtype(PDFOutputIntent.GTS_PDFX); outputIntent.setDestOutputProfile(this.outputProfile); outputIntent.setOutputConditionIdentifier(desc); outputIntent.setInfo(outputIntent.getOutputConditionIdentifier()); pdfDoc.getRoot().addOutputIntent(outputIntent); }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
public PDFDocument setupPDFDocument(OutputStream out) throws IOException { if (this.pdfDoc != null) { throw new IllegalStateException("PDFDocument already set up"); } String producer = userAgent.getProducer() != null ? userAgent.getProducer() : ""; if (maxPDFVersion == null) { this.pdfDoc = new PDFDocument(producer); } else { VersionController controller = VersionController.getFixedVersionController(maxPDFVersion); this.pdfDoc = new PDFDocument(producer, controller); } updateInfo(); updatePDFProfiles(); pdfDoc.setFilterMap(filterMap); pdfDoc.outputHeader(out); //Setup encryption if necessary PDFEncryptionManager.setupPDFEncryption(encryptionParams, pdfDoc); addsRGBColorSpace(); if (this.outputProfileURI != null) { addDefaultOutputProfile(); } if (pdfXMode != PDFXMode.DISABLED) { log.debug(pdfXMode + " is active."); log.warn("Note: " + pdfXMode + " support is work-in-progress and not fully implemented, yet!"); addPDFXOutputIntent(); } if (pdfAMode.isPDFA1LevelB()) { log.debug("PDF/A is active. Conformance Level: " + pdfAMode); addPDFA1OutputIntent(); } this.pdfDoc.enableAccessibility(userAgent.isAccessibilityEnabled()); return this.pdfDoc; }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
public void addEmbeddedFile(PDFEmbeddedFileExtensionAttachment embeddedFile) throws IOException { this.pdfDoc.getProfile().verifyEmbeddedFilesAllowed(); PDFNames names = this.pdfDoc.getRoot().getNames(); if (names == null) { //Add Names if not already present names = this.pdfDoc.getFactory().makeNames(); this.pdfDoc.getRoot().setNames(names); } //Create embedded file PDFEmbeddedFile file = new PDFEmbeddedFile(); this.pdfDoc.registerObject(file); Source src = getUserAgent().resolveURI(embeddedFile.getSrc()); InputStream in = ImageUtil.getInputStream(src); if (in == null) { throw new FileNotFoundException(embeddedFile.getSrc()); } try { OutputStream out = file.getBufferOutputStream(); IOUtils.copyLarge(in, out); } finally { IOUtils.closeQuietly(in); } PDFDictionary dict = new PDFDictionary(); dict.put("F", file); String filename = PDFText.toPDFString(embeddedFile.getFilename(), '_'); PDFFileSpec fileSpec = new PDFFileSpec(filename); fileSpec.setEmbeddedFile(dict); if (embeddedFile.getDesc() != null) { fileSpec.setDescription(embeddedFile.getDesc()); } this.pdfDoc.registerObject(fileSpec); //Make sure there is an EmbeddedFiles in the Names dictionary PDFEmbeddedFiles embeddedFiles = names.getEmbeddedFiles(); if (embeddedFiles == null) { embeddedFiles = new PDFEmbeddedFiles(); this.pdfDoc.assignObjectNumber(embeddedFiles); this.pdfDoc.addTrailerObject(embeddedFiles); names.setEmbeddedFiles(embeddedFiles); } //Add to EmbeddedFiles in the Names dictionary PDFArray nameArray = embeddedFiles.getNames(); if (nameArray == null) { nameArray = new PDFArray(); embeddedFiles.setNames(nameArray); } String name = PDFText.toPDFString(filename); nameArray.add(name); nameArray.add(new PDFReference(fileSpec)); }
// in src/java/org/apache/fop/render/pdf/PDFContentGenerator.java
public void flushPDFDoc() throws IOException { this.document.output(this.outputStream); }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
public void handleImage(RenderingContext context, // CSOK: MethodLength Image image, Rectangle pos) throws IOException { PDFRenderingContext pdfContext = (PDFRenderingContext)context; PDFContentGenerator generator = pdfContext.getGenerator(); ImageXMLDOM imageSVG = (ImageXMLDOM)image; FOUserAgent userAgent = context.getUserAgent(); final float deviceResolution = userAgent.getTargetResolution(); if (log.isDebugEnabled()) { log.debug("Generating SVG at " + deviceResolution + "dpi."); } final float uaResolution = userAgent.getSourceResolution(); SVGUserAgent ua = new SVGUserAgent(userAgent, new AffineTransform()); GVTBuilder builder = new GVTBuilder(); //Controls whether text painted by Batik is generated using text or path operations boolean strokeText = false; //TODO connect with configuration elsewhere. BridgeContext ctx = new PDFBridgeContext(ua, (strokeText ? null : pdfContext.getFontInfo()), userAgent.getFactory().getImageManager(), userAgent.getImageSessionContext(), new AffineTransform()); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(imageSVG.getDocument()); GraphicsNode root; try { root = builder.build(ctx, clonedDoc); builder = null; } catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; } // get the 'width' and 'height' attributes of the SVG document float w = image.getSize().getWidthMpt(); float h = image.getSize().getHeightMpt(); float sx = pos.width / w; float sy = pos.height / h; //Scaling and translation for the bounding box of the image AffineTransform scaling = new AffineTransform( sx, 0, 0, sy, pos.x / 1000f, pos.y / 1000f); double sourceScale = UnitConv.IN2PT / uaResolution; scaling.scale(sourceScale, sourceScale); //Scale for higher resolution on-the-fly images from Batik AffineTransform resolutionScaling = new AffineTransform(); double targetScale = uaResolution / deviceResolution; resolutionScaling.scale(targetScale, targetScale); resolutionScaling.scale(1.0 / sx, 1.0 / sy); //Transformation matrix that establishes the local coordinate system for the SVG graphic //in relation to the current coordinate system AffineTransform imageTransform = new AffineTransform(); imageTransform.concatenate(scaling); imageTransform.concatenate(resolutionScaling); if (log.isTraceEnabled()) { log.trace("nat size: " + w + "/" + h); log.trace("req size: " + pos.width + "/" + pos.height); log.trace("source res: " + uaResolution + ", targetRes: " + deviceResolution + " --> target scaling: " + targetScale); log.trace(image.getSize()); log.trace("sx: " + sx + ", sy: " + sy); log.trace("scaling: " + scaling); log.trace("resolution scaling: " + resolutionScaling); log.trace("image transform: " + resolutionScaling); } /* * Clip to the svg area. * Note: To have the svg overlay (under) a text area then use * an fo:block-container */ if (log.isTraceEnabled()) { generator.comment("SVG setup"); } generator.saveGraphicsState(); if (context.getUserAgent().isAccessibilityEnabled()) { MarkedContentInfo mci = pdfContext.getMarkedContentInfo(); generator.beginMarkedContentSequence(mci.tag, mci.mcid); } generator.updateColor(Color.black, false, null); generator.updateColor(Color.black, true, null); if (!scaling.isIdentity()) { if (log.isTraceEnabled()) { generator.comment("viewbox"); } generator.add(CTMHelper.toPDFString(scaling, false) + " cm\n"); } //SVGSVGElement svg = ((SVGDocument)doc).getRootElement(); PDFGraphics2D graphics = new PDFGraphics2D(true, pdfContext.getFontInfo(), generator.getDocument(), generator.getResourceContext(), pdfContext.getPage().referencePDF(), "", 0); graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); if (!resolutionScaling.isIdentity()) { if (log.isTraceEnabled()) { generator.comment("resolution scaling for " + uaResolution + " -> " + deviceResolution); } generator.add( CTMHelper.toPDFString(resolutionScaling, false) + " cm\n"); graphics.scale( 1.0 / resolutionScaling.getScaleX(), 1.0 / resolutionScaling.getScaleY()); } if (log.isTraceEnabled()) { generator.comment("SVG start"); } //Save state and update coordinate system for the SVG image generator.getState().save(); generator.getState().concatenate(imageTransform); //Now that we have the complete transformation matrix for the image, we can update the //transformation matrix for the AElementBridge. PDFAElementBridge aBridge = (PDFAElementBridge)ctx.getBridge( SVGDOMImplementation.SVG_NAMESPACE_URI, SVGConstants.SVG_A_TAG); aBridge.getCurrentTransform().setTransform(generator.getState().getTransform()); graphics.setPaintingState(generator.getState()); graphics.setOutputStream(generator.getOutputStream()); try { root.paint(graphics); ctx.dispose(); generator.add(graphics.getString()); } catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); } generator.getState().restore(); if (context.getUserAgent().isAccessibilityEnabled()) { generator.restoreGraphicsStateAccess(); } else { generator.restoreGraphicsState(); } if (log.isTraceEnabled()) { generator.comment("SVG end"); } }
// in src/java/org/apache/fop/render/pdf/AbstractPDFImageHandler.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { assert context instanceof PDFRenderingContext; PDFRenderingContext pdfContext = (PDFRenderingContext)context; PDFContentGenerator generator = pdfContext.getGenerator(); PDFImage pdfimage = createPDFImage(image, image.getInfo().getOriginalURI()); PDFXObject xobj = generator.getDocument().addImage( generator.getResourceContext(), pdfimage); float x = (float)pos.getX() / 1000f; float y = (float)pos.getY() / 1000f; float w = (float)pos.getWidth() / 1000f; float h = (float)pos.getHeight() / 1000f; if (context.getUserAgent().isAccessibilityEnabled()) { MarkedContentInfo mci = pdfContext.getMarkedContentInfo(); generator.placeImage(x, y, w, h, xobj, mci.tag, mci.mcid); } else { generator.placeImage(x, y, w, h, xobj); } }
// in src/java/org/apache/fop/render/pdf/ImageRawCCITTFaxAdapter.java
public void outputContents(OutputStream out) throws IOException { getImage().writeTo(out); }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerGraphics2D.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PDFRenderingContext pdfContext = (PDFRenderingContext)context; PDFContentGenerator generator = pdfContext.getGenerator(); ImageGraphics2D imageG2D = (ImageGraphics2D)image; float fwidth = pos.width / 1000f; float fheight = pos.height / 1000f; float fx = pos.x / 1000f; float fy = pos.y / 1000f; // get the 'width' and 'height' attributes of the SVG document Dimension dim = image.getInfo().getSize().getDimensionMpt(); float imw = (float)dim.getWidth() / 1000f; float imh = (float)dim.getHeight() / 1000f; float sx = fwidth / imw; float sy = fheight / imh; generator.comment("G2D start"); boolean accessibilityEnabled = context.getUserAgent().isAccessibilityEnabled(); if (accessibilityEnabled) { MarkedContentInfo mci = pdfContext.getMarkedContentInfo(); generator.saveGraphicsState(mci.tag, mci.mcid); } else { generator.saveGraphicsState(); } generator.updateColor(Color.black, false, null); generator.updateColor(Color.black, true, null); //TODO Clip to the image area. // transform so that the coordinates (0,0) is from the top left // and positive is down and to the right. (0,0) is where the // viewBox puts it. generator.add(sx + " 0 0 " + sy + " " + fx + " " + fy + " cm\n"); final boolean textAsShapes = false; PDFGraphics2D graphics = new PDFGraphics2D(textAsShapes, pdfContext.getFontInfo(), generator.getDocument(), generator.getResourceContext(), pdfContext.getPage().referencePDF(), "", 0.0f); graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); AffineTransform transform = new AffineTransform(); transform.translate(fx, fy); generator.getState().concatenate(transform); graphics.setPaintingState(generator.getState()); graphics.setOutputStream(generator.getOutputStream()); Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, imw, imh); imageG2D.getGraphics2DImagePainter().paint(graphics, area); generator.add(graphics.getString()); if (accessibilityEnabled) { generator.restoreGraphicsStateAccess(); } else { generator.restoreGraphicsState(); } generator.comment("G2D end"); }
// in src/java/org/apache/fop/render/pdf/ImageRawJPEGAdapter.java
public void outputContents(OutputStream out) throws IOException { InputStream in = getImage().createInputStream(); in = ImageUtil.decorateMarkSupported(in); try { JPEGFile jpeg = new JPEGFile(in); DataInput din = jpeg.getDataInput(); //Copy the whole JPEG file except: // - the ICC profile //TODO Thumbnails could safely be skipped, too. //TODO Metadata (XMP, IPTC, EXIF) could safely be skipped, too. while (true) { int reclen; int segID = jpeg.readMarkerSegment(); switch (segID) { case JPEGConstants.SOI: out.write(0xFF); out.write(segID); break; case JPEGConstants.EOI: case JPEGConstants.SOS: out.write(0xFF); out.write(segID); IOUtils.copy(in, out); //Just copy the rest! return; /* case JPEGConstants.APP1: //Metadata case JPEGConstants.APPD: jpeg.skipCurrentMarkerSegment(); break;*/ case JPEGConstants.APP2: //ICC (see ICC1V42.pdf) boolean skipICCProfile = false; in.mark(16); try { reclen = jpeg.readSegmentLength(); // Check for ICC profile byte[] iccString = new byte[11]; din.readFully(iccString); din.skipBytes(1); //string terminator (null byte) if ("ICC_PROFILE".equals(new String(iccString, "US-ASCII"))) { skipICCProfile = (this.image.getICCProfile() != null); } } finally { in.reset(); } if (skipICCProfile) { //ICC profile is skipped as it is already embedded as a PDF object jpeg.skipCurrentMarkerSegment(); break; } default: out.write(0xFF); out.write(segID); reclen = jpeg.readSegmentLength(); //write short out.write((reclen >>> 8) & 0xFF); out.write((reclen >>> 0) & 0xFF); int left = reclen - 2; byte[] buf = new byte[2048]; while (left > 0) { int part = Math.min(buf.length, left); din.readFully(buf, 0, part); out.write(buf, 0, part); left -= part; } } } } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { if (this.handler == null) { SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); try { TransformerHandler transformerHandler = factory.newTransformerHandler(); setContentHandler(transformerHandler); StreamResult res = new StreamResult(outputStream); transformerHandler.setResult(res); } catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); } this.out = outputStream; } try { handler.startDocument(); } catch (SAXException saxe) { handleSAXException(saxe); } }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
public void stopRenderer() throws IOException { try { handler.endDocument(); } catch (SAXException saxe) { handleSAXException(saxe); } if (this.out != null) { this.out.flush(); } }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
Override public void startRenderer(OutputStream outputStream) throws IOException { log.debug("Rendering areas to Area Tree XML"); if (this.handler == null) { SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); try { TransformerHandler transformerHandler = factory.newTransformerHandler(); this.handler = transformerHandler; StreamResult res = new StreamResult(outputStream); transformerHandler.setResult(res); } catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); } this.out = outputStream; } try { handler.startDocument(); } catch (SAXException saxe) { handleSAXException(saxe); } if (userAgent.getProducer() != null) { comment("Produced by " + userAgent.getProducer()); } atts.clear(); addAttribute("version", VERSION); startElement("areaTree", atts); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
Override public void stopRenderer() throws IOException { endPageSequence(); endElement("areaTree"); try { handler.endDocument(); } catch (SAXException saxe) { handleSAXException(saxe); } if (this.out != null) { this.out.flush(); } log.debug("Written out Area Tree XML"); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
Override public void renderPage(PageViewport page) throws IOException, FOPException { atts.clear(); addAttribute("bounds", page.getViewArea()); addAttribute("key", page.getKey()); addAttribute("nr", page.getPageNumber()); addAttribute("formatted-nr", page.getPageNumberString()); if (page.getSimplePageMasterName() != null) { addAttribute("simple-page-master-name", page.getSimplePageMasterName()); } if (page.isBlank()) { addAttribute("blank", "true"); } transferForeignObjects(page); startElement("pageViewport", atts); startElement("page"); handlePageExtensionAttachments(page); super.renderPage(page); endElement("page"); endElement("pageViewport"); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImageUsingImageHandler(ImageInfo info, Rectangle rect) throws ImageException, IOException { ImageManager manager = getFopFactory().getImageManager(); ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry(); //Load and convert the image to a supported format RenderingContext context = createRenderingContext(); Map hints = createDefaultImageProcessingHints(sessionContext); context.putHints(hints); ImageFlavor[] flavors = imageHandlerRegistry.getSupportedFlavors(context); org.apache.xmlgraphics.image.loader.Image img = manager.getImage( info, flavors, hints, sessionContext); try { drawImage(img, rect, context); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageWritingError(this, ioe); } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImage(Image image, Rectangle rect, RenderingContext context) throws IOException, ImageException { drawImage(image, rect, context, false, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImage(Image image, Rectangle rect, RenderingContext context, boolean convert, Map additionalHints) throws IOException, ImageException { ImageManager manager = getFopFactory().getImageManager(); ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry(); Image effImage; context.putHints(additionalHints); if (convert) { Map hints = createDefaultImageProcessingHints(getUserAgent().getImageSessionContext()); if (additionalHints != null) { hints.putAll(additionalHints); } effImage = manager.convertImage(image, imageHandlerRegistry.getSupportedFlavors(context), hints); } else { effImage = image; } //First check for a dynamically registered handler ImageHandler handler = imageHandlerRegistry.getHandler(context, effImage); if (handler == null) { throw new UnsupportedOperationException( "No ImageHandler available for image: " + effImage.getInfo() + " (" + effImage.getClass().getName() + ")"); } if (log.isTraceEnabled()) { log.trace("Using ImageHandler: " + handler.getClass().getName()); } handler.handleImage(context, effImage, rect); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
private void handleIFExceptionWithIOException(IFException ife) throws IOException { if (ife.getCause() instanceof IOException) { throw (IOException)ife.getCause(); } else { handleIFException(ife); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { try { if (outputStream != null) { StreamResult result = new StreamResult(outputStream); if (getUserAgent().getOutputFile() != null) { result.setSystemId( getUserAgent().getOutputFile().toURI().toURL().toExternalForm()); } if (this.documentHandler == null) { this.documentHandler = createDefaultDocumentHandler(); } this.documentHandler.setResult(result); } super.startRenderer(null); if (log.isDebugEnabled()) { log.debug("Rendering areas via IF document handler (" + this.documentHandler.getClass().getName() + ")..."); } documentHandler.startDocument(); documentHandler.startDocumentHeader(); } catch (IFException e) { handleIFExceptionWithIOException(e); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
public void stopRenderer() throws IOException { try { if (this.inPageSequence) { documentHandler.endPageSequence(); this.inPageSequence = false; } documentHandler.startDocumentTrailer(); //Wrap up document navigation if (hasDocumentNavigation()) { finishOpenGoTos(); Iterator iter = this.deferredDestinations.iterator(); while (iter.hasNext()) { NamedDestination dest = (NamedDestination)iter.next(); iter.remove(); getDocumentNavigationHandler().renderNamedDestination(dest); } if (this.bookmarkTree != null) { getDocumentNavigationHandler().renderBookmarkTree(this.bookmarkTree); } } documentHandler.endDocumentTrailer(); documentHandler.endDocument(); } catch (IFException e) { handleIFExceptionWithIOException(e); } pageIndices.clear(); idPositions.clear(); actionSet.clear(); super.stopRenderer(); log.debug("Rendering finished."); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
public void renderPage(PageViewport page) throws IOException, FOPException { if (log.isTraceEnabled()) { log.trace("renderPage() " + page); } try { pageIndices.put(page.getKey(), new Integer(page.getPageIndex())); Rectangle viewArea = page.getViewArea(); Dimension dim = new Dimension(viewArea.width, viewArea.height); establishForeignAttributes(page.getForeignAttributes()); documentHandler.startPage(page.getPageIndex(), page.getPageNumberString(), page.getSimplePageMasterName(), dim); resetForeignAttributes(); documentHandler.startPageHeader(); //Add page attachments to page header processExtensionAttachments(page); documentHandler.endPageHeader(); this.painter = documentHandler.startPageContent(); super.renderPage(page); this.painter = null; documentHandler.endPageContent(); documentHandler.startPageTrailer(); if (hasDocumentNavigation()) { Iterator iter = this.deferredLinks.iterator(); while (iter.hasNext()) { Link link = (Link)iter.next(); iter.remove(); getDocumentNavigationHandler().renderLink(link); } } documentHandler.endPageTrailer(); establishForeignAttributes(page.getForeignAttributes()); documentHandler.endPage(); resetForeignAttributes(); } catch (IFException e) { handleIFException(e); } }
// in src/java/org/apache/fop/render/intermediate/BorderPainter.java
public void drawBorders(Rectangle borderRect, // CSOK: MethodLength BorderProps bpsTop, BorderProps bpsBottom, BorderProps bpsLeft, BorderProps bpsRight) throws IOException { int startx = borderRect.x; int starty = borderRect.y; int width = borderRect.width; int height = borderRect.height; boolean[] b = new boolean[] { (bpsTop != null), (bpsRight != null), (bpsBottom != null), (bpsLeft != null)}; if (!b[0] && !b[1] && !b[2] && !b[3]) { return; } int[] bw = new int[] { (b[0] ? bpsTop.width : 0), (b[1] ? bpsRight.width : 0), (b[2] ? bpsBottom.width : 0), (b[3] ? bpsLeft.width : 0)}; int[] clipw = new int[] { BorderProps.getClippedWidth(bpsTop), BorderProps.getClippedWidth(bpsRight), BorderProps.getClippedWidth(bpsBottom), BorderProps.getClippedWidth(bpsLeft)}; starty += clipw[0]; height -= clipw[0]; height -= clipw[2]; startx += clipw[3]; width -= clipw[3]; width -= clipw[1]; boolean[] slant = new boolean[] { (b[3] && b[0]), (b[0] && b[1]), (b[1] && b[2]), (b[2] && b[3])}; if (bpsTop != null) { int sx1 = startx; int sx2 = (slant[0] ? sx1 + bw[3] - clipw[3] : sx1); int ex1 = startx + width; int ex2 = (slant[1] ? ex1 - bw[1] + clipw[1] : ex1); int outery = starty - clipw[0]; int clipy = outery + clipw[0]; int innery = outery + bw[0]; saveGraphicsState(); moveTo(sx1, clipy); int sx1a = sx1; int ex1a = ex1; if (bpsTop.mode == BorderProps.COLLAPSE_OUTER) { if (bpsLeft != null && bpsLeft.mode == BorderProps.COLLAPSE_OUTER) { sx1a -= clipw[3]; } if (bpsRight != null && bpsRight.mode == BorderProps.COLLAPSE_OUTER) { ex1a += clipw[1]; } lineTo(sx1a, outery); lineTo(ex1a, outery); } lineTo(ex1, clipy); lineTo(ex2, innery); lineTo(sx2, innery); closePath(); clip(); drawBorderLine(sx1a, outery, ex1a, innery, true, true, bpsTop.style, bpsTop.color); restoreGraphicsState(); } if (bpsRight != null) { int sy1 = starty; int sy2 = (slant[1] ? sy1 + bw[0] - clipw[0] : sy1); int ey1 = starty + height; int ey2 = (slant[2] ? ey1 - bw[2] + clipw[2] : ey1); int outerx = startx + width + clipw[1]; int clipx = outerx - clipw[1]; int innerx = outerx - bw[1]; saveGraphicsState(); moveTo(clipx, sy1); int sy1a = sy1; int ey1a = ey1; if (bpsRight.mode == BorderProps.COLLAPSE_OUTER) { if (bpsTop != null && bpsTop.mode == BorderProps.COLLAPSE_OUTER) { sy1a -= clipw[0]; } if (bpsBottom != null && bpsBottom.mode == BorderProps.COLLAPSE_OUTER) { ey1a += clipw[2]; } lineTo(outerx, sy1a); lineTo(outerx, ey1a); } lineTo(clipx, ey1); lineTo(innerx, ey2); lineTo(innerx, sy2); closePath(); clip(); drawBorderLine(innerx, sy1a, outerx, ey1a, false, false, bpsRight.style, bpsRight.color); restoreGraphicsState(); } if (bpsBottom != null) { int sx1 = startx; int sx2 = (slant[3] ? sx1 + bw[3] - clipw[3] : sx1); int ex1 = startx + width; int ex2 = (slant[2] ? ex1 - bw[1] + clipw[1] : ex1); int outery = starty + height + clipw[2]; int clipy = outery - clipw[2]; int innery = outery - bw[2]; saveGraphicsState(); moveTo(ex1, clipy); int sx1a = sx1; int ex1a = ex1; if (bpsBottom.mode == BorderProps.COLLAPSE_OUTER) { if (bpsLeft != null && bpsLeft.mode == BorderProps.COLLAPSE_OUTER) { sx1a -= clipw[3]; } if (bpsRight != null && bpsRight.mode == BorderProps.COLLAPSE_OUTER) { ex1a += clipw[1]; } lineTo(ex1a, outery); lineTo(sx1a, outery); } lineTo(sx1, clipy); lineTo(sx2, innery); lineTo(ex2, innery); closePath(); clip(); drawBorderLine(sx1a, innery, ex1a, outery, true, false, bpsBottom.style, bpsBottom.color); restoreGraphicsState(); } if (bpsLeft != null) { int sy1 = starty; int sy2 = (slant[0] ? sy1 + bw[0] - clipw[0] : sy1); int ey1 = sy1 + height; int ey2 = (slant[3] ? ey1 - bw[2] + clipw[2] : ey1); int outerx = startx - clipw[3]; int clipx = outerx + clipw[3]; int innerx = outerx + bw[3]; saveGraphicsState(); moveTo(clipx, ey1); int sy1a = sy1; int ey1a = ey1; if (bpsLeft.mode == BorderProps.COLLAPSE_OUTER) { if (bpsTop != null && bpsTop.mode == BorderProps.COLLAPSE_OUTER) { sy1a -= clipw[0]; } if (bpsBottom != null && bpsBottom.mode == BorderProps.COLLAPSE_OUTER) { ey1a += clipw[2]; } lineTo(outerx, ey1a); lineTo(outerx, sy1a); } lineTo(clipx, sy1); lineTo(innerx, sy2); lineTo(innerx, ey2); closePath(); clip(); drawBorderLine(outerx, sy1a, innerx, ey1a, false, true, bpsLeft.style, bpsLeft.color); restoreGraphicsState(); } }
// in src/java/org/apache/fop/render/AbstractGenericSVGHandler.java
protected void renderSVGDocument(final RendererContext rendererContext, final Document doc) throws IOException { updateRendererContext(rendererContext); //Prepare FOUserAgent userAgent = rendererContext.getUserAgent(); SVGUserAgent svgUserAgent = new SVGUserAgent(userAgent, new AffineTransform()); //Create Batik BridgeContext final BridgeContext bridgeContext = new BridgeContext(svgUserAgent); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(doc); //Build the GVT tree final GraphicsNode root = buildGraphicsNode(userAgent, bridgeContext, clonedDoc); // Create Graphics2DImagePainter final RendererContextWrapper wrappedContext = RendererContext.wrapRendererContext( rendererContext); Dimension imageSize = getImageSize(wrappedContext); final Graphics2DImagePainter painter = createGraphics2DImagePainter( root, bridgeContext, imageSize); //Let the painter paint the SVG on the Graphics2D instance Graphics2DAdapter g2dAdapter = rendererContext.getRenderer().getGraphics2DAdapter(); //Paint the image final int x = wrappedContext.getCurrentXPosition(); final int y = wrappedContext.getCurrentYPosition(); final int width = wrappedContext.getWidth(); final int height = wrappedContext.getHeight(); g2dAdapter.paintImage(painter, rendererContext, x, y, width, height); }
// in src/java/org/apache/fop/render/txt/TXTRenderer.java
public void renderPage(PageViewport page) throws IOException, FOPException { if (firstPage) { firstPage = false; } else { currentStream.add(pageEnding); } Rectangle2D bounds = page.getViewArea(); double width = bounds.getWidth(); double height = bounds.getHeight(); pageWidth = Helper.ceilPosition((int) width, CHAR_WIDTH); pageHeight = Helper.ceilPosition((int) height, CHAR_HEIGHT + 2 * LINE_LEADING); // init buffers charData = new StringBuffer[pageHeight]; decoData = new StringBuffer[pageHeight]; for (int i = 0; i < pageHeight; i++) { charData[i] = new StringBuffer(); decoData[i] = new StringBuffer(); } bm = new BorderManager(pageWidth, pageHeight, currentState); super.renderPage(page); flushBorderToBuffer(); flushBuffer(); }
// in src/java/org/apache/fop/render/txt/TXTRenderer.java
public void startRenderer(OutputStream os) throws IOException { log.info("Rendering areas to TEXT."); this.outputStream = os; currentStream = new TXTStream(os); currentStream.setEncoding(this.encoding); firstPage = true; }
// in src/java/org/apache/fop/render/txt/TXTRenderer.java
public void stopRenderer() throws IOException { log.info("writing out TEXT"); outputStream.flush(); super.stopRenderer(); }
// in src/java/org/apache/fop/render/AbstractRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { if (userAgent == null) { throw new IllegalStateException("FOUserAgent has not been set on Renderer"); } }
// in src/java/org/apache/fop/render/AbstractRenderer.java
public void stopRenderer() throws IOException { }
// in src/java/org/apache/fop/render/AbstractRenderer.java
public void renderPage(PageViewport page) throws IOException, FOPException { this.currentPageViewport = page; try { Page p = page.getPage(); renderPageAreas(p); } finally { this.currentPageViewport = null; } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
private void selectPageFormat(long pagewidth, long pageheight) throws IOException { //Only set the page format if it changes (otherwise duplex printing won't work) if ((pagewidth != this.pageWidth) || (pageheight != this.pageHeight)) { this.pageWidth = pagewidth; this.pageHeight = pageheight; this.currentPageDefinition = PCLPageDefinition.getPageDefinition( pagewidth, pageheight, 1000); if (this.currentPageDefinition == null) { this.currentPageDefinition = PCLPageDefinition.getDefaultPageDefinition(); log.warn("Paper type could not be determined. Falling back to: " + this.currentPageDefinition.getName()); } if (log.isDebugEnabled()) { log.debug("page size: " + currentPageDefinition.getPhysicalPageSize()); log.debug("logical page: " + currentPageDefinition.getLogicalPageRect()); } if (this.currentPageDefinition.isLandscapeFormat()) { gen.writeCommand("&l1O"); //Landscape Orientation } else { gen.writeCommand("&l0O"); //Portrait Orientation } gen.selectPageSize(this.currentPageDefinition.getSelector()); gen.clearHorizontalMargins(); gen.setTopMargin(0); } }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PCLRenderingContext pclContext = (PCLRenderingContext)context; ImageGraphics2D imageG2D = (ImageGraphics2D)image; Dimension imageDim = imageG2D.getSize().getDimensionMpt(); PCLGenerator gen = pclContext.getPCLGenerator(); Point2D transPoint = pclContext.transformedPoint(pos.x, pos.y); gen.setCursorPos(transPoint.getX(), transPoint.getY()); boolean painted = false; ByteArrayOutputStream baout = new ByteArrayOutputStream(); PCLGenerator tempGen = new PCLGenerator(baout, gen.getMaximumBitmapResolution()); tempGen.setDitheringQuality(gen.getDitheringQuality()); try { GraphicContext ctx = (GraphicContext)pclContext.getGraphicContext().clone(); AffineTransform prepareHPGL2 = new AffineTransform(); prepareHPGL2.scale(0.001, 0.001); ctx.setTransform(prepareHPGL2); PCLGraphics2D graphics = new PCLGraphics2D(tempGen); graphics.setGraphicContext(ctx); graphics.setClippingDisabled(false /*pclContext.isClippingDisabled()*/); Rectangle2D area = new Rectangle2D.Double( 0.0, 0.0, imageDim.getWidth(), imageDim.getHeight()); imageG2D.getGraphics2DImagePainter().paint(graphics, area); //If we arrive here, the graphic is natively paintable, so write the graphic gen.writeCommand("*c" + gen.formatDouble4(pos.width / 100f) + "x" + gen.formatDouble4(pos.height / 100f) + "Y"); gen.writeCommand("*c0T"); gen.enterHPGL2Mode(false); gen.writeText("\nIN;"); gen.writeText("SP1;"); //One Plotter unit is 0.025mm! double scale = imageDim.getWidth() / UnitConv.mm2pt(imageDim.getWidth() * 0.025); gen.writeText("SC0," + gen.formatDouble4(scale) + ",0,-" + gen.formatDouble4(scale) + ",2;"); gen.writeText("IR0,100,0,100;"); gen.writeText("PU;PA0,0;\n"); baout.writeTo(gen.getOutputStream()); //Buffer is written to output stream gen.writeText("\n"); gen.enterPCLMode(false); painted = true; } catch (UnsupportedOperationException uoe) { log.debug( "Cannot paint graphic natively. Falling back to bitmap painting. Reason: " + uoe.getMessage()); } if (!painted) { //Fallback solution: Paint to a BufferedImage FOUserAgent ua = context.getUserAgent(); ImageManager imageManager = ua.getFactory().getImageManager(); ImageRendered imgRend; try { imgRend = (ImageRendered)imageManager.convertImage( imageG2D, new ImageFlavor[] {ImageFlavor.RENDERED_IMAGE}/*, hints*/); } catch (ImageException e) { throw new IOException( "Image conversion error while converting the image to a bitmap" + " as a fallback measure: " + e.getMessage()); } gen.paintBitmap(imgRend.getRenderedImage(), new Dimension(pos.width, pos.height), pclContext.isSourceTransparencyEnabled()); } }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
protected void applyStroke(Stroke stroke) throws IOException { if (stroke instanceof BasicStroke) { BasicStroke bs = (BasicStroke)stroke; float[] da = bs.getDashArray(); if (da != null) { gen.writeText("UL1,"); int len = Math.min(20, da.length); float patternLen = 0.0f; for (int idx = 0; idx < len; idx++) { patternLen += da[idx]; } if (len == 1) { patternLen *= 2; } for (int idx = 0; idx < len; idx++) { float perc = da[idx] * 100 / patternLen; gen.writeText(gen.formatDouble2(perc)); if (idx < da.length - 1) { gen.writeText(","); } } if (len == 1) { gen.writeText("," + gen.formatDouble2(da[0] * 100 / patternLen )); } gen.writeText(";"); /* TODO Dash phase NYI float offset = bs.getDashPhase(); gen.writeln(gen.formatDouble4(offset) + " setdash"); */ Point2D ptLen = new Point2D.Double(patternLen, 0); //interpret as absolute length getTransform().deltaTransform(ptLen, ptLen); double transLen = UnitConv.pt2mm(ptLen.distance(0, 0)); gen.writeText("LT1," + gen.formatDouble4(transLen) + ",1;"); } else { gen.writeText("LT;"); } gen.writeText("LA1"); //line cap int ec = bs.getEndCap(); switch (ec) { case BasicStroke.CAP_BUTT: gen.writeText(",1"); break; case BasicStroke.CAP_ROUND: gen.writeText(",4"); break; case BasicStroke.CAP_SQUARE: gen.writeText(",2"); break; default: System.err.println("Unsupported line cap: " + ec); } gen.writeText(",2"); //line join int lj = bs.getLineJoin(); switch (lj) { case BasicStroke.JOIN_MITER: gen.writeText(",1"); break; case BasicStroke.JOIN_ROUND: gen.writeText(",4"); break; case BasicStroke.JOIN_BEVEL: gen.writeText(",5"); break; default: System.err.println("Unsupported line join: " + lj); } float ml = bs.getMiterLimit(); gen.writeText(",3" + gen.formatDouble4(ml)); float lw = bs.getLineWidth(); Point2D ptSrc = new Point2D.Double(lw, 0); //Pen widths are set as absolute metric values (WU0;) Point2D ptDest = getTransform().deltaTransform(ptSrc, null); double transDist = UnitConv.pt2mm(ptDest.distance(0, 0)); //System.out.println("--" + ptDest.distance(0, 0) + " " + transDist); gen.writeText(";PW" + gen.formatDouble4(transDist) + ";"); } else { handleUnsupportedFeature("Unsupported Stroke: " + stroke.getClass().getName()); } }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
protected void applyPaint(Paint paint) throws IOException { if (paint instanceof Color) { Color col = (Color)paint; int shade = gen.convertToPCLShade(col); gen.writeText("TR0;FT10," + shade + ";"); } else { handleUnsupportedFeature("Unsupported Paint: " + paint.getClass().getName()); } }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
private void writeClip(Shape imclip) throws IOException { if (clippingDisabled) { return; } if (imclip == null) { //gen.writeText("IW;"); } else { handleUnsupportedFeature("Clipping is not supported. Shape: " + imclip); /* This is an attempt to clip using the "InputWindow" (IW) but this only allows to * clip a rectangular area. Force falling back to bitmap mode for now. Rectangle2D bounds = imclip.getBounds2D(); Point2D p1 = new Point2D.Double(bounds.getX(), bounds.getY()); Point2D p2 = new Point2D.Double( bounds.getX() + bounds.getWidth(), bounds.getY() + bounds.getHeight()); getTransform().transform(p1, p1); getTransform().transform(p2, p2); gen.writeText("IW" + gen.formatDouble4(p1.getX()) + "," + gen.formatDouble4(p2.getY()) + "," + gen.formatDouble4(p2.getX()) + "," + gen.formatDouble4(p1.getY()) + ";"); */ } }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
public void processPathIteratorStroke(PathIterator iter) throws IOException { gen.writeText("\n"); double[] vals = new double[6]; boolean penDown = false; double x = 0; double y = 0; StringBuffer sb = new StringBuffer(256); penUp(sb); while (!iter.isDone()) { int type = iter.currentSegment(vals); if (type == PathIterator.SEG_CLOSE) { gen.writeText("PM;"); gen.writeText(sb.toString()); gen.writeText("PM2;EP;"); sb.setLength(0); iter.next(); continue; } else if (type == PathIterator.SEG_MOVETO) { gen.writeText(sb.toString()); sb.setLength(0); if (penDown) { penUp(sb); penDown = false; } } else { if (!penDown) { penDown(sb); penDown = true; } } switch (type) { case PathIterator.SEG_CLOSE: break; case PathIterator.SEG_MOVETO: x = vals[0]; y = vals[1]; plotAbsolute(x, y, sb); gen.writeText(sb.toString()); sb.setLength(0); break; case PathIterator.SEG_LINETO: x = vals[0]; y = vals[1]; plotAbsolute(x, y, sb); break; case PathIterator.SEG_CUBICTO: x = vals[4]; y = vals[5]; bezierAbsolute(vals[0], vals[1], vals[2], vals[3], x, y, sb); break; case PathIterator.SEG_QUADTO: double originX = x; double originY = y; x = vals[2]; y = vals[3]; quadraticBezierAbsolute(originX, originY, vals[0], vals[1], x, y, sb); break; default: break; } iter.next(); } sb.append("\n"); gen.writeText(sb.toString()); }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
public void processPathIteratorFill(PathIterator iter) throws IOException { gen.writeText("\n"); double[] vals = new double[6]; boolean penDown = false; double x = 0; double y = 0; boolean pendingPM0 = true; StringBuffer sb = new StringBuffer(256); penUp(sb); while (!iter.isDone()) { int type = iter.currentSegment(vals); if (type == PathIterator.SEG_CLOSE) { sb.append("PM1;"); iter.next(); continue; } else if (type == PathIterator.SEG_MOVETO) { if (penDown) { penUp(sb); penDown = false; } } else { if (!penDown) { penDown(sb); penDown = true; } } switch (type) { case PathIterator.SEG_MOVETO: x = vals[0]; y = vals[1]; plotAbsolute(x, y, sb); break; case PathIterator.SEG_LINETO: x = vals[0]; y = vals[1]; plotAbsolute(x, y, sb); break; case PathIterator.SEG_CUBICTO: x = vals[4]; y = vals[5]; bezierAbsolute(vals[0], vals[1], vals[2], vals[3], x, y, sb); break; case PathIterator.SEG_QUADTO: double originX = x; double originY = y; x = vals[2]; y = vals[3]; quadraticBezierAbsolute(originX, originY, vals[0], vals[1], x, y, sb); break; default: throw new IllegalStateException("Must not get here"); } if (pendingPM0) { pendingPM0 = false; sb.append("PM;"); } iter.next(); } sb.append("PM2;"); fillPolygon(iter.getWindingRule(), sb); sb.append("\n"); gen.writeText(sb.toString()); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
private void drawTextNative(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text, FontTriplet triplet) throws IOException { Color textColor = state.getTextColor(); if (textColor != null) { gen.setTransparencyMode(true, false); gen.selectGrayscale(textColor); } gen.setTransparencyMode(true, true); setCursorPos(x, y); float fontSize = state.getFontSize() / 1000f; Font font = parent.getFontInfo().getFontInstance(triplet, state.getFontSize()); int l = text.length(); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); StringBuffer sb = new StringBuffer(Math.max(16, l)); if (dx != null && dxl > 0 && dx[0] != 0) { sb.append("\u001B&a+").append(gen.formatDouble2(dx[0] / 100.0)).append('H'); } for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); char ch; float glyphAdjust = 0; if (font.hasChar(orgChar)) { ch = font.mapChar(orgChar); } else { if (CharUtilities.isFixedWidthSpace(orgChar)) { //Fixed width space are rendered as spaces so copy/paste works in a reader ch = font.mapChar(CharUtilities.SPACE); int spaceDiff = font.getCharWidth(ch) - font.getCharWidth(orgChar); glyphAdjust = -(10 * spaceDiff / fontSize); } else { ch = font.mapChar(orgChar); } } sb.append(ch); if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust += wordSpacing; } glyphAdjust += letterSpacing; if (dx != null && i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { sb.append("\u001B&a+").append(gen.formatDouble2(glyphAdjust / 100.0)).append('H'); } } gen.getOutputStream().write(sb.toString().getBytes(gen.getTextEncoding())); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
private void concatenateTransformationMatrix(AffineTransform transform) throws IOException { if (!transform.isIdentity()) { graphicContext.transform(transform); changePrintDirection(); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
private void changePrintDirection() throws IOException { AffineTransform at = graphicContext.getTransform(); int newDir; newDir = PCLRenderingUtil.determinePrintDirection(at); if (newDir != this.currentPrintDirection) { this.currentPrintDirection = newDir; gen.changePrintDirection(this.currentPrintDirection); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
void setCursorPos(int x, int y) throws IOException { Point2D transPoint = transformedPoint(x, y); gen.setCursorPos(transPoint.getX(), transPoint.getY()); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void writeCommand(String cmd) throws IOException { out.write(27); //ESC out.write(cmd.getBytes(US_ASCII)); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void writeText(String s) throws IOException { out.write(s.getBytes(ISO_8859_1)); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void universalEndOfLanguage() throws IOException { writeCommand("%-12345X"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void resetPrinter() throws IOException { writeCommand("E"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void separateJobs() throws IOException { writeCommand("&l1T"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void formFeed() throws IOException { out.write(12); //=OC ("FF", Form feed) }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setUnitOfMeasure(int value) throws IOException { writeCommand("&u" + value + "D"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setRasterGraphicsResolution(int value) throws IOException { writeCommand("*t" + value + "R"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void selectPageSize(int selector) throws IOException { writeCommand("&l" + selector + "A"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void selectPaperSource(int selector) throws IOException { writeCommand("&l" + selector + "H"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void selectOutputBin(int selector) throws IOException { writeCommand("&l" + selector + "G"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void selectDuplexMode(int selector) throws IOException { writeCommand("&l" + selector + "S"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void clearHorizontalMargins() throws IOException { writeCommand("9"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setTopMargin(int numberOfLines) throws IOException { writeCommand("&l" + numberOfLines + "E"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setTextLength(int numberOfLines) throws IOException { writeCommand("&l" + numberOfLines + "F"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setVMI(double value) throws IOException { writeCommand("&l" + formatDouble4(value) + "C"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setCursorPos(double x, double y) throws IOException { if (x < 0) { //A negative x value will result in a relative movement so go to "0" first. //But this will most probably have no effect anyway since you can't paint to the left //of the logical page writeCommand("&a0h" + formatDouble2(x / 100) + "h" + formatDouble2(y / 100) + "V"); } else { writeCommand("&a" + formatDouble2(x / 100) + "h" + formatDouble2(y / 100) + "V"); } }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void pushCursorPos() throws IOException { writeCommand("&f0S"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void popCursorPos() throws IOException { writeCommand("&f1S"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void changePrintDirection(int rotate) throws IOException { writeCommand("&a" + rotate + "P"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void enterHPGL2Mode(boolean restorePreviousHPGL2Cursor) throws IOException { if (restorePreviousHPGL2Cursor) { writeCommand("%0B"); } else { writeCommand("%1B"); } }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void enterPCLMode(boolean restorePreviousPCLCursor) throws IOException { if (restorePreviousPCLCursor) { writeCommand("%0A"); } else { writeCommand("%1A"); } }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
protected void fillRect(int w, int h, Color col) throws IOException { if ((w == 0) || (h == 0)) { return; } if (h < 0) { h *= -1; } else { //y += h; } setPatternTransparencyMode(false); if (usePCLShades || Color.black.equals(col) || Color.white.equals(col)) { writeCommand("*c" + formatDouble4(w / 100.0) + "h" + formatDouble4(h / 100.0) + "V"); int lineshade = convertToPCLShade(col); writeCommand("*c" + lineshade + "G"); writeCommand("*c2P"); //Shaded fill } else { defineGrayscalePattern(col, 32, DitherUtil.DITHER_MATRIX_4X4); writeCommand("*c" + formatDouble4(w / 100.0) + "h" + formatDouble4(h / 100.0) + "V"); writeCommand("*c32G"); writeCommand("*c4P"); //User-defined pattern } // Reset pattern transparency mode. setPatternTransparencyMode(true); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void defineGrayscalePattern(Color col, int patternID, int ditherMatrixSize) throws IOException { ByteArrayOutputStream baout = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(baout); data.writeByte(0); //Format data.writeByte(0); //Continuation data.writeByte(1); //Pixel Encoding data.writeByte(0); //Reserved data.writeShort(8); //Width in Pixels data.writeShort(8); //Height in Pixels //data.writeShort(600); //X Resolution (didn't manage to get that to work) //data.writeShort(600); //Y Resolution int gray255 = convertToGray(col.getRed(), col.getGreen(), col.getBlue()); byte[] pattern; if (ditherMatrixSize == 8) { pattern = DitherUtil.getBayerDither(DitherUtil.DITHER_MATRIX_8X8, gray255, false); } else { //Since a 4x4 pattern did not work, the 4x4 pattern is applied 4 times to an //8x8 pattern. Maybe this could be changed to use an 8x8 bayer dither pattern //instead of the 4x4 one. pattern = DitherUtil.getBayerDither(DitherUtil.DITHER_MATRIX_4X4, gray255, true); } data.write(pattern); if ((baout.size() % 2) > 0) { baout.write(0); } writeCommand("*c" + patternID + "G"); writeCommand("*c" + baout.size() + "W"); baout.writeTo(this.out); writeCommand("*c4Q"); //temporary pattern }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setSourceTransparencyMode(boolean transparent) throws IOException { setTransparencyMode(transparent, currentPatternTransparency); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setPatternTransparencyMode(boolean transparent) throws IOException { setTransparencyMode(currentSourceTransparency, transparent); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setTransparencyMode(boolean source, boolean pattern) throws IOException { if (source != currentSourceTransparency && pattern != currentPatternTransparency) { writeCommand("*v" + (source ? '0' : '1') + "n" + (pattern ? '0' : '1') + "O"); } else if (source != currentSourceTransparency) { writeCommand("*v" + (source ? '0' : '1') + "N"); } else if (pattern != currentPatternTransparency) { writeCommand("*v" + (pattern ? '0' : '1') + "O"); } this.currentSourceTransparency = source; this.currentPatternTransparency = pattern; }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void selectGrayscale(Color col) throws IOException { if (Color.black.equals(col)) { selectCurrentPattern(0, 0); //black } else if (Color.white.equals(col)) { selectCurrentPattern(0, 1); //white } else { if (usePCLShades) { selectCurrentPattern(convertToPCLShade(col), 2); } else { defineGrayscalePattern(col, 32, DitherUtil.DITHER_MATRIX_4X4); selectCurrentPattern(32, 4); } } }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void selectCurrentPattern(int patternID, int pattern) throws IOException { if (pattern > 1) { writeCommand("*c" + patternID + "G"); } writeCommand("*v" + pattern + "T"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void paintBitmap(RenderedImage img, Dimension targetDim, boolean sourceTransparency) throws IOException { double targetHResolution = img.getWidth() / UnitConv.mpt2in(targetDim.width); double targetVResolution = img.getHeight() / UnitConv.mpt2in(targetDim.height); double targetResolution = Math.max(targetHResolution, targetVResolution); int resolution = (int)Math.round(targetResolution); int effResolution = calculatePCLResolution(resolution, true); Dimension orgDim = new Dimension(img.getWidth(), img.getHeight()); Dimension effDim; if (targetResolution == effResolution) { effDim = orgDim; //avoid scaling side-effects } else { effDim = new Dimension( (int)Math.ceil(UnitConv.mpt2px(targetDim.width, effResolution)), (int)Math.ceil(UnitConv.mpt2px(targetDim.height, effResolution))); } boolean scaled = !orgDim.equals(effDim); //ImageWriterUtil.saveAsPNG(img, new java.io.File("D:/text-0-org.png")); boolean monochrome = isMonochromeImage(img); if (!monochrome) { //Transparency mask disabled. Doesn't work reliably final boolean transparencyDisabled = true; RenderedImage mask = (transparencyDisabled ? null : getMask(img, effDim)); if (mask != null) { pushCursorPos(); selectCurrentPattern(0, 1); //Solid white setTransparencyMode(true, true); paintMonochromeBitmap(mask, effResolution); popCursorPos(); } RenderedImage red = BitmapImageUtil.convertToMonochrome( img, effDim, this.ditheringQuality); selectCurrentPattern(0, 0); //Solid black setTransparencyMode(sourceTransparency || mask != null, true); paintMonochromeBitmap(red, effResolution); } else { RenderedImage effImg = img; if (scaled) { effImg = BitmapImageUtil.convertToMonochrome(img, effDim); } setSourceTransparencyMode(sourceTransparency); selectCurrentPattern(0, 0); //Solid black paintMonochromeBitmap(effImg, effResolution); } }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void paintMonochromeBitmap(RenderedImage img, int resolution) throws IOException { if (!isValidPCLResolution(resolution)) { throw new IllegalArgumentException("Invalid PCL resolution: " + resolution); } boolean monochrome = isMonochromeImage(img); if (!monochrome) { throw new IllegalArgumentException("img must be a monochrome image"); } setRasterGraphicsResolution(resolution); writeCommand("*r0f" + img.getHeight() + "t" + img.getWidth() + "s1A"); Raster raster = img.getData(); Encoder encoder = new Encoder(img); // Transfer graphics data int imgw = img.getWidth(); IndexColorModel cm = (IndexColorModel)img.getColorModel(); if (cm.getTransferType() == DataBuffer.TYPE_BYTE) { DataBufferByte dataBuffer = (DataBufferByte)raster.getDataBuffer(); MultiPixelPackedSampleModel packedSampleModel = new MultiPixelPackedSampleModel( DataBuffer.TYPE_BYTE, img.getWidth(), img.getHeight(), 1); if (img.getSampleModel().equals(packedSampleModel) && dataBuffer.getNumBanks() == 1) { //Optimized packed encoding byte[] buf = dataBuffer.getData(); int scanlineStride = packedSampleModel.getScanlineStride(); int idx = 0; int c0 = toGray(cm.getRGB(0)); int c1 = toGray(cm.getRGB(1)); boolean zeroIsWhite = c0 > c1; for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { for (int x = 0, maxx = scanlineStride; x < maxx; x++) { if (zeroIsWhite) { encoder.add8Bits(buf[idx]); } else { encoder.add8Bits((byte)~buf[idx]); } idx++; } encoder.endLine(); } } else { //Optimized non-packed encoding for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { byte[] line = (byte[])raster.getDataElements(0, y, imgw, 1, null); for (int x = 0, maxx = imgw; x < maxx; x++) { encoder.addBit(line[x] == 0); } encoder.endLine(); } } } else { //Safe but slow fallback for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { for (int x = 0, maxx = imgw; x < maxx; x++) { int sample = raster.getSample(x, y, 0); encoder.addBit(sample == 0); } encoder.endLine(); } } // End raster graphics writeCommand("*rB"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void endLine() throws IOException { if (zeroRow && PCLGenerator.this.currentSourceTransparency) { writeCommand("*b1Y"); } else if (rlewidth < bytewidth) { writeCommand("*b1m" + rlewidth + "W"); out.write(rle, 0, rlewidth); } else { writeCommand("*b0m" + bytewidth + "W"); out.write(uncompressed); } lastcount = -1; rlewidth = 0; ib = 0; x = 0; zeroRow = true; }
// in src/java/org/apache/fop/render/pcl/HardcodedFonts.java
public static boolean setFont(PCLGenerator gen, String name, int size, String text) throws IOException { byte[] encoded = text.getBytes("ISO-8859-1"); for (int i = 0, c = encoded.length; i < c; i++) { if (encoded[i] == 0x3F && text.charAt(i) != '?') { return false; } } return selectFont(gen, name, size); }
// in src/java/org/apache/fop/render/pcl/HardcodedFonts.java
private static boolean selectFont(PCLGenerator gen, String name, int size) throws IOException { int fontcode = 0; if (name.length() > 1 && name.charAt(0) == 'F') { try { fontcode = Integer.parseInt(name.substring(1)); } catch (Exception e) { LOG.error(e); } } //Note "(ON" selects ISO 8859-1 symbol set as used by PCLGenerator String formattedSize = gen.formatDouble2(size / 1000.0); switch (fontcode) { case 1: // F1 = Helvetica // gen.writeCommand("(8U"); // gen.writeCommand("(s1p" + formattedSize + "v0s0b24580T"); // Arial is more common among PCL5 printers than Helvetica - so use Arial gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v0s0b16602T"); break; case 2: // F2 = Helvetica Oblique gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v1s0b16602T"); break; case 3: // F3 = Helvetica Bold gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v0s3b16602T"); break; case 4: // F4 = Helvetica Bold Oblique gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v1s3b16602T"); break; case 5: // F5 = Times Roman // gen.writeCommand("(8U"); // gen.writeCommand("(s1p" + formattedSize + "v0s0b25093T"); // Times New is more common among PCL5 printers than Times - so use Times New gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v0s0b16901T"); break; case 6: // F6 = Times Italic gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v1s0b16901T"); break; case 7: // F7 = Times Bold gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v0s3b16901T"); break; case 8: // F8 = Times Bold Italic gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v1s3b16901T"); break; case 9: // F9 = Courier gen.writeCommand("(0N"); gen.writeCommand("(s0p" + gen.formatDouble2(120.01f / (size / 1000.00f)) + "h0s0b4099T"); break; case 10: // F10 = Courier Oblique gen.writeCommand("(0N"); gen.writeCommand("(s0p" + gen.formatDouble2(120.01f / (size / 1000.00f)) + "h1s0b4099T"); break; case 11: // F11 = Courier Bold gen.writeCommand("(0N"); gen.writeCommand("(s0p" + gen.formatDouble2(120.01f / (size / 1000.00f)) + "h0s3b4099T"); break; case 12: // F12 = Courier Bold Oblique gen.writeCommand("(0N"); gen.writeCommand("(s0p" + gen.formatDouble2(120.01f / (size / 1000.00f)) + "h1s3b4099T"); break; case 13: // F13 = Symbol return false; //gen.writeCommand("(19M"); //gen.writeCommand("(s1p" + formattedSize + "v0s0b16686T"); // ECMA Latin 1 Symbol Set in Times Roman??? // gen.writeCommand("(9U"); // gen.writeCommand("(s1p" + formattedSize + "v0s0b25093T"); //break; case 14: // F14 = Zapf Dingbats return false; //gen.writeCommand("(14L"); //gen.writeCommand("(s1p" + formattedSize + "v0s0b45101T"); //break; default: //gen.writeCommand("(0N"); //gen.writeCommand("(s" + formattedSize + "V"); return false; } return true; }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerRenderedImage.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PCLRenderingContext pclContext = (PCLRenderingContext)context; ImageRendered imageRend = (ImageRendered)image; PCLGenerator gen = pclContext.getPCLGenerator(); RenderedImage ri = imageRend.getRenderedImage(); Point2D transPoint = pclContext.transformedPoint(pos.x, pos.y); gen.setCursorPos(transPoint.getX(), transPoint.getY()); gen.paintBitmap(ri, new Dimension(pos.width, pos.height), pclContext.isSourceTransparencyEnabled()); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public RtfTableCell newTableCell(int cellWidth) throws IOException { highestCell++; cell = new RtfTableCell(this, writer, cellWidth, highestCell); return cell; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public RtfTableCell newTableCell(int cellWidth, RtfAttributes attrs) throws IOException { highestCell++; cell = new RtfTableCell(this, writer, cellWidth, attrs, highestCell); return cell; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public RtfTableCell newTableCellMergedVertically(int cellWidth, RtfAttributes attrs) throws IOException { highestCell++; cell = new RtfTableCell (this, writer, cellWidth, attrs, highestCell); cell.setVMerge(RtfTableCell.MERGE_WITH_PREVIOUS); return cell; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public RtfTableCell newTableCellMergedHorizontally (int cellWidth, RtfAttributes attrs) throws IOException, FOPException { highestCell++; // Added by Normand Masse // Inherit attributes from base cell for merge RtfAttributes wAttributes = null; if (attrs != null) { try { wAttributes = (RtfAttributes)attrs.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } } cell = new RtfTableCell(this, writer, cellWidth, wAttributes, highestCell); cell.setHMerge(RtfTableCell.MERGE_WITH_PREVIOUS); return cell; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
protected void writeRtfPrefix() throws IOException { newLine(); writeGroupMark(true); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
protected void writeRtfContent() throws IOException { if (getTable().isNestedTable()) { //nested table writeControlWord("intbl"); //itap is the depth (level) of the current nested table writeControlWord("itap" + getTable().getNestedTableDepth()); } else { //normal (not nested) table writeRowAndCellsDefintions(); } // now children can write themselves, we have the correct RTF prefix code super.writeRtfContent(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public void writeRowAndCellsDefintions() throws IOException { // render the row and cells definitions writeControlWord("trowd"); if (!getTable().isNestedTable()) { writeControlWord("itap0"); } //check for keep-together if (attrib != null && attrib.isSet(ITableAttributes.ROW_KEEP_TOGETHER)) { writeControlWord(ROW_KEEP_TOGETHER); } writePaddingAttributes(); final RtfTable parentTable = (RtfTable) parent; adjustBorderProperties(parentTable); writeAttributes(attrib, new String[]{ITableAttributes.ATTR_HEADER}); writeAttributes(attrib, ITableAttributes.ROW_BORDER); writeAttributes(attrib, ITableAttributes.CELL_BORDER); writeAttributes(attrib, IBorderAttributes.BORDERS); if (attrib.isSet(ITableAttributes.ROW_HEIGHT)) { writeOneAttribute( ITableAttributes.ROW_HEIGHT, attrib.getValue(ITableAttributes.ROW_HEIGHT)); } // write X positions of our cells int xPos = 0; final Object leftIndent = attrib.getValue(ITableAttributes.ATTR_ROW_LEFT_INDENT); if (leftIndent != null) { xPos = ((Integer)leftIndent).intValue(); } RtfAttributes tableBorderAttributes = getTable().getBorderAttributes(); int index = 0; for (Iterator it = getChildren().iterator(); it.hasNext();) { final RtfElement e = (RtfElement)it.next(); if (e instanceof RtfTableCell) { RtfTableCell rtfcell = (RtfTableCell)e; // Adjust the cell's display attributes so the table's/row's borders // are drawn properly. if (tableBorderAttributes != null) { // get border attributes from table if (index == 0) { String border = ITableAttributes.CELL_BORDER_LEFT; if (!rtfcell.getRtfAttributes().isSet(border)) { rtfcell.getRtfAttributes().set(border, (RtfAttributes) tableBorderAttributes.getValue(border)); } } if (index == this.getChildCount() - 1) { String border = ITableAttributes.CELL_BORDER_RIGHT; if (!rtfcell.getRtfAttributes().isSet(border)) { rtfcell.getRtfAttributes().set(border, (RtfAttributes) tableBorderAttributes.getValue(border)); } } if (isFirstRow()) { String border = ITableAttributes.CELL_BORDER_TOP; if (!rtfcell.getRtfAttributes().isSet(border)) { rtfcell.getRtfAttributes().set(border, (RtfAttributes) tableBorderAttributes.getValue(border)); } } if ((parentTable != null) && (parentTable.isHighestRow(id))) { String border = ITableAttributes.CELL_BORDER_BOTTOM; if (!rtfcell.getRtfAttributes().isSet(border)) { rtfcell.getRtfAttributes().set(border, (RtfAttributes) tableBorderAttributes.getValue(border)); } } } // get border attributes from row if (index == 0) { if (!rtfcell.getRtfAttributes().isSet(ITableAttributes.CELL_BORDER_LEFT)) { rtfcell.getRtfAttributes().set(ITableAttributes.CELL_BORDER_LEFT, (String) attrib.getValue(ITableAttributes.ROW_BORDER_LEFT)); } } if (index == this.getChildCount() - 1) { if (!rtfcell.getRtfAttributes().isSet(ITableAttributes.CELL_BORDER_RIGHT)) { rtfcell.getRtfAttributes().set(ITableAttributes.CELL_BORDER_RIGHT, (String) attrib.getValue(ITableAttributes.ROW_BORDER_RIGHT)); } } if (isFirstRow()) { if (!rtfcell.getRtfAttributes().isSet(ITableAttributes.CELL_BORDER_TOP)) { rtfcell.getRtfAttributes().set(ITableAttributes.CELL_BORDER_TOP, (String) attrib.getValue(ITableAttributes.ROW_BORDER_TOP)); } } if ((parentTable != null) && (parentTable.isHighestRow(id))) { if (!rtfcell.getRtfAttributes().isSet(ITableAttributes.CELL_BORDER_BOTTOM)) { rtfcell.getRtfAttributes().set(ITableAttributes.CELL_BORDER_BOTTOM, (String) attrib.getValue(ITableAttributes.ROW_BORDER_BOTTOM)); } } // write cell's definition xPos = rtfcell.writeCellDef(xPos); } index++; // Added by Boris POUDEROUS on 2002/07/02 } newLine(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
protected void writeRtfSuffix() throws IOException { if (getTable().isNestedTable()) { //nested table writeGroupMark(true); writeStarControlWord("nesttableprops"); writeRowAndCellsDefintions(); writeControlWordNS("nestrow"); writeGroupMark(false); writeGroupMark(true); writeControlWord("nonesttables"); writeControlWord("par"); writeGroupMark(false); } else { writeControlWord("row"); } writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
private void writePaddingAttributes() throws IOException { // Row padding attributes generated in the converter package // use RTF 1.6 definitions - try to compute a reasonable RTF 1.5 value // out of them if present // how to do vertical padding with RTF 1.5? if (attrib != null && !attrib.isSet(ATTR_RTF_15_TRGAPH)) { int gaph = -1; try { // set (RTF 1.5) gaph to the average of the (RTF 1.6) left and right padding values final Integer leftPadStr = (Integer)attrib.getValue(ATTR_ROW_PADDING_LEFT); if (leftPadStr != null) { gaph = leftPadStr.intValue(); } final Integer rightPadStr = (Integer)attrib.getValue(ATTR_ROW_PADDING_RIGHT); if (rightPadStr != null) { gaph = (gaph + rightPadStr.intValue()) / 2; } } catch (Exception e) { final String msg = "RtfTableRow.writePaddingAttributes: " + e.toString(); // getRtfFile().getLog().logWarning(msg); } if (gaph >= 0) { attrib.set(ATTR_RTF_15_TRGAPH, gaph); } } // write all padding attributes writeAttributes(attrib, ATTRIB_ROW_PADDING); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfPageNumber.java
protected void writeRtfContent() throws IOException { /* writeGroupMark(true); writeControlWord(RTF_FIELD); writeGroupMark(true); writeAttributes(attrib, RtfText.ATTR_NAMES); // Added by Boris Poudérous writeStarControlWord(RTF_FIELD_PAGE); writeGroupMark(false); writeGroupMark(true); writeControlWord(RTF_FIELD_RESULT); writeGroupMark(false); writeGroupMark(false); */ writeGroupMark(true); writeAttributes(attrib, RtfText.ATTR_NAMES); writeControlWord("chpgn"); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfHeader startHeader() throws IOException, RtfStructureException { if (header != null) { throw new RtfStructureException("startHeader called more than once"); } header = new RtfHeader(this, writer); listTableContainer = new RtfContainer(this, writer); return header; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfListTable startListTable(RtfAttributes attr) throws IOException { listNum++; if (listTable != null) { return listTable; } else { listTable = new RtfListTable(this, writer, new Integer(listNum), attr); listTableContainer.addChild(listTable); } return listTable; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfPageArea startPageArea() throws IOException, RtfStructureException { if (pageArea != null) { throw new RtfStructureException("startPageArea called more than once"); } // create an empty header if there was none if (header == null) { startHeader(); } header.close(); pageArea = new RtfPageArea(this, writer); addChild(pageArea); return pageArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfPageArea getPageArea() throws IOException, RtfStructureException { if (pageArea == null) { return startPageArea(); } return pageArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfDocumentArea startDocumentArea() throws IOException, RtfStructureException { if (docArea != null) { throw new RtfStructureException("startDocumentArea called more than once"); } // create an empty header if there was none if (header == null) { startHeader(); } header.close(); docArea = new RtfDocumentArea(this, writer); addChild(docArea); return docArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfDocumentArea getDocumentArea() throws IOException, RtfStructureException { if (docArea == null) { return startDocumentArea(); } return docArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
protected void writeRtfPrefix() throws IOException { writeGroupMark(true); writeControlWord("rtf1"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
protected void writeRtfSuffix() throws IOException { writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public synchronized void flush() throws IOException { writeRtf(); writer.flush(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfText.java
public void writeRtfContent() throws IOException { writeChars: { //these lines were added by Boris Pouderous if (attr != null) { writeAttributes(attr, new String[] {RtfText.SPACE_BEFORE}); writeAttributes(attr, new String[] {RtfText.SPACE_AFTER}); } if (isTab()) { writeControlWord("tab"); } else if (isNewLine()) { break writeChars; } else if (isBold(true)) { writeControlWord("b"); } else if (isBold(false)) { writeControlWord("b0"); // TODO not optimal, consecutive RtfText with same attributes // could be written without group marks } else { writeGroupMark(true); if (attr != null && mustWriteAttributes()) { writeAttributes(attr, RtfText.ATTR_NAMES); } RtfStringConverter.getInstance().writeRtfString(writer, text); writeGroupMark(false); } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public RtfParagraph newParagraph() throws IOException { closeAll(); para = new RtfParagraph(this, writer); return para; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public RtfParagraph newParagraph(RtfAttributes attrs) throws IOException { closeAll(); para = new RtfParagraph(this, writer, attrs); return para; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public RtfExternalGraphic newImage() throws IOException { closeAll(); externalGraphic = new RtfExternalGraphic(this, writer); return externalGraphic; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
private void closeCurrentParagraph() throws IOException { if (para != null) { para.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
private void closeCurrentExternalGraphic() throws IOException { if (externalGraphic != null) { externalGraphic.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
private void closeCurrentTable() throws IOException { if (table != null) { table.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
protected void writeRtfPrefix() throws IOException { writeGroupMark(true); writeMyAttributes(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
protected void writeRtfSuffix() throws IOException { writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public void closeAll() throws IOException { closeCurrentParagraph(); closeCurrentExternalGraphic(); closeCurrentTable(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public RtfTable newTable(RtfAttributes attrs, ITableColumnsInfo tc) throws IOException { closeAll(); table = new RtfTable(this, writer, attrs, tc); return table; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public RtfTable newTable(ITableColumnsInfo tc) throws IOException { closeAll(); table = new RtfTable(this, writer, tc); return table; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public RtfTextrun getTextrun() throws IOException { return RtfTextrun.getTextrun(this, writer, null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyle.java
public void writeListPrefix(RtfListItem item) throws IOException { }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyle.java
public void writeParagraphPrefix(RtfElement element) throws IOException { }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyle.java
public void writeLevelGroup(RtfElement element) throws IOException { }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfExternalGraphic newImage() throws IOException { closeAll(); externalGraphic = new RtfExternalGraphic(this, writer); return externalGraphic; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfParagraph newParagraph(RtfAttributes attrs) throws IOException { closeAll(); paragraph = new RtfParagraph(this, writer, attrs); return paragraph; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfParagraph newParagraph() throws IOException { return newParagraph(null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfParagraphKeepTogether newParagraphKeepTogether() throws IOException { return new RtfParagraphKeepTogether(this, writer); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfTable newTable(ITableColumnsInfo tc) throws IOException { closeAll(); table = new RtfTable(this, writer, tc); return table; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfTable newTable(RtfAttributes attrs, ITableColumnsInfo tc) throws IOException { closeAll(); table = new RtfTable(this, writer, attrs, tc); return table; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfList newList(RtfAttributes attrs) throws IOException { closeAll(); list = new RtfList(this, writer, attrs); return list; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfBefore newBefore(RtfAttributes attrs) throws IOException { closeAll(); before = new RtfBefore(this, writer, attrs); return before; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfAfter newAfter(RtfAttributes attrs) throws IOException { closeAll(); after = new RtfAfter(this, writer, attrs); return after; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfJforCmd newJforCmd(RtfAttributes attrs) throws IOException { jforCmd = new RtfJforCmd(this, writer, attrs); return jforCmd; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
protected void writeRtfPrefix() throws IOException { writeAttributes(attrib, RtfPage.PAGE_ATTR); newLine(); writeControlWord("sectd"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
protected void writeRtfSuffix() throws IOException { // write suffix /sect only if this section is not last section (see bug #51484) List siblings = parent.getChildren(); if ( ( siblings.indexOf ( this ) + 1 ) < siblings.size() ) { writeControlWord("sect"); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
private void closeCurrentTable() throws IOException { if (table != null) { table.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
private void closeCurrentParagraph() throws IOException { if (paragraph != null) { paragraph.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
private void closeCurrentList() throws IOException { if (list != null) { list.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
private void closeCurrentExternalGraphic() throws IOException { if (externalGraphic != null) { externalGraphic.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
private void closeCurrentBefore() throws IOException { if (before != null) { before.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
private void closeAll() throws IOException { closeCurrentTable(); closeCurrentParagraph(); closeCurrentList(); closeCurrentExternalGraphic(); closeCurrentBefore(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfTextrun getTextrun() throws IOException { return RtfTextrun.getTextrun(this, writer, null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfLeader.java
protected void writeRtfContent() throws IOException { int thickness = LEADER_STANDARD_WIDTH; String tablead = null; String tabwidth = null; for (Iterator it = attrs.nameIterator(); it.hasNext();) { final String name = (String)it.next(); if (attrs.isSet(name)) { if (name.equals(LEADER_TABLEAD)) { tablead = attrs.getValue(LEADER_TABLEAD).toString(); } else if (name.equals(LEADER_WIDTH)) { tabwidth = attrs.getValue(LEADER_WIDTH).toString(); } } } if (attrs.getValue(LEADER_RULE_THICKNESS) != null) { thickness += Integer.parseInt(attrs.getValue(LEADER_RULE_THICKNESS).toString()) / 1000 * 2; attrs.unset(LEADER_RULE_THICKNESS); } //Remove private attributes attrs.unset(LEADER_WIDTH); attrs.unset(LEADER_TABLEAD); // If leader is 100% we use a tabulator, because its more // comfortable, specially for the table of content if (attrs.getValue(LEADER_USETAB) != null) { attrs.unset(LEADER_USETAB); writeControlWord(LEADER_TAB_RIGHT); if (tablead != null) { writeControlWord(tablead); } writeControlWord(LEADER_TAB_WIDTH + tabwidth); writeGroupMark(true); writeControlWord(LEADER_IGNORE_STYLE); writeAttributes(attrs, null); writeControlWord(LEADER_EXPAND); writeControlWord(LEADER_TAB_VALUE); writeGroupMark(false); } else { // Using white spaces with different underline formats writeControlWord(LEADER_IGNORE_STYLE); writeControlWord(LEADER_ZERO_WIDTH); writeGroupMark(true); writeControlWord(LEADER_RULE_THICKNESS + thickness); writeControlWord(LEADER_UP); super.writeAttributes(attrs, null); if (tablead != null) { writeControlWord(tablead); } // Calculation for the necessary amount of white spaces // Depending on font-size 15 -> 1cm = 7,5 spaces // TODO for rule-thickness this has to be done better for (double d = (Integer.parseInt(tabwidth) / 560) * 7.5; d >= 1; d--) { RtfStringConverter.getInstance().writeRtfString(writer, " "); } writeGroupMark(false); writeControlWord(LEADER_ZERO_WIDTH); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfContainer.java
protected void writeRtfContent() throws IOException { for (Iterator it = children.iterator(); it.hasNext();) { final RtfElement e = (RtfElement)it.next(); e.writeRtf(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfContainer.java
void dump(Writer w, int indent) throws IOException { super.dump(w, indent); for (Iterator it = children.iterator(); it.hasNext();) { final RtfElement e = (RtfElement)it.next(); e.dump(w, indent + 1); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFontTable.java
protected void writeRtfContent() throws IOException { RtfFontManager.getInstance ().writeFonts ((RtfHeader)parent); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleBullet.java
public void writeListPrefix(RtfListItem item) throws IOException { // bulleted list item.writeControlWord("pnlvlblt"); item.writeControlWord("ilvl0"); item.writeOneAttribute(RtfListTable.LIST_NUMBER, new Integer(item.getNumber())); item.writeOneAttribute("pnindent", item.getParentList().attrib.getValue(RtfListTable.LIST_INDENT)); item.writeControlWord("pnf1"); item.writeGroupMark(true); item.writeControlWord("pndec"); item.writeOneAttribute(RtfListTable.LIST_FONT_TYPE, "2"); item.writeControlWord("pntxtb"); item.writeControlWord("'b7"); item.writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleBullet.java
public void writeParagraphPrefix(RtfElement element) throws IOException { element.writeGroupMark(true); element.writeControlWord("pntext"); element.writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleBullet.java
public void writeLevelGroup(RtfElement element) throws IOException { element.attrib.set(RtfListTable.LIST_NUMBER_TYPE, 23); element.writeGroupMark(true); element.writeOneAttributeNS(RtfListTable.LIST_TEXT_FORM, "\\'01\\'b7"); element.writeGroupMark(false); element.writeGroupMark(true); element.writeOneAttributeNS(RtfListTable.LIST_NUM_POSITION, null); element.writeGroupMark(false); element.attrib.set(RtfListTable.LIST_FONT_TYPE, 2); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfter.java
protected void writeMyAttributes() throws IOException { writeAttributes(attrib, FOOTER_ATTR); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfDocumentArea.java
public RtfSection newSection() throws IOException { if (currentSection != null) { currentSection.close(); } currentSection = new RtfSection(this, writer); return currentSection; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFontManager.java
public void writeFonts (RtfHeader header) throws IOException { if (fontTable == null || fontTable.size () == 0) { return; } header.newLine(); header.writeGroupMark(true); header.writeControlWord("fonttbl"); int len = fontTable.size (); for (int i = 0; i < len; i++) { header.writeGroupMark(true); header.newLine(); header.write("\\f" + i); header.write(" " + (String) fontTable.elementAt (i)); header.write(";"); header.writeGroupMark(false); } header.newLine(); header.writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
protected void writeRtfContent() throws IOException { writeGroupMark(true); writeAttributes(getRtfAttributes(), null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
protected void writeRtfContent() throws IOException { writeGroupMark(false); boolean bHasTableCellParent = this.getParentOfClass(RtfTableCell.class) != null; //Unknown behavior when a table starts a new section, //Word may crash if (breakType != BREAK_NONE) { if (!bHasTableCellParent) { writeControlWord("sect"); /* The following modifiers don't seem to appear in the right place */ switch (breakType) { case BREAK_EVEN_PAGE: writeControlWord("sbkeven"); break; case BREAK_ODD_PAGE: writeControlWord("sbkodd"); break; case BREAK_COLUMN: writeControlWord("sbkcol"); break; default: writeControlWord("sbkpage"); } } else { log.warn("Cannot create break-after for a paragraph inside a table."); } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
private void addOpenGroupMark(RtfAttributes attrs) throws IOException { RtfOpenGroupMark r = new RtfOpenGroupMark(this, writer, attrs); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
private void addCloseGroupMark(int breakType) throws IOException { RtfCloseGroupMark r = new RtfCloseGroupMark(this, writer, breakType); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
private void addCloseGroupMark() throws IOException { RtfCloseGroupMark r = new RtfCloseGroupMark(this, writer, BREAK_NONE); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void pushBlockAttributes(RtfAttributes attrs) throws IOException { rtfSpaceManager.stopUpdatingSpaceBefore(); RtfSpaceSplitter splitter = rtfSpaceManager.pushRtfSpaceSplitter(attrs); addOpenGroupMark(splitter.getCommonAttributes()); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void popBlockAttributes(int breakType) throws IOException { rtfSpaceManager.popRtfSpaceSplitter(); rtfSpaceManager.stopUpdatingSpaceBefore(); addCloseGroupMark(breakType); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void pushInlineAttributes(RtfAttributes attrs) throws IOException { rtfSpaceManager.pushInlineAttributes(attrs); addOpenGroupMark(attrs); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void addPageNumberCitation(String refId) throws IOException { RtfPageNumberCitation r = new RtfPageNumberCitation(this, writer, refId); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void popInlineAttributes() throws IOException { rtfSpaceManager.popInlineAttributes(); addCloseGroupMark(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void addString(String s) throws IOException { if (s.equals("")) { return; } RtfAttributes attrs = rtfSpaceManager.getLastInlineAttribute(); //add RtfSpaceSplitter to inherit accumulated space rtfSpaceManager.pushRtfSpaceSplitter(attrs); rtfSpaceManager.setCandidate(attrs); // create a string and add it as a child new RtfString(this, writer, s); rtfSpaceManager.popRtfSpaceSplitter(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public RtfFootnote addFootnote() throws IOException { return new RtfFootnote(this, writer); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public RtfParagraphBreak addParagraphBreak() throws IOException { // get copy of children list List children = getChildren(); Stack tmp = new Stack(); RtfParagraphBreak par = null; // delete all previous CloseGroupMark int deletedCloseGroupCount = 0; ListIterator lit = children.listIterator(children.size()); while (lit.hasPrevious() && (lit.previous() instanceof RtfCloseGroupMark)) { tmp.push(Integer.valueOf(((RtfCloseGroupMark)lit.next()).getBreakType())); lit.remove(); deletedCloseGroupCount++; } if (children.size() != 0) { // add paragraph break and restore all deleted close group marks setChildren(children); par = new RtfParagraphBreak(this, writer); for (int i = 0; i < deletedCloseGroupCount; i++) { addCloseGroupMark(((Integer)tmp.pop()).intValue()); } } return par; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void addLeader(RtfAttributes attrs) throws IOException { new RtfLeader(this, writer, attrs); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void addPageNumber(RtfAttributes attr) throws IOException { RtfPageNumber r = new RtfPageNumber(this, writer, attr); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public RtfHyperLink addHyperlink(RtfAttributes attr) throws IOException { return new RtfHyperLink(this, writer, attr); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void addBookmark(String id) throws IOException { if (id != "") { // if id is not empty, add boormark new RtfBookmark(this, writer, id); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public RtfExternalGraphic newImage() throws IOException { return new RtfExternalGraphic(this, writer); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public static RtfTextrun getTextrun(RtfContainer container, Writer writer, RtfAttributes attrs) throws IOException { List list = container.getChildren(); if (list.size() == 0) { //add a new RtfTextrun RtfTextrun textrun = new RtfTextrun(container, writer, attrs); list.add(textrun); return textrun; } Object obj = list.get(list.size() - 1); if (obj instanceof RtfTextrun) { //if the last child is a RtfTextrun, return it return (RtfTextrun) obj; } //add a new RtfTextrun as the last child RtfTextrun textrun = new RtfTextrun(container, writer, attrs); list.add(textrun); return textrun; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
protected void writeRtfContent() throws IOException { /** *TODO: The textrun's children are iterated twice: * 1. To determine the last RtfParagraphBreak * 2. To write the children * Maybe this can be done more efficient. */ boolean bHasTableCellParent = this.getParentOfClass(RtfTableCell.class) != null; RtfAttributes attrBlockLevel = new RtfAttributes(); //determine, if this RtfTextrun is the last child of its parent boolean bLast = false; for (Iterator it = parent.getChildren().iterator(); it.hasNext();) { if (it.next() == this) { bLast = !it.hasNext(); break; } } //get last RtfParagraphBreak, which is not followed by any visible child RtfParagraphBreak lastParagraphBreak = null; if (bLast) { RtfElement aBefore = null; for (Iterator it = getChildren().iterator(); it.hasNext();) { final RtfElement e = (RtfElement)it.next(); if (e instanceof RtfParagraphBreak) { //If the element before was a paragraph break or a bookmark //they will be hidden and are therefore not considered as visible if (!(aBefore instanceof RtfParagraphBreak) && !(aBefore instanceof RtfBookmark)) { lastParagraphBreak = (RtfParagraphBreak)e; } } else { if (!(e instanceof RtfOpenGroupMark) && !(e instanceof RtfCloseGroupMark) && e.isEmpty()) { lastParagraphBreak = null; } } aBefore = e; } } //may contain for example \intbl writeAttributes(attrib, null); if (rtfListItem != null) { rtfListItem.getRtfListStyle().writeParagraphPrefix(this); } //write all children boolean bPrevPar = false; boolean bBookmark = false; boolean bFirst = true; for (Iterator it = getChildren().iterator(); it.hasNext();) { final RtfElement e = (RtfElement)it.next(); final boolean bRtfParagraphBreak = (e instanceof RtfParagraphBreak); if (bHasTableCellParent) { attrBlockLevel.set(e.getRtfAttributes()); } /** * -Write RtfParagraphBreak only, if the previous visible child * was't also a RtfParagraphBreak. * -Write RtfParagraphBreak only, if it is not the first visible * child. * -If the RtfTextrun is the last child of its parent, write a * RtfParagraphBreak only, if it is not the last child. * -If the RtfParagraphBreak can not be hidden (e.g. a table cell requires it) * it is also written */ boolean bHide = false; bHide = bRtfParagraphBreak; bHide = bHide && (bPrevPar || bFirst || (bSuppressLastPar && bLast && lastParagraphBreak != null && e == lastParagraphBreak) || bBookmark) && ((RtfParagraphBreak)e).canHide(); if (!bHide) { newLine(); e.writeRtf(); if (rtfListItem != null && e instanceof RtfParagraphBreak) { rtfListItem.getRtfListStyle().writeParagraphPrefix(this); } } if (e instanceof RtfParagraphBreak) { bPrevPar = true; } else if (e instanceof RtfBookmark) { bBookmark = true; } else if (e instanceof RtfCloseGroupMark) { //do nothing } else if (e instanceof RtfOpenGroupMark) { //do nothing } else { bPrevPar = bPrevPar && e.isEmpty(); bFirst = bFirst && e.isEmpty(); bBookmark = false; } } //for (Iterator it = ...) // if (bHasTableCellParent) { writeAttributes(attrBlockLevel, null); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfLineBreak.java
protected void writeRtfContent() throws IOException { writeControlWord("line"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleText.java
public void writeListPrefix(RtfListItem item) throws IOException { // bulleted list item.writeControlWord("pnlvlblt"); item.writeControlWord("ilvl0"); item.writeOneAttribute(RtfListTable.LIST_NUMBER, new Integer(item.getNumber())); item.writeOneAttribute("pnindent", item.getParentList().attrib.getValue(RtfListTable.LIST_INDENT)); item.writeControlWord("pnf1"); item.writeGroupMark(true); //item.writeControlWord("pndec"); item.writeOneAttribute(RtfListTable.LIST_FONT_TYPE, "2"); item.writeControlWord("pntxtb"); RtfStringConverter.getInstance().writeRtfString(item.writer, text); item.writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleText.java
public void writeParagraphPrefix(RtfElement element) throws IOException { element.writeGroupMark(true); element.writeControlWord("pntext"); element.writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleText.java
public void writeLevelGroup(RtfElement element) throws IOException { element.attrib.set(RtfListTable.LIST_NUMBER_TYPE, 23); element.writeGroupMark(true); String sCount; if (text.length() < 10) { sCount = "0" + String.valueOf(text.length()); } else { sCount = String.valueOf(Integer.toHexString(text.length())); if (sCount.length() == 1) { sCount = "0" + sCount; } } element.writeOneAttributeNS( RtfListTable.LIST_TEXT_FORM, "\\'" + sCount + RtfStringConverter.getInstance().escape(text)); element.writeGroupMark(false); element.writeGroupMark(true); element.writeOneAttributeNS(RtfListTable.LIST_NUM_POSITION, null); element.writeGroupMark(false); element.attrib.set(RtfListTable.LIST_FONT_TYPE, 2); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTemplate.java
public void setTemplateFilePath(String templateFilePath) throws IOException { // no validity checks here - leave this to the RTF client if (templateFilePath == null) { this.templateFilePath = null; } else { this.templateFilePath = templateFilePath.trim(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTemplate.java
public void writeTemplate (RtfHeader header) throws IOException { if (templateFilePath == null || templateFilePath.length() == 0) { return; } header.writeGroupMark (true); header.writeControlWord ("template"); header.writeRtfString(this.templateFilePath); header.writeGroupMark (false); header.writeGroupMark (true); header.writeControlWord ("linkstyles"); header.writeGroupMark (false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleNumber.java
public void writeListPrefix(RtfListItem item) throws IOException { item.writeControlWord("pnlvlbody"); item.writeControlWord("ilvl0"); item.writeOneAttribute(RtfListTable.LIST_NUMBER, "0"); item.writeControlWord("pndec"); item.writeOneAttribute("pnstart", new Integer(1)); item.writeOneAttribute("pnindent", item.attrib.getValue(RtfListTable.LIST_INDENT)); item.writeControlWord("pntxta."); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleNumber.java
public void writeParagraphPrefix(RtfElement element) throws IOException { element.writeGroupMark(true); element.writeControlWord("pntext"); element.writeControlWord("f" + RtfFontManager.getInstance().getFontNumber("Symbol")); element.writeControlWord("'b7"); element.writeControlWord("tab"); element.writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleNumber.java
public void writeLevelGroup(RtfElement element) throws IOException { element.writeOneAttributeNS( RtfListTable.LIST_START_AT, new Integer(1)); element.attrib.set(RtfListTable.LIST_NUMBER_TYPE, 0); element.writeGroupMark(true); element.writeOneAttributeNS( RtfListTable.LIST_TEXT_FORM, "\\'03\\\'00. ;"); element.writeGroupMark(false); element.writeGroupMark(true); element.writeOneAttributeNS( RtfListTable.LIST_NUM_POSITION, "\\'01;"); element.writeGroupMark(false); element.writeOneAttribute(RtfListTable.LIST_FONT_TYPE, new Integer(0)); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExtraRowSet.java
RtfTableCell createExtraCell(int rowIndex, int xOffset, int cellWidth, RtfAttributes parentCellAttributes) throws IOException { final RtfTableCell c = new RtfTableCell(null, writer, cellWidth, parentCellAttributes, DEFAULT_IDNUM); cells.add(new PositionedCell(c, rowIndex, xOffset)); return c; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExtraRowSet.java
protected void writeRtfContent() throws IOException { // sort cells by rowIndex and xOffset Collections.sort(cells); // process all extra cells by rendering them into extra rows List rowCells = null; int rowIndex = -1; for (Iterator it = cells.iterator(); it.hasNext();) { final PositionedCell pc = (PositionedCell)it.next(); if (pc.rowIndex != rowIndex) { // starting a new row, render previous one if (rowCells != null) { writeRow(rowCells); } rowIndex = pc.rowIndex; rowCells = new LinkedList(); } rowCells.add(pc); } // render last row if (rowCells != null) { writeRow(rowCells); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExtraRowSet.java
private void writeRow(List cells) throws IOException { if (allCellsEmpty(cells)) { return; } final RtfTableRow row = new RtfTableRow(null, writer, DEFAULT_IDNUM); int cellIndex = 0; // Get the context of the table that holds the nested table ITableColumnsInfo parentITableColumnsInfo = getParentITableColumnsInfo(); parentITableColumnsInfo.selectFirstColumn(); // X offset of the current empty cell to add float xOffset = 0; float xOffsetOfLastPositionedCell = 0; for (Iterator it = cells.iterator(); it.hasNext();) { final PositionedCell pc = (PositionedCell)it.next(); // if first cell is not at offset 0, add placeholder cell // TODO should be merged with the cell that is above it if (cellIndex == 0 && pc.xOffset > 0) { /** * Added by Boris Poudérous */ // Add empty cells merged vertically with the cells above and with the same widths // (BEFORE the cell that contains the nested table) for (int i = 0; (xOffset < pc.xOffset) && (i < parentITableColumnsInfo.getNumberOfColumns()); i++) { // Get the width of the cell above xOffset += parentITableColumnsInfo.getColumnWidth(); // Create the empty cell merged vertically row.newTableCellMergedVertically((int)parentITableColumnsInfo.getColumnWidth(), pc.cell.attrib); // Select next column in order to have its width parentITableColumnsInfo.selectNextColumn(); } } row.addChild(pc.cell); // Line added by Boris Poudérous xOffsetOfLastPositionedCell = pc.xOffset + pc.cell.getCellWidth(); cellIndex++; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
protected void writeRtfPrefix() throws IOException { super.writeRtfPrefix(); getRtfListStyle().writeParagraphPrefix(this); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
public RtfTextrun getTextrun() throws IOException { return this; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
public void addString(String s) throws IOException { final String label = s.trim(); if (label.length() > 0 && Character.isDigit(label.charAt(0))) { rtfListItem.setRtfListStyle(new RtfListStyleNumber()); } else { rtfListItem.setRtfListStyle(new RtfListStyleText(label)); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
public RtfParagraph newParagraph(RtfAttributes attrs) throws IOException { if (paragraph != null) { paragraph.close(); } paragraph = new RtfListItemParagraph(this, attrs); return paragraph; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
public RtfParagraph newParagraph() throws IOException { return newParagraph(null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
public RtfTextrun getTextrun() throws IOException { RtfTextrun textrun = RtfTextrun.getTextrun(this, writer, null); textrun.setRtfListItem(this); return textrun; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
public RtfList newList(RtfAttributes attrs) throws IOException { RtfList list = new RtfList(this, writer, attrs); return list; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
protected void writeRtfPrefix() throws IOException { // pard causes word97 (and sometimes 2000 too) to crash if the list is nested in a table if (!parentList.getHasTableParent()) { writeControlWord("pard"); } writeOneAttribute(RtfText.LEFT_INDENT_FIRST, "360"); //attrib.getValue(RtfListTable.LIST_INDENT)); writeOneAttribute(RtfText.LEFT_INDENT_BODY, attrib.getValue(RtfText.LEFT_INDENT_BODY)); // group for list setup info writeGroupMark(true); writeStarControlWord("pn"); //Modified by Chris Scott //fixes second line indentation getRtfListStyle().writeListPrefix(this); writeGroupMark(false); writeOneAttribute(RtfListTable.LIST_NUMBER, new Integer(number)); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
protected void writeRtfSuffix() throws IOException { super.writeRtfSuffix(); /* reset paragraph defaults to make sure list ends * but pard causes word97 (and sometimes 2000 too) to crash if the list * is nested in a table */ if (!parentList.getHasTableParent()) { writeControlWord("pard"); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfPage.java
protected void writeRtfContent() throws IOException { writeAttributes(attrib, PAGE_ATTR); if (attrib != null) { Object widthRaw = attrib.getValue(PAGE_WIDTH); Object heightRaw = attrib.getValue(PAGE_HEIGHT); if ((widthRaw instanceof Integer) && (heightRaw instanceof Integer) && ((Integer) widthRaw).intValue() > ((Integer) heightRaw).intValue()) { writeControlWord(LANDSCAPE); } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHeader.java
protected void writeRtfContent() throws IOException { writeControlWord(charset); writeUserProperties(); RtfColorTable.getInstance().writeColors(this); super.writeRtfContent(); RtfTemplate.getInstance().writeTemplate(this); RtfStyleSheetTable.getInstance().writeStyleSheet(this); writeFootnoteProperties(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHeader.java
private void writeUserProperties() throws IOException { if (userProperties.size() > 0) { writeGroupMark(true); writeStarControlWord("userprops"); for (Iterator it = userProperties.entrySet().iterator(); it.hasNext();) { final Map.Entry entry = (Map.Entry)it.next(); writeGroupMark(true); writeControlWord("propname"); RtfStringConverter.getInstance().writeRtfString(writer, entry.getKey().toString()); writeGroupMark(false); writeControlWord("proptype30"); writeGroupMark(true); writeControlWord("staticval"); RtfStringConverter.getInstance().writeRtfString(writer, entry.getValue().toString()); writeGroupMark(false); } writeGroupMark(false); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHeader.java
void write(String toWrite) throws IOException { writer.write(toWrite); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHeader.java
void writeRtfString(String toWrite) throws IOException { RtfStringConverter.getInstance().writeRtfString(writer, toWrite); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHeader.java
private void writeFootnoteProperties() throws IOException { newLine(); writeControlWord("fet0"); //footnotes, not endnotes writeControlWord("ftnbj"); //place footnotes at the end of the //page (should be the default, but //Word 2000 thinks otherwise) }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
protected void writeRtfContent() throws IOException { try { writeRtfContentWithException(); } catch (ExternalGraphicException ie) { writeExceptionInRtf(ie); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
protected void writeRtfContentWithException() throws IOException { if (writer == null) { return; } if (url == null && imagedata == null) { throw new ExternalGraphicException( "No image data is available (neither URL, nor in-memory)"); } String linkToRoot = System.getProperty("jfor_link_to_root"); if (url != null && linkToRoot != null) { writer.write("{\\field {\\* \\fldinst { INCLUDEPICTURE \""); writer.write(linkToRoot); File urlFile = new File(url.getFile()); writer.write(urlFile.getName()); writer.write("\" \\\\* MERGEFORMAT \\\\d }}}"); return; } // getRtfFile ().getLog ().logInfo ("Writing image '" + url + "'."); if (imagedata == null) { try { final InputStream in = url.openStream(); try { imagedata = IOUtils.toByteArray(url.openStream()); } finally { IOUtils.closeQuietly(in); } } catch (Exception e) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + url + "' (" + e + ")"); } } if (imagedata == null) { return; } // Determine image file format String file = (url != null ? url.getFile() : "<unknown>"); imageformat = FormatBase.determineFormat(imagedata); if (imageformat != null) { imageformat = imageformat.convert(imageformat, imagedata); } if (imageformat == null || imageformat.getType() == ImageConstants.I_NOT_SUPPORTED || "".equals(imageformat.getRtfTag())) { throw new ExternalGraphicException("The tag <fo:external-graphic> " + "does not support " + file.substring(file.lastIndexOf(".") + 1) + " - image type."); } // Writes the beginning of the rtf image writeGroupMark(true); writeStarControlWord("shppict"); writeGroupMark(true); writeControlWord("pict"); StringBuffer buf = new StringBuffer(imagedata.length * 3); writeControlWord(imageformat.getRtfTag()); computeImageSize(); writeSizeInfo(); writeAttributes(getRtfAttributes(), null); for (int i = 0; i < imagedata.length; i++) { int iData = imagedata [i]; // Make positive byte if (iData < 0) { iData += 256; } if (iData < 16) { // Set leading zero and append buf.append('0'); } buf.append(Integer.toHexString(iData)); } int len = buf.length(); char[] chars = new char[len]; buf.getChars(0, len, chars, 0); writer.write(chars); // Writes the end of RTF image writeGroupMark(false); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
private void writeSizeInfo () throws IOException { // Set image size if (width != -1) { writeControlWord("picw" + width); } if (height != -1) { writeControlWord("pich" + height); } if (widthDesired != -1) { if (perCentW) { writeControlWord("picscalex" + widthDesired); } else { //writeControlWord("picscalex" + widthDesired * 100 / width); writeControlWord("picwgoal" + widthDesired); } } else if (scaleUniform && heightDesired != -1) { if (perCentH) { writeControlWord("picscalex" + heightDesired); } else { writeControlWord("picscalex" + heightDesired * 100 / height); } } if (heightDesired != -1) { if (perCentH) { writeControlWord("picscaley" + heightDesired); } else { //writeControlWord("picscaley" + heightDesired * 100 / height); writeControlWord("pichgoal" + heightDesired); } } else if (scaleUniform && widthDesired != -1) { if (perCentW) { writeControlWord("picscaley" + widthDesired); } else { writeControlWord("picscaley" + widthDesired * 100 / width); } } if (this.cropValues[0] != 0) { writeOneAttribute("piccropl", new Integer(this.cropValues[0])); } if (this.cropValues[1] != 0) { writeOneAttribute("piccropt", new Integer(this.cropValues[1])); } if (this.cropValues[2] != 0) { writeOneAttribute("piccropr", new Integer(this.cropValues[2])); } if (this.cropValues[3] != 0) { writeOneAttribute("piccropb", new Integer(this.cropValues[3])); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
public void setImageData(byte[] data) throws IOException { this.imagedata = data; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
public void setURL(String urlString) throws IOException { URL tmpUrl = null; try { tmpUrl = new URL (urlString); } catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } } this.url = tmpUrl; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfGenerator.java
protected void writeRtfContent() throws IOException { newLine(); writeGroupMark(true); writeStarControlWord("generator"); writer.write("Apache XML Graphics RTF Library"); writer.write(";"); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListTable.java
public void writeRtfContent() throws IOException { newLine(); if (lists != null) { //write '\listtable' writeGroupMark(true); writeStarControlWordNS(LIST_TABLE); newLine(); for (Iterator it = lists.iterator(); it.hasNext();) { final RtfList list = (RtfList)it.next(); writeListTableEntry(list); newLine(); } writeGroupMark(false); newLine(); //write '\listoveridetable' writeGroupMark(true); writeStarControlWordNS(LIST_OVR_TABLE); int z = 1; newLine(); for (Iterator it = styles.iterator(); it.hasNext();) { final RtfListStyle style = (RtfListStyle)it.next(); writeGroupMark(true); writeStarControlWordNS(LIST_OVR); writeGroupMark(true); writeOneAttributeNS(LIST_ID, style.getRtfList().getListId().toString()); writeOneAttributeNS(LIST_OVR_COUNT, new Integer(0)); writeOneAttributeNS(LIST_NUMBER, new Integer(z++)); writeGroupMark(false); writeGroupMark(false); newLine(); } writeGroupMark(false); newLine(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListTable.java
private void writeListTableEntry(RtfList list) throws IOException { //write list-specific attributes writeGroupMark(true); writeControlWordNS(LIST); writeOneAttributeNS(LIST_TEMPLATE_ID, list.getListTemplateId().toString()); writeOneAttributeNS(LIST, attrib.getValue(LIST)); // write level-specific attributes writeGroupMark(true); writeControlWordNS(LIST_LEVEL); writeOneAttributeNS(LIST_JUSTIFICATION, attrib.getValue(LIST_JUSTIFICATION)); writeOneAttributeNS(LIST_FOLLOWING_CHAR, attrib.getValue(LIST_FOLLOWING_CHAR)); writeOneAttributeNS(LIST_SPACE, new Integer(0)); writeOneAttributeNS(LIST_INDENT, attrib.getValue(LIST_INDENT)); RtfListItem item = (RtfListItem)list.getChildren().get(0); if (item != null) { item.getRtfListStyle().writeLevelGroup(this); } writeGroupMark(false); writeGroupMark(true); writeControlWordNS(LIST_NAME); writeGroupMark(false); writeOneAttributeNS(LIST_ID, list.getListId().toString()); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFootnote.java
public RtfTextrun getTextrun() throws IOException { if (bBody) { RtfTextrun textrun = RtfTextrun.getTextrun(body, writer, null); textrun.setSuppressLastPar(true); return textrun; } else { return textrunInline; } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFootnote.java
protected void writeRtfContent() throws IOException { textrunInline.writeRtfContent(); writeGroupMark(true); writeControlWord("footnote"); writeControlWord("ftnalt"); body.writeRtfContent(); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFootnote.java
public RtfList newList(RtfAttributes attrs) throws IOException { if (list != null) { list.close(); } list = new RtfList(body, writer, attrs); return list; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
public final void close() throws IOException { closed = true; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
public final void writeRtf() throws IOException { if (!written) { written = true; if (okToWriteRtf()) { writeRtfPrefix(); writeRtfContent(); writeRtfSuffix(); } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
public void newLine() throws IOException { writer.write("\n"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected final void writeControlWord(String word) throws IOException { writer.write('\\'); writer.write(word); writer.write(' '); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected final void writeStarControlWord(String word) throws IOException { writer.write("\\*\\"); writer.write(word); writer.write(' '); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected final void writeStarControlWordNS(String word) throws IOException { writer.write("\\*\\"); writer.write(word); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected final void writeControlWordNS(String word) throws IOException { writer.write('\\'); writer.write(word); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected void writeRtfPrefix() throws IOException { }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected void writeRtfSuffix() throws IOException { }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected final void writeGroupMark(boolean isStart) throws IOException { writer.write(isStart ? "{" : "}"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected void writeAttributes(RtfAttributes attr, String [] nameList) throws IOException { if (attr == null) { return; } if (nameList != null) { // process only given attribute names for (int i = 0; i < nameList.length; i++) { final String name = nameList[i]; if (attr.isSet(name)) { writeOneAttribute(name, attr.getValue(name)); } } } else { // process all defined attributes for (Iterator it = attr.nameIterator(); it.hasNext();) { final String name = (String)it.next(); if (attr.isSet(name)) { writeOneAttribute(name, attr.getValue(name)); } } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected void writeOneAttribute(String name, Object value) throws IOException { String cw = name; if (value instanceof Integer) { // attribute has integer value, must write control word + value cw += value; } else if (value instanceof String) { cw += value; } else if (value instanceof RtfAttributes) { writeControlWord(cw); writeAttributes((RtfAttributes) value, null); return; } writeControlWord(cw); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected void writeOneAttributeNS(String name, Object value) throws IOException { String cw = name; if (value instanceof Integer) { // attribute has integer value, must write control word + value cw += value; } else if (value instanceof String) { cw += value; } else if (value instanceof RtfAttributes) { writeControlWord(cw); writeAttributes((RtfAttributes) value, null); return; } writeControlWordNS(cw); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
void dump(Writer w, int indent) throws IOException { for (int i = 0; i < indent; i++) { w.write(' '); } w.write(this.toString()); w.write('\n'); w.flush(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected void writeExceptionInRtf(Exception ie) throws IOException { writeGroupMark(true); writeControlWord("par"); // make the exception message stand out so that the problem is visible writeControlWord("fs48"); // RtfStringConverter.getInstance().writeRtfString(m_writer, // JForVersionInfo.getShortVersionInfo() + ": "); RtfStringConverter.getInstance().writeRtfString(writer, ie.getClass().getName()); writeControlWord("fs20"); RtfStringConverter.getInstance().writeRtfString(writer, " " + ie.toString()); writeControlWord("par"); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfStyleSheetTable.java
public void writeStyleSheet (RtfHeader header) throws IOException { if (styles == null || styles.size () == 0) { return; } header.writeGroupMark (true); header.writeControlWord ("stylesheet"); int number = nameTable.size (); for (int i = 0; i < number; i++) { String name = (String) nameTable.elementAt (i); header.writeGroupMark (true); header.writeControlWord ("*\\" + this.getRtfStyleReference (name)); Object o = attrTable.get (name); if (o != null) { header.writeAttributes ((RtfAttributes) o, RtfText.ATTR_NAMES); header.writeAttributes ((RtfAttributes) o, RtfText.ALIGNMENT); } header.write (name + ";"); header.writeGroupMark (false); } header.writeGroupMark (false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmark.java
public void writeRtfPrefix () throws IOException { startBookmark (); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmark.java
public void writeRtfContent () throws IOException { // this.getRtfFile ().getLog ().logInfo ("Write bookmark '" + bookmark + "'."); // No content to write }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmark.java
public void writeRtfSuffix () throws IOException { endBookmark (); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmark.java
private void startBookmark () throws IOException { // {\*\bkmkstart test} writeRtfBookmark ("bkmkstart"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmark.java
private void endBookmark () throws IOException { // {\*\bkmkend test} writeRtfBookmark ("bkmkend"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmark.java
private void writeRtfBookmark (String tag) throws IOException { if (bookmark == null) { return; } this.writeGroupMark (true); //changed. Now using writeStarControlWord this.writeStarControlWord (tag); writer.write (bookmark); this.writeGroupMark (false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraphKeepTogether.java
protected void writeRtfContent() throws IOException { //First reet paragraph properties // create a new one with keepn if (status == STATUS_OPEN_PARAGRAPH) { writeControlWord("pard"); writeControlWord("par"); writeControlWord("keepn"); writeGroupMark(true); status = STATUS_NULL; } if (status == STATUS_CLOSE_PARAGRAPH) { writeGroupMark(false); status = STATUS_NULL; } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfColorTable.java
public void writeColors (RtfHeader header) throws IOException { if (colorTable == null || colorTable.size () == 0) { return; } header.newLine(); header.writeGroupMark (true); //Don't use writeControlWord, because it appends a blank, //which may confuse Wordpad. //This also implicitly writes the first color (=index 0), which //is reserved for auto-colored. header.write ("\\colortbl;"); int len = colorTable.size (); for (int i = 0; i < len; i++) { int identifier = ((Integer) colorTable.get (i)).intValue (); header.newLine(); header.write ("\\red" + determineColorLevel (identifier, RED)); header.write ("\\green" + determineColorLevel (identifier, GREEN)); header.write ("\\blue" + determineColorLevel (identifier, BLUE) + ";"); } header.newLine(); header.writeGroupMark (false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfString.java
protected void writeRtfContent() throws IOException { RtfStringConverter.getInstance().writeRtfString(writer, text); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfPageNumberCitation.java
protected void writeRtfContent() throws IOException { // If we have a valid ID if (isValid()) { // Build page reference field String pageRef = RTF_FIELD_PAGEREF_MODEL; final int insertionIndex = pageRef.indexOf("}"); pageRef = pageRef.substring(0, insertionIndex) + "\"" + id + "\"" + " " + pageRef.substring(insertionIndex, pageRef.length()); id = null; // Write RTF content writeGroupMark(true); writeControlWord(RTF_FIELD); writeGroupMark(true); writeAttributes(attrib, RtfText.ATTR_NAMES); // Added by Boris Poudérous writeStarControlWord(pageRef); writeGroupMark(false); writeGroupMark(true); writeControlWord(RTF_FIELD_RESULT + '#'); //To see where the page-number would be writeGroupMark(false); writeGroupMark(false); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfList.java
public RtfListItem newListItem() throws IOException { if (item != null) { item.close(); } item = new RtfListItem(this, writer); return item; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfStringConverter.java
public void writeRtfString(Writer w, String str) throws IOException { if (str == null) { return; } w.write(escape(str)); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmarkContainerImpl.java
public RtfBookmark newBookmark (String bookmark) throws IOException { if (mBookmark != null) { mBookmark.close (); } mBookmark = new RtfBookmark (this, writer, bookmark); return mBookmark; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBefore.java
protected void writeMyAttributes() throws IOException { writeAttributes(attrib, HEADER_ATTR); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
protected void writeRtfPrefix() throws IOException { //Reset paragraph properties if needed if (resetProperties) { writeControlWord("pard"); } /* * Original comment said "do not write text attributes here, they are * handled by RtfText." However, the text attributes appear to be * relevant to paragraphs as well. */ writeAttributes(attrib, RtfText.ATTR_NAMES); writeAttributes(attrib, PARA_ATTRIBUTES); // Added by Normand Masse // Write alignment attributes after \intbl for cells if (attrib.isSet("intbl") && mustWriteAttributes()) { writeAttributes(attrib, RtfText.ALIGNMENT); } //Set keepn if needed (Keep paragraph with the next paragraph) if (keepn) { writeControlWord("keepn"); } // start a group for this paragraph and write our own attributes if needed if (mustWriteGroupMark()) { writeGroupMark(true); } if (mustWriteAttributes()) { // writeAttributes(m_attrib, new String [] {"cs"}); // Added by Normand Masse // If \intbl then attributes have already been written (see higher in method) if (!attrib.isSet("intbl")) { writeAttributes(attrib, RtfText.ALIGNMENT); } //this line added by Chris Scott, Westinghouse writeAttributes(attrib, RtfText.BORDER); writeAttributes(attrib, RtfText.INDENT); writeAttributes(attrib, RtfText.TABS); if (writeForBreak) { writeControlWord("pard\\par"); } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
protected void writeRtfSuffix() throws IOException { // sometimes the end of paragraph mark must be suppressed in table cells boolean writeMark = true; if (parent instanceof RtfTableCell) { writeMark = ((RtfTableCell)parent).paragraphNeedsPar(this); } if (writeMark) { writeControlWord("par"); } if (mustWriteGroupMark()) { writeGroupMark(false); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfText newText(String str) throws IOException { return newText(str, null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfText newText(String str, RtfAttributes attr) throws IOException { closeAll(); text = new RtfText(this, writer, str, attr); return text; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public void newPageBreak() throws IOException { writeForBreak = true; new RtfPageBreak(this, writer); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public void newLineBreak() throws IOException { new RtfLineBreak(this, writer); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfPageNumber newPageNumber()throws IOException { pageNumber = new RtfPageNumber(this, writer); return pageNumber; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfPageNumberCitation newPageNumberCitation(String id) throws IOException { pageNumberCitation = new RtfPageNumberCitation(this, writer, id); return pageNumberCitation; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfHyperLink newHyperLink(String str, RtfAttributes attr) throws IOException { hyperlink = new RtfHyperLink(this, writer, str, attr); return hyperlink; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfExternalGraphic newImage() throws IOException { closeAll(); externalGraphic = new RtfExternalGraphic(this, writer); return externalGraphic; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
private void closeCurrentText() throws IOException { if (text != null) { text.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
private void closeCurrentHyperLink() throws IOException { if (hyperlink != null) { hyperlink.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
private void closeAll() throws IOException { closeCurrentText(); closeCurrentHyperLink(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraphBreak.java
protected void writeRtfContent() throws IOException { if (controlWord != null ) { writeControlWord(controlWord); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfPageBreak.java
protected void writeRtfContent() throws IOException { writeControlWord("page"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfParagraph newParagraph(RtfAttributes attrs) throws IOException { closeAll(); // in tables, RtfParagraph must have the intbl attribute if (attrs == null) { attrs = new RtfAttributes(); } attrs.set("intbl"); paragraph = new RtfParagraph(this, writer, attrs); if (paragraph.attrib.isSet("qc")) { setCenter = true; attrs.set("qc"); } else if (paragraph.attrib.isSet("qr")) { setRight = true; attrs.set("qr"); } else { attrs.set("ql"); } attrs.set("intbl"); //lines modified by Chris Scott, Westinghouse return paragraph; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfExternalGraphic newImage() throws IOException { closeAll(); externalGraphic = new RtfExternalGraphic(this, writer); return externalGraphic; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfParagraph newParagraph() throws IOException { return newParagraph(null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfList newList(RtfAttributes attrib) throws IOException { closeAll(); list = new RtfList(this, writer, attrib); return list; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfTable newTable(ITableColumnsInfo tc) throws IOException { closeAll(); table = new RtfTable(this, writer, tc); return table; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfTable newTable(RtfAttributes attrs, ITableColumnsInfo tc) throws IOException { closeAll(); table = new RtfTable(this, writer, attrs, tc); // Added tc Boris Poudérous 07/22/2002 return table; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
int writeCellDef(int offset) throws IOException { /* * Don't write \clmgf or \clmrg. Instead add the widths * of all spanned columns and create a single wider cell, * because \clmgf and \clmrg won't work in last row of a * table (Word2000 seems to do the same). * Cause of this, dont't write horizontally merged cells. * They just exist as placeholders in TableContext class, * and are never written to RTF file. */ // horizontal cell merge codes if (hMerge == MERGE_WITH_PREVIOUS) { return offset; } newLine(); this.widthOffset = offset; // vertical cell merge codes if (vMerge == MERGE_START) { writeControlWord("clvmgf"); } else if (vMerge == MERGE_WITH_PREVIOUS) { writeControlWord("clvmrg"); } /** * Added by Boris POUDEROUS on 2002/06/26 */ // Cell background color processing : writeAttributes (attrib, ITableAttributes.CELL_COLOR); /** - end - */ writeAttributes (attrib, ITableAttributes.ATTRIB_CELL_PADDING); writeAttributes (attrib, ITableAttributes.CELL_BORDER); writeAttributes (attrib, IBorderAttributes.BORDERS); // determine cell width int iCurrentWidth = this.cellWidth; if (attrib.getValue("number-columns-spanned") != null) { // Get the number of columns spanned int nbMergedCells = ((Integer)attrib.getValue("number-columns-spanned")).intValue(); RtfTable tab = getRow().getTable(); // Get the context of the current table in order to get the width of each column ITableColumnsInfo tableColumnsInfo = tab.getITableColumnsInfo(); tableColumnsInfo.selectFirstColumn(); // Reach the column index in table context corresponding to the current column cell // id is the index of the current cell (it begins at 1) // getColumnIndex() is the index of the current column in table context (it begins at 0) // => so we must withdraw 1 when comparing these two variables. while ((this.id - 1) != tableColumnsInfo.getColumnIndex()) { tableColumnsInfo.selectNextColumn(); } // We withdraw one cell because the first cell is already created // (it's the current cell) ! int i = nbMergedCells - 1; while (i > 0) { tableColumnsInfo.selectNextColumn(); iCurrentWidth += (int)tableColumnsInfo.getColumnWidth(); i--; } } final int xPos = offset + iCurrentWidth; //these lines added by Chris Scott, Westinghouse //some attributes need to be written before opening block if (setCenter) { writeControlWord("trqc"); } else if (setRight) { writeControlWord("trqr"); } else { writeControlWord("trql"); } writeAttributes (attrib, ITableAttributes.CELL_VERT_ALIGN); writeControlWord("cellx" + xPos); return xPos; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
protected void writeRtfContent() throws IOException { // Never write horizontally merged cells. if (hMerge == MERGE_WITH_PREVIOUS) { return; } super.writeRtfContent(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
protected void writeRtfPrefix() throws IOException { // Never write horizontally merged cells. if (hMerge == MERGE_WITH_PREVIOUS) { return; } super.writeRtfPrefix(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
protected void writeRtfSuffix() throws IOException { // Never write horizontally merged cells. if (hMerge == MERGE_WITH_PREVIOUS) { return; } if (getRow().getTable().isNestedTable()) { //nested table if (lastBreak == null) { writeControlWordNS("nestcell"); } writeGroupMark(true); writeControlWord("nonesttables"); writeControlWord("par"); writeGroupMark(false); } else { // word97 hangs if cell does not contain at least one "par" control word // TODO this is what causes the extra spaces in nested table of test // 004-spacing-in-tables.fo, // but if is not here we generate invalid RTF for word97 if (setCenter) { writeControlWord("qc"); } else if (setRight) { writeControlWord("qr"); } else { RtfElement lastChild = null; if (getChildren().size() > 0) { lastChild = (RtfElement) getChildren().get(getChildren().size() - 1); } if (lastChild != null && lastChild instanceof RtfTextrun) { //Don't write \ql in order to allow for example a right aligned paragraph //in a not right aligned table-cell to write its \qr. } else { writeControlWord("ql"); } } if (!containsText()) { writeControlWord("intbl"); //R.Marra this create useless paragraph //Seem working into Word97 with the "intbl" only //writeControlWord("par"); } if (lastBreak == null) { writeControlWord("cell"); } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
private void closeCurrentParagraph() throws IOException { if (paragraph != null) { paragraph.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
private void closeCurrentList() throws IOException { if (list != null) { list.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
private void closeCurrentTable() throws IOException { if (table != null) { table.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
private void closeCurrentExternalGraphic() throws IOException { if (externalGraphic != null) { externalGraphic.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
private void closeAll() throws IOException { closeCurrentTable(); closeCurrentParagraph(); closeCurrentList(); closeCurrentExternalGraphic(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfTextrun getTextrun() throws IOException { RtfAttributes attrs = new RtfAttributes(); if (!getRow().getTable().isNestedTable()) { attrs.set("intbl"); } RtfTextrun textrun = RtfTextrun.getTextrun(this, writer, attrs); //Suppress the very last \par, because the closing \cell applies the //paragraph attributes. textrun.setSuppressLastPar(true); return textrun; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public void writeRtfPrefix () throws IOException { super.writeGroupMark (true); super.writeControlWord ("field"); super.writeGroupMark (true); super.writeStarControlWord ("fldinst"); writer.write ("HYPERLINK \"" + url + "\" "); super.writeGroupMark (false); super.writeGroupMark (true); super.writeControlWord ("fldrslt"); // start a group for this paragraph and write our own attributes if needed if (attrib != null && attrib.isSet ("cs")) { writeGroupMark (true); writeAttributes(attrib, new String [] {"cs"}); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public void writeRtfSuffix () throws IOException { if (attrib != null && attrib.isSet ("cs")) { writeGroupMark (false); } super.writeGroupMark (false); super.writeGroupMark (false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public RtfText newText (String str) throws IOException { return newText (str, null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public RtfText newText (String str, RtfAttributes attr) throws IOException { closeAll (); mText = new RtfText (this, writer, str, attr); return mText; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public void newLineBreak () throws IOException { new RtfLineBreak (this, writer); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
private void closeCurrentText () throws IOException { if (mText != null) { mText.close (); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
private void closeAll () throws IOException { closeCurrentText(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public RtfTextrun getTextrun() throws IOException { RtfTextrun textrun = RtfTextrun.getTextrun(this, writer, null); return textrun; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfPageArea.java
public RtfPage newPage(RtfAttributes attr) throws IOException { if (currentPage != null) { currentPage.close(); } currentPage = new RtfPage(this, writer, attr); return currentPage; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
public RtfTableRow newTableRow() throws IOException { if (row != null) { row.close(); } highestRow++; row = new RtfTableRow(this, writer, attrib, highestRow); return row; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
public RtfTableRow newTableRow(RtfAttributes attrs) throws IOException, FOPException { RtfAttributes attr = null; if (attrib != null) { try { attr = (RtfAttributes) attrib.clone (); } catch (CloneNotSupportedException e) { throw new FOPException(e); } attr.set (attrs); } else { attr = attrs; } if (row != null) { row.close(); } highestRow++; row = new RtfTableRow(this, writer, attr, highestRow); return row; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
protected void writeRtfPrefix() throws IOException { if (isNestedTable()) { writeControlWordNS("pard"); } writeGroupMark(true); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
protected void writeRtfSuffix() throws IOException { writeGroupMark(false); if (isNestedTable()) { getRow().writeRowAndCellsDefintions(); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
private void putGraphic(AbstractGraphics abstractGraphic, ImageInfo info) throws IOException { try { FOUserAgent userAgent = abstractGraphic.getUserAgent(); ImageManager manager = userAgent.getFactory().getImageManager(); ImageSessionContext sessionContext = userAgent.getImageSessionContext(); Map hints = ImageUtil.getDefaultHints(sessionContext); Image image = manager.getImage(info, FLAVORS, hints, sessionContext); putGraphic(abstractGraphic, image); } catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
private void putGraphic(AbstractGraphics abstractGraphic, Image image) throws IOException { byte[] rawData = null; final ImageInfo info = image.getInfo(); if (image instanceof ImageRawStream) { ImageRawStream rawImage = (ImageRawStream)image; InputStream in = rawImage.createInputStream(); try { rawData = IOUtils.toByteArray(in); } finally { IOUtils.closeQuietly(in); } } if (rawData == null) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageWritingError(this, null); return; } //Set up percentage calculations this.percentManager.setDimension(abstractGraphic); PercentBaseContext pContext = new PercentBaseContext() { public int getBaseLength(int lengthBase, FObj fobj) { switch (lengthBase) { case LengthBase.IMAGE_INTRINSIC_WIDTH: return info.getSize().getWidthMpt(); case LengthBase.IMAGE_INTRINSIC_HEIGHT: return info.getSize().getHeightMpt(); default: return percentManager.getBaseLength(lengthBase, fobj); } } }; ImageLayout layout = new ImageLayout(abstractGraphic, pContext, image.getInfo().getSize().getDimensionMpt()); final IRtfTextrunContainer c = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); final RtfExternalGraphic rtfGraphic = c.getTextrun().newImage(); //set URL if (info.getOriginalURI() != null) { rtfGraphic.setURL(info.getOriginalURI()); } rtfGraphic.setImageData(rawData); FoUnitsConverter converter = FoUnitsConverter.getInstance(); Dimension viewport = layout.getViewportSize(); Rectangle placement = layout.getPlacement(); int cropLeft = Math.round(converter.convertMptToTwips(-placement.x)); int cropTop = Math.round(converter.convertMptToTwips(-placement.y)); int cropRight = Math.round(converter.convertMptToTwips( -1 * (viewport.width - placement.x - placement.width))); int cropBottom = Math.round(converter.convertMptToTwips( -1 * (viewport.height - placement.y - placement.height))); rtfGraphic.setCropping(cropLeft, cropTop, cropRight, cropBottom); int width = Math.round(converter.convertMptToTwips(viewport.width)); int height = Math.round(converter.convertMptToTwips(viewport.height)); width += cropLeft + cropRight; height += cropTop + cropBottom; rtfGraphic.setWidthTwips(width); rtfGraphic.setHeightTwips(height); //TODO: make this configurable: // int compression = m_context.m_options.getRtfExternalGraphicCompressionRate (); int compression = 0; if (compression != 0) { if (!rtfGraphic.setCompressionRate(compression)) { log.warn("The compression rate " + compression + " is invalid. The value has to be between 1 and 100 %."); } } }
// in src/java/org/apache/fop/render/bitmap/PNGRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { log.info("rendering areas to PNG"); multiFileUtil = new MultiFileRenderingUtil(PNG_FILE_EXTENSION, getUserAgent().getOutputFile()); this.firstOutputStream = outputStream; }
// in src/java/org/apache/fop/render/bitmap/PNGRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); for (int i = 0; i < pageViewportList.size(); i++) { OutputStream os = getCurrentOutputStream(i); if (os == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.stoppingAfterFirstPageNoFilename(this); break; } try { // Do the rendering: get the image for this page PageViewport pv = (PageViewport)pageViewportList.get(i); RenderedImage image = (RenderedImage)getPageImage(pv); // Encode this image if (log.isDebugEnabled()) { log.debug("Encoding page " + (i + 1)); } writeImage(os, image); } finally { //Only close self-created OutputStreams if (os != firstOutputStream) { IOUtils.closeQuietly(os); } } } }
// in src/java/org/apache/fop/render/bitmap/PNGRenderer.java
private void writeImage(OutputStream os, RenderedImage image) throws IOException { ImageWriterParams params = new ImageWriterParams(); params.setResolution(Math.round(userAgent.getTargetResolution())); // Encode PNG image ImageWriter writer = ImageWriterRegistry.getInstance().getWriterFor(getMimeType()); if (writer == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noImageWriterFound(this, getMimeType()); } if (log.isDebugEnabled()) { log.debug("Writing image using " + writer.getClass().getName()); } writer.writeImage(image, os, params); }
// in src/java/org/apache/fop/render/bitmap/PNGRenderer.java
protected OutputStream getCurrentOutputStream(int pageNumber) throws IOException { if (pageNumber == 0) { return firstOutputStream; } else { return multiFileUtil.createOutputStream(pageNumber); } }
// in src/java/org/apache/fop/render/bitmap/MultiFileRenderingUtil.java
public OutputStream createOutputStream(int pageNumber) throws IOException { if (filePrefix == null) { return null; } else { File f = new File(outputDir, filePrefix + (pageNumber + 1) + "." + fileExtension); OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); return os; } }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { this.outputStream = outputStream; super.startRenderer(outputStream); }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); log.debug("Starting TIFF encoding ..."); // Creates lazy iterator over generated page images Iterator pageImagesItr = new LazyPageImagesIterator(getNumberOfPages(), log); // Creates writer ImageWriter writer = ImageWriterRegistry.getInstance().getWriterFor(getMimeType()); if (writer == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noImageWriterFound(this, getMimeType()); } if (writer.supportsMultiImageWriter()) { MultiImageWriter multiWriter = writer.createMultiImageWriter(outputStream); try { // Write all pages/images while (pageImagesItr.hasNext()) { RenderedImage img = (RenderedImage) pageImagesItr.next(); multiWriter.writeImage(img, writerParams); } } finally { multiWriter.close(); } } else { RenderedImage renderedImage = null; if (pageImagesItr.hasNext()) { renderedImage = (RenderedImage) pageImagesItr.next(); } writer.writeImage(renderedImage, outputStream, writerParams); if (pageImagesItr.hasNext()) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.stoppingAfterFirstPageNoFilename(this); } } // Cleaning outputStream.flush(); clearViewportList(); log.debug("TIFF encoding done."); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private AFPFont fontFromType(String type, String codepage, String encoding, ResourceAccessor accessor, Configuration afpFontCfg) throws ConfigurationException, IOException { if ("raster".equalsIgnoreCase(type)) { String name = afpFontCfg.getAttribute("name", "Unknown"); // Create a new font object RasterFont font = new RasterFont(name); Configuration[] rasters = afpFontCfg.getChildren("afp-raster-font"); if (rasters.length == 0) { eventProducer.fontConfigMissing(this, "<afp-raster-font...", afpFontCfg.getLocation()); return null; } for (int j = 0; j < rasters.length; j++) { Configuration rasterCfg = rasters[j]; String characterset = rasterCfg.getAttribute("characterset"); if (characterset == null) { eventProducer.fontConfigMissing(this, "characterset attribute", afpFontCfg.getLocation()); return null; } float size = rasterCfg.getAttributeAsFloat("size"); int sizeMpt = (int) (size * 1000); String base14 = rasterCfg.getAttribute("base14-font", null); if (base14 != null) { try { Class<? extends Typeface> clazz = Class.forName( "org.apache.fop.fonts.base14." + base14).asSubclass(Typeface.class); try { Typeface tf = clazz.newInstance(); font.addCharacterSet(sizeMpt, CharacterSetBuilder.getSingleByteInstance() .build(characterset, codepage, encoding, tf, eventProducer)); } catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); } } catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); } } else { font.addCharacterSet(sizeMpt, CharacterSetBuilder.getSingleByteInstance() .buildSBCS(characterset, codepage, encoding, accessor, eventProducer)); } } return font; } else if ("outline".equalsIgnoreCase(type)) { String characterset = afpFontCfg.getAttribute("characterset"); if (characterset == null) { eventProducer.fontConfigMissing(this, "characterset attribute", afpFontCfg.getLocation()); return null; } String name = afpFontCfg.getAttribute("name", characterset); CharacterSet characterSet = null; String base14 = afpFontCfg.getAttribute("base14-font", null); if (base14 != null) { try { Class<? extends Typeface> clazz = Class.forName("org.apache.fop.fonts.base14." + base14).asSubclass(Typeface.class); try { Typeface tf = clazz.newInstance(); characterSet = CharacterSetBuilder.getSingleByteInstance() .build(characterset, codepage, encoding, tf, eventProducer); } catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); } } catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); } } else { characterSet = CharacterSetBuilder.getSingleByteInstance().buildSBCS( characterset, codepage, encoding, accessor, eventProducer); } // Return new font object return new OutlineFont(name, characterSet); } else if ("CIDKeyed".equalsIgnoreCase(type)) { String characterset = afpFontCfg.getAttribute("characterset"); if (characterset == null) { eventProducer.fontConfigMissing(this, "characterset attribute", afpFontCfg.getLocation()); return null; } String name = afpFontCfg.getAttribute("name", characterset); CharacterSet characterSet = null; CharacterSetType charsetType = afpFontCfg.getAttributeAsBoolean("ebcdic-dbcs", false) ? CharacterSetType.DOUBLE_BYTE_LINE_DATA : CharacterSetType.DOUBLE_BYTE; characterSet = CharacterSetBuilder.getDoubleByteInstance().buildDBCS(characterset, codepage, encoding, charsetType, accessor, eventProducer); // Create a new font object DoubleByteFont font = new DoubleByteFont(name, characterSet); return font; } else { log.error("No or incorrect type attribute: " + type); } return null; }
// in src/java/org/apache/fop/render/afp/AFPSVGHandler.java
protected void renderSVGDocument(final RendererContext rendererContext, final Document doc) throws IOException { AFPRendererContext afpRendererContext = (AFPRendererContext)rendererContext; AFPInfo afpInfo = afpRendererContext.getInfo(); this.paintAsBitmap = afpInfo.paintAsBitmap(); FOUserAgent userAgent = rendererContext.getUserAgent(); // fallback paint as bitmap String uri = getDocumentURI(doc); if (paintAsBitmap) { try { super.renderSVGDocument(rendererContext, doc); } catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, uri); } return; } // Create a new AFPGraphics2D final boolean textAsShapes = afpInfo.strokeText(); AFPGraphics2D g2d = afpInfo.createGraphics2D(textAsShapes); AFPPaintingState paintingState = g2d.getPaintingState(); paintingState.setImageUri(uri); // Create an AFPBridgeContext BridgeContext bridgeContext = createBridgeContext(userAgent, g2d); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(doc); // Build the SVG DOM and provide the painter with it GraphicsNode root = buildGraphicsNode(userAgent, bridgeContext, clonedDoc); // Create Graphics2DImagePainter final RendererContextWrapper wrappedContext = RendererContext.wrapRendererContext(rendererContext); Dimension imageSize = getImageSize(wrappedContext); Graphics2DImagePainter painter = createGraphics2DImagePainter(bridgeContext, root, imageSize); // Create AFPObjectAreaInfo RendererContextWrapper rctx = RendererContext.wrapRendererContext(rendererContext); int x = rctx.getCurrentXPosition(); int y = rctx.getCurrentYPosition(); int width = afpInfo.getWidth(); int height = afpInfo.getHeight(); int resolution = afpInfo.getResolution(); paintingState.save(); // save AFPObjectAreaInfo objectAreaInfo = createObjectAreaInfo(paintingState, x, y, width, height, resolution); // Create AFPGraphicsObjectInfo AFPResourceInfo resourceInfo = afpInfo.getResourceInfo(); AFPGraphicsObjectInfo graphicsObjectInfo = createGraphicsObjectInfo( paintingState, painter, userAgent, resourceInfo, g2d); graphicsObjectInfo.setObjectAreaInfo(objectAreaInfo); // Create the GOCA GraphicsObject in the DataStream AFPResourceManager resourceManager = afpInfo.getResourceManager(); resourceManager.createObject(graphicsObjectInfo); paintingState.restore(); // resume }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void clip() throws IOException { //not supported by AFP }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void closePath() throws IOException { //used for clipping only, so not implemented }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void moveTo(int x, int y) throws IOException { //used for clipping only, so not implemented }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void lineTo(int x, int y) throws IOException { //used for clipping only, so not implemented }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void saveGraphicsState() throws IOException { //used for clipping only, so not implemented }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void restoreGraphicsState() throws IOException { //used for clipping only, so not implemented }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void drawBorderLine( // CSOK: ParameterNumber int x1, int y1, int x2, int y2, boolean horz, boolean startOrBefore, int style, Color color) throws IOException { BorderPaintingInfo borderPaintInfo = new BorderPaintingInfo( toPoints(x1), toPoints(y1), toPoints(x2), toPoints(y2), horz, style, color); delegate.paint(borderPaintInfo); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IOException { if (start.y != end.y) { //TODO Support arbitrary lines if necessary throw new UnsupportedOperationException( "Can only deal with horizontal lines right now"); } //Simply delegates to drawBorderLine() as AFP line painting is not very sophisticated. int halfWidth = width / 2; drawBorderLine(start.x, start.y - halfWidth, end.x, start.y + halfWidth, true, true, style.getEnumValue(), color); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void drawText( // CSOK: MethodLength int x, int y, final int letterSpacing, final int wordSpacing, final int[][] dp, final String text) throws IFException { final int fontSize = this.state.getFontSize(); getPaintingState().setFontSize(fontSize); FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() String fontKey = getFontInfo().getInternalFontKey(triplet); if (fontKey == null) { triplet = new FontTriplet("any", Font.STYLE_NORMAL, Font.WEIGHT_NORMAL); fontKey = getFontInfo().getInternalFontKey(triplet); } // register font as necessary Map<String, Typeface> fontMetricMap = documentHandler.getFontInfo().getFonts(); final AFPFont afpFont = (AFPFont)fontMetricMap.get(fontKey); final Font font = getFontInfo().getFontInstance(triplet, fontSize); AFPPageFonts pageFonts = getPaintingState().getPageFonts(); AFPFontAttributes fontAttributes = pageFonts.registerFont(fontKey, afpFont, fontSize); final int fontReference = fontAttributes.getFontReference(); final int[] coords = unitConv.mpts2units(new float[] {x, y} ); final CharacterSet charSet = afpFont.getCharacterSet(fontSize); if (afpFont.isEmbeddable()) { try { documentHandler.getResourceManager().embedFont(afpFont, charSet); } catch (IOException ioe) { throw new IFException("Error while embedding font resources", ioe); } } AbstractPageObject page = getDataStream().getCurrentPage(); PresentationTextObject pto = page.getPresentationTextObject(); try { pto.createControlSequences(new PtocaProducer() { public void produce(PtocaBuilder builder) throws IOException { Point p = getPaintingState().getPoint(coords[X], coords[Y]); builder.setTextOrientation(getPaintingState().getRotation()); builder.absoluteMoveBaseline(p.y); builder.absoluteMoveInline(p.x); builder.setExtendedTextColor(state.getTextColor()); builder.setCodedFont((byte)fontReference); int l = text.length(); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); StringBuffer sb = new StringBuffer(); if (dxl > 0 && dx[0] != 0) { int dxu = Math.round(unitConv.mpt2units(dx[0])); builder.relativeMoveInline(-dxu); } //Following are two variants for glyph placement. //SVI does not seem to be implemented in the same way everywhere, so //a fallback alternative is preserved here. final boolean usePTOCAWordSpacing = true; if (usePTOCAWordSpacing) { int interCharacterAdjustment = 0; if (letterSpacing != 0) { interCharacterAdjustment = Math.round(unitConv.mpt2units( letterSpacing)); } builder.setInterCharacterAdjustment(interCharacterAdjustment); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + letterSpacing)); int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement; if (wordSpacing != 0) { varSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + wordSpacing + letterSpacing)); } builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement); boolean fixedSpaceMode = false; for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( fixedSpaceCharacterIncrement); fixedSpaceMode = true; sb.append(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { if (fixedSpaceMode) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( varSpaceCharacterIncrement); fixedSpaceMode = false; } char ch; if (orgChar == CharUtilities.NBSPACE) { ch = ' '; //converted to normal space to allow word spacing } else { ch = orgChar; } sb.append(ch); } if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } else { for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { sb.append(CharUtilities.SPACE); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { sb.append(orgChar); } if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust += wordSpacing; } glyphAdjust += letterSpacing; if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } flushText(builder, sb, charSet); } private void flushText(PtocaBuilder builder, StringBuffer sb, final CharacterSet charSet) throws IOException { if (sb.length() > 0) { builder.addTransparentData(charSet.encodeChars(sb)); sb.setLength(0); } } }); } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void produce(PtocaBuilder builder) throws IOException { Point p = getPaintingState().getPoint(coords[X], coords[Y]); builder.setTextOrientation(getPaintingState().getRotation()); builder.absoluteMoveBaseline(p.y); builder.absoluteMoveInline(p.x); builder.setExtendedTextColor(state.getTextColor()); builder.setCodedFont((byte)fontReference); int l = text.length(); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); StringBuffer sb = new StringBuffer(); if (dxl > 0 && dx[0] != 0) { int dxu = Math.round(unitConv.mpt2units(dx[0])); builder.relativeMoveInline(-dxu); } //Following are two variants for glyph placement. //SVI does not seem to be implemented in the same way everywhere, so //a fallback alternative is preserved here. final boolean usePTOCAWordSpacing = true; if (usePTOCAWordSpacing) { int interCharacterAdjustment = 0; if (letterSpacing != 0) { interCharacterAdjustment = Math.round(unitConv.mpt2units( letterSpacing)); } builder.setInterCharacterAdjustment(interCharacterAdjustment); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + letterSpacing)); int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement; if (wordSpacing != 0) { varSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + wordSpacing + letterSpacing)); } builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement); boolean fixedSpaceMode = false; for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( fixedSpaceCharacterIncrement); fixedSpaceMode = true; sb.append(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { if (fixedSpaceMode) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( varSpaceCharacterIncrement); fixedSpaceMode = false; } char ch; if (orgChar == CharUtilities.NBSPACE) { ch = ' '; //converted to normal space to allow word spacing } else { ch = orgChar; } sb.append(ch); } if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } else { for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { sb.append(CharUtilities.SPACE); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { sb.append(orgChar); } if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust += wordSpacing; } glyphAdjust += letterSpacing; if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } flushText(builder, sb, charSet); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
private void flushText(PtocaBuilder builder, StringBuffer sb, final CharacterSet charSet) throws IOException { if (sb.length() > 0) { builder.addTransparentData(charSet.encodeChars(sb)); sb.setLength(0); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
protected void saveGraphicsState() throws IOException { getPaintingState().save(); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
protected void restoreGraphicsState() throws IOException { getPaintingState().restore(); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { AFPRenderingContext afpContext = (AFPRenderingContext)context; AFPImageObjectInfo imageObjectInfo = (AFPImageObjectInfo)createDataObjectInfo(); AFPPaintingState paintingState = afpContext.getPaintingState(); // set resource information setResourceInformation(imageObjectInfo, image.getInfo().getOriginalURI(), afpContext.getForeignAttributes()); setDefaultResourceLevel(imageObjectInfo, afpContext.getResourceManager()); // Positioning imageObjectInfo.setObjectAreaInfo(createObjectAreaInfo(paintingState, pos)); Dimension targetSize = pos.getSize(); // Image content ImageRendered imageRend = (ImageRendered)image; RenderedImageEncoder encoder = new RenderedImageEncoder(imageRend, targetSize); encoder.prepareEncoding(imageObjectInfo, paintingState); boolean included = afpContext.getResourceManager().tryIncludeObject(imageObjectInfo); if (!included) { long start = System.currentTimeMillis(); //encode only if the same image has not been encoded, yet encoder.encodeImage(imageObjectInfo, paintingState); if (log.isDebugEnabled()) { long duration = System.currentTimeMillis() - start; log.debug("Image encoding took " + duration + "ms."); } // Create image afpContext.getResourceManager().createObject(imageObjectInfo); } }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
private AFPDataObjectInfo encodeImage (AFPImageObjectInfo imageObjectInfo, AFPPaintingState paintingState) throws IOException { RenderedImage renderedImage = imageRendered.getRenderedImage(); FunctionSet functionSet = useFS10 ? FunctionSet.FS10 : FunctionSet.FS11; if (usePageSegments) { assert resampledDim != null; //Resize, optionally resample and convert image imageObjectInfo.setCreatePageSegment(true); float ditheringQuality = paintingState.getDitheringQuality(); if (this.resample) { if (log.isDebugEnabled()) { log.debug("Resample from " + intrinsicSize.getDimensionPx() + " to " + resampledDim); } renderedImage = BitmapImageUtil.convertToMonochrome(renderedImage, resampledDim, ditheringQuality); } else if (ditheringQuality >= 0.5f) { renderedImage = BitmapImageUtil.convertToMonochrome(renderedImage, intrinsicSize.getDimensionPx(), ditheringQuality); } } //TODO To reduce AFP file size, investigate using a compression scheme. //Currently, all image data is uncompressed. ColorModel cm = renderedImage.getColorModel(); if (log.isTraceEnabled()) { log.trace("ColorModel: " + cm); } int pixelSize = cm.getPixelSize(); if (cm.hasAlpha()) { pixelSize -= 8; } byte[] imageData = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); boolean allowDirectEncoding = true; if (allowDirectEncoding && (pixelSize <= maxPixelSize)) { //Attempt to encode without resampling the image ImageEncodingHelper helper = new ImageEncodingHelper(renderedImage, pixelSize == 32); ColorModel encodedColorModel = helper.getEncodedColorModel(); boolean directEncode = true; if (helper.getEncodedColorModel().getPixelSize() > maxPixelSize) { directEncode = false; //pixel size needs to be reduced } if (BitmapImageUtil.getColorIndexSize(renderedImage) > 2) { directEncode = false; //Lookup tables are not implemented, yet } if (useFS10 && BitmapImageUtil.isMonochromeImage(renderedImage) && BitmapImageUtil.isZeroBlack(renderedImage)) { directEncode = false; //need a special method to invert the bit-stream since setting the //subtractive mode in AFP alone doesn't seem to do the trick. if (encodeInvertedBilevel(helper, imageObjectInfo, baos)) { imageData = baos.toByteArray(); } } if (directEncode) { log.debug("Encoding image directly..."); imageObjectInfo.setBitsPerPixel(encodedColorModel.getPixelSize()); if (pixelSize == 32) { functionSet = FunctionSet.FS45; //IOCA FS45 required for CMYK } //Lossy or loss-less? if (!paintingState.canEmbedJpeg() && paintingState.getBitmapEncodingQuality() < 1.0f) { try { if (log.isDebugEnabled()) { log.debug("Encoding using baseline DCT (JPEG, q=" + paintingState.getBitmapEncodingQuality() + ")..."); } encodeToBaselineDCT(renderedImage, paintingState.getBitmapEncodingQuality(), paintingState.getResolution(), baos); imageObjectInfo.setCompression(ImageContent.COMPID_JPEG); } catch (IOException ioe) { //Some JPEG codecs cannot encode CMYK helper.encode(baos); } } else { helper.encode(baos); } imageData = baos.toByteArray(); } } if (imageData == null) { log.debug("Encoding image via RGB..."); imageData = encodeViaRGB(renderedImage, imageObjectInfo, paintingState, baos); } // Should image be FS45? if (paintingState.getFS45()) { functionSet = FunctionSet.FS45; } //Wrapping 300+ resolution FS11 IOCA in a page segment is apparently necessary(?) imageObjectInfo.setCreatePageSegment( (functionSet.equals(FunctionSet.FS11) || functionSet.equals(FunctionSet.FS45)) && paintingState.getWrapPSeg() ); imageObjectInfo.setMimeType(functionSet.getMimeType()); imageObjectInfo.setData(imageData); return imageObjectInfo; }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
private byte[] encodeViaRGB(RenderedImage renderedImage, AFPImageObjectInfo imageObjectInfo, AFPPaintingState paintingState, ByteArrayOutputStream baos) throws IOException { byte[] imageData; //Convert image to 24bit RGB ImageEncodingHelper.encodeRenderedImageAsRGB(renderedImage, baos); imageData = baos.toByteArray(); imageObjectInfo.setBitsPerPixel(24); boolean colorImages = paintingState.isColorImages(); imageObjectInfo.setColor(colorImages); // convert to grayscale if (!colorImages) { log.debug("Converting RGB image to grayscale..."); baos.reset(); int bitsPerPixel = paintingState.getBitsPerPixel(); imageObjectInfo.setBitsPerPixel(bitsPerPixel); //TODO this should be done off the RenderedImage to avoid buffering the //intermediate 24bit image ImageEncodingHelper.encodeRGBAsGrayScale( imageData, renderedImage.getWidth(), renderedImage.getHeight(), bitsPerPixel, baos); imageData = baos.toByteArray(); if (bitsPerPixel == 1) { imageObjectInfo.setSubtractive(true); } } return imageData; }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
private boolean encodeInvertedBilevel(ImageEncodingHelper helper, AFPImageObjectInfo imageObjectInfo, OutputStream out) throws IOException { RenderedImage renderedImage = helper.getImage(); if (!BitmapImageUtil.isMonochromeImage(renderedImage)) { throw new IllegalStateException("This method only supports binary images!"); } int tiles = renderedImage.getNumXTiles() * renderedImage.getNumYTiles(); if (tiles > 1) { return false; } SampleModel sampleModel = renderedImage.getSampleModel(); SampleModel expectedSampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, renderedImage.getWidth(), renderedImage.getHeight(), 1); if (!expectedSampleModel.equals(sampleModel)) { return false; //Pixels are not packed } imageObjectInfo.setBitsPerPixel(1); Raster raster = renderedImage.getTile(0, 0); DataBuffer buffer = raster.getDataBuffer(); if (buffer instanceof DataBufferByte) { DataBufferByte byteBuffer = (DataBufferByte)buffer; log.debug("Encoding image as inverted bi-level..."); byte[] rawData = byteBuffer.getData(); int remaining = rawData.length; int pos = 0; byte[] data = new byte[4096]; while (remaining > 0) { int size = Math.min(remaining, data.length); for (int i = 0; i < size; i++) { data[i] = (byte)~rawData[pos]; //invert bits pos++; } out.write(data, 0, size); remaining -= size; } return true; } return false; }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
private void encodeToBaselineDCT(RenderedImage image, float quality, int resolution, OutputStream out) throws IOException { ImageWriter writer = ImageWriterRegistry.getInstance().getWriterFor("image/jpeg"); ImageWriterParams params = new ImageWriterParams(); params.setJPEGQuality(quality, true); params.setResolution(resolution); writer.writeImage(image, out, params); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRawCCITTFax.java
Override public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { log.debug("Embedding undecoded CCITT data as data container..."); super.handleImage(context, image, pos); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerGraphics2D.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { AFPRenderingContext afpContext = (AFPRenderingContext)context; AFPGraphicsObjectInfo graphicsObjectInfo = (AFPGraphicsObjectInfo)createDataObjectInfo(); // set resource information setResourceInformation(graphicsObjectInfo, image.getInfo().getOriginalURI(), afpContext.getForeignAttributes()); // Positioning graphicsObjectInfo.setObjectAreaInfo( createObjectAreaInfo(afpContext.getPaintingState(), pos)); setDefaultResourceLevel(graphicsObjectInfo, afpContext.getResourceManager()); AFPPaintingState paintingState = afpContext.getPaintingState(); paintingState.save(); // save AffineTransform placement = new AffineTransform(); placement.translate(pos.x, pos.y); paintingState.concatenate(placement); // Image content ImageGraphics2D imageG2D = (ImageGraphics2D)image; final boolean textAsShapes = paintingState.isStrokeGOCAText(); AFPGraphics2D g2d = new AFPGraphics2D( textAsShapes, afpContext.getPaintingState(), afpContext.getResourceManager(), graphicsObjectInfo.getResourceInfo(), (textAsShapes ? null : afpContext.getFontInfo())); g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); graphicsObjectInfo.setGraphics2D(g2d); graphicsObjectInfo.setPainter(imageG2D.getGraphics2DImagePainter()); // Create image afpContext.getResourceManager().createObject(graphicsObjectInfo); paintingState.restore(); // resume }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRawStream.java
Override public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { if (log.isDebugEnabled()) { log.debug("Embedding undecoded image data (" + image.getInfo().getMimeType() + ") as data container..."); } super.handleImage(context, image, pos); }
// in src/java/org/apache/fop/render/afp/AbstractAFPImageHandlerRawStream.java
private void updateDataObjectInfo(AFPDataObjectInfo dataObjectInfo, ImageRawStream rawStream, AFPResourceManager resourceManager) throws IOException { dataObjectInfo.setMimeType(rawStream.getFlavor().getMimeType()); AFPResourceInfo resourceInfo = dataObjectInfo.getResourceInfo(); if (!resourceInfo.levelChanged()) { resourceInfo.setLevel(resourceManager.getResourceLevelDefaults() .getDefaultResourceLevel(ResourceObject.TYPE_IMAGE)); } InputStream inputStream = rawStream.createInputStream(); try { dataObjectInfo.setData(IOUtils.toByteArray(inputStream)); } finally { IOUtils.closeQuietly(inputStream); } int dataHeight = rawStream.getSize().getHeightPx(); dataObjectInfo.setDataHeight(dataHeight); int dataWidth = rawStream.getSize().getWidthPx(); dataObjectInfo.setDataWidth(dataWidth); ImageSize imageSize = rawStream.getSize(); dataObjectInfo.setDataHeightRes((int) (imageSize.getDpiHorizontal() * 10)); dataObjectInfo.setDataWidthRes((int) (imageSize.getDpiVertical() * 10)); }
// in src/java/org/apache/fop/render/afp/AbstractAFPImageHandlerRawStream.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { AFPRenderingContext afpContext = (AFPRenderingContext)context; AFPDataObjectInfo dataObjectInfo = createDataObjectInfo(); // set resource information setResourceInformation(dataObjectInfo, image.getInfo().getOriginalURI(), afpContext.getForeignAttributes()); // Positioning dataObjectInfo.setObjectAreaInfo(createObjectAreaInfo(afpContext.getPaintingState(), pos)); // set object area info //AFPObjectAreaInfo objectAreaInfo = dataObjectInfo.getObjectAreaInfo(); AFPPaintingState paintingState = afpContext.getPaintingState(); int resolution = paintingState.getResolution(); AFPObjectAreaInfo objectAreaInfo = dataObjectInfo.getObjectAreaInfo(); objectAreaInfo.setResolution(resolution); // Image content ImageRawStream imageStream = (ImageRawStream)image; updateDataObjectInfo(dataObjectInfo, imageStream, afpContext.getResourceManager()); setAdditionalParameters(dataObjectInfo, imageStream); // Create image afpContext.getResourceManager().createObject(dataObjectInfo); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRawJPEG.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { AFPRenderingContext afpContext = (AFPRenderingContext)context; AFPImageObjectInfo imageObjectInfo = (AFPImageObjectInfo)createDataObjectInfo(); AFPPaintingState paintingState = afpContext.getPaintingState(); // set resource information setResourceInformation(imageObjectInfo, image.getInfo().getOriginalURI(), afpContext.getForeignAttributes()); setDefaultResourceLevel(imageObjectInfo, afpContext.getResourceManager()); // Positioning imageObjectInfo.setObjectAreaInfo(createObjectAreaInfo(paintingState, pos)); updateIntrinsicSize(imageObjectInfo, paintingState, image.getSize()); // Image content ImageRawJPEG jpeg = (ImageRawJPEG)image; imageObjectInfo.setCompression(ImageContent.COMPID_JPEG); ColorSpace cs = jpeg.getColorSpace(); switch (cs.getType()) { case ColorSpace.TYPE_GRAY: imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS11); imageObjectInfo.setColor(false); imageObjectInfo.setBitsPerPixel(8); break; case ColorSpace.TYPE_RGB: imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS11); imageObjectInfo.setColor(true); imageObjectInfo.setBitsPerPixel(24); break; case ColorSpace.TYPE_CMYK: imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS45); imageObjectInfo.setColor(true); imageObjectInfo.setBitsPerPixel(32); break; default: throw new IllegalStateException( "Color space of JPEG image not supported: " + cs); } boolean included = afpContext.getResourceManager().tryIncludeObject(imageObjectInfo); if (!included) { log.debug("Embedding undecoded JPEG as IOCA image..."); InputStream inputStream = jpeg.createInputStream(); try { imageObjectInfo.setData(IOUtils.toByteArray(inputStream)); } finally { IOUtils.closeQuietly(inputStream); } // Create image afpContext.getResourceManager().createObject(imageObjectInfo); } }
// in src/java/org/apache/fop/render/afp/AFPGraphics2DAdapter.java
public void paintImage(Graphics2DImagePainter painter, RendererContext rendererContext, int x, int y, int width, int height) throws IOException { AFPRendererContext afpRendererContext = (AFPRendererContext)rendererContext; AFPInfo afpInfo = afpRendererContext.getInfo(); final boolean textAsShapes = false; AFPGraphics2D g2d = afpInfo.createGraphics2D(textAsShapes); paintingState.save(); //Fallback solution: Paint to a BufferedImage if (afpInfo.paintAsBitmap()) { // paint image RendererContextWrapper rendererContextWrapper = RendererContext.wrapRendererContext(rendererContext); float targetResolution = rendererContext.getUserAgent().getTargetResolution(); int resolution = Math.round(targetResolution); boolean colorImages = afpInfo.isColorSupported(); BufferedImage bufferedImage = paintToBufferedImage( painter, rendererContextWrapper, resolution, !colorImages, false); // draw image AffineTransform at = paintingState.getData().getTransform(); at.translate(x, y); g2d.drawImage(bufferedImage, at, null); } else { AFPGraphicsObjectInfo graphicsObjectInfo = new AFPGraphicsObjectInfo(); graphicsObjectInfo.setPainter(painter); graphicsObjectInfo.setGraphics2D(g2d); // get the 'width' and 'height' attributes of the SVG document Dimension imageSize = painter.getImageSize(); float imw = (float)imageSize.getWidth() / 1000f; float imh = (float)imageSize.getHeight() / 1000f; Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, imw, imh); graphicsObjectInfo.setArea(area); AFPResourceManager resourceManager = afpInfo.getResourceManager(); resourceManager.createObject(graphicsObjectInfo); } paintingState.restore(); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { AFPRenderingContext afpContext = (AFPRenderingContext)context; ImageXMLDOM imageSVG = (ImageXMLDOM)image; FOUserAgent userAgent = afpContext.getUserAgent(); AFPGraphicsObjectInfo graphicsObjectInfo = (AFPGraphicsObjectInfo)createDataObjectInfo(); AFPResourceInfo resourceInfo = graphicsObjectInfo.getResourceInfo(); setDefaultToInlineResourceLevel(graphicsObjectInfo); // Create a new AFPGraphics2D AFPPaintingState paintingState = afpContext.getPaintingState(); final boolean textAsShapes = paintingState.isStrokeGOCAText(); AFPGraphics2D g2d = new AFPGraphics2D( textAsShapes, afpContext.getPaintingState(), afpContext.getResourceManager(), resourceInfo, (textAsShapes ? null : afpContext.getFontInfo())); g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); paintingState.setImageUri(image.getInfo().getOriginalURI()); // Create an AFPBridgeContext BridgeContext bridgeContext = AFPSVGHandler.createBridgeContext(userAgent, g2d); // Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) // to it. Document clonedDoc = BatikUtil.cloneSVGDocument(imageSVG.getDocument()); // Build the SVG DOM and provide the painter with it GraphicsNode root; try { GVTBuilder builder = new GVTBuilder(); root = builder.build(bridgeContext, clonedDoc); } catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; } // Image positioning AFPObjectAreaInfo objectAreaInfo = AFPImageHandler.createObjectAreaInfo(paintingState, pos); graphicsObjectInfo.setObjectAreaInfo(objectAreaInfo); paintingState.save(); // save AffineTransform placement = new AffineTransform(); placement.translate(pos.x, pos.y); paintingState.concatenate(placement); //Set up painter and target graphicsObjectInfo.setGraphics2D(g2d); // Create Graphics2DImagePainter Dimension imageSize = image.getSize().getDimensionMpt(); Graphics2DImagePainter painter = new Graphics2DImagePainterImpl( root, bridgeContext, imageSize); graphicsObjectInfo.setPainter(painter); // Create the GOCA GraphicsObject in the DataStream AFPResourceManager resourceManager = afpContext.getResourceManager(); resourceManager.createObject(graphicsObjectInfo); paintingState.restore(); // resume }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public void renderPage(PageViewport pageViewport) throws IOException, FOPException { super.renderPage(pageViewport); if (statusListener != null) { statusListener.notifyPageRendered(); } }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); if (statusListener != null) { statusListener.notifyRendererStopped(); // Refreshes view of page } }
// in src/java/org/apache/fop/render/AbstractGraphics2DAdapter.java
public void paintImage(Graphics2DImagePainter painter, RendererContext context, int x, int y, int width, int height) throws IOException { //TODO Deprecated method to be removed once Barcode4J 2.1 is released. paintImage((org.apache.xmlgraphics.java2d.Graphics2DImagePainter)painter, context, x, y, width, height); }
// in src/java/org/apache/fop/render/ps/PSRenderingUtil.java
public static void writeSetupCodeList(PSGenerator gen, List setupCodeList, String type) throws IOException { if (setupCodeList != null) { Iterator i = setupCodeList.iterator(); while (i.hasNext()) { PSSetupCode setupCode = (PSSetupCode)i.next(); gen.commentln("%FOPBegin" + type + ": (" + (setupCode.getName() != null ? setupCode.getName() : "") + ")"); LineNumberReader reader = new LineNumberReader( new java.io.StringReader(setupCode.getContent())); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { gen.writeln(line.trim()); } } gen.commentln("%FOPEnd" + type); i.remove(); } } }
// in src/java/org/apache/fop/render/ps/PSRenderingUtil.java
public static void writeEnclosedExtensionAttachments(PSGenerator gen, Collection attachmentCollection) throws IOException { Iterator iter = attachmentCollection.iterator(); while (iter.hasNext()) { PSExtensionAttachment attachment = (PSExtensionAttachment)iter.next(); if (attachment != null) { writeEnclosedExtensionAttachment(gen, attachment); } iter.remove(); } }
// in src/java/org/apache/fop/render/ps/PSRenderingUtil.java
public static void writeEnclosedExtensionAttachment(PSGenerator gen, PSExtensionAttachment attachment) throws IOException { if (attachment instanceof PSCommentBefore) { gen.commentln("%" + attachment.getContent()); } else if (attachment instanceof PSCommentAfter) { gen.commentln("%" + attachment.getContent()); } else { String info = ""; if (attachment instanceof PSSetupCode) { PSSetupCode setupCodeAttach = (PSSetupCode)attachment; String name = setupCodeAttach.getName(); if (name != null) { info += ": (" + name + ")"; } } String type = attachment.getType(); gen.commentln("%FOPBegin" + type + info); LineNumberReader reader = new LineNumberReader( new java.io.StringReader(attachment.getContent())); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { gen.writeln(line); } } gen.commentln("%FOPEnd" + type); } }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
public static Map writeFontDict(PSGenerator gen, FontInfo fontInfo) throws IOException { return writeFontDict(gen, fontInfo, fontInfo.getFonts(), true); }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
public static Map writeFontDict(PSGenerator gen, FontInfo fontInfo, Map<String, Typeface> fonts) throws IOException { return writeFontDict(gen, fontInfo, fonts, false); }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
private static Map writeFontDict(PSGenerator gen, FontInfo fontInfo, Map<String, Typeface> fonts, boolean encodeAllCharacters) throws IOException { gen.commentln("%FOPBeginFontDict"); Map fontResources = new java.util.HashMap(); for (String key : fonts.keySet()) { Typeface tf = getTypeFace(fontInfo, fonts, key); PSResource fontRes = new PSResource(PSResource.TYPE_FONT, tf.getFontName()); fontResources.put(key, fontRes); embedFont(gen, tf, fontRes); if (tf instanceof SingleByteFont) { SingleByteFont sbf = (SingleByteFont)tf; if (encodeAllCharacters) { sbf.encodeAllUnencodedCharacters(); } for (int i = 0, c = sbf.getAdditionalEncodingCount(); i < c; i++) { SingleByteEncoding encoding = sbf.getAdditionalEncoding(i); defineEncoding(gen, encoding); String postFix = "_" + (i + 1); PSResource derivedFontRes = defineDerivedFont(gen, tf.getFontName(), tf.getFontName() + postFix, encoding.getName()); fontResources.put(key + postFix, derivedFontRes); } } } gen.commentln("%FOPEndFontDict"); reencodeFonts(gen, fonts); return fontResources; }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
private static void reencodeFonts(PSGenerator gen, Map<String, Typeface> fonts) throws IOException { ResourceTracker tracker = gen.getResourceTracker(); if (!tracker.isResourceSupplied(WINANSI_ENCODING_RESOURCE)) { //Only out Base 14 fonts still use that defineWinAnsiEncoding(gen); } gen.commentln("%FOPBeginFontReencode"); //Rewrite font encodings for (String key : fonts.keySet()) { Typeface tf = fonts.get(key); if (tf instanceof LazyFont) { tf = ((LazyFont)tf).getRealFont(); if (tf == null) { continue; } } if (null == tf.getEncodingName()) { //ignore (ZapfDingbats and Symbol used to run through here, kept for safety reasons) } else if ("SymbolEncoding".equals(tf.getEncodingName())) { //ignore (no encoding redefinition) } else if ("ZapfDingbatsEncoding".equals(tf.getEncodingName())) { //ignore (no encoding redefinition) } else { if (tf instanceof Base14Font) { //Our Base 14 fonts don't use the default encoding redefineFontEncoding(gen, tf.getFontName(), tf.getEncodingName()); } else if (tf instanceof SingleByteFont) { SingleByteFont sbf = (SingleByteFont)tf; if (!sbf.isUsingNativeEncoding()) { //Font has been configured to use an encoding other than the default one redefineFontEncoding(gen, tf.getFontName(), tf.getEncodingName()); } } } } gen.commentln("%FOPEndFontReencode"); }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
public static void embedFont(PSGenerator gen, Typeface tf, PSResource fontRes) throws IOException { boolean embeddedFont = false; if (FontType.TYPE1 == tf.getFontType()) { if (tf instanceof CustomFont) { CustomFont cf = (CustomFont)tf; if (isEmbeddable(cf)) { InputStream in = getInputStreamOnFont(gen, cf); if (in != null) { gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, fontRes); embedType1Font(gen, in); gen.writeDSCComment(DSCConstants.END_RESOURCE); gen.getResourceTracker().registerSuppliedResource(fontRes); embeddedFont = true; } else { gen.commentln("%WARNING: Could not embed font: " + cf.getFontName()); log.warn("Font " + cf.getFontName() + " is marked as supplied in the" + " PostScript file but could not be embedded!"); } } } } if (!embeddedFont) { gen.writeDSCComment(DSCConstants.INCLUDE_RESOURCE, fontRes); } }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
private static InputStream getInputStreamOnFont(PSGenerator gen, CustomFont font) throws IOException { if (isEmbeddable(font)) { Source source = font.getEmbedFileSource(); if (source == null && font.getEmbedResourceName() != null) { source = new StreamSource(PSFontUtils.class .getResourceAsStream(font.getEmbedResourceName())); } if (source == null) { return null; } InputStream in = null; if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null && source.getSystemId() != null) { try { in = new java.net.URL(source.getSystemId()).openStream(); } catch (MalformedURLException e) { new FileNotFoundException( "File not found. URL could not be resolved: " + e.getMessage()); } } if (in == null) { return null; } //Make sure the InputStream is decorated with a BufferedInputStream if (!(in instanceof java.io.BufferedInputStream)) { in = new java.io.BufferedInputStream(in); } return in; } else { return null; } }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
public static PSResource defineEncoding(PSGenerator gen, SingleByteEncoding encoding) throws IOException { PSResource res = new PSResource(PSResource.TYPE_ENCODING, encoding.getName()); gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, res); gen.writeln("/" + encoding.getName() + " ["); String[] charNames = encoding.getCharNameMap(); for (int i = 0; i < 256; i++) { if (i > 0) { if ((i % 5) == 0) { gen.newLine(); } else { gen.write(" "); } } String glyphname = null; if (i < charNames.length) { glyphname = charNames[i]; } if (glyphname == null || "".equals(glyphname)) { glyphname = Glyphs.NOTDEF; } gen.write("/"); gen.write(glyphname); } gen.newLine(); gen.writeln("] def"); gen.writeDSCComment(DSCConstants.END_RESOURCE); gen.getResourceTracker().registerSuppliedResource(res); return res; }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
public static PSResource defineDerivedFont (PSGenerator gen, String baseFontName, String fontName, String encoding) throws IOException { PSResource res = new PSResource(PSResource.TYPE_FONT, fontName); gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, res); gen.commentln("%XGCDependencies: font " + baseFontName); gen.commentln("%XGC+ encoding " + encoding); gen.writeln("/" + baseFontName + " findfont"); gen.writeln("dup length dict begin"); gen.writeln(" {1 index /FID ne {def} {pop pop} ifelse} forall"); gen.writeln(" /Encoding " + encoding + " def"); gen.writeln(" currentdict"); gen.writeln("end"); gen.writeln("/" + fontName + " exch definefont pop"); gen.writeDSCComment(DSCConstants.END_RESOURCE); gen.getResourceTracker().registerSuppliedResource(res); return res; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerRawJPEG.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRawJPEG jpeg = (ImageRawJPEG)image; float x = (float)pos.getX() / 1000f; float y = (float)pos.getY() / 1000f; float w = (float)pos.getWidth() / 1000f; float h = (float)pos.getHeight() / 1000f; Rectangle2D targetRect = new Rectangle2D.Float( x, y, w, h); ImageInfo info = image.getInfo(); ImageEncoder encoder = new ImageEncoderJPEG(jpeg); PSImageUtils.writeImage(encoder, info.getSize().getDimensionPx(), info.getOriginalURI(), targetRect, jpeg.getColorSpace(), 8, jpeg.isInverted(), gen); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerRawJPEG.java
public void generateForm(RenderingContext context, Image image, PSImageFormResource form) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRawJPEG jpeg = (ImageRawJPEG)image; ImageInfo info = image.getInfo(); String imageDescription = info.getMimeType() + " " + info.getOriginalURI(); ImageEncoder encoder = new ImageEncoderJPEG(jpeg); FormGenerator formGen = new ImageFormGenerator( form.getName(), imageDescription, info.getSize().getDimensionPt(), info.getSize().getDimensionPx(), encoder, jpeg.getColorSpace(), jpeg.isInverted()); formGen.generate(gen); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
public void process(InputStream in, OutputStream out, int pageCount, Rectangle2D documentBoundingBox) throws DSCException, IOException { DSCParser parser = new DSCParser(in); PSGenerator gen = new PSGenerator(out); parser.addListener(new DefaultNestedDocumentHandler(gen)); parser.addListener(new IncludeResourceListener(gen)); //Skip DSC header DSCHeaderComment header = DSCTools.checkAndSkipDSC30Header(parser); header.generate(gen); parser.setFilter(new DSCFilter() { private final Set filtered = new java.util.HashSet(); { //We rewrite those as part of the processing filtered.add(DSCConstants.PAGES); filtered.add(DSCConstants.BBOX); filtered.add(DSCConstants.HIRES_BBOX); filtered.add(DSCConstants.DOCUMENT_NEEDED_RESOURCES); filtered.add(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES); } public boolean accept(DSCEvent event) { if (event.isDSCComment()) { //Filter %%Pages which we add manually from a parameter return !(filtered.contains(event.asDSCComment().getName())); } else { return true; } } }); //Get PostScript language level (may be missing) while (true) { DSCEvent event = parser.nextEvent(); if (event == null) { reportInvalidDSC(); } if (DSCTools.headerCommentsEndHere(event)) { //Set number of pages DSCCommentPages pages = new DSCCommentPages(pageCount); pages.generate(gen); new DSCCommentBoundingBox(documentBoundingBox).generate(gen); new DSCCommentHiResBoundingBox(documentBoundingBox).generate(gen); PSFontUtils.determineSuppliedFonts(resTracker, fontInfo, fontInfo.getUsedFonts()); registerSuppliedForms(resTracker, globalFormResources); //Supplied Resources DSCCommentDocumentSuppliedResources supplied = new DSCCommentDocumentSuppliedResources( resTracker.getDocumentSuppliedResources()); supplied.generate(gen); //Needed Resources DSCCommentDocumentNeededResources needed = new DSCCommentDocumentNeededResources( resTracker.getDocumentNeededResources()); needed.generate(gen); //Write original comment that ends the header comments event.generate(gen); break; } if (event.isDSCComment()) { DSCComment comment = event.asDSCComment(); if (DSCConstants.LANGUAGE_LEVEL.equals(comment.getName())) { DSCCommentLanguageLevel level = (DSCCommentLanguageLevel)comment; gen.setPSLevel(level.getLanguageLevel()); } } event.generate(gen); } //Skip to the FOPFontSetup PostScriptComment fontSetupPlaceholder = parser.nextPSComment("FOPFontSetup", gen); if (fontSetupPlaceholder == null) { throw new DSCException("Didn't find %FOPFontSetup comment in stream"); } PSFontUtils.writeFontDict(gen, fontInfo, fontInfo.getUsedFonts()); generateForms(globalFormResources, gen); //Skip the prolog and to the first page DSCComment pageOrTrailer = parser.nextDSCComment(DSCConstants.PAGE, gen); if (pageOrTrailer == null) { throw new DSCException("Page expected, but none found"); } //Process individual pages (and skip as necessary) while (true) { DSCCommentPage page = (DSCCommentPage)pageOrTrailer; page.generate(gen); pageOrTrailer = DSCTools.nextPageOrTrailer(parser, gen); if (pageOrTrailer == null) { reportInvalidDSC(); } else if (!DSCConstants.PAGE.equals(pageOrTrailer.getName())) { pageOrTrailer.generate(gen); break; } } //Write the rest while (parser.hasNext()) { DSCEvent event = parser.nextEvent(); event.generate(gen); } gen.flush(); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private static void registerSuppliedForms(ResourceTracker resTracker, Map formResources) throws IOException { if (formResources == null) { return; } Iterator iter = formResources.values().iterator(); while (iter.hasNext()) { PSImageFormResource form = (PSImageFormResource)iter.next(); resTracker.registerSuppliedResource(form); } }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private void generateForms(Map formResources, PSGenerator gen) throws IOException { if (formResources == null) { return; } Iterator iter = formResources.values().iterator(); while (iter.hasNext()) { PSImageFormResource form = (PSImageFormResource)iter.next(); generateFormForImage(gen, form); } }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private void generateFormForImage(PSGenerator gen, PSImageFormResource form) throws IOException { final String uri = form.getImageURI(); ImageManager manager = userAgent.getFactory().getImageManager(); ImageInfo info = null; try { ImageSessionContext sessionContext = userAgent.getImageSessionContext(); info = manager.getImageInfo(uri, sessionContext); //Create a rendering context for form creation PSRenderingContext formContext = new PSRenderingContext( userAgent, gen, fontInfo, true); ImageFlavor[] flavors; ImageHandlerRegistry imageHandlerRegistry = userAgent.getFactory().getImageHandlerRegistry(); flavors = imageHandlerRegistry.getSupportedFlavors(formContext); Map hints = ImageUtil.getDefaultHints(sessionContext); org.apache.xmlgraphics.image.loader.Image img = manager.getImage( info, flavors, hints, sessionContext); ImageHandler basicHandler = imageHandlerRegistry.getHandler(formContext, img); if (basicHandler == null) { throw new UnsupportedOperationException( "No ImageHandler available for image: " + img.getInfo() + " (" + img.getClass().getName() + ")"); } if (!(basicHandler instanceof PSImageHandler)) { throw new IllegalStateException( "ImageHandler implementation doesn't behave properly." + " It should have returned false in isCompatible(). Class: " + basicHandler.getClass().getName()); } PSImageHandler handler = (PSImageHandler)basicHandler; if (log.isTraceEnabled()) { log.trace("Using ImageHandler: " + handler.getClass().getName()); } handler.generateForm(formContext, img, form); } catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.imageError(resTracker, (info != null ? info.toString() : uri), ie, null); } }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private static FormGenerator createMissingForm(String formName, final Dimension2D dimensions) { FormGenerator formGen = new FormGenerator(formName, null, dimensions) { protected void generatePaintProc(PSGenerator gen) throws IOException { gen.writeln("0 setgray"); gen.writeln("0 setlinewidth"); String w = gen.formatDouble(dimensions.getWidth()); String h = gen.formatDouble(dimensions.getHeight()); gen.writeln(w + " " + h + " scale"); gen.writeln("0 0 1 1 rectstroke"); gen.writeln("newpath"); gen.writeln("0 0 moveto"); gen.writeln("1 1 lineto"); gen.writeln("stroke"); gen.writeln("newpath"); gen.writeln("0 1 moveto"); gen.writeln("1 0 lineto"); gen.writeln("stroke"); } }; return formGen; }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
protected void generatePaintProc(PSGenerator gen) throws IOException { gen.writeln("0 setgray"); gen.writeln("0 setlinewidth"); String w = gen.formatDouble(dimensions.getWidth()); String h = gen.formatDouble(dimensions.getHeight()); gen.writeln(w + " " + h + " scale"); gen.writeln("0 0 1 1 rectstroke"); gen.writeln("newpath"); gen.writeln("0 0 moveto"); gen.writeln("1 1 lineto"); gen.writeln("stroke"); gen.writeln("newpath"); gen.writeln("0 1 moveto"); gen.writeln("1 0 lineto"); gen.writeln("stroke"); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
public void processEvent(DSCEvent event, DSCParser parser) throws IOException, DSCException { if (event.isDSCComment() && event instanceof DSCCommentIncludeResource) { DSCCommentIncludeResource include = (DSCCommentIncludeResource)event; PSResource res = include.getResource(); if (res.getType().equals(PSResource.TYPE_FORM)) { if (inlineFormResources.containsValue(res)) { PSImageFormResource form = (PSImageFormResource) inlineFormResources.get(res); //Create an inline form //Wrap in save/restore pair to release memory gen.writeln("save"); generateFormForImage(gen, form); boolean execformFound = false; DSCEvent next = parser.nextEvent(); if (next.isLine()) { PostScriptLine line = next.asLine(); if (line.getLine().endsWith(" execform")) { line.generate(gen); execformFound = true; } } if (!execformFound) { throw new IOException( "Expected a PostScript line in the form: <form> execform"); } gen.writeln("restore"); } else { //Do nothing } parser.next(); } } }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageGraphics2D imageG2D = (ImageGraphics2D)image; Graphics2DImagePainter painter = imageG2D.getGraphics2DImagePainter(); float fx = (float)pos.getX() / 1000f; float fy = (float)pos.getY() / 1000f; float fwidth = (float)pos.getWidth() / 1000f; float fheight = (float)pos.getHeight() / 1000f; // get the 'width' and 'height' attributes of the SVG document Dimension dim = painter.getImageSize(); float imw = (float)dim.getWidth() / 1000f; float imh = (float)dim.getHeight() / 1000f; float sx = fwidth / (float)imw; float sy = fheight / (float)imh; gen.commentln("%FOPBeginGraphics2D"); gen.saveGraphicsState(); final boolean clip = false; if (clip) { // Clip to the image area. gen.writeln("newpath"); gen.defineRect(fx, fy, fwidth, fheight); gen.writeln("clip"); } // transform so that the coordinates (0,0) is from the top left // and positive is down and to the right. (0,0) is where the // viewBox puts it. gen.concatMatrix(sx, 0, 0, sy, fx, fy); final boolean textAsShapes = false; PSGraphics2D graphics = new PSGraphics2D(textAsShapes, gen); graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); AffineTransform transform = new AffineTransform(); // scale to viewbox transform.translate(fx, fy); gen.getCurrentState().concatMatrix(transform); Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, imw, imh); painter.paint(graphics, area); gen.restoreGraphicsState(); gen.commentln("%FOPEndGraphics2D"); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
public void generateForm(RenderingContext context, Image image, final PSImageFormResource form) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); final ImageGraphics2D imageG2D = (ImageGraphics2D)image; ImageInfo info = image.getInfo(); FormGenerator formGen = buildFormGenerator(gen.getPSLevel(), form, info, imageG2D); formGen.generate(gen); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
private FormGenerator buildFormGenerator(int psLanguageLevel, final PSImageFormResource form, final ImageInfo info, final ImageGraphics2D imageG2D) { String imageDescription = info.getMimeType() + " " + info.getOriginalURI(); final Dimension2D dimensionsPt = info.getSize().getDimensionPt(); final Dimension2D dimensionsMpt = info.getSize().getDimensionMpt(); FormGenerator formGen; if (psLanguageLevel <= 2) { formGen = new EPSFormGenerator(form.getName(), imageDescription, dimensionsPt) { @Override void doGeneratePaintProc(PSGenerator gen) throws IOException { paintImageG2D(imageG2D, dimensionsMpt, gen); } }; } else { formGen = new EPSFormGenerator(form.getName(), imageDescription, dimensionsPt) { @Override protected void generateAdditionalDataStream(PSGenerator gen) throws IOException { gen.writeln("/" + form.getName() + ":Data currentfile <<"); gen.writeln(" /Filter /SubFileDecode"); gen.writeln(" /DecodeParms << /EODCount 0 /EODString (%FOPEndOfData) >>"); gen.writeln(">> /ReusableStreamDecode filter"); paintImageG2D(imageG2D, dimensionsMpt, gen); gen.writeln("%FOPEndOfData"); gen.writeln("def"); } @Override void doGeneratePaintProc(PSGenerator gen) throws IOException { gen.writeln(form.getName() + ":Data 0 setfileposition"); gen.writeln(form.getName() + ":Data cvx exec"); } }; } return formGen; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
Override void doGeneratePaintProc(PSGenerator gen) throws IOException { paintImageG2D(imageG2D, dimensionsMpt, gen); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
Override protected void generateAdditionalDataStream(PSGenerator gen) throws IOException { gen.writeln("/" + form.getName() + ":Data currentfile <<"); gen.writeln(" /Filter /SubFileDecode"); gen.writeln(" /DecodeParms << /EODCount 0 /EODString (%FOPEndOfData) >>"); gen.writeln(">> /ReusableStreamDecode filter"); paintImageG2D(imageG2D, dimensionsMpt, gen); gen.writeln("%FOPEndOfData"); gen.writeln("def"); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
Override void doGeneratePaintProc(PSGenerator gen) throws IOException { gen.writeln(form.getName() + ":Data 0 setfileposition"); gen.writeln(form.getName() + ":Data cvx exec"); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
protected void paintImageG2D(final ImageGraphics2D imageG2D, Dimension2D dimensionsMpt, PSGenerator gen) throws IOException { PSGraphics2DAdapter adapter = new PSGraphics2DAdapter(gen, false); adapter.paintImage(imageG2D.getGraphics2DImagePainter(), null, 0, 0, (int) Math.round(dimensionsMpt.getWidth()), (int) Math.round(dimensionsMpt.getHeight())); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
Override protected final void generatePaintProc(PSGenerator gen) throws IOException { gen.getResourceTracker().notifyResourceUsageOnPage( PSProcSets.EPS_PROCSET); gen.writeln("BeginEPSF"); doGeneratePaintProc(gen); gen.writeln("EndEPSF"); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
private void writeHeader() throws IOException { //PostScript Header gen.writeln(DSCConstants.PS_ADOBE_30); gen.writeDSCComment(DSCConstants.CREATOR, new String[] {getUserAgent().getProducer()}); gen.writeDSCComment(DSCConstants.CREATION_DATE, new Object[] {new java.util.Date()}); gen.writeDSCComment(DSCConstants.LANGUAGE_LEVEL, new Integer(gen.getPSLevel())); gen.writeDSCComment(DSCConstants.PAGES, new Object[] {DSCConstants.ATEND}); gen.writeDSCComment(DSCConstants.BBOX, DSCConstants.ATEND); gen.writeDSCComment(DSCConstants.HIRES_BBOX, DSCConstants.ATEND); gen.writeDSCComment(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES, new Object[] {DSCConstants.ATEND}); writeExtensions(COMMENT_DOCUMENT_HEADER); gen.writeDSCComment(DSCConstants.END_COMMENTS); //Defaults gen.writeDSCComment(DSCConstants.BEGIN_DEFAULTS); gen.writeDSCComment(DSCConstants.END_DEFAULTS); //Prolog and Setup written right before the first page-sequence, see startPageSequence() //Do this only once, as soon as we have all the content for the Setup section! //Prolog gen.writeDSCComment(DSCConstants.BEGIN_PROLOG); PSProcSets.writeStdProcSet(gen); PSProcSets.writeEPSProcSet(gen); FOPProcSet.INSTANCE.writeTo(gen); gen.writeDSCComment(DSCConstants.END_PROLOG); //Setup gen.writeDSCComment(DSCConstants.BEGIN_SETUP); PSRenderingUtil.writeSetupCodeList(gen, setupCodeList, "SetupCode"); if (!psUtil.isOptimizeResources()) { this.fontResources.addAll(PSFontUtils.writeFontDict(gen, fontInfo)); } else { gen.commentln("%FOPFontSetup"); //Place-holder, will be replaced in the second pass } gen.writeDSCComment(DSCConstants.END_SETUP); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
private void rewritePostScriptFile() throws IOException { log.debug("Processing PostScript resources..."); long startTime = System.currentTimeMillis(); ResourceTracker resTracker = gen.getResourceTracker(); InputStream in = new java.io.FileInputStream(this.tempFile); in = new java.io.BufferedInputStream(in); try { try { ResourceHandler handler = new ResourceHandler(getUserAgent(), this.fontInfo, resTracker, this.formResources); handler.process(in, this.outputStream, this.currentPageNumber, this.documentBoundingBox); this.outputStream.flush(); } catch (DSCException e) { throw new RuntimeException(e.getMessage()); } } finally { IOUtils.closeQuietly(in); if (!this.tempFile.delete()) { this.tempFile.deleteOnExit(); log.warn("Could not delete temporary file: " + this.tempFile); } } if (log.isDebugEnabled()) { long duration = System.currentTimeMillis() - startTime; log.debug("Resource Processing complete in " + duration + " ms."); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
private void writeExtensions(int which) throws IOException { Collection extensions = comments[which]; if (extensions != null) { PSRenderingUtil.writeEnclosedExtensionAttachments(gen, extensions); extensions.clear(); } }
// in src/java/org/apache/fop/render/ps/PSImageHandlerRawCCITTFax.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRawCCITTFax ccitt = (ImageRawCCITTFax)image; float x = (float)pos.getX() / 1000f; float y = (float)pos.getY() / 1000f; float w = (float)pos.getWidth() / 1000f; float h = (float)pos.getHeight() / 1000f; Rectangle2D targetRect = new Rectangle2D.Float( x, y, w, h); ImageInfo info = image.getInfo(); ImageEncoder encoder = new ImageEncoderCCITTFax(ccitt); PSImageUtils.writeImage(encoder, info.getSize().getDimensionPx(), info.getOriginalURI(), targetRect, ccitt.getColorSpace(), 1, false, gen); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerRawCCITTFax.java
public void generateForm(RenderingContext context, Image image, PSImageFormResource form) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRawCCITTFax ccitt = (ImageRawCCITTFax)image; ImageInfo info = image.getInfo(); String imageDescription = info.getMimeType() + " " + info.getOriginalURI(); ImageEncoder encoder = new ImageEncoderCCITTFax(ccitt); FormGenerator formGen = new ImageFormGenerator( form.getName(), imageDescription, info.getSize().getDimensionPt(), info.getSize().getDimensionPx(), encoder, ccitt.getColorSpace(), 1, false); formGen.generate(gen); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageXMLDOM imageSVG = (ImageXMLDOM)image; //Controls whether text painted by Batik is generated using text or path operations boolean strokeText = false; //TODO Configure text stroking SVGUserAgent ua = new SVGUserAgent(context.getUserAgent(), new AffineTransform()); PSGraphics2D graphics = new PSGraphics2D(strokeText, gen); graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); BridgeContext ctx = new PSBridgeContext(ua, (strokeText ? null : psContext.getFontInfo()), context.getUserAgent().getFactory().getImageManager(), context.getUserAgent().getImageSessionContext()); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(imageSVG.getDocument()); GraphicsNode root; try { GVTBuilder builder = new GVTBuilder(); root = builder.build(ctx, clonedDoc); } catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; } // get the 'width' and 'height' attributes of the SVG document float w = (float)ctx.getDocumentSize().getWidth() * 1000f; float h = (float)ctx.getDocumentSize().getHeight() * 1000f; float sx = pos.width / w; float sy = pos.height / h; ctx = null; gen.commentln("%FOPBeginSVG"); gen.saveGraphicsState(); final boolean clip = false; if (clip) { /* * Clip to the svg area. * Note: To have the svg overlay (under) a text area then use * an fo:block-container */ gen.writeln("newpath"); gen.defineRect(pos.getMinX() / 1000f, pos.getMinY() / 1000f, pos.width / 1000f, pos.height / 1000f); gen.writeln("clip"); } // transform so that the coordinates (0,0) is from the top left // and positive is down and to the right. (0,0) is where the // viewBox puts it. gen.concatMatrix(sx, 0, 0, sy, pos.getMinX() / 1000f, pos.getMinY() / 1000f); AffineTransform transform = new AffineTransform(); // scale to viewbox transform.translate(pos.getMinX(), pos.getMinY()); gen.getCurrentState().concatMatrix(transform); try { root.paint(graphics); } catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); } gen.restoreGraphicsState(); gen.commentln("%FOPEndSVG"); }
// in src/java/org/apache/fop/render/ps/FOPProcSet.java
public void writeTo(PSGenerator gen) throws IOException { gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, new Object[] {TYPE_PROCSET, getName(), Float.toString(getVersion()), Integer.toString(getRevision())}); gen.writeDSCComment(DSCConstants.VERSION, new Object[] {Float.toString(getVersion()), Integer.toString(getRevision())}); gen.writeDSCComment(DSCConstants.COPYRIGHT, "Copyright 2009 " + "The Apache Software Foundation. " + "License terms: http://www.apache.org/licenses/LICENSE-2.0"); gen.writeDSCComment(DSCConstants.TITLE, "Basic set of procedures used by Apache FOP"); gen.writeln("/TJ { % Similar but not equal to PDF's TJ operator"); gen.writeln(" {"); gen.writeln(" dup type /stringtype eq"); gen.writeln(" { show }"); //normal text show gen.writeln(" { neg 1000 div 0 rmoveto }"); //negative X movement gen.writeln(" ifelse"); gen.writeln(" } forall"); gen.writeln("} bd"); gen.writeln("/ATJ { % As TJ but adds letter-spacing"); gen.writeln(" /ATJls exch def"); gen.writeln(" {"); gen.writeln(" dup type /stringtype eq"); gen.writeln(" { ATJls 0 3 2 roll ashow }"); //normal text show gen.writeln(" { neg 1000 div 0 rmoveto }"); //negative X movement gen.writeln(" ifelse"); gen.writeln(" } forall"); gen.writeln("} bd"); gen.writeDSCComment(DSCConstants.END_RESOURCE); gen.getResourceTracker().registerSuppliedResource(this); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerEPS.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRawEPS eps = (ImageRawEPS)image; float x = (float)pos.getX() / 1000f; float y = (float)pos.getY() / 1000f; float w = (float)pos.getWidth() / 1000f; float h = (float)pos.getHeight() / 1000f; ImageInfo info = image.getInfo(); Rectangle2D bbox = eps.getBoundingBox(); if (bbox == null) { bbox = new Rectangle2D.Double(); bbox.setFrame(new Point2D.Double(), info.getSize().getDimensionPt()); } InputStream in = eps.createInputStream(); try { String resourceName = info.getOriginalURI(); if (resourceName == null) { resourceName = "inline image"; } PSImageUtils.renderEPS(in, resourceName, new Rectangle2D.Float(x, y, w, h), bbox, gen); } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/render/ps/ImageEncoderJPEG.java
public void writeTo(OutputStream out) throws IOException { jpeg.writeTo(out); }
// in src/java/org/apache/fop/render/ps/ImageEncoderCCITTFax.java
public void writeTo(OutputStream out) throws IOException { ccitt.writeTo(out); }
// in src/java/org/apache/fop/render/ps/PSGraphics2DAdapter.java
public void paintImage(Graphics2DImagePainter painter, RendererContext context, int x, int y, int width, int height) throws IOException { float fwidth = width / 1000f; float fheight = height / 1000f; float fx = x / 1000f; float fy = y / 1000f; // get the 'width' and 'height' attributes of the SVG document Dimension dim = painter.getImageSize(); float imw = (float)dim.getWidth() / 1000f; float imh = (float)dim.getHeight() / 1000f; boolean paintAsBitmap = false; if (context != null) { Map foreign = (Map)context.getProperty(RendererContextConstants.FOREIGN_ATTRIBUTES); paintAsBitmap = (foreign != null && ImageHandlerUtil.isConversionModeBitmap(foreign)); } float sx = paintAsBitmap ? 1.0f : (fwidth / (float)imw); float sy = paintAsBitmap ? 1.0f : (fheight / (float)imh); gen.commentln("%FOPBeginGraphics2D"); gen.saveGraphicsState(); if (clip) { // Clip to the image area. gen.writeln("newpath"); gen.defineRect(fx, fy, fwidth, fheight); gen.writeln("clip"); } // transform so that the coordinates (0,0) is from the top left // and positive is down and to the right. (0,0) is where the // viewBox puts it. gen.concatMatrix(sx, 0, 0, sy, fx, fy); final boolean textAsShapes = false; PSGraphics2D graphics = new PSGraphics2D(textAsShapes, gen); graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); AffineTransform transform = new AffineTransform(); // scale to viewbox transform.translate(fx, fy); gen.getCurrentState().concatMatrix(transform); if (paintAsBitmap) { //Fallback solution: Paint to a BufferedImage int resolution = (int)Math.round(context.getUserAgent().getTargetResolution()); RendererContextWrapper ctx = RendererContext.wrapRendererContext(context); BufferedImage bi = paintToBufferedImage(painter, ctx, resolution, false, false); float scale = PDFFactory.DEFAULT_PDF_RESOLUTION / context.getUserAgent().getTargetResolution(); graphics.drawImage(bi, new AffineTransform(scale, 0, 0, scale, 0, 0), null); } else { Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, imw, imh); painter.paint(graphics, area); } gen.restoreGraphicsState(); gen.commentln("%FOPEndGraphics2D"); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
protected void drawImageUsingImageHandler(ImageInfo info, Rectangle rect) throws ImageException, IOException { if (!getPSUtil().isOptimizeResources() || PSImageUtils.isImageInlined(info, (PSRenderingContext)createRenderingContext())) { super.drawImageUsingImageHandler(info, rect); } else { if (log.isDebugEnabled()) { log.debug("Image " + info + " is embedded as a form later"); } //Don't load image at this time, just put a form placeholder in the stream PSResource form = documentHandler.getFormForImage(info.getOriginalURI()); PSImageUtils.drawForm(form, info, rect, getGenerator()); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
protected void saveGraphicsState() throws IOException { endTextObject(); getGenerator().saveGraphicsState(); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
protected void restoreGraphicsState() throws IOException { endTextObject(); getGenerator().restoreGraphicsState(); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
protected void beginTextObject() throws IOException { if (!inTextMode) { PSGenerator generator = getGenerator(); generator.saveGraphicsState(); generator.writeln("BT"); inTextMode = true; } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
protected void endTextObject() throws IOException { if (inTextMode) { inTextMode = false; PSGenerator generator = getGenerator(); generator.writeln("ET"); generator.restoreGraphicsState(); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
private void writeText( // CSOK: ParameterNumber String text, int start, int len, int letterSpacing, int wordSpacing, int[][] dp, Font font, Typeface tf) throws IOException { PSGenerator generator = getGenerator(); int end = start + len; int initialSize = len; initialSize += initialSize / 2; boolean hasLetterSpacing = (letterSpacing != 0); boolean needTJ = false; int lineStart = 0; StringBuffer accText = new StringBuffer(initialSize); StringBuffer sb = new StringBuffer(initialSize); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); for (int i = start; i < end; i++) { char orgChar = text.charAt(i); char ch; int cw; int glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { //Fixed width space are rendered as spaces so copy/paste works in a reader ch = font.mapChar(CharUtilities.SPACE); cw = font.getCharWidth(orgChar); glyphAdjust = font.getCharWidth(ch) - cw; } else { if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust -= wordSpacing; } ch = font.mapChar(orgChar); cw = font.getCharWidth(orgChar); } if (dx != null && i < dxl - 1) { glyphAdjust -= dx[i + 1]; } char codepoint = (char)(ch % 256); PSGenerator.escapeChar(codepoint, accText); //add character to accumulated text if (glyphAdjust != 0) { needTJ = true; if (sb.length() == 0) { sb.append('['); //Need to start TJ } if (accText.length() > 0) { if ((sb.length() - lineStart + accText.length()) > 200) { sb.append(PSGenerator.LF); lineStart = sb.length(); } sb.append('('); sb.append(accText); sb.append(") "); accText.setLength(0); //reset accumulated text } sb.append(Integer.toString(glyphAdjust)).append(' '); } } if (needTJ) { if (accText.length() > 0) { sb.append('('); sb.append(accText); sb.append(')'); } if (hasLetterSpacing) { sb.append("] " + formatMptAsPt(generator, letterSpacing) + " ATJ"); } else { sb.append("] TJ"); } } else { sb.append('(').append(accText).append(")"); if (hasLetterSpacing) { StringBuffer spb = new StringBuffer(); spb.append(formatMptAsPt(generator, letterSpacing)) .append(" 0 "); sb.insert(0, spb.toString()); sb.append(" " + generator.mapCommand("ashow")); } else { sb.append(" " + generator.mapCommand("show")); } } generator.writeln(sb.toString()); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
private void useFont(String key, int size) throws IOException { PSResource res = this.documentHandler.getPSResourceForFontKey(key); PSGenerator generator = getGenerator(); generator.useFont("/" + res.getName(), size / 1000f); generator.getResourceTracker().notifyResourceUsageOnPage(res); }
// in src/java/org/apache/fop/render/ps/PSImageUtils.java
public static void drawForm(PSResource form, ImageInfo info, Rectangle rect, PSGenerator generator) throws IOException { Rectangle2D targetRect = new Rectangle2D.Double( rect.getMinX() / 1000.0, rect.getMinY() / 1000.0, rect.getWidth() / 1000.0, rect.getHeight() / 1000.0); generator.saveGraphicsState(); translateAndScale(generator, info.getSize().getDimensionPt(), targetRect); //The following %%IncludeResource marker is needed later by ResourceHandler! generator.writeDSCComment(DSCConstants.INCLUDE_RESOURCE, form); generator.getResourceTracker().notifyResourceUsageOnPage(form); generator.writeln(form.getName() + " execform"); generator.restoreGraphicsState(); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerRenderedImage.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRendered imageRend = (ImageRendered)image; float x = (float)pos.getX() / 1000f; float y = (float)pos.getY() / 1000f; float w = (float)pos.getWidth() / 1000f; float h = (float)pos.getHeight() / 1000f; RenderedImage ri = imageRend.getRenderedImage(); PSImageUtils.renderBitmapImage(ri, x, y, w, h, gen); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerRenderedImage.java
public void generateForm(RenderingContext context, Image image, PSImageFormResource form) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRendered imageRend = (ImageRendered)image; ImageInfo info = image.getInfo(); String imageDescription = info.getMimeType() + " " + info.getOriginalURI(); RenderedImage ri = imageRend.getRenderedImage(); FormGenerator formGen = new ImageFormGenerator( form.getName(), imageDescription, info.getSize().getDimensionPt(), ri, false); formGen.generate(gen); }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
protected void paintTextRun(TextRun textRun, Graphics2D g2d) throws IOException { AttributedCharacterIterator runaci = textRun.getACI(); runaci.first(); TextPaintInfo tpi = (TextPaintInfo)runaci.getAttribute(PAINT_INFO); if (tpi == null || !tpi.visible) { return; } if ((tpi != null) && (tpi.composite != null)) { g2d.setComposite(tpi.composite); } //------------------------------------ TextSpanLayout layout = textRun.getLayout(); logTextRun(runaci, layout); CharSequence chars = collectCharacters(runaci); runaci.first(); //Reset ACI final PSGraphics2D ps = (PSGraphics2D)g2d; final PSGenerator gen = ps.getPSGenerator(); ps.preparePainting(); if (DEBUG) { log.debug("Text: " + chars); gen.commentln("%Text: " + chars); } GeneralPath debugShapes = null; if (DEBUG) { debugShapes = new GeneralPath(); } TextUtil textUtil = new TextUtil(gen); textUtil.setupFonts(runaci); if (!textUtil.hasFonts()) { //Draw using Java2D when no native fonts are available textRun.getLayout().draw(g2d); return; } gen.saveGraphicsState(); gen.concatMatrix(g2d.getTransform()); Shape imclip = g2d.getClip(); clip(ps, imclip); gen.writeln("BT"); //beginTextObject() AffineTransform localTransform = new AffineTransform(); Point2D prevPos = null; GVTGlyphVector gv = layout.getGlyphVector(); PSTextRun psRun = new PSTextRun(); //Used to split a text run into smaller runs for (int index = 0, c = gv.getNumGlyphs(); index < c; index++) { char ch = chars.charAt(index); boolean visibleChar = gv.isGlyphVisible(index) || (CharUtilities.isAnySpace(ch) && !CharUtilities.isZeroWidthSpace(ch)); logCharacter(ch, layout, index, visibleChar); if (!visibleChar) { continue; } Point2D glyphPos = gv.getGlyphPosition(index); AffineTransform glyphTransform = gv.getGlyphTransform(index); if (log.isTraceEnabled()) { log.trace("pos " + glyphPos + ", transform " + glyphTransform); } if (DEBUG) { Shape sh = gv.getGlyphLogicalBounds(index); if (sh == null) { sh = new Ellipse2D.Double(glyphPos.getX(), glyphPos.getY(), 2, 2); } debugShapes.append(sh, false); } //Exact position of the glyph localTransform.setToIdentity(); localTransform.translate(glyphPos.getX(), glyphPos.getY()); if (glyphTransform != null) { localTransform.concatenate(glyphTransform); } localTransform.scale(1, -1); boolean flushCurrentRun = false; //Try to optimize by combining characters using the same font and on the same line. if (glyphTransform != null) { //Happens for text-on-a-path flushCurrentRun = true; } if (psRun.getRunLength() >= 128) { //Don't let a run get too long flushCurrentRun = true; } //Note the position of the glyph relative to the previous one Point2D relPos; if (prevPos == null) { relPos = new Point2D.Double(0, 0); } else { relPos = new Point2D.Double( glyphPos.getX() - prevPos.getX(), glyphPos.getY() - prevPos.getY()); } if (psRun.vertChanges == 0 && psRun.getHorizRunLength() > 2 && relPos.getY() != 0) { //new line flushCurrentRun = true; } //Select the actual character to paint char paintChar = (CharUtilities.isAnySpace(ch) ? ' ' : ch); //Select (sub)font for character Font f = textUtil.selectFontForChar(paintChar); char mapped = f.mapChar(ch); boolean fontChanging = textUtil.isFontChanging(f, mapped); if (fontChanging) { flushCurrentRun = true; } if (flushCurrentRun) { //Paint the current run and reset for the next run psRun.paint(ps, textUtil, tpi); psRun.reset(); } //Track current run psRun.addCharacter(paintChar, relPos); psRun.noteStartingTransformation(localTransform); //Change font if necessary if (fontChanging) { textUtil.setCurrentFont(f, mapped); } //Update last position prevPos = glyphPos; } psRun.paint(ps, textUtil, tpi); gen.writeln("ET"); //endTextObject() gen.restoreGraphicsState(); if (DEBUG) { //Paint debug shapes g2d.setStroke(new BasicStroke(0)); g2d.setColor(Color.LIGHT_GRAY); g2d.draw(debugShapes); } }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
private void applyColor(Paint paint, final PSGenerator gen) throws IOException { if (paint == null) { return; } else if (paint instanceof Color) { Color col = (Color)paint; gen.useColor(col); } else { log.warn("Paint not supported: " + paint.toString()); } }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
private void clip(PSGraphics2D ps, Shape shape) throws IOException { if (shape == null) { return; } ps.getPSGenerator().writeln("newpath"); PathIterator iter = shape.getPathIterator(IDENTITY_TRANSFORM); ps.processPathIterator(iter); ps.getPSGenerator().writeln("clip"); }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
public void writeTextMatrix(AffineTransform transform) throws IOException { double[] matrix = new double[6]; transform.getMatrix(matrix); gen.writeln(gen.formatDouble5(matrix[0]) + " " + gen.formatDouble5(matrix[1]) + " " + gen.formatDouble5(matrix[2]) + " " + gen.formatDouble5(matrix[3]) + " " + gen.formatDouble5(matrix[4]) + " " + gen.formatDouble5(matrix[5]) + " Tm"); }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
public void selectFont(Font f, char mapped) throws IOException { int encoding = mapped / 256; String postfix = (encoding == 0 ? null : Integer.toString(encoding)); PSResource res = getResourceForFont(f, postfix); gen.useFont("/" + res.getName(), f.getFontSize() / 1000f); gen.getResourceTracker().notifyResourceUsageOnPage(res); }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
public void paint(PSGraphics2D g2d, TextUtil textUtil, TextPaintInfo tpi) throws IOException { if (getRunLength() > 0) { if (log.isDebugEnabled()) { log.debug("Text run: " + currentChars); } textUtil.writeTextMatrix(this.textTransform); if (isXShow()) { log.debug("Horizontal text: xshow"); paintXYShow(g2d, textUtil, tpi.fillPaint, true, false); } else if (isYShow()) { log.debug("Vertical text: yshow"); paintXYShow(g2d, textUtil, tpi.fillPaint, false, true); } else { log.debug("Arbitrary text: xyshow"); paintXYShow(g2d, textUtil, tpi.fillPaint, true, true); } boolean stroke = (tpi.strokePaint != null) && (tpi.strokeStroke != null); if (stroke) { log.debug("Stroked glyph outlines"); paintStrokedGlyphs(g2d, textUtil, tpi.strokePaint, tpi.strokeStroke); } } }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
private void paintXYShow(PSGraphics2D g2d, TextUtil textUtil, Paint paint, boolean x, boolean y) throws IOException { PSGenerator gen = textUtil.gen; char firstChar = this.currentChars.charAt(0); //Font only has to be setup up before the first character Font f = textUtil.selectFontForChar(firstChar); char mapped = f.mapChar(firstChar); textUtil.selectFont(f, mapped); textUtil.setCurrentFont(f, mapped); applyColor(paint, gen); StringBuffer sb = new StringBuffer(); sb.append('('); for (int i = 0, c = this.currentChars.length(); i < c; i++) { char ch = this.currentChars.charAt(i); mapped = f.mapChar(ch); char codepoint = (char) (mapped % 256); PSGenerator.escapeChar(codepoint, sb); } sb.append(')'); if (x || y) { sb.append("\n["); int idx = 0; Iterator iter = this.relativePositions.iterator(); while (iter.hasNext()) { Point2D pt = (Point2D)iter.next(); if (idx > 0) { if (x) { sb.append(format(gen, pt.getX())); } if (y) { if (x) { sb.append(' '); } sb.append(format(gen, -pt.getY())); } if (idx % 8 == 0) { sb.append('\n'); } else { sb.append(' '); } } idx++; } if (x) { sb.append('0'); } if (y) { if (x) { sb.append(' '); } sb.append('0'); } sb.append(']'); } sb.append(' '); if (x) { sb.append('x'); } if (y) { sb.append('y'); } sb.append("show"); // --> xshow, yshow or xyshow gen.writeln(sb.toString()); }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
private void paintStrokedGlyphs(PSGraphics2D g2d, TextUtil textUtil, Paint strokePaint, Stroke stroke) throws IOException { PSGenerator gen = textUtil.gen; applyColor(strokePaint, gen); PSGraphics2D.applyStroke(stroke, gen); Font f = null; Iterator iter = this.relativePositions.iterator(); iter.next(); Point2D pos = new Point2D.Double(0, 0); gen.writeln("0 0 M"); for (int i = 0, c = this.currentChars.length(); i < c; i++) { char ch = this.currentChars.charAt(0); if (i == 0) { //Font only has to be setup up before the first character f = textUtil.selectFontForChar(ch); } char mapped = f.mapChar(ch); if (i == 0) { textUtil.selectFont(f, mapped); textUtil.setCurrentFont(f, mapped); } mapped = f.mapChar(this.currentChars.charAt(i)); //add glyph outlines to current path char codepoint = (char)(mapped % 256); gen.write("(" + codepoint + ")"); gen.writeln(" false charpath"); if (iter.hasNext()) { //Position for the next character Point2D pt = (Point2D)iter.next(); pos.setLocation(pos.getX() + pt.getX(), pos.getY() - pt.getY()); gen.writeln(gen.formatDouble5(pos.getX()) + " " + gen.formatDouble5(pos.getY()) + " M"); } } gen.writeln("stroke"); //paints all accumulated glyph outlines }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void drawBorderLine( // CSOK: ParameterNumber int x1, int y1, int x2, int y2, boolean horz, boolean startOrBefore, int style, Color col) throws IOException { drawBorderLine(generator, toPoints(x1), toPoints(y1), toPoints(x2), toPoints(y2), horz, startOrBefore, style, col); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
private static void drawLine(PSGenerator gen, float startx, float starty, float endx, float endy) throws IOException { gen.writeln(gen.formatDouble(startx) + " " + gen.formatDouble(starty) + " " + gen.mapCommand("moveto") + " " + gen.formatDouble(endx) + " " + gen.formatDouble(endy) + " " + gen.mapCommand("lineto") + " " + gen.mapCommand("stroke") + " " + gen.mapCommand("newpath")); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
public static void drawBorderLine( // CSOK: ParameterNumber PSGenerator gen, float x1, float y1, float x2, float y2, boolean horz, // CSOK: JavadocMethod boolean startOrBefore, int style, Color col) // CSOK: JavadocMethod throws IOException { // CSOK: JavadocMethod float w = x2 - x1; float h = y2 - y1; if ((w < 0) || (h < 0)) { log.error("Negative extent received. Border won't be painted."); return; } switch (style) { case Constants.EN_DASHED: gen.useColor(col); if (horz) { float unit = Math.abs(2 * h); int rep = (int)(w / unit); if (rep % 2 == 0) { rep++; } unit = w / rep; gen.useDash("[" + unit + "] 0"); gen.useLineCap(0); gen.useLineWidth(h); float ym = y1 + (h / 2); drawLine(gen, x1, ym, x2, ym); } else { float unit = Math.abs(2 * w); int rep = (int)(h / unit); if (rep % 2 == 0) { rep++; } unit = h / rep; gen.useDash("[" + unit + "] 0"); gen.useLineCap(0); gen.useLineWidth(w); float xm = x1 + (w / 2); drawLine(gen, xm, y1, xm, y2); } break; case Constants.EN_DOTTED: gen.useColor(col); gen.useLineCap(1); //Rounded! if (horz) { float unit = Math.abs(2 * h); int rep = (int)(w / unit); if (rep % 2 == 0) { rep++; } unit = w / rep; gen.useDash("[0 " + unit + "] 0"); gen.useLineWidth(h); float ym = y1 + (h / 2); drawLine(gen, x1, ym, x2, ym); } else { float unit = Math.abs(2 * w); int rep = (int)(h / unit); if (rep % 2 == 0) { rep++; } unit = h / rep; gen.useDash("[0 " + unit + "] 0"); gen.useLineWidth(w); float xm = x1 + (w / 2); drawLine(gen, xm, y1, xm, y2); } break; case Constants.EN_DOUBLE: gen.useColor(col); gen.useDash(null); if (horz) { float h3 = h / 3; gen.useLineWidth(h3); float ym1 = y1 + (h3 / 2); float ym2 = ym1 + h3 + h3; drawLine(gen, x1, ym1, x2, ym1); drawLine(gen, x1, ym2, x2, ym2); } else { float w3 = w / 3; gen.useLineWidth(w3); float xm1 = x1 + (w3 / 2); float xm2 = xm1 + w3 + w3; drawLine(gen, xm1, y1, xm1, y2); drawLine(gen, xm2, y1, xm2, y2); } break; case Constants.EN_GROOVE: case Constants.EN_RIDGE: float colFactor = (style == Constants.EN_GROOVE ? 0.4f : -0.4f); gen.useDash(null); if (horz) { Color uppercol = ColorUtil.lightenColor(col, -colFactor); Color lowercol = ColorUtil.lightenColor(col, colFactor); float h3 = h / 3; gen.useLineWidth(h3); float ym1 = y1 + (h3 / 2); gen.useColor(uppercol); drawLine(gen, x1, ym1, x2, ym1); gen.useColor(col); drawLine(gen, x1, ym1 + h3, x2, ym1 + h3); gen.useColor(lowercol); drawLine(gen, x1, ym1 + h3 + h3, x2, ym1 + h3 + h3); } else { Color leftcol = ColorUtil.lightenColor(col, -colFactor); Color rightcol = ColorUtil.lightenColor(col, colFactor); float w3 = w / 3; gen.useLineWidth(w3); float xm1 = x1 + (w3 / 2); gen.useColor(leftcol); drawLine(gen, xm1, y1, xm1, y2); gen.useColor(col); drawLine(gen, xm1 + w3, y1, xm1 + w3, y2); gen.useColor(rightcol); drawLine(gen, xm1 + w3 + w3, y1, xm1 + w3 + w3, y2); } break; case Constants.EN_INSET: case Constants.EN_OUTSET: colFactor = (style == Constants.EN_OUTSET ? 0.4f : -0.4f); gen.useDash(null); if (horz) { Color c = ColorUtil.lightenColor(col, (startOrBefore ? 1 : -1) * colFactor); gen.useLineWidth(h); float ym1 = y1 + (h / 2); gen.useColor(c); drawLine(gen, x1, ym1, x2, ym1); } else { Color c = ColorUtil.lightenColor(col, (startOrBefore ? 1 : -1) * colFactor); gen.useLineWidth(w); float xm1 = x1 + (w / 2); gen.useColor(c); drawLine(gen, xm1, y1, xm1, y2); } break; case Constants.EN_HIDDEN: break; default: gen.useColor(col); gen.useDash(null); gen.useLineCap(0); if (horz) { gen.useLineWidth(h); float ym = y1 + (h / 2); drawLine(gen, x1, ym, x2, ym); } else { gen.useLineWidth(w); float xm = x1 + (w / 2); drawLine(gen, xm, y1, xm, y2); } } }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IOException { if (start.y != end.y) { //TODO Support arbitrary lines if necessary throw new UnsupportedOperationException( "Can only deal with horizontal lines right now"); } saveGraphicsState(); int half = width / 2; int starty = start.y - half; //Rectangle boundingRect = new Rectangle(start.x, start.y - half, end.x - start.x, width); switch (style.getEnumValue()) { case Constants.EN_SOLID: case Constants.EN_DASHED: case Constants.EN_DOUBLE: drawBorderLine(start.x, starty, end.x, starty + width, true, true, style.getEnumValue(), color); break; case Constants.EN_DOTTED: clipRect(start.x, starty, end.x - start.x, width); //This displaces the dots to the right by half a dot's width //TODO There's room for improvement here generator.concatMatrix(1, 0, 0, 1, toPoints(half), 0); drawBorderLine(start.x, starty, end.x, starty + width, true, true, style.getEnumValue(), color); break; case Constants.EN_GROOVE: case Constants.EN_RIDGE: generator.useColor(ColorUtil.lightenColor(color, 0.6f)); moveTo(start.x, starty); lineTo(end.x, starty); lineTo(end.x, starty + 2 * half); lineTo(start.x, starty + 2 * half); closePath(); generator.write(" " + generator.mapCommand("fill")); generator.writeln(" " + generator.mapCommand("newpath")); generator.useColor(color); if (style == RuleStyle.GROOVE) { moveTo(start.x, starty); lineTo(end.x, starty); lineTo(end.x, starty + half); lineTo(start.x + half, starty + half); lineTo(start.x, starty + 2 * half); } else { moveTo(end.x, starty); lineTo(end.x, starty + 2 * half); lineTo(start.x, starty + 2 * half); lineTo(start.x, starty + half); lineTo(end.x - half, starty + half); } closePath(); generator.write(" " + generator.mapCommand("fill")); generator.writeln(" " + generator.mapCommand("newpath")); break; default: throw new UnsupportedOperationException("rule style not supported"); } restoreGraphicsState(); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void moveTo(int x, int y) throws IOException { generator.writeln(generator.formatDouble(toPoints(x)) + " " + generator.formatDouble(toPoints(y)) + " " + generator.mapCommand("moveto")); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void lineTo(int x, int y) throws IOException { generator.writeln(generator.formatDouble(toPoints(x)) + " " + generator.formatDouble(toPoints(y)) + " " + generator.mapCommand("lineto")); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void closePath() throws IOException { generator.writeln("cp"); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
private void clipRect(int x, int y, int width, int height) throws IOException { generator.defineRect(toPoints(x), toPoints(y), toPoints(width), toPoints(height)); clip(); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void clip() throws IOException { generator.writeln(generator.mapCommand("clip") + " " + generator.mapCommand("newpath")); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void saveGraphicsState() throws IOException { generator.saveGraphicsState(); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void restoreGraphicsState() throws IOException { generator.restoreGraphicsState(); }
// in src/java/org/apache/fop/render/ps/NativeTextHandler.java
public void writeSetup() throws IOException { if (fontInfo != null) { PSFontUtils.writeFontDict(getPSGenerator(), fontInfo); } }
// in src/java/org/apache/fop/render/ps/NativeTextHandler.java
public void writePageSetup() throws IOException { //nop }
// in src/java/org/apache/fop/render/ps/NativeTextHandler.java
public void drawString(String text, float x, float y) throws IOException { // TODO Remove me after removing the deprecated method in TextHandler. throw new UnsupportedOperationException("Deprecated method!"); }
// in src/java/org/apache/fop/render/ps/NativeTextHandler.java
public void drawString(Graphics2D g, String s, float x, float y) throws IOException { PSGraphics2D g2d = (PSGraphics2D)g; g2d.preparePainting(); if (this.overrideFont == null) { java.awt.Font awtFont = g2d.getFont(); this.font = createFont(awtFont); } else { this.font = this.overrideFont; this.overrideFont = null; } //Color and Font state g2d.establishColor(g2d.getColor()); establishCurrentFont(); PSGenerator gen = getPSGenerator(); gen.saveGraphicsState(); //Clip Shape imclip = g2d.getClip(); g2d.writeClip(imclip); //Prepare correct transformation AffineTransform trans = g2d.getTransform(); gen.concatMatrix(trans); gen.writeln(gen.formatDouble(x) + " " + gen.formatDouble(y) + " moveto "); gen.writeln("1 -1 scale"); StringBuffer sb = new StringBuffer("("); escapeText(s, sb); sb.append(") t "); gen.writeln(sb.toString()); gen.restoreGraphicsState(); }
// in src/java/org/apache/fop/render/ps/NativeTextHandler.java
private void establishCurrentFont() throws IOException { if ((currentFontName != this.font.getFontName()) || (currentFontSize != this.font.getFontSize())) { PSGenerator gen = getPSGenerator(); gen.writeln("/" + this.font.getFontTriplet().getName() + " " + gen.formatDouble(font.getFontSize() / 1000f) + " F"); currentFontName = this.font.getFontName(); currentFontSize = this.font.getFontSize(); } }
// in src/java/org/apache/fop/render/java2d/Java2DImageHandlerRenderedImage.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { Java2DRenderingContext java2dContext = (Java2DRenderingContext)context; ImageInfo info = image.getInfo(); ImageRendered imageRend = (ImageRendered)image; Graphics2D g2d = java2dContext.getGraphics2D(); AffineTransform at = new AffineTransform(); at.translate(pos.x, pos.y); //scaling based on layout instructions double sx = pos.getWidth() / (double)info.getSize().getWidthMpt(); double sy = pos.getHeight() / (double)info.getSize().getHeightMpt(); //scaling because of image resolution //float sourceResolution = java2dContext.getUserAgent().getSourceResolution(); //source resolution seems to be a bad idea, not sure why float sourceResolution = GraphicsConstants.DEFAULT_DPI; sourceResolution *= 1000; //we're working in the millipoint area sx *= sourceResolution / info.getSize().getDpiHorizontal(); sy *= sourceResolution / info.getSize().getDpiVertical(); at.scale(sx, sy); RenderedImage rend = imageRend.getRenderedImage(); if (imageRend.getTransparentColor() != null && !rend.getColorModel().hasAlpha()) { int transCol = imageRend.getTransparentColor().getRGB(); BufferedImage bufImage = makeTransparentImage(rend); WritableRaster alphaRaster = bufImage.getAlphaRaster(); //TODO Masked images: Does anyone know a more efficient method to do this? final int[] transparent = new int[] {0x00}; for (int y = 0, maxy = bufImage.getHeight(); y < maxy; y++) { for (int x = 0, maxx = bufImage.getWidth(); x < maxx; x++) { int col = bufImage.getRGB(x, y); if (col == transCol) { //Mask out all pixels that match the transparent color alphaRaster.setPixel(x, y, transparent); } } } g2d.drawRenderedImage(bufImage, at); } else { g2d.drawRenderedImage(rend, at); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
private void concatenateTransformationMatrix(AffineTransform transform) throws IOException { g2dState.transform(transform); }
// in src/java/org/apache/fop/render/java2d/Java2DImageHandlerGraphics2D.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { Java2DRenderingContext java2dContext = (Java2DRenderingContext)context; ImageInfo info = image.getInfo(); ImageGraphics2D imageG2D = (ImageGraphics2D)image; Dimension dim = info.getSize().getDimensionMpt(); Graphics2D g2d = (Graphics2D)java2dContext.getGraphics2D().create(); g2d.translate(pos.x, pos.y); double sx = pos.width / dim.getWidth(); double sy = pos.height / dim.getHeight(); g2d.scale(sx, sy); Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, dim.getWidth(), dim.getHeight()); imageG2D.getGraphics2DImagePainter().paint(g2d, area); g2d.dispose(); }
// in src/java/org/apache/fop/render/java2d/Java2DGraphics2DAdapter.java
public void paintImage(Graphics2DImagePainter painter, RendererContext context, int x, int y, int width, int height) throws IOException { float fwidth = width / 1000f; float fheight = height / 1000f; float fx = x / 1000f; float fy = y / 1000f; // get the 'width' and 'height' attributes of the SVG document Dimension dim = painter.getImageSize(); float imw = (float)dim.getWidth() / 1000f; float imh = (float)dim.getHeight() / 1000f; float sx = fwidth / (float)imw; float sy = fheight / (float)imh; Java2DRenderer renderer = (Java2DRenderer)context.getRenderer(); Java2DGraphicsState state = renderer.state; //Create copy and paint on that Graphics2D g2d = (Graphics2D)state.getGraph().create(); g2d.setColor(Color.black); g2d.setBackground(Color.black); //TODO Clip to the image area. // transform so that the coordinates (0,0) is from the top left // and positive is down and to the right. (0,0) is where the // viewBox puts it. g2d.translate(fx, fy); AffineTransform at = AffineTransform.getScaleInstance(sx, sy); if (!at.isIdentity()) { g2d.transform(at); } Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, imw, imh); painter.paint(g2d, area); g2d.dispose(); }
// in src/java/org/apache/fop/render/java2d/CustomFontMetricsMapper.java
private void initialize(final Source source) throws FontFormatException, IOException { int type = Font.TRUETYPE_FONT; if (FontType.TYPE1.equals(typeface.getFontType())) { type = TYPE1_FONT; //Font.TYPE1_FONT; only available in Java 1.5 } InputStream is = null; if (source instanceof StreamSource) { is = ((StreamSource) source).getInputStream(); } else if (source.getSystemId() != null) { is = new java.net.URL(source.getSystemId()).openStream(); } else { throw new IllegalArgumentException("No font source provided."); } this.font = Font.createFont(type, is); is.close(); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public void startRenderer(OutputStream out) throws IOException { super.startRenderer(out); // do nothing by default }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public void stopRenderer() throws IOException { log.debug("Java2DRenderer stopped"); renderingDone = true; int numberOfPages = currentPageNumber; // TODO set all vars to null for gc if (numberOfPages == 0) { new FOPException("No page could be rendered"); } }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public void renderPage(PageViewport pageViewport) throws IOException, FOPException { try { rememberPage((PageViewport)pageViewport.clone()); } catch (CloneNotSupportedException e) { throw new FOPException(e); } //The clone() call is necessary as we store the page for later. Otherwise, the //RenderPagesModel calls PageViewport.clear() to release memory as early as possible. currentPageNumber++; }
// in src/java/org/apache/fop/afp/apps/FontPatternExtractor.java
public void extract(File file, File targetDir) throws IOException { InputStream in = new java.io.FileInputStream(file); try { MODCAParser parser = new MODCAParser(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); UnparsedStructuredField strucField; while ((strucField = parser.readNextStructuredField()) != null) { if (strucField.getSfTypeID() == 0xD3EE89) { byte[] sfData = strucField.getData(); println(strucField.toString()); HexDump.dump(sfData, 0, printStream, 0); baout.write(sfData); } } ByteArrayInputStream bin = new ByteArrayInputStream(baout.toByteArray()); DataInputStream din = new DataInputStream(bin); long len = din.readInt() & 0xFFFFFFFFL; println("Length: " + len); din.skip(4); //checksum int tidLen = din.readUnsignedShort() - 2; byte[] tid = new byte[tidLen]; din.readFully(tid); String filename = new String(tid, "ISO-8859-1"); int asciiCount1 = countUSAsciiCharacters(filename); String filenameEBCDIC = new String(tid, "Cp1146"); int asciiCount2 = countUSAsciiCharacters(filenameEBCDIC); println("TID: " + filename + " " + filenameEBCDIC); if (asciiCount2 > asciiCount1) { //Haven't found an indicator if the name is encoded in EBCDIC or not //so we use a trick. filename = filenameEBCDIC; } if (!filename.toLowerCase().endsWith(".pfb")) { filename = filename + ".pfb"; } println("Output filename: " + filename); File out = new File(targetDir, filename); OutputStream fout = new java.io.FileOutputStream(out); try { IOUtils.copyLarge(din, fout); } finally { IOUtils.closeQuietly(fout); } } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/afp/ptoca/TextDataInfoProducer.java
public void produce(PtocaBuilder builder) throws IOException { builder.setTextOrientation(textDataInfo.getRotation()); builder.absoluteMoveBaseline(textDataInfo.getY()); builder.absoluteMoveInline(textDataInfo.getX()); builder.setVariableSpaceCharacterIncrement( textDataInfo.getVariableSpaceCharacterIncrement()); builder.setInterCharacterAdjustment( textDataInfo.getInterCharacterAdjustment()); builder.setExtendedTextColor(textDataInfo.getColor()); builder.setCodedFont((byte)textDataInfo.getFontReference()); // Add transparent data String textString = textDataInfo.getString(); String encoding = textDataInfo.getEncoding(); builder.addTransparentData(CharactersetEncoder.encodeSBCS(textString, encoding)); }
// in src/java/org/apache/fop/afp/ptoca/TransparentDataControlSequence.java
void writeTo(OutputStream outStream) throws IOException { encodedChars.writeTo(outStream, offset, length); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
private void commit(byte functionType) throws IOException { int length = baout.size() + 2; assert length < 256; OutputStream out = getOutputStreamForControlSequence(length); out.write(length); out.write(functionType); baout.writeTo(out); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void writeIntroducer() throws IOException { OutputStream out = getOutputStreamForControlSequence(ESCAPE.length); out.write(ESCAPE); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void setCodedFont(byte font) throws IOException { // Avoid unnecessary specification of the font if (currentFont == font) { return; } else { currentFont = font; } newControlSequence(); writeBytes(font); commit(chained(SCFL)); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void absoluteMoveInline(int coordinate) throws IOException { if (coordinate == this.currentX) { return; } newControlSequence(); writeShort(coordinate); commit(chained(AMI)); currentX = coordinate; }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void relativeMoveInline(int increment) throws IOException { newControlSequence(); writeShort(increment); commit(chained(RMI)); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void absoluteMoveBaseline(int coordinate) throws IOException { if (coordinate == this.currentY) { return; } newControlSequence(); writeShort(coordinate); commit(chained(AMB)); currentY = coordinate; currentX = -1; }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void addTransparentData(EncodedChars encodedChars) throws IOException { for (TransparentData trn : new TransparentDataControlSequence(encodedChars)) { newControlSequence(); trn.writeTo(baout); commit(chained(TRN)); } }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void drawBaxisRule(int length, int width) throws IOException { newControlSequence(); writeShort(length); // Rule length writeShort(width); // Rule width writeBytes(0); // Rule width fraction is always null. enough? commit(chained(DBR)); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void drawIaxisRule(int length, int width) throws IOException { newControlSequence(); writeShort(length); // Rule length writeShort(width); // Rule width writeBytes(0); // Rule width fraction is always null. enough? commit(chained(DIR)); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void setTextOrientation(int orientation) throws IOException { if (orientation == this.currentOrientation) { return; } newControlSequence(); AxisOrientation.getRightHandedAxisOrientationFor(orientation).writeTo(baout); commit(chained(STO)); this.currentOrientation = orientation; currentX = -1; currentY = -1; }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void setExtendedTextColor(Color col) throws IOException { if (ColorUtil.isSameColor(col, currentColor)) { return; } if (col instanceof ColorWithAlternatives) { ColorWithAlternatives cwa = (ColorWithAlternatives)col; Color alt = cwa.getFirstAlternativeOfType(ColorSpace.TYPE_CMYK); if (alt != null) { col = alt; } } ColorSpace cs = col.getColorSpace(); newControlSequence(); if (col.getColorSpace().getType() == ColorSpace.TYPE_CMYK) { // Color space - 0x04 = CMYK, all else are reserved and must be zero writeBytes(0x00, 0x04, 0x00, 0x00, 0x00, 0x00); writeBytes(8, 8, 8, 8); // Number of bits in component 1, 2, 3 & 4 respectively float[] comps = col.getColorComponents(null); assert comps.length == 4; for (int i = 0; i < 4; i++) { int component = Math.round(comps[i] * 255); writeBytes(component); } } else if (cs instanceof CIELabColorSpace) { // Color space - 0x08 = CIELAB, all else are reserved and must be zero writeBytes(0x00, 0x08, 0x00, 0x00, 0x00, 0x00); writeBytes(8, 8, 8, 0); // Number of bits in component 1,2,3 & 4 //Sadly, 16 bit components don't seem to work float[] colorComponents = col.getColorComponents(null); int l = Math.round(colorComponents[0] * 255f); int a = Math.round(colorComponents[1] * 255f) - 128; int b = Math.round(colorComponents[2] * 255f) - 128; writeBytes(l, a, b); // l*, a* and b* } else { // Color space - 0x01 = RGB, all else are reserved and must be zero writeBytes(0x00, 0x01, 0x00, 0x00, 0x00, 0x00); writeBytes(8, 8, 8, 0); // Number of bits in component 1, 2, 3 & 4 respectively writeBytes(col.getRed(), col.getGreen(), col.getBlue()); // RGB intensity } commit(chained(SEC)); this.currentColor = col; }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void setVariableSpaceCharacterIncrement(int incr) throws IOException { if (incr == this.currentVariableSpaceCharacterIncrement) { return; } assert incr >= 0 && incr < (1 << 16); newControlSequence(); writeShort(Math.abs(incr)); //Increment commit(chained(SVI)); this.currentVariableSpaceCharacterIncrement = incr; }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void setInterCharacterAdjustment(int incr) throws IOException { if (incr == this.currentInterCharacterAdjustment) { return; } assert incr >= Short.MIN_VALUE && incr <= Short.MAX_VALUE; newControlSequence(); writeShort(Math.abs(incr)); //Increment writeBytes(incr >= 0 ? 0 : 1); // Direction commit(chained(SIA)); this.currentInterCharacterAdjustment = incr; }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void endChainedControlSequence() throws IOException { newControlSequence(); commit(NOP); }
// in src/java/org/apache/fop/afp/ptoca/LineDataInfoProducer.java
public void produce(PtocaBuilder builder) throws IOException { builder.setTextOrientation(lineDataInfo.getRotation()); int x1 = ensurePositive(lineDataInfo.getX1()); int y1 = ensurePositive(lineDataInfo.getY1()); builder.absoluteMoveBaseline(y1); builder.absoluteMoveInline(x1); builder.setExtendedTextColor(lineDataInfo.getColor()); int x2 = ensurePositive(lineDataInfo.getX2()); int y2 = ensurePositive(lineDataInfo.getY2()); int thickness = lineDataInfo.getThickness(); if (y1 == y2) { builder.drawIaxisRule(x2 - x1, thickness); } else if (x1 == x2) { builder.drawBaxisRule(y2 - y1, thickness); } else { LOG.error("Invalid axis rule: unable to draw line"); return; } }
// in src/java/org/apache/fop/afp/DataStream.java
public void endDocument() throws IOException { if (complete) { String msg = "Invalid state - document already ended."; LOG.warn("endDocument():: " + msg); throw new IllegalStateException(msg); } if (currentPageObject != null) { // End the current page if necessary endPage(); } if (currentPageGroup != null) { // End the current page group if necessary endPageGroup(); } // Write out document if (document != null) { document.endDocument(); document.writeToStream(this.outputStream); } this.outputStream.flush(); this.complete = true; this.document = null; this.outputStream = null; }
// in src/java/org/apache/fop/afp/DataStream.java
public void endOverlay() throws IOException { if (currentOverlay != null) { currentOverlay.endPage(); currentOverlay = null; currentPage = currentPageObject; } }
// in src/java/org/apache/fop/afp/DataStream.java
public void endPage() throws IOException { if (currentPageObject != null) { currentPageObject.endPage(); if (currentPageGroup != null) { currentPageGroup.addPage(currentPageObject); currentPageGroup.writeToStream(this.outputStream); } else { document.addPage(currentPageObject); document.writeToStream(this.outputStream); } currentPageObject = null; currentPage = null; } }
// in src/java/org/apache/fop/afp/DataStream.java
public void createText(final AFPTextDataInfo textDataInfo, final int letterSpacing, final int wordSpacing, final Font font, final CharacterSet charSet) throws UnsupportedEncodingException { int rotation = paintingState.getRotation(); if (rotation != 0) { textDataInfo.setRotation(rotation); Point p = getPoint(textDataInfo.getX(), textDataInfo.getY()); textDataInfo.setX(p.x); textDataInfo.setY(p.y); } // use PtocaProducer to create PTX records PtocaProducer producer = new PtocaProducer() { public void produce(PtocaBuilder builder) throws IOException { builder.setTextOrientation(textDataInfo.getRotation()); builder.absoluteMoveBaseline(textDataInfo.getY()); builder.absoluteMoveInline(textDataInfo.getX()); builder.setExtendedTextColor(textDataInfo.getColor()); builder.setCodedFont((byte)textDataInfo.getFontReference()); int l = textDataInfo.getString().length(); StringBuffer sb = new StringBuffer(); int interCharacterAdjustment = 0; AFPUnitConverter unitConv = paintingState.getUnitConverter(); if (letterSpacing != 0) { interCharacterAdjustment = Math.round(unitConv.mpt2units(letterSpacing)); } builder.setInterCharacterAdjustment(interCharacterAdjustment); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int spacing = spaceWidth + letterSpacing; int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units(spacing)); int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement; if (wordSpacing != 0) { varSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + wordSpacing + letterSpacing)); } builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement); boolean fixedSpaceMode = false; for (int i = 0; i < l; i++) { char orgChar = textDataInfo.getString().charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( fixedSpaceCharacterIncrement); fixedSpaceMode = true; sb.append(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { if (fixedSpaceMode) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( varSpaceCharacterIncrement); fixedSpaceMode = false; } char ch; if (orgChar == CharUtilities.NBSPACE) { ch = ' '; //converted to normal space to allow word spacing } else { ch = orgChar; } sb.append(ch); } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } flushText(builder, sb, charSet); } private void flushText(PtocaBuilder builder, StringBuffer sb, final CharacterSet charSet) throws IOException { if (sb.length() > 0) { builder.addTransparentData(charSet.encodeChars(sb)); sb.setLength(0); } } }; currentPage.createText(producer); }
// in src/java/org/apache/fop/afp/DataStream.java
public void produce(PtocaBuilder builder) throws IOException { builder.setTextOrientation(textDataInfo.getRotation()); builder.absoluteMoveBaseline(textDataInfo.getY()); builder.absoluteMoveInline(textDataInfo.getX()); builder.setExtendedTextColor(textDataInfo.getColor()); builder.setCodedFont((byte)textDataInfo.getFontReference()); int l = textDataInfo.getString().length(); StringBuffer sb = new StringBuffer(); int interCharacterAdjustment = 0; AFPUnitConverter unitConv = paintingState.getUnitConverter(); if (letterSpacing != 0) { interCharacterAdjustment = Math.round(unitConv.mpt2units(letterSpacing)); } builder.setInterCharacterAdjustment(interCharacterAdjustment); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int spacing = spaceWidth + letterSpacing; int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units(spacing)); int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement; if (wordSpacing != 0) { varSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + wordSpacing + letterSpacing)); } builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement); boolean fixedSpaceMode = false; for (int i = 0; i < l; i++) { char orgChar = textDataInfo.getString().charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( fixedSpaceCharacterIncrement); fixedSpaceMode = true; sb.append(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { if (fixedSpaceMode) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( varSpaceCharacterIncrement); fixedSpaceMode = false; } char ch; if (orgChar == CharUtilities.NBSPACE) { ch = ' '; //converted to normal space to allow word spacing } else { ch = orgChar; } sb.append(ch); } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } flushText(builder, sb, charSet); }
// in src/java/org/apache/fop/afp/DataStream.java
private void flushText(PtocaBuilder builder, StringBuffer sb, final CharacterSet charSet) throws IOException { if (sb.length() > 0) { builder.addTransparentData(charSet.encodeChars(sb)); sb.setLength(0); } }
// in src/java/org/apache/fop/afp/DataStream.java
public void startDocument() throws IOException { this.document = factory.createDocument(); document.writeToStream(this.outputStream); }
// in src/java/org/apache/fop/afp/DataStream.java
public void startPageGroup() throws IOException { endPageGroup(); this.currentPageGroup = factory.createPageGroup(tleSequence); }
// in src/java/org/apache/fop/afp/DataStream.java
public void endPageGroup() throws IOException { if (currentPageGroup != null) { currentPageGroup.endPageGroup(); tleSequence = currentPageGroup.getTleSequence(); document.addPageGroup(currentPageGroup); currentPageGroup = null; } document.writeToStream(outputStream); //Flush objects }
// in src/java/org/apache/fop/afp/AFPDitheredRectanglePainter.java
public void paint(PaintingInfo paintInfo) throws IOException { RectanglePaintingInfo rectanglePaintInfo = (RectanglePaintingInfo)paintInfo; if (rectanglePaintInfo.getWidth() <= 0 || rectanglePaintInfo.getHeight() <= 0) { return; } int ditherMatrix = DitherUtil.DITHER_MATRIX_8X8; Dimension ditherSize = new Dimension(ditherMatrix, ditherMatrix); //Prepare an FS10 bi-level image AFPImageObjectInfo imageObjectInfo = new AFPImageObjectInfo(); imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS10); //imageObjectInfo.setCreatePageSegment(true); imageObjectInfo.getResourceInfo().setLevel(new AFPResourceLevel(AFPResourceLevel.INLINE)); imageObjectInfo.getResourceInfo().setImageDimension(ditherSize); imageObjectInfo.setBitsPerPixel(1); imageObjectInfo.setColor(false); //Note: the following may not be supported by older implementations imageObjectInfo.setMappingOption(MappingOptionTriplet.REPLICATE_AND_TRIM); //Dither image size int resolution = paintingState.getResolution(); ImageSize ditherBitmapSize = new ImageSize( ditherSize.width, ditherSize.height, resolution); imageObjectInfo.setDataHeightRes((int)Math.round( ditherBitmapSize.getDpiHorizontal() * 10)); imageObjectInfo.setDataWidthRes((int)Math.round( ditherBitmapSize.getDpiVertical() * 10)); imageObjectInfo.setDataWidth(ditherSize.width); imageObjectInfo.setDataHeight(ditherSize.height); //Create dither image Color col = paintingState.getColor(); byte[] dither = DitherUtil.getBayerDither(ditherMatrix, col, false); imageObjectInfo.setData(dither); //Positioning int rotation = paintingState.getRotation(); AffineTransform at = paintingState.getData().getTransform(); Point2D origin = at.transform(new Point2D.Float( rectanglePaintInfo.getX() * 1000, rectanglePaintInfo.getY() * 1000), null); AFPUnitConverter unitConv = paintingState.getUnitConverter(); float width = unitConv.pt2units(rectanglePaintInfo.getWidth()); float height = unitConv.pt2units(rectanglePaintInfo.getHeight()); AFPObjectAreaInfo objectAreaInfo = new AFPObjectAreaInfo( (int) Math.round(origin.getX()), (int) Math.round(origin.getY()), Math.round(width), Math.round(height), resolution, rotation); imageObjectInfo.setObjectAreaInfo(objectAreaInfo); //Create rectangle resourceManager.createObject(imageObjectInfo); }
// in src/java/org/apache/fop/afp/parser/MODCAParser.java
public UnparsedStructuredField readNextStructuredField() throws IOException { //Find the SF delimiter do { //Exhausted streams and so no next SF // - null return represents this case // TODO should this happen? if (din.available() == 0) { return null; } } while (din.readByte() != CARRIAGE_CONTROL_CHAR); //Read introducer as byte array to preserve any data not parsed below byte[] introducerData = new byte[INTRODUCER_LENGTH]; //Length of introducer din.readFully(introducerData); Introducer introducer = new Introducer(introducerData); int dataLength = introducer.getLength() - INTRODUCER_LENGTH; //Handle optional extension byte[] extData = null; if (introducer.isExtensionPresent()) { short extLength = 0; extLength = (short)((din.readByte()) & 0xFF); if (extLength > 0) { extData = new byte[extLength - 1]; din.readFully(extData); dataLength -= extLength; } } //Read payload byte[] data = new byte[dataLength]; din.readFully(data); UnparsedStructuredField sf = new UnparsedStructuredField(introducer, data, extData); if (LOG.isTraceEnabled()) { LOG.trace(sf); } return sf; }
// in src/java/org/apache/fop/afp/parser/UnparsedStructuredField.java
public void writeTo(OutputStream out) throws IOException { out.write(introducer.introducerData); if (isSfiExtensionPresent()) { out.write(this.extData.length + 1); out.write(this.extData); } out.write(this.data); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetCharacterSet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GSCS order code BinaryUtils.convert(fontReference)[0] }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsFullArc.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); // integer portion of multiplier data[6] = BinaryUtils.convert(mh, 1)[0]; // fractional portion of multiplier data[7] = BinaryUtils.convert(mhr, 1)[0]; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsCharacterString.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); byte[] strData = getStringAsBytes(); System.arraycopy(strData, 0, data, 6, strData.length); os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetFractionalLineWidth.java
public void writeToStream(OutputStream os) throws IOException { int integral = (int) multiplier; int fractional = (int) ((multiplier - (float) integral) * 256); byte[] data = new byte[] { getOrderCode(), // GSLW order code 0x02, // two bytes next (byte) integral, // integral line with (byte) fractional // and fractional }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetLineType.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GSLW order code type // line type }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetPatternSymbol.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GSPT order code pattern }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/AbstractGraphicsCoord.java
public void writeToStream(OutputStream os) throws IOException { os.write(getData()); }
// in src/java/org/apache/fop/afp/goca/GraphicsData.java
Override public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[9]; copySF(data, SF_CLASS, Type.DATA, Category.GRAPHICS); int dataLength = getDataLength(); byte[] len = BinaryUtils.convert(dataLength, 2); data[1] = len[0]; // Length byte 1 data[2] = len[1]; // Length byte 2 if (this.segmentedData) { data[6] |= 32; //Data is segmented } os.write(data); writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetLineWidth.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GSLW order code (byte) multiplier // MH (line-width) }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetProcessColor.java
public void writeToStream(OutputStream os) throws IOException { float[] colorComponents = color.getColorComponents(null); // COLSPCE byte colspace; ColorSpace cs = color.getColorSpace(); int colSpaceType = cs.getType(); ByteArrayOutputStream baout = new ByteArrayOutputStream(); byte[] colsizes; if (colSpaceType == ColorSpace.TYPE_CMYK) { colspace = CMYK; colsizes = new byte[] {0x08, 0x08, 0x08, 0x08}; for (int i = 0; i < colorComponents.length; i++) { baout.write(Math.round(colorComponents[i] * 255)); } } else if (colSpaceType == ColorSpace.TYPE_RGB) { colspace = RGB; colsizes = new byte[] {0x08, 0x08, 0x08, 0x00}; for (int i = 0; i < colorComponents.length; i++) { baout.write(Math.round(colorComponents[i] * 255)); } } else if (cs instanceof CIELabColorSpace) { colspace = CIELAB; colsizes = new byte[] {0x08, 0x08, 0x08, 0x00}; DataOutput dout = new java.io.DataOutputStream(baout); //According to GOCA, I'd expect the multiplicator below to be 255f, not 100f //But only IBM AFP Workbench seems to support Lab colors and it requires "c * 100f" int l = Math.round(colorComponents[0] * 100f); int a = Math.round(colorComponents[1] * 255f) - 128; int b = Math.round(colorComponents[2] * 255f) - 128; dout.writeByte(l); dout.writeByte(a); dout.writeByte(b); } else { throw new IllegalStateException(); } int len = getDataLength(); byte[] data = new byte[12]; data[0] = getOrderCode(); // GSPCOL order code data[1] = (byte) (len - 2); // LEN data[2] = 0x00; // reserved; must be zero data[3] = colspace; // COLSPCE data[4] = 0x00; // reserved; must be zero data[5] = 0x00; // reserved; must be zero data[6] = 0x00; // reserved; must be zero data[7] = 0x00; // reserved; must be zero data[8] = colsizes[0]; // COLSIZE(S) data[9] = colsizes[1]; data[10] = colsizes[2]; data[11] = colsizes[3]; os.write(data); baout.writeTo(os); }
// in src/java/org/apache/fop/afp/goca/GraphicsImage.java
public void writeToStream(OutputStream os) throws IOException { byte[] xcoord = BinaryUtils.convert(x, 2); byte[] ycoord = BinaryUtils.convert(y, 2); byte[] w = BinaryUtils.convert(width, 2); byte[] h = BinaryUtils.convert(height, 2); byte[] startData = new byte[] { getOrderCode(), // GBIMG order code (byte) 0x0A, // LENGTH xcoord[0], xcoord[1], ycoord[0], ycoord[1], 0x00, // FORMAT 0x00, // RES w[0], // WIDTH w[1], // h[0], // HEIGHT h[1] // }; os.write(startData); byte[] dataHeader = new byte[] { (byte) 0x92 // GIMD }; final int lengthOffset = 1; writeChunksToStream(imageData, dataHeader, lengthOffset, MAX_DATA_LEN, os); byte[] endData = new byte[] { (byte) 0x93, // GEIMG order code 0x00 // LENGTH }; os.write(endData); }
// in src/java/org/apache/fop/afp/goca/GraphicsBox.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = (byte)0x20; // CONTROL draw control flags data[3] = 0x00; // reserved os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsAreaEnd.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GEAR order code 0x00, // LENGTH }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsChainedSegment.java
Override public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[14]; data[0] = getOrderCode(); // BEGIN_SEGMENT data[1] = 0x0C; // Length of following parameters // segment name byte[] nameBytes = getNameBytes(); System.arraycopy(nameBytes, 0, data, 2, NAME_LENGTH); data[6] = 0x00; // FLAG1 (ignored) //FLAG2 data[7] |= this.appended ? APPEND_TO_EXISING : APPEND_NEW_SEGMENT; if (this.prologPresent) { data[7] |= PROLOG; } int dataLength = super.getDataLength(); byte[] len = BinaryUtils.convert(dataLength, 2); data[8] = len[0]; // SEGL data[9] = len[1]; // P/S NAME (predecessor name) if (predecessorNameBytes != null) { System.arraycopy(predecessorNameBytes, 0, data, 10, NAME_LENGTH); } os.write(data); writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/goca/GraphicsLine.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsAreaBegin.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GBAR order code (byte)(RES1 + (drawBoundary ? BOUNDARY : NO_BOUNDARY)) }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/AbstractGraphicsDrawingOrderContainer.java
protected void writeStart(OutputStream os) throws IOException { setStarted(true); }
// in src/java/org/apache/fop/afp/goca/AbstractGraphicsDrawingOrderContainer.java
protected void writeContent(OutputStream os) throws IOException { writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/goca/GraphicsEndProlog.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GEPROL order code 0x00, // Reserved }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetMix.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { 0x0C, // GSMX order code mode // MODE (mix mode value) }; os.write(data); }
// in src/java/org/apache/fop/afp/fonts/CharactersetEncoder.java
public void writeTo(OutputStream out, int offset, int length) throws IOException { if (offset < 0 || length < 0 || offset + length > bytes.length) { throw new IllegalArgumentException(); } out.write(bytes, this.offset + offset, length); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected InputStream openInputStream(ResourceAccessor accessor, String filename, AFPEventProducer eventProducer) throws IOException { URI uri; try { uri = new URI(filename.trim()); } catch (URISyntaxException e) { throw new FileNotFoundException("Invalid filename: " + filename + " (" + e.getMessage() + ")"); } if (LOG.isDebugEnabled()) { LOG.debug("Opening " + uri); } InputStream inputStream = accessor.createInputStream(uri); return inputStream; }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
public CharacterSet buildSBCS(String characterSetName, String codePageName, String encoding, ResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException { return processFont(characterSetName, codePageName, encoding, CharacterSetType.SINGLE_BYTE, accessor, eventProducer); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
public CharacterSet buildDBCS(String characterSetName, String codePageName, String encoding, CharacterSetType charsetType, ResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException { return processFont(characterSetName, codePageName, encoding, charsetType, accessor, eventProducer); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
public CharacterSet build(String characterSetName, String codePageName, String encoding, Typeface typeface, AFPEventProducer eventProducer) throws IOException { return new FopCharacterSet(codePageName, encoding, characterSetName, typeface, eventProducer); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
private CharacterSet processFont(String characterSetName, String codePageName, String encoding, CharacterSetType charsetType, ResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException { // check for cached version of the characterset String descriptor = characterSetName + "_" + encoding + "_" + codePageName; CharacterSet characterSet = (CharacterSet) characterSetsCache.get(descriptor); if (characterSet != null) { return characterSet; } // characterset not in the cache, so recreating characterSet = new CharacterSet(codePageName, encoding, charsetType, characterSetName, accessor, eventProducer); InputStream inputStream = null; try { /** * Get the code page which contains the character mapping * information to map the unicode character id to the graphic * chracter global identifier. */ Map<String, String> codePage; synchronized (codePagesCache) { codePage = codePagesCache.get(codePageName); if (codePage == null) { codePage = loadCodePage(codePageName, encoding, accessor, eventProducer); codePagesCache.put(codePageName, codePage); } } inputStream = openInputStream(accessor, characterSetName, eventProducer); StructuredFieldReader structuredFieldReader = new StructuredFieldReader(inputStream); // Process D3A689 Font Descriptor FontDescriptor fontDescriptor = processFontDescriptor(structuredFieldReader); characterSet.setNominalVerticalSize(fontDescriptor.getNominalFontSizeInMillipoints()); // Process D3A789 Font Control FontControl fontControl = processFontControl(structuredFieldReader); if (fontControl != null) { //process D3AE89 Font Orientation CharacterSetOrientation[] characterSetOrientations = processFontOrientation(structuredFieldReader); double metricNormalizationFactor; if (fontControl.isRelative()) { metricNormalizationFactor = 1; } else { int dpi = fontControl.getDpi(); metricNormalizationFactor = 1000.0d * 72000.0d / fontDescriptor.getNominalFontSizeInMillipoints() / dpi; } //process D3AC89 Font Position processFontPosition(structuredFieldReader, characterSetOrientations, metricNormalizationFactor); //process D38C89 Font Index (per orientation) for (int i = 0; i < characterSetOrientations.length; i++) { processFontIndex(structuredFieldReader, characterSetOrientations[i], codePage, metricNormalizationFactor); characterSet.addCharacterSetOrientation(characterSetOrientations[i]); } } else { throw new IOException("Missing D3AE89 Font Control structured field."); } } finally { closeInputStream(inputStream); } characterSetsCache.put(descriptor, characterSet); return characterSet; }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected Map<String, String> loadCodePage(String codePage, String encoding, ResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException { // Create the HashMap to store code page information Map<String, String> codePages = new HashMap<String, String>(); InputStream inputStream = null; try { inputStream = openInputStream(accessor, codePage.trim(), eventProducer); StructuredFieldReader structuredFieldReader = new StructuredFieldReader(inputStream); byte[] data = structuredFieldReader.getNext(CHARACTER_TABLE_SF); int position = 0; byte[] gcgiBytes = new byte[8]; byte[] charBytes = new byte[1]; // Read data, ignoring bytes 0 - 2 for (int index = 3; index < data.length; index++) { if (position < 8) { // Build the graphic character global identifier key gcgiBytes[position] = data[index]; position++; } else if (position == 9) { position = 0; // Set the character charBytes[0] = data[index]; String gcgiString = new String(gcgiBytes, AFPConstants.EBCIDIC_ENCODING); //Use the 8-bit char index to find the Unicode character using the Java encoding //given in the configuration. If the code page and the Java encoding don't //match, a wrong Unicode character will be associated with the AFP GCGID. //Idea: we could use IBM's GCGID to Unicode map and build code pages ourselves. String charString = new String(charBytes, encoding); codePages.put(gcgiString, charString); } else { position++; } } } catch (FileNotFoundException e) { eventProducer.codePageNotFound(this, e); } finally { closeInputStream(inputStream); } return codePages; }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected static FontDescriptor processFontDescriptor( StructuredFieldReader structuredFieldReader) throws IOException { byte[] fndData = structuredFieldReader.getNext(FONT_DESCRIPTOR_SF); return new FontDescriptor(fndData); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected FontControl processFontControl(StructuredFieldReader structuredFieldReader) throws IOException { byte[] fncData = structuredFieldReader.getNext(FONT_CONTROL_SF); FontControl fontControl = null; if (fncData != null) { fontControl = new FontControl(); if (fncData[7] == (byte) 0x02) { fontControl.setRelative(true); } int metricResolution = getUBIN(fncData, 9); if (metricResolution == 1000) { //Special case: 1000 units per em (rather than dpi) fontControl.setUnitsPerEm(1000); } else { fontControl.setDpi(metricResolution / 10); } } return fontControl; }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected CharacterSetOrientation[] processFontOrientation( StructuredFieldReader structuredFieldReader) throws IOException { byte[] data = structuredFieldReader.getNext(FONT_ORIENTATION_SF); int position = 0; byte[] fnoData = new byte[26]; List<CharacterSetOrientation> orientations = new ArrayList<CharacterSetOrientation>(); // Read data, ignoring bytes 0 - 2 for (int index = 3; index < data.length; index++) { // Build the font orientation record fnoData[position] = data[index]; position++; if (position == 26) { position = 0; int orientation = determineOrientation(fnoData[2]); // Space Increment int space = ((fnoData[8] & 0xFF ) << 8) + (fnoData[9] & 0xFF); // Em-Space Increment int em = ((fnoData[14] & 0xFF ) << 8) + (fnoData[15] & 0xFF); CharacterSetOrientation cso = new CharacterSetOrientation(orientation); cso.setSpaceIncrement(space); cso.setEmSpaceIncrement(em); orientations.add(cso); } } return orientations.toArray(EMPTY_CSO_ARRAY); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected void processFontPosition(StructuredFieldReader structuredFieldReader, CharacterSetOrientation[] characterSetOrientations, double metricNormalizationFactor) throws IOException { byte[] data = structuredFieldReader.getNext(FONT_POSITION_SF); int position = 0; byte[] fpData = new byte[26]; int characterSetOrientationIndex = 0; // Read data, ignoring bytes 0 - 2 for (int index = 3; index < data.length; index++) { if (position < 22) { // Build the font orientation record fpData[position] = data[index]; if (position == 9) { CharacterSetOrientation characterSetOrientation = characterSetOrientations[characterSetOrientationIndex]; int xHeight = getSBIN(fpData, 2); int capHeight = getSBIN(fpData, 4); int ascHeight = getSBIN(fpData, 6); int dscHeight = getSBIN(fpData, 8); dscHeight = dscHeight * -1; characterSetOrientation.setXHeight( (int)Math.round(xHeight * metricNormalizationFactor)); characterSetOrientation.setCapHeight( (int)Math.round(capHeight * metricNormalizationFactor)); characterSetOrientation.setAscender( (int)Math.round(ascHeight * metricNormalizationFactor)); characterSetOrientation.setDescender( (int)Math.round(dscHeight * metricNormalizationFactor)); } } else if (position == 22) { position = 0; characterSetOrientationIndex++; fpData[position] = data[index]; } position++; } }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected void processFontIndex(StructuredFieldReader structuredFieldReader, CharacterSetOrientation cso, Map<String, String> codepage, double metricNormalizationFactor) throws IOException { byte[] data = structuredFieldReader.getNext(FONT_INDEX_SF); int position = 0; byte[] gcgid = new byte[8]; byte[] fiData = new byte[20]; char lowest = 255; char highest = 0; String firstABCMismatch = null; // Read data, ignoring bytes 0 - 2 for (int index = 3; index < data.length; index++) { if (position < 8) { gcgid[position] = data[index]; position++; } else if (position < 27) { fiData[position - 8] = data[index]; position++; } else if (position == 27) { fiData[position - 8] = data[index]; position = 0; String gcgiString = new String(gcgid, AFPConstants.EBCIDIC_ENCODING); String idx = codepage.get(gcgiString); if (idx != null) { char cidx = idx.charAt(0); int width = getUBIN(fiData, 0); int a = getSBIN(fiData, 10); int b = getUBIN(fiData, 12); int c = getSBIN(fiData, 14); int abc = a + b + c; int diff = Math.abs(abc - width); if (diff != 0 && width != 0) { double diffPercent = 100 * diff / (double)width; if (diffPercent > 2) { if (LOG.isTraceEnabled()) { LOG.trace(gcgiString + ": " + a + " + " + b + " + " + c + " = " + (a + b + c) + " but found: " + width); } if (firstABCMismatch == null) { firstABCMismatch = gcgiString; } } } if (cidx < lowest) { lowest = cidx; } if (cidx > highest) { highest = cidx; } int normalizedWidth = (int)Math.round(width * metricNormalizationFactor); cso.setWidth(cidx, normalizedWidth); } } } cso.setFirstChar(lowest); cso.setLastChar(highest); if (LOG.isDebugEnabled() && firstABCMismatch != null) { //Debug level because it usually is no problem. LOG.debug("Font has metrics inconsitencies where A+B+C doesn't equal the" + " character increment. The first such character found: " + firstABCMismatch); } }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected Map<String, String> loadCodePage(String codePage, String encoding, ResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException { // Create the HashMap to store code page information Map<String, String> codePages = new HashMap<String, String>(); InputStream inputStream = null; try { inputStream = openInputStream(accessor, codePage.trim(), eventProducer); StructuredFieldReader structuredFieldReader = new StructuredFieldReader(inputStream); byte[] data; while ((data = structuredFieldReader.getNext(CHARACTER_TABLE_SF)) != null) { int position = 0; byte[] gcgiBytes = new byte[8]; byte[] charBytes = new byte[2]; // Read data, ignoring bytes 0 - 2 for (int index = 3; index < data.length; index++) { if (position < 8) { // Build the graphic character global identifier key gcgiBytes[position] = data[index]; position++; } else if (position == 9) { // Set the character charBytes[0] = data[index]; position++; } else if (position == 10) { position = 0; // Set the character charBytes[1] = data[index]; String gcgiString = new String(gcgiBytes, AFPConstants.EBCIDIC_ENCODING); String charString = new String(charBytes, encoding); codePages.put(gcgiString, charString); } else { position++; } } } } catch (FileNotFoundException e) { eventProducer.codePageNotFound(this, e); } finally { closeInputStream(inputStream); } return codePages; }
// in src/java/org/apache/fop/afp/AFPStreamer.java
public DataStream createDataStream(AFPPaintingState paintingState) throws IOException { this.tempFile = File.createTempFile(AFPDATASTREAM_TEMP_FILE_PREFIX, null); this.documentFile = new RandomAccessFile(tempFile, "rw"); this.documentOutputStream = new BufferedOutputStream( new FileOutputStream(documentFile.getFD())); this.dataStream = factory.createDataStream(paintingState, documentOutputStream); return dataStream; }
// in src/java/org/apache/fop/afp/AFPStreamer.java
public void close() throws IOException { Iterator it = pathResourceGroupMap.values().iterator(); while (it.hasNext()) { StreamedResourceGroup resourceGroup = (StreamedResourceGroup)it.next(); resourceGroup.close(); } // close any open print-file resource group if (printFileResourceGroup != null) { printFileResourceGroup.close(); } // write out document writeToStream(outputStream); outputStream.close(); if (documentOutputStream != null) { documentOutputStream.close(); } if (documentFile != null) { documentFile.close(); } // delete temporary file tempFile.delete(); }
// in src/java/org/apache/fop/afp/AFPStreamer.java
public void writeToStream(OutputStream os) throws IOException { // long start = System.currentTimeMillis(); int len = (int)documentFile.length(); int numChunks = len / BUFFER_SIZE; int remainingChunkSize = len % BUFFER_SIZE; byte[] buffer; documentFile.seek(0); if (numChunks > 0) { buffer = new byte[BUFFER_SIZE]; for (int i = 0; i < numChunks; i++) { documentFile.read(buffer, 0, BUFFER_SIZE); os.write(buffer, 0, BUFFER_SIZE); } } else { buffer = new byte[remainingChunkSize]; } if (remainingChunkSize > 0) { documentFile.read(buffer, 0, remainingChunkSize); os.write(buffer, 0, remainingChunkSize); } os.flush(); // long end = System.currentTimeMillis(); // log.debug("writing time " + (end - start) + "ms"); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public DataStream createDataStream(AFPPaintingState paintingState, OutputStream outputStream) throws IOException { this.dataStream = streamer.createDataStream(paintingState); streamer.setOutputStream(outputStream); return this.dataStream; }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void writeToStream() throws IOException { streamer.close(); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public boolean tryIncludeObject(AFPDataObjectInfo dataObjectInfo) throws IOException { AFPResourceInfo resourceInfo = dataObjectInfo.getResourceInfo(); updateResourceInfoUri(resourceInfo); String objectName = includeNameMap.get(resourceInfo); if (objectName != null) { // an existing data resource so reference it by adding an include to the current page includeObject(dataObjectInfo, objectName); return true; } objectName = pageSegmentMap.get(resourceInfo); if (objectName != null) { // an existing data resource so reference it by adding an include to the current page includePageSegment(dataObjectInfo, objectName); return true; } return false; }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void createObject(AFPDataObjectInfo dataObjectInfo) throws IOException { if (tryIncludeObject(dataObjectInfo)) { //Object has already been produced and is available by inclusion, so return early. return; } AbstractNamedAFPObject namedObj = null; AFPResourceInfo resourceInfo = dataObjectInfo.getResourceInfo(); boolean useInclude = true; Registry.ObjectType objectType = null; // new resource so create if (dataObjectInfo instanceof AFPImageObjectInfo) { AFPImageObjectInfo imageObjectInfo = (AFPImageObjectInfo)dataObjectInfo; namedObj = dataObjectFactory.createImage(imageObjectInfo); } else if (dataObjectInfo instanceof AFPGraphicsObjectInfo) { AFPGraphicsObjectInfo graphicsObjectInfo = (AFPGraphicsObjectInfo)dataObjectInfo; namedObj = dataObjectFactory.createGraphic(graphicsObjectInfo); } else { // natively embedded data object namedObj = dataObjectFactory.createObjectContainer(dataObjectInfo); objectType = dataObjectInfo.getObjectType(); useInclude = objectType != null && objectType.isIncludable(); } AFPResourceLevel resourceLevel = resourceInfo.getLevel(); ResourceGroup resourceGroup = streamer.getResourceGroup(resourceLevel); useInclude &= resourceGroup != null; if (useInclude) { boolean usePageSegment = dataObjectInfo.isCreatePageSegment(); // if it is to reside within a resource group at print-file or external level if (resourceLevel.isPrintFile() || resourceLevel.isExternal()) { if (usePageSegment) { String pageSegmentName = "S10" + namedObj.getName().substring(3); namedObj.setName(pageSegmentName); PageSegment seg = new PageSegment(pageSegmentName); seg.addObject(namedObj); namedObj = seg; } // wrap newly created data object in a resource object namedObj = dataObjectFactory.createResource(namedObj, resourceInfo, objectType); } // add data object into its resource group destination resourceGroup.addObject(namedObj); // create the include object String objectName = namedObj.getName(); if (usePageSegment) { includePageSegment(dataObjectInfo, objectName); pageSegmentMap.put(resourceInfo, objectName); } else { includeObject(dataObjectInfo, objectName); // record mapping of resource info to data object resource name includeNameMap.put(resourceInfo, objectName); } } else { // not to be included so inline data object directly into the current page dataStream.getCurrentPage().addObject(namedObj); } }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void embedFont(AFPFont afpFont, CharacterSet charSet) throws IOException { if (afpFont.isEmbeddable()) { //Embed fonts (char sets and code pages) if (charSet.getResourceAccessor() != null) { ResourceAccessor accessor = charSet.getResourceAccessor(); createIncludedResource( charSet.getName(), accessor, ResourceObject.TYPE_FONT_CHARACTER_SET); createIncludedResource( charSet.getCodePage(), accessor, ResourceObject.TYPE_CODE_PAGE); } } }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void createIncludedResource(String resourceName, ResourceAccessor accessor, byte resourceObjectType) throws IOException { URI uri; try { uri = new URI(resourceName.trim()); } catch (URISyntaxException e) { throw new IOException("Could not create URI from resource name: " + resourceName + " (" + e.getMessage() + ")"); } createIncludedResource(resourceName, uri, accessor, resourceObjectType); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void createIncludedResource(String resourceName, URI uri, ResourceAccessor accessor, byte resourceObjectType) throws IOException { AFPResourceLevel resourceLevel = new AFPResourceLevel(AFPResourceLevel.PRINT_FILE); AFPResourceInfo resourceInfo = new AFPResourceInfo(); resourceInfo.setLevel(resourceLevel); resourceInfo.setName(resourceName); resourceInfo.setUri(uri.toASCIIString()); String objectName = includeNameMap.get(resourceInfo); if (objectName == null) { if (log.isDebugEnabled()) { log.debug("Adding included resource: " + resourceName); } IncludedResourceObject resourceContent = new IncludedResourceObject( resourceName, accessor, uri); ResourceObject resourceObject = factory.createResource(resourceName); resourceObject.setDataObject(resourceContent); resourceObject.setType(resourceObjectType); ResourceGroup resourceGroup = streamer.getResourceGroup(resourceLevel); resourceGroup.addObject(resourceObject); // record mapping of resource info to data object resource name includeNameMap.put(resourceInfo, resourceName); } else { //skip, already created } }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void createIncludedResourceFromExternal(final String resourceName, final URI uri, final ResourceAccessor accessor) throws IOException { AFPResourceLevel resourceLevel = new AFPResourceLevel(AFPResourceLevel.PRINT_FILE); AFPResourceInfo resourceInfo = new AFPResourceInfo(); resourceInfo.setLevel(resourceLevel); resourceInfo.setName(resourceName); resourceInfo.setUri(uri.toASCIIString()); String resource = includeNameMap.get(resourceInfo); if (resource == null) { ResourceGroup resourceGroup = streamer.getResourceGroup(resourceLevel); //resourceObject delegates write commands to copyNamedResource() //The included resource may already be wrapped in a resource object AbstractNamedAFPObject resourceObject = new AbstractNamedAFPObject(null) { @Override protected void writeContent(OutputStream os) throws IOException { InputStream inputStream = null; try { inputStream = accessor.createInputStream(uri); BufferedInputStream bin = new BufferedInputStream(inputStream); AFPResourceUtil.copyNamedResource(resourceName, bin, os); } finally { IOUtils.closeQuietly(inputStream); } } //bypass super.writeStart @Override protected void writeStart(OutputStream os) throws IOException { } //bypass super.writeEnd @Override protected void writeEnd(OutputStream os) throws IOException { } }; resourceGroup.addObject(resourceObject); includeNameMap.put(resourceInfo, resourceName); } }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
Override protected void writeContent(OutputStream os) throws IOException { InputStream inputStream = null; try { inputStream = accessor.createInputStream(uri); BufferedInputStream bin = new BufferedInputStream(inputStream); AFPResourceUtil.copyNamedResource(resourceName, bin, os); } finally { IOUtils.closeQuietly(inputStream); } }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
Override protected void writeStart(OutputStream os) throws IOException { }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
Override protected void writeEnd(OutputStream os) throws IOException { }
// in src/java/org/apache/fop/afp/modca/MapImageObject.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[11]; copySF(data, Type.MAP, Category.IMAGE); int tripletLen = getTripletDataLength(); byte[] len = BinaryUtils.convert(10 + tripletLen, 2); data[1] = len[0]; data[2] = len[1]; len = BinaryUtils.convert(2 + tripletLen, 2); data[9] = len[0]; data[10] = len[1]; os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/MapPageSegment.java
public void writeToStream(OutputStream os) throws IOException { int count = getPageSegments().size(); byte groupLength = 0x0C; int groupsLength = count * groupLength; byte[] data = new byte[groupsLength + 12 + 1]; data[0] = 0x5A; // Set the total record length byte[] rl1 = BinaryUtils.convert(data.length - 1, 2); //Ignore the // first byte in // the length data[1] = rl1[0]; data[2] = rl1[1]; // Structured field ID for a MPS data[3] = (byte) 0xD3; data[4] = Type.MIGRATION; data[5] = Category.PAGE_SEGMENT; data[6] = 0x00; // Flags data[7] = 0x00; // Reserved data[8] = 0x00; // Reserved data[9] = groupLength; data[10] = 0x00; // Reserved data[11] = 0x00; // Reserved data[12] = 0x00; // Reserved int pos = 13; Iterator iter = this.pageSegments.iterator(); while (iter.hasNext()) { pos += 4; String name = (String)iter.next(); try { byte[] nameBytes = name.getBytes(AFPConstants.EBCIDIC_ENCODING); System.arraycopy(nameBytes, 0, data, pos, nameBytes.length); } catch (UnsupportedEncodingException usee) { LOG.error("UnsupportedEncodingException translating the name " + name); } pos += 8; } os.write(data); }
// in src/java/org/apache/fop/afp/modca/InvokeMediumMap.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.MAP, Category.MEDIUM_MAP); // Set the total record length byte[] len = BinaryUtils.convert(16, 2); //Ignore first byte data[1] = len[0]; data[2] = len[1]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/StreamedResourceGroup.java
public void addObject(AbstractNamedAFPObject namedObject) throws IOException { if (!started) { writeStart(os); started = true; } try { namedObject.writeToStream(os); } finally { os.flush(); } }
// in src/java/org/apache/fop/afp/modca/StreamedResourceGroup.java
public void close() throws IOException { writeEnd(os); complete = true; }
// in src/java/org/apache/fop/afp/modca/GraphicsObject.java
Override protected void writeStart(OutputStream os) throws IOException { super.writeStart(os); byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.GRAPHICS); os.write(data); }
// in src/java/org/apache/fop/afp/modca/GraphicsObject.java
Override protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/modca/GraphicsObject.java
Override protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.GRAPHICS); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PreprocessPresentationObject.java
public void writeStart(OutputStream os) throws IOException { super.writeStart(os); byte[] data = new byte[9]; copySF(data, Type.PROCESS, Category.DATA_RESOURCE); byte[] l = BinaryUtils.convert(19 + getTripletDataLength(), 2); data[1] = l[0]; // Length byte 1 data[2] = l[1]; // Length byte 1 os.write(data); }
// in src/java/org/apache/fop/afp/modca/PreprocessPresentationObject.java
public void writeContent(OutputStream os) throws IOException { byte[] data = new byte[12]; byte[] l = BinaryUtils.convert(12 + getTripletDataLength(), 2); data[0] = l[0]; // RGLength data[1] = l[1]; // RGLength data[2] = objType; // ObjType data[3] = 0x00; // Reserved data[4] = 0x00; // Reserved data[5] = objOrent; // ObjOrent if (objXOffset > 0) { byte[] xOff = BinaryUtils.convert(objYOffset, 3); data[6] = xOff[0]; // XocaOset (not specified) data[7] = xOff[1]; // XocaOset data[8] = xOff[2]; // XocaOset } else { data[6] = (byte)0xFF; // XocaOset (not specified) data[7] = (byte)0xFF; // XocaOset data[8] = (byte)0xFF; // XocaOset } if (objYOffset > 0) { byte[] yOff = BinaryUtils.convert(objYOffset, 3); data[9] = yOff[0]; // YocaOset (not specified) data[10] = yOff[1]; // YocaOset data[11] = yOff[2]; // YocaOset } else { data[9] = (byte)0xFF; // YocaOset (not specified) data[10] = (byte)0xFF; // YocaOset data[11] = (byte)0xFF; // YocaOset } os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/ResourceObject.java
protected void writeStart(OutputStream os) throws IOException { super.writeStart(os); byte[] data = new byte[19]; copySF(data, Type.BEGIN, Category.NAME_RESOURCE); // Set the total record length int tripletDataLength = getTripletDataLength(); byte[] len = BinaryUtils.convert(18 + tripletDataLength, 2); data[1] = len[0]; // Length byte 1 data[2] = len[1]; // Length byte 2 // Set reserved bits data[17] = 0x00; // Reserved data[18] = 0x00; // Reserved os.write(data); // Write triplets writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/ResourceObject.java
protected void writeContent(OutputStream os) throws IOException { if (namedObject != null) { namedObject.writeToStream(os); } }
// in src/java/org/apache/fop/afp/modca/ResourceObject.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.NAME_RESOURCE); os.write(data); }
// in src/java/org/apache/fop/afp/modca/IMImageObject.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); if (imageOutputControl != null) { imageOutputControl.writeToStream(os); } if (imageInputDescriptor != null) { imageInputDescriptor.writeToStream(os); } if (imageCellPosition != null) { imageCellPosition.writeToStream(os); } if (imageRasterData != null) { imageRasterData.writeToStream(os); } }
// in src/java/org/apache/fop/afp/modca/IMImageObject.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.IM_IMAGE); os.write(data); }
// in src/java/org/apache/fop/afp/modca/IMImageObject.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.IM_IMAGE); os.write(data); }
// in src/java/org/apache/fop/afp/modca/IncludePageSegment.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[23]; //(9 +14) copySF(data, Type.INCLUDE, Category.PAGE_SEGMENT); // Set the total record length byte[] len = BinaryUtils.convert(22, 2); //Ignore first byte data[1] = len[0]; data[2] = len[1]; byte[] xPos = BinaryUtils.convert(x, 3); data[17] = xPos[0]; // x coordinate data[18] = xPos[1]; data[19] = xPos[2]; byte[] yPos = BinaryUtils.convert(y, 3); data[20] = yPos[0]; // y coordinate data[21] = yPos[1]; data[22] = yPos[2]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/MapContainerData.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[11]; copySF(data, Type.MAP, Category.OBJECT_CONTAINER); int tripletLen = getTripletDataLength(); byte[] len = BinaryUtils.convert(10 + tripletLen, 2); data[1] = len[0]; data[2] = len[1]; len = BinaryUtils.convert(2 + tripletLen, 2); data[9] = len[0]; data[10] = len[1]; os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/TagLogicalElement.java
public void writeToStream(OutputStream os) throws IOException { setFullyQualifiedName( FullyQualifiedNameTriplet.TYPE_ATTRIBUTE_GID, FullyQualifiedNameTriplet.FORMAT_CHARSTR, name); setAttributeValue(value); setAttributeQualifier(tleID, 1); byte[] data = new byte[SF_HEADER_LENGTH]; copySF(data, Type.ATTRIBUTE, Category.PROCESS_ELEMENT); int tripletDataLength = getTripletDataLength(); byte[] l = BinaryUtils.convert(data.length + tripletDataLength - 1, 2); data[1] = l[0]; data[2] = l[1]; os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/PresentationEnvironmentControl.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[11]; copySF(data, Type.CONTROL, Category.DOCUMENT); int tripletDataLen = getTripletDataLength(); byte[] len = BinaryUtils.convert(10 + tripletDataLen); data[1] = len[0]; data[2] = len[1]; data[9] = 0x00; // Reserved; must be zero data[10] = 0x00; // Reserved; must be zero os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/ResourceGroup.java
public void addObject(AbstractNamedAFPObject namedObject) throws IOException { resourceSet.add(namedObject); }
// in src/java/org/apache/fop/afp/modca/ResourceGroup.java
public void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.RESOURCE_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ResourceGroup.java
public void writeContent(OutputStream os) throws IOException { Iterator it = resourceSet.iterator(); while (it.hasNext()) { Object object = it.next(); if (object instanceof Streamable) { Streamable streamableObject = (Streamable)object; streamableObject.writeToStream(os); } } }
// in src/java/org/apache/fop/afp/modca/ResourceGroup.java
public void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.RESOURCE_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.PRESENTATION_TEXT); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
protected void writeContent(OutputStream os) throws IOException { writeObjects(this.presentationTextDataList, os); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.PRESENTATION_TEXT); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ObjectEnvironmentGroup.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.OBJECT_ENVIRONMENT_GROUP); int tripletDataLength = getTripletDataLength(); int sfLen = data.length + tripletDataLength - 1; byte[] len = BinaryUtils.convert(sfLen, 2); data[1] = len[0]; data[2] = len[1]; os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/ObjectEnvironmentGroup.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); if (presentationEnvironmentControl != null) { presentationEnvironmentControl.writeToStream(os); } if (objectAreaDescriptor != null) { objectAreaDescriptor.writeToStream(os); } if (objectAreaPosition != null) { objectAreaPosition.writeToStream(os); } if (mapImageObject != null) { mapImageObject.writeToStream(os); } if (mapContainerData != null) { mapContainerData.writeToStream(os); } if (mapDataResource != null) { mapDataResource.writeToStream(os); } if (dataDescriptor != null) { dataDescriptor.writeToStream(os); } }
// in src/java/org/apache/fop/afp/modca/ObjectEnvironmentGroup.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.OBJECT_ENVIRONMENT_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/IncludeObject.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[36]; super.copySF(data, Type.INCLUDE, Category.DATA_RESOURCE); // Set the total record length int tripletDataLength = getTripletDataLength(); byte[] len = BinaryUtils.convert(35 + tripletDataLength, 2); //Ignore first byte data[1] = len[0]; data[2] = len[1]; data[17] = 0x00; // reserved data[18] = objectType; writeOsetTo(data, 19, xoaOset); writeOsetTo(data, 22, yoaOset); oaOrent.writeTo(data, 25); writeOsetTo(data, 29, xocaOset); writeOsetTo(data, 32, yocaOset); // RefCSys (Reference coordinate system) data[35] = 0x01; // Page or overlay coordinate system // Write structured field data os.write(data); // Write triplet for FQN internal/external object reference writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/ImageObject.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.IMAGE); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ImageObject.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); if (imageSegment != null) { final byte[] dataHeader = new byte[9]; copySF(dataHeader, SF_CLASS, Type.DATA, Category.IMAGE); final int lengthOffset = 1; // TODO save memory! ByteArrayOutputStream baos = new ByteArrayOutputStream(); imageSegment.writeToStream(baos); byte[] data = baos.toByteArray(); writeChunksToStream(data, dataHeader, lengthOffset, MAX_DATA_LEN, os); } }
// in src/java/org/apache/fop/afp/modca/ImageObject.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.IMAGE); os.write(data); }
// in src/java/org/apache/fop/afp/modca/GraphicsDataDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] headerData = new byte[9]; copySF(headerData, Type.DESCRIPTOR, Category.GRAPHICS); byte[] drawingOrderSubsetData = getDrawingOrderSubset(); byte[] windowSpecificationData = getWindowSpecification(); byte[] len = BinaryUtils.convert(headerData.length + drawingOrderSubsetData.length + windowSpecificationData.length - 1, 2); headerData[1] = len[0]; headerData[2] = len[1]; os.write(headerData); os.write(drawingOrderSubsetData); os.write(windowSpecificationData); }
// in src/java/org/apache/fop/afp/modca/ObjectAreaDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[9]; copySF(data, Type.DESCRIPTOR, Category.OBJECT_AREA); addTriplet(new DescriptorPositionTriplet(OBJECT_AREA_POSITION_ID)); addTriplet(new MeasurementUnitsTriplet(widthRes, heightRes)); addTriplet(new ObjectAreaSizeTriplet(width, height)); /* not allowed in Presentation Interchange Set 1 addTriplet(new PresentationSpaceResetMixingTriplet( PresentationSpaceResetMixingTriplet.NOT_RESET)); */ int tripletDataLength = getTripletDataLength(); byte[] len = BinaryUtils.convert(data.length + tripletDataLength - 1, 2); data[1] = len[0]; // Length data[2] = len[1]; os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/ImageDataDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[22]; copySF(data, Type.DESCRIPTOR, Category.IMAGE); // SF length byte[] len = BinaryUtils.convert(data.length - 1, 2); data[1] = len[0]; data[2] = len[1]; byte[] x = BinaryUtils.convert(widthRes, 2); data[10] = x[0]; data[11] = x[1]; byte[] y = BinaryUtils.convert(heightRes, 2); data[12] = y[0]; data[13] = y[1]; byte[] w = BinaryUtils.convert(width, 2); data[14] = w[0]; data[15] = w[1]; byte[] h = BinaryUtils.convert(height, 2); data[16] = h[0]; data[17] = h[1]; //IOCA Function Set Field data[18] = (byte)0xF7; // ID = Set IOCA Function Set data[19] = 0x02; // Length data[20] = 0x01; // Category = Function set identifier data[21] = functionSet; os.write(data); }
// in src/java/org/apache/fop/afp/modca/ResourceEnvironmentGroup.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.RESOURCE_ENVIROMENT_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ResourceEnvironmentGroup.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.RESOURCE_ENVIROMENT_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ResourceEnvironmentGroup.java
protected void writeContent(OutputStream os) throws IOException { writeObjects(mapDataResources, os); writeObjects(mapPageOverlays, os); writeObjects(preProcessPresentationObjects, os); }
// in src/java/org/apache/fop/afp/modca/AbstractResourceEnvironmentGroupContainer.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); if (resourceEnvironmentGroup != null) { resourceEnvironmentGroup.writeToStream(os); } }
// in src/java/org/apache/fop/afp/modca/AxisOrientation.java
public void writeTo(OutputStream stream) throws IOException { byte[] data = new byte[4]; writeTo(data, 0); stream.write(data); }
// in src/java/org/apache/fop/afp/modca/Document.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.DOCUMENT); os.write(data); }
// in src/java/org/apache/fop/afp/modca/Document.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.DOCUMENT); os.write(data); }
// in src/java/org/apache/fop/afp/modca/AbstractResourceGroupContainer.java
Override public void writeToStream(OutputStream os) throws IOException { if (!started) { writeStart(os); started = true; } writeContent(os); if (complete) { writeEnd(os); } }
// in src/java/org/apache/fop/afp/modca/AbstractResourceGroupContainer.java
Override protected void writeObjects(Collection/*<AbstractAFPObject>*/ objects, OutputStream os) throws IOException { writeObjects(objects, os, false); }
// in src/java/org/apache/fop/afp/modca/AbstractResourceGroupContainer.java
protected void writeObjects(Collection/*<AbstractAFPObject>*/ objects, OutputStream os, boolean forceWrite) throws IOException { if (objects != null && objects.size() > 0) { Iterator it = objects.iterator(); while (it.hasNext()) { AbstractAFPObject ao = (AbstractAFPObject)it.next(); if (forceWrite || canWrite(ao)) { ao.writeToStream(os); it.remove(); } else { break; } } } }
// in src/java/org/apache/fop/afp/modca/ContainerDataDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[21]; copySF(data, Type.DESCRIPTOR, Category.OBJECT_CONTAINER); // SF length byte[] len = BinaryUtils.convert(data.length - 1, 2); data[1] = len[0]; data[2] = len[1]; // XocBase = 10 inches data[9] = 0x00; // YocBase = 10 inches data[10] = 0x00; // XocUnits byte[] xdpi = BinaryUtils.convert(widthRes * 10, 2); data[11] = xdpi[0]; data[12] = xdpi[1]; // YocUnits byte[] ydpi = BinaryUtils.convert(heightRes * 10, 2); data[13] = ydpi[0]; data[14] = ydpi[1]; // XocSize byte[] xsize = BinaryUtils.convert(width, 3); data[15] = xsize[0]; data[16] = xsize[1]; data[17] = xsize[2]; // YocSize byte[] ysize = BinaryUtils.convert(height, 3); data[18] = ysize[0]; data[19] = ysize[1]; data[20] = ysize[2]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/AbstractDataObject.java
protected void writeStart(OutputStream os) throws IOException { setStarted(true); }
// in src/java/org/apache/fop/afp/modca/AbstractDataObject.java
protected void writeContent(OutputStream os) throws IOException { writeTriplets(os); if (objectEnvironmentGroup != null) { objectEnvironmentGroup.writeToStream(os); } }
// in src/java/org/apache/fop/afp/modca/PresentationTextDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[23]; copySF(data, Type.MIGRATION, Category.PRESENTATION_TEXT); data[1] = 0x00; // length data[2] = 0x16; data[9] = 0x00; data[10] = 0x00; byte[] xdpi = BinaryUtils.convert(widthRes * 10, 2); data[11] = xdpi[0]; // xdpi data[12] = xdpi[1]; byte[] ydpi = BinaryUtils.convert(heightRes * 10, 2); data[13] = ydpi[0]; // ydpi data[14] = ydpi[1]; byte[] x = BinaryUtils.convert(width, 3); data[15] = x[0]; data[16] = x[1]; data[17] = x[2]; byte[] y = BinaryUtils.convert(height, 3); data[18] = y[0]; data[19] = y[1]; data[20] = y[2]; data[21] = 0x00; data[22] = 0x00; os.write(data); }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
public void writeContent(OutputStream os) throws IOException { super.writeTriplets(os); writeObjects(mapCodedFonts, os); writeObjects(mapDataResources, os); writeObjects(mapPageOverlays, os); writeObjects(mapPageSegments, os); if (pageDescriptor != null) { pageDescriptor.writeToStream(os); } if (objectAreaDescriptor != null && objectAreaPosition != null) { objectAreaDescriptor.writeToStream(os); objectAreaPosition.writeToStream(os); } if (presentationTextDataDescriptor != null) { presentationTextDataDescriptor.writeToStream(os); } }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.ACTIVE_ENVIRONMENT_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.ACTIVE_ENVIRONMENT_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/Overlay.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.OVERLAY); os.write(data); }
// in src/java/org/apache/fop/afp/modca/Overlay.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); getActiveEnvironmentGroup().writeToStream(os); writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/modca/Overlay.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.OVERLAY); os.write(data); }
// in src/java/org/apache/fop/afp/modca/IncludePageOverlay.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[25]; //(9 +16) copySF(data, Type.INCLUDE, Category.PAGE_OVERLAY); // Set the total record length byte[] len = BinaryUtils.convert(24, 2); //Ignore first byte data[1] = len[0]; data[2] = len[1]; byte[] xPos = BinaryUtils.convert(x, 3); data[17] = xPos[0]; // x coordinate data[18] = xPos[1]; data[19] = xPos[2]; byte[] yPos = BinaryUtils.convert(y, 3); data[20] = yPos[0]; // y coordinate data[21] = yPos[1]; data[22] = yPos[2]; switch (orientation) { case 90: data[23] = 0x2D; data[24] = 0x00; break; case 180: data[23] = 0x5A; data[24] = 0x00; break; case 270: data[23] = (byte) 0x87; data[24] = 0x00; break; default: data[23] = 0x00; data[24] = 0x00; break; } os.write(data); }
// in src/java/org/apache/fop/afp/modca/IncludedResourceObject.java
public void writeToStream(OutputStream os) throws IOException { InputStream in = resourceAccessor.createInputStream(this.uri); try { AFPResourceUtil.copyResourceFile(in, os); } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/afp/modca/AbstractPageObject.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); writeObjects(this.objects, os); }
// in src/java/org/apache/fop/afp/modca/AbstractTripletStructuredObject.java
protected void writeTriplets(OutputStream os) throws IOException { if (hasTriplets()) { writeObjects(triplets, os); triplets = null; // gc } }
// in src/java/org/apache/fop/afp/modca/PresentationTextData.java
public void writeToStream(OutputStream os) throws IOException { assert getBytesAvailable() >= 0; byte[] data = baos.toByteArray(); byte[] size = BinaryUtils.convert(data.length - 1, 2); data[1] = size[0]; data[2] = size[1]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/NoOperation.java
public void writeToStream(OutputStream os) throws IOException { byte[] contentData = content.getBytes(AFPConstants.EBCIDIC_ENCODING); int contentLen = contentData.length; // packet maximum of 32759 bytes if (contentLen > MAX_DATA_LEN) { contentLen = MAX_DATA_LEN; } byte[] data = new byte[9 + contentLen]; data[0] = 0x5A; // Set the total record length byte[] rl1 = BinaryUtils.convert(8 + contentLen, 2); //Ignore first byte data[1] = rl1[0]; data[2] = rl1[1]; // Structured field ID for a NOP data[3] = (byte) 0xD3; data[4] = (byte) 0xEE; data[5] = (byte) 0xEE; data[6] = 0x00; // Reserved data[7] = 0x00; // Reserved data[8] = 0x00; // Reserved int pos = 9; for (int i = 0; i < contentLen; i++) { data[pos++] = contentData[i]; } os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/MeasurementUnitsTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = TEN_INCHES; // XoaBase data[3] = TEN_INCHES; // YoaBase byte[] xUnits = BinaryUtils.convert(xRes * 10, 2); data[4] = xUnits[0]; // XoaUnits (x units per unit base) data[5] = xUnits[1]; byte[] yUnits = BinaryUtils.convert(yRes * 10, 2); data[6] = yUnits[0]; // YoaUnits (y units per unit base) data[7] = yUnits[1]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/AttributeValueTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = super.getData(); data[2] = 0x00; // Reserved data[3] = 0x00; // Reserved // convert name and value to ebcdic byte[] tleByteValue = null; try { tleByteValue = attVal.getBytes(AFPConstants.EBCIDIC_ENCODING); } catch (UnsupportedEncodingException usee) { tleByteValue = attVal.getBytes(); throw new IllegalArgumentException(attVal + " encoding failed"); } System.arraycopy(tleByteValue, 0, data, 4, tleByteValue.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/ObjectAreaSizeTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = type; // SizeType byte[] xOASize = BinaryUtils.convert(x, 3); data[3] = xOASize[0]; // XoaSize - Object area extent for X axis data[4] = xOASize[1]; data[5] = xOASize[2]; byte[] yOASize = BinaryUtils.convert(y, 3); data[6] = yOASize[0]; // YoaSize - Object area extent for Y axis data[7] = yOASize[1]; data[8] = yOASize[2]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/CommentTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); byte[] strData = commentString.getBytes(AFPConstants.EBCIDIC_ENCODING); System.arraycopy(strData, 0, data, 2, strData.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/DescriptorPositionTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = oapId; os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/ResourceObjectTypeTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = objectType; os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/ObjectByteExtentTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); byte[] extData = BinaryUtils.convert(byteExt, 4); System.arraycopy(extData, 0, data, 2, extData.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/ObjectClassificationTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = 0x00; // reserved (must be zero) data[3] = objectClass; // ObjClass data[4] = 0x00; // reserved (must be zero) data[5] = 0x00; // reserved (must be zero) // StrucFlgs - Information on the structure of the object container byte[] structureFlagsBytes = getStructureFlagsAsBytes(dataInContainer, containerHasOEG, dataInOCD); data[6] = structureFlagsBytes[0]; data[7] = structureFlagsBytes[1]; byte[] objectIdBytes = objectType.getOID(); // RegObjId - MOD:CA-registered ASN.1 OID for object type (8-23) System.arraycopy(objectIdBytes, 0, data, 8, objectIdBytes.length); // ObjTpName - name of object type (24-55) byte[] objectTypeNameBytes; objectTypeNameBytes = StringUtils.rpad(objectType.getName(), ' ', OBJECT_TYPE_NAME_LEN).getBytes( AFPConstants.EBCIDIC_ENCODING); System.arraycopy(objectTypeNameBytes, 0, data, 24, objectTypeNameBytes.length); // ObjLev - release level or version number of object type (56-63) byte[] objectLevelBytes; objectLevelBytes = StringUtils.rpad(objectLevel, ' ', OBJECT_LEVEL_LEN).getBytes( AFPConstants.EBCIDIC_ENCODING); System.arraycopy(objectLevelBytes, 0, data, 56, objectLevelBytes.length); // CompName - name of company or organization that owns object definition (64-95) byte[] companyNameBytes; companyNameBytes = StringUtils.rpad(companyName, ' ', COMPANY_NAME_LEN).getBytes( AFPConstants.EBCIDIC_ENCODING); System.arraycopy(companyNameBytes, 0, data, 64, companyNameBytes.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/PresentationSpaceMixingRulesTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); System.arraycopy(rules, 0, data, 2, rules.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/MappingOptionTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = mapValue; os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/PresentationSpaceResetMixingTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = backgroundMixFlag; os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/AttributeQualifierTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); byte[] id = BinaryUtils.convert(seqNumber, 4); System.arraycopy(id, 0, data, 2, id.length); byte[] level = BinaryUtils.convert(levNumber, 4); System.arraycopy(level, 0, data, 6, level.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/ExtendedResourceLocalIdentifierTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = type; byte[] resLID = BinaryUtils.convert(localId, 4); // 4 bytes System.arraycopy(resLID, 0, data, 3, resLID.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/FullyQualifiedNameTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = type; data[3] = format; // FQName byte[] fqNameBytes; String encoding = AFPConstants.EBCIDIC_ENCODING; if (format == FORMAT_URL) { encoding = AFPConstants.US_ASCII_ENCODING; } try { fqNameBytes = fqName.getBytes(encoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( encoding + " encoding failed"); } System.arraycopy(fqNameBytes, 0, data, 4, fqNameBytes.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PageDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[24]; copySF(data, Type.DESCRIPTOR, Category.PAGE); data[2] = 0x17; // XpgBase data[9] = 0x00; // XpgBase = 10 inches // YpgBase data[10] = 0x00; // YpgBase = 10 inches // XpgUnits byte[] xdpi = BinaryUtils.convert(widthRes * 10, 2); data[11] = xdpi[0]; data[12] = xdpi[1]; // YpgUnits byte[] ydpi = BinaryUtils.convert(heightRes * 10, 2); data[13] = ydpi[0]; data[14] = ydpi[1]; // XpgSize byte[] x = BinaryUtils.convert(width, 3); data[15] = x[0]; data[16] = x[1]; data[17] = x[2]; // YpgSize byte[] y = BinaryUtils.convert(height, 3); data[18] = y[0]; data[19] = y[1]; data[20] = y[2]; data[21] = 0x00; // Reserved data[22] = 0x00; // Reserved data[23] = 0x00; // Reserved os.write(data); }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
public void writeToStream(OutputStream os) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] startData = new byte[9]; copySF(startData, Type.MAP, Category.CODED_FONT); baos.write(startData); Iterator iter = fontList.iterator(); while (iter.hasNext()) { FontDefinition fd = (FontDefinition) iter.next(); // Start of repeating groups (occurs 1 to 254) baos.write(0x00); if (fd.scale == 0) { // Raster Font baos.write(0x22); // Length of 34 } else { // Outline Font baos.write(0x3A); // Length of 58 } // Font Character Set Name Reference baos.write(0x0C); //TODO Relax requirement for 8 chars in the name baos.write(0x02); baos.write((byte) 0x86); baos.write(0x00); baos.write(fd.characterSet); // Font Code Page Name Reference baos.write(0x0C); //TODO Relax requirement for 8 chars in the name baos.write(0x02); baos.write((byte) 0x85); baos.write(0x00); baos.write(fd.codePage); //TODO idea: for CIDKeyed fonts, maybe hint at Unicode encoding with X'50' triplet //to allow font substitution. // Character Rotation baos.write(0x04); baos.write(0x26); baos.write(fd.orientation); baos.write(0x00); // Resource Local Identifier baos.write(0x04); baos.write(0x24); baos.write(0x05); baos.write(fd.fontReferenceKey); if (fd.scale != 0) { // Outline Font (triplet '1F') baos.write(0x14); baos.write(0x1F); baos.write(0x00); baos.write(0x00); baos.write(BinaryUtils.convert(fd.scale, 2)); // Height baos.write(new byte[] {0x00, 0x00}); // Width baos.write(new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); baos.write(0x60); // Outline Font (triplet '5D') baos.write(0x04); baos.write(0x5D); baos.write(BinaryUtils.convert(fd.scale, 2)); } } byte[] data = baos.toByteArray(); // Set the total record length byte[] rl1 = BinaryUtils.convert(data.length - 1, 2); data[1] = rl1[0]; data[2] = rl1[1]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); }
// in src/java/org/apache/fop/afp/modca/ObjectContainer.java
protected void writeStart(OutputStream os) throws IOException { byte[] headerData = new byte[17]; copySF(headerData, Type.BEGIN, Category.OBJECT_CONTAINER); // Set the total record length int containerLen = headerData.length + getTripletDataLength() - 1; byte[] len = BinaryUtils.convert(containerLen, 2); headerData[1] = len[0]; // Length byte 1 headerData[2] = len[1]; // Length byte 2 os.write(headerData); }
// in src/java/org/apache/fop/afp/modca/ObjectContainer.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); // write triplets and OEG // write OCDs byte[] dataHeader = new byte[9]; copySF(dataHeader, SF_CLASS, Type.DATA, Category.OBJECT_CONTAINER); final int lengthOffset = 1; if (data != null) { writeChunksToStream(data, dataHeader, lengthOffset, MAX_DATA_LEN, os); } }
// in src/java/org/apache/fop/afp/modca/ObjectContainer.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.OBJECT_CONTAINER); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PageGroup.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.PAGE_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PageGroup.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.PAGE_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ObjectAreaPosition.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[33]; copySF(data, Type.POSITION, Category.OBJECT_AREA); byte[] len = BinaryUtils.convert(32, 2); data[1] = len[0]; // Length data[2] = len[1]; data[9] = 0x01; // OAPosID = 1 data[10] = 0x17; // RGLength = 23 byte[] xcoord = BinaryUtils.convert(x, 3); data[11] = xcoord[0]; // XoaOSet data[12] = xcoord[1]; data[13] = xcoord[2]; byte[] ycoord = BinaryUtils.convert(y, 3); data[14] = ycoord[0]; // YoaOSet data[15] = ycoord[1]; data[16] = ycoord[2]; byte xorient = (byte)(rotation / 2); data[17] = xorient; // XoaOrent byte yorient = (byte)(rotation / 2 + 45); data[19] = yorient; // YoaOrent byte[] xoffset = BinaryUtils.convert(xOffset, 3); data[22] = xoffset[0]; // XocaOSet data[23] = xoffset[1]; data[24] = xoffset[2]; byte[] yoffset = BinaryUtils.convert(yOffset, 3); data[25] = yoffset[0]; // YocaOSet data[26] = yoffset[1]; data[27] = yoffset[2]; data[28] = 0x00; // XocaOrent data[29] = 0x00; data[30] = 0x2D; // YocaOrent data[31] = 0x00; data[32] = this.refCSys; // RefCSys os.write(data); }
// in src/java/org/apache/fop/afp/modca/PageSegment.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.PAGE_SEGMENT); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PageSegment.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/modca/PageSegment.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.PAGE_SEGMENT); os.write(data); }
// in src/java/org/apache/fop/afp/modca/AbstractAFPObject.java
protected <S extends Streamable> void writeObjects(Collection<S> objects, OutputStream os) throws IOException { if (objects != null) { Iterator<S> it = objects.iterator(); while (it.hasNext()) { Streamable s = it.next(); s.writeToStream(os); it.remove(); // once written, immediately remove the object } } }
// in src/java/org/apache/fop/afp/modca/AbstractAFPObject.java
protected static void writeChunksToStream(byte[] data, byte[] dataHeader, int lengthOffset, int maxChunkLength, OutputStream os) throws IOException { int dataLength = data.length; int numFullChunks = dataLength / maxChunkLength; int lastChunkLength = dataLength % maxChunkLength; int headerLen = dataHeader.length - lengthOffset; // length field is just before data so do not include in data length if (headerLen == 2) { headerLen = 0; } byte[] len; int off = 0; if (numFullChunks > 0) { // write out full data chunks len = BinaryUtils.convert(headerLen + maxChunkLength, 2); dataHeader[lengthOffset] = len[0]; // Length byte 1 dataHeader[lengthOffset + 1] = len[1]; // Length byte 2 for (int i = 0; i < numFullChunks; i++, off += maxChunkLength) { os.write(dataHeader); os.write(data, off, maxChunkLength); } } if (lastChunkLength > 0) { // write last data chunk len = BinaryUtils.convert(headerLen + lastChunkLength, 2); dataHeader[lengthOffset] = len[0]; // Length byte 1 dataHeader[lengthOffset + 1] = len[1]; // Length byte 2 os.write(dataHeader); os.write(data, off, lastChunkLength); } }
// in src/java/org/apache/fop/afp/modca/AbstractStructuredObject.java
protected void writeStart(OutputStream os) throws IOException { }
// in src/java/org/apache/fop/afp/modca/AbstractStructuredObject.java
protected void writeEnd(OutputStream os) throws IOException { }
// in src/java/org/apache/fop/afp/modca/AbstractStructuredObject.java
protected void writeContent(OutputStream os) throws IOException { }
// in src/java/org/apache/fop/afp/modca/AbstractStructuredObject.java
public void writeToStream(OutputStream os) throws IOException { writeStart(os); writeContent(os); writeEnd(os); }
// in src/java/org/apache/fop/afp/modca/MapPageOverlay.java
public void writeToStream(OutputStream os) throws IOException { int oLayCount = getOverlays().size(); int recordlength = oLayCount * 18; byte[] data = new byte[recordlength + 9]; data[0] = 0x5A; // Set the total record length byte[] rl1 = BinaryUtils.convert(recordlength + 8, 2); //Ignore the // first byte in // the length data[1] = rl1[0]; data[2] = rl1[1]; // Structured field ID for a MPO data[3] = (byte) 0xD3; data[4] = (byte) Type.MAP; data[5] = (byte) Category.PAGE_OVERLAY; data[6] = 0x00; // Reserved data[7] = 0x00; // Reserved data[8] = 0x00; // Reserved int pos = 8; //For each overlay byte olayref = 0x00; for (int i = 0; i < oLayCount; i++) { olayref = (byte) (olayref + 1); data[++pos] = 0x00; data[++pos] = 0x12; //the length of repeating group data[++pos] = 0x0C; //Fully Qualified Name data[++pos] = 0x02; data[++pos] = (byte) 0x84; data[++pos] = 0x00; //now add the name byte[] name = (byte[]) overLays.get(i); for (int j = 0; j < name.length; j++) { data[++pos] = name[j]; } data[++pos] = 0x04; //Resource Local Identifier (RLI) data[++pos] = 0x24; data[++pos] = 0x02; //now add the unique id to the RLI data[++pos] = olayref; } os.write(data); }
// in src/java/org/apache/fop/afp/modca/MapDataResource.java
public void writeToStream(OutputStream os) throws IOException { super.writeStart(os); byte[] data = new byte[11]; copySF(data, Type.MAP, Category.DATA_RESOURCE); int tripletDataLen = getTripletDataLength(); byte[] len = BinaryUtils.convert(10 + tripletDataLen, 2); data[1] = len[0]; data[2] = len[1]; len = BinaryUtils.convert(2 + tripletDataLen, 2); data[9] = len[0]; data[10] = len[1]; os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/PageObject.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.PAGE); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PageObject.java
protected void writeContent(OutputStream os) throws IOException { writeTriplets(os); getActiveEnvironmentGroup().writeToStream(os); writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/modca/PageObject.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.PAGE); os.write(data); }
// in src/java/org/apache/fop/afp/util/StructuredFieldReader.java
public byte[] getNext(byte[] identifier) throws IOException { byte[] bytes = AFPResourceUtil.getNext(identifier, this.inputStream); if (bytes != null) { //Users of this class expect the field data without length and identifier int srcPos = 2 + identifier.length; byte[] tmp = new byte[bytes.length - srcPos]; System.arraycopy(bytes, srcPos, tmp, 0, tmp.length); bytes = tmp; } return bytes; }
// in src/java/org/apache/fop/afp/util/SimpleResourceAccessor.java
public InputStream createInputStream(URI uri) throws IOException { URI resolved = resolveAgainstBase(uri); URL url = resolved.toURL(); return url.openStream(); }
// in src/java/org/apache/fop/afp/util/DTDEntityResolver.java
public InputSource resolveEntity(String publicId, String systemId) throws IOException { URL resource = null; if ( AFP_DTD_1_2_ID.equals(publicId) ) { resource = getResource( AFP_DTD_1_2_RESOURCE ); } else if ( AFP_DTD_1_1_ID.equals(publicId) ) { resource = getResource( AFP_DTD_1_1_RESOURCE ); } else if ( AFP_DTD_1_0_ID.equals(publicId) ) { throw new FontRuntimeException( "The AFP Installed Font Definition 1.0 DTD is not longer supported" ); } else if (systemId != null && systemId.indexOf("afp-fonts.dtd") >= 0 ) { throw new FontRuntimeException( "The AFP Installed Font Definition DTD must be specified using the public id" ); } else { return null; } InputSource inputSource = new InputSource( resource.openStream() ); inputSource.setPublicId( publicId ); inputSource.setSystemId( systemId ); return inputSource; }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
public static byte[] getNext(byte[] identifier, InputStream inputStream) throws IOException { MODCAParser parser = new MODCAParser(inputStream); while (true) { UnparsedStructuredField field = parser.readNextStructuredField(); if (field == null) { return null; } if (field.getSfClassCode() == identifier[0] && field.getSfTypeCode() == identifier[1] && field.getSfCategoryCode() == identifier[2]) { return field.getCompleteFieldAsBytes(); } } }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
public static void copyResourceFile(final InputStream in, OutputStream out) throws IOException { MODCAParser parser = new MODCAParser(in); while (true) { UnparsedStructuredField field = parser.readNextStructuredField(); if (field == null) { break; } out.write(MODCAParser.CARRIAGE_CONTROL_CHAR); field.writeTo(out); } }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
public static void copyNamedResource(String name, final InputStream in, final OutputStream out) throws IOException { final MODCAParser parser = new MODCAParser(in); Collection<String> resourceNames = new java.util.HashSet<String>(); //Find matching "Begin" field final UnparsedStructuredField fieldBegin; while (true) { final UnparsedStructuredField field = parser.readNextStructuredField(); if (field == null) { throw new IOException("Requested resource '" + name + "' not found. Encountered resource names: " + resourceNames); } if (field.getSfTypeCode() != TYPE_CODE_BEGIN) { //0xA8=Begin continue; //Not a "Begin" field } final String resourceName = getResourceName(field); resourceNames.add(resourceName); if (resourceName.equals(name)) { if (LOG.isDebugEnabled()) { LOG.debug("Start of requested structured field found:\n" + field); } fieldBegin = field; break; //Name doesn't match } } //Decide whether the resource file has to be wrapped in a resource object boolean wrapInResource; if (fieldBegin.getSfCategoryCode() == Category.PAGE_SEGMENT) { //A naked page segment must be wrapped in a resource object wrapInResource = true; } else if (fieldBegin.getSfCategoryCode() == Category.NAME_RESOURCE) { //A resource object can be copied directly wrapInResource = false; } else { throw new IOException("Cannot handle resource: " + fieldBegin); } //Copy structured fields (wrapped or as is) if (wrapInResource) { ResourceObject resourceObject = new ResourceObject(name) { protected void writeContent(OutputStream os) throws IOException { copyNamedStructuredFields(name, fieldBegin, parser, out); } }; resourceObject.setType(ResourceObject.TYPE_PAGE_SEGMENT); resourceObject.writeToStream(out); } else { copyNamedStructuredFields(name, fieldBegin, parser, out); } }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
protected void writeContent(OutputStream os) throws IOException { copyNamedStructuredFields(name, fieldBegin, parser, out); }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
private static void copyNamedStructuredFields(final String name, UnparsedStructuredField fieldBegin, MODCAParser parser, OutputStream out) throws IOException { UnparsedStructuredField field = fieldBegin; while (true) { if (field == null) { throw new IOException("Ending structured field not found for resource " + name); } out.write(MODCAParser.CARRIAGE_CONTROL_CHAR); field.writeTo(out); if (field.getSfTypeCode() == TYPE_CODE_END && fieldBegin.getSfCategoryCode() == field.getSfCategoryCode() && name.equals(getResourceName(field))) { break; } field = parser.readNextStructuredField(); } }
// in src/java/org/apache/fop/afp/util/DefaultFOPResourceAccessor.java
public InputStream createInputStream(URI uri) throws IOException { //Step 1: resolve against local base URI --> URI URI resolved = resolveAgainstBase(uri); //Step 2: resolve against the user agent --> stream String base = (this.categoryBaseURI != null ? this.categoryBaseURI : this.userAgent.getBaseURL()); Source src = userAgent.resolveURI(resolved.toASCIIString(), base); if (src == null) { throw new FileNotFoundException("Resource not found: " + uri.toASCIIString()); } else if (src instanceof StreamSource) { StreamSource ss = (StreamSource)src; InputStream in = ss.getInputStream(); if (in != null) { return in; } if (ss.getReader() != null) { //Don't support reader, retry using system ID below IOUtils.closeQuietly(ss.getReader()); } } URL url = new URL(src.getSystemId()); return url.openStream(); }
// in src/java/org/apache/fop/afp/ioca/ImageInputDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[45]; copySF(data, Type.DESCRIPTOR, Category.IM_IMAGE); data[1] = 0x00; // length data[2] = 0x2C; // Constant data. data[9] = 0x00; data[10] = 0x00; data[11] = 0x09; data[12] = 0x60; data[13] = 0x09; data[14] = 0x60; data[15] = 0x00; data[16] = 0x00; data[17] = 0x00; data[18] = 0x00; data[19] = 0x00; data[20] = 0x00; // X Base (Fixed x00) data[21] = 0x00; // Y Base (Fixed x00) data[22] = 0x00; byte[] imagepoints = BinaryUtils.convert(resolution * 10, 2); /** * Specifies the number of image points per unit base for the X axis * of the image. This value is ten times the resolution of the image * in the X direction. */ data[23] = imagepoints[0]; data[24] = imagepoints[1]; /** * Specifies the number of image points per unit base for the Y axis * of the image. This value is ten times the resolution of the image * in the Y direction. */ data[25] = imagepoints[0]; data[26] = imagepoints[1]; /** * Specifies the extent in the X direction, in image points, of an * non-celled (simple) image. */ data[27] = 0x00; data[28] = 0x01; /** * Specifies the extent in the Y direction, in image points, of an * non-celled (simple) image. */ data[29] = 0x00; data[30] = 0x01; // Constant Data data[31] = 0x00; data[32] = 0x00; data[33] = 0x00; data[34] = 0x00; data[35] = 0x2D; data[36] = 0x00; // Default size of image cell in X direction data[37] = 0x00; data[38] = 0x01; // Default size of image cell in Y direction data[39] = 0x00; data[40] = 0x01; // Constant Data data[41] = 0x00; data[42] = 0x01; // Image Color data[43] = (byte)0xFF; data[44] = (byte)0xFF; os.write(data); }
// in src/java/org/apache/fop/afp/ioca/IDEStructureParameter.java
public void writeToStream(OutputStream os) throws IOException { int length = 7 + bitsPerIDE.length; byte flags = 0x00; if (subtractive) { flags |= 1 << 7; } if (grayCoding) { flags |= 1 << 6; } DataOutputStream dout = new DataOutputStream(os); dout.writeByte(0x9B); //ID dout.writeByte(length - 2); //LENGTH dout.writeByte(flags); //FLAGS dout.writeByte(this.colorModel); //FORMAT for (int i = 0; i < 3; i++) { dout.writeByte(0); //RESERVED } dout.write(this.bitsPerIDE); //component sizes }
// in src/java/org/apache/fop/afp/ioca/ImageContent.java
Override protected void writeContent(OutputStream os) throws IOException { if (imageSizeParameter != null) { imageSizeParameter.writeToStream(os); } // TODO convert to triplet/parameter class os.write(getImageEncodingParameter()); os.write(getImageIDESizeParameter()); if (getIDEStructureParameter() != null) { getIDEStructureParameter().writeToStream(os); } boolean useFS10 = (this.ideSize == 1); if (!useFS10) { os.write(getExternalAlgorithmParameter()); } final byte[] dataHeader = new byte[] { (byte)0xFE, // ID (byte)0x92, // ID 0x00, // length 0x00 // length }; final int lengthOffset = 2; // Image Data if (data != null) { writeChunksToStream(data, dataHeader, lengthOffset, MAX_DATA_LEN, os); } }
// in src/java/org/apache/fop/afp/ioca/ImageContent.java
Override protected void writeStart(OutputStream os) throws IOException { final byte[] startData = new byte[] { (byte)0x91, // ID 0x01, // Length (byte)0xff, // Object Type = IOCA Image Object }; os.write(startData); }
// in src/java/org/apache/fop/afp/ioca/ImageContent.java
Override protected void writeEnd(OutputStream os) throws IOException { final byte[] endData = new byte[] { (byte)0x93, // ID 0x00, // Length }; os.write(endData); }
// in src/java/org/apache/fop/afp/ioca/ImageSizeParameter.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { (byte)0x94, // ID = Image Size Parameter 0x09, // Length 0x00, // Unit base - 10 Inches 0x00, // HRESOL 0x00, // 0x00, // VRESOL 0x00, // 0x00, // HSIZE 0x00, // 0x00, // VSIZE 0x00, // }; byte[] x = BinaryUtils.convert(hRes, 2); data[3] = x[0]; data[4] = x[1]; byte[] y = BinaryUtils.convert(vRes, 2); data[5] = y[0]; data[6] = y[1]; byte[] w = BinaryUtils.convert(hSize, 2); data[7] = w[0]; data[8] = w[1]; byte[] h = BinaryUtils.convert(vSize, 2); data[9] = h[0]; data[10] = h[1]; os.write(data); }
// in src/java/org/apache/fop/afp/ioca/ImageOutputControl.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[33]; data[0] = 0x5A; data[1] = 0x00; data[2] = 0x20; data[3] = (byte) 0xD3; data[4] = (byte) 0xA7; data[5] = (byte) 0x7B; data[6] = 0x00; data[7] = 0x00; data[8] = 0x00; // XoaOset byte[] x1 = BinaryUtils.convert(xCoord, 3); data[9] = x1[0]; data[10] = x1[1]; data[11] = x1[2]; // YoaOset byte[] x2 = BinaryUtils.convert(yCoord, 3); data[12] = x2[0]; data[13] = x2[1]; data[14] = x2[2]; switch (orientation) { case 0: // 0 and 90 degrees respectively data[15] = 0x00; data[16] = 0x00; data[17] = 0x2D; data[18] = 0x00; break; case 90: // 90 and 180 degrees respectively data[15] = 0x2D; data[16] = 0x00; data[17] = 0x5A; data[18] = 0x00; break; case 180: // 180 and 270 degrees respectively data[15] = 0x5A; data[16] = 0x00; data[17] = (byte) 0x87; data[18] = 0x00; break; case 270: // 270 and 0 degrees respectively data[15] = (byte) 0x87; data[16] = 0x00; data[17] = 0x00; data[18] = 0x00; break; default: // 0 and 90 degrees respectively data[15] = 0x00; data[16] = 0x00; data[17] = 0x2D; data[18] = 0x00; break; } // Constant Data data[19] = 0x00; data[20] = 0x00; data[21] = 0x00; data[22] = 0x00; data[23] = 0x00; data[24] = 0x00; data[25] = 0x00; data[26] = 0x00; if (singlePoint) { data[27] = 0x03; data[28] = (byte) 0xE8; data[29] = 0x03; data[30] = (byte) 0xE8; } else { data[27] = 0x07; data[28] = (byte) 0xD0; data[29] = 0x07; data[30] = (byte) 0xD0; } // Constant Data data[31] = (byte) 0xFF; data[32] = (byte) 0xFF; os.write(data); }
// in src/java/org/apache/fop/afp/ioca/ImageCellPosition.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[21]; copySF(data, Type.POSITION, Category.IM_IMAGE); data[1] = 0x00; // length data[2] = 0x14; /** * Specifies the offset along the Xp direction, in image points, * of this image cell from the IM image object area origin. */ byte[] x1 = BinaryUtils.convert(xOffset, 2); data[9] = x1[0]; data[10] = x1[1]; /** * Specifies the offset along the Yp direction, in image points, * of this image cell from the IM image object area origin. */ byte[] x2 = BinaryUtils.convert(yOffset, 2); data[11] = x2[0]; data[12] = x2[1]; data[13] = xSize[0]; data[14] = xSize[1]; data[15] = ySize[0]; data[16] = ySize[1]; data[17] = xFillSize[0]; data[18] = xFillSize[1]; data[19] = yFillSize[0]; data[20] = yFillSize[1]; os.write(data); }
// in src/java/org/apache/fop/afp/ioca/ImageRasterData.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[9]; copySF(data, Type.DATA, Category.IM_IMAGE); // The size of the structured field byte[] len = BinaryUtils.convert(rasterData.length + 8, 2); data[1] = len[0]; data[2] = len[1]; os.write(data); os.write(rasterData); }
// in src/java/org/apache/fop/afp/ioca/ImageSegment.java
public void writeContent(OutputStream os) throws IOException { if (imageContent != null) { imageContent.writeToStream(os); } }
// in src/java/org/apache/fop/afp/ioca/ImageSegment.java
protected void writeStart(OutputStream os) throws IOException { //Name disabled, it's optional and not referenced by our code //byte[] nameBytes = getNameBytes(); byte[] data = new byte[] { 0x70, // ID 0x00, // Length /* nameBytes[0], // Name byte 1 nameBytes[1], // Name byte 2 nameBytes[2], // Name byte 3 nameBytes[3], // Name byte 4 */ }; os.write(data); }
// in src/java/org/apache/fop/afp/ioca/ImageSegment.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[] { 0x71, // ID 0x00, // Length }; os.write(data); }
// in src/java/org/apache/fop/events/model/EventModel.java
private void writeXMLizable(XMLizable object, File outputFile) throws IOException { //These two approaches do not seem to work in all environments: //Result res = new StreamResult(outputFile); //Result res = new StreamResult(outputFile.toURI().toURL().toExternalForm()); //With an old Xalan version: file:/C:/.... --> file:\C:\..... OutputStream out = new java.io.FileOutputStream(outputFile); out = new java.io.BufferedOutputStream(out); Result res = new StreamResult(out); try { SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler handler = tFactory.newTransformerHandler(); Transformer transformer = handler.getTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); handler.setResult(res); handler.startDocument(); object.toSAX(handler); handler.endDocument(); } catch (TransformerConfigurationException e) { throw new IOException(e.getMessage()); } catch (TransformerFactoryConfigurationError e) { throw new IOException(e.getMessage()); } catch (SAXException e) { throw new IOException(e.getMessage()); } finally { IOUtils.closeQuietly(out); } }
// in src/java/org/apache/fop/events/model/EventModel.java
public void saveToXML(File modelFile) throws IOException { writeXMLizable(this, modelFile); }
// in src/java/org/apache/fop/area/PageViewport.java
public void savePage(ObjectOutputStream out) throws IOException { // set the unresolved references so they are serialized page.setUnresolvedReferences(unresolvedIDRefs); out.writeObject(page); page = null; }
// in src/java/org/apache/fop/area/PageViewport.java
public void loadPage(ObjectInputStream in) throws IOException, ClassNotFoundException { page = (Page) in.readObject(); unresolvedIDRefs = page.getUnresolvedReferences(); if (unresolvedIDRefs != null && pendingResolved != null) { for (String id : pendingResolved.keySet()) { resolveIDRef(id, pendingResolved.get(id)); } pendingResolved = null; } }
// in src/java/org/apache/fop/area/inline/InlineViewport.java
private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeBoolean(contentPosition != null); if (contentPosition != null) { out.writeFloat((float) contentPosition.getX()); out.writeFloat((float) contentPosition.getY()); out.writeFloat((float) contentPosition.getWidth()); out.writeFloat((float) contentPosition.getHeight()); } out.writeBoolean(clip); out.writeObject((TreeMap)traits); out.writeObject(content); }
// in src/java/org/apache/fop/area/inline/InlineViewport.java
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { if (in.readBoolean()) { contentPosition = new Rectangle2D.Float(in.readFloat(), in.readFloat(), in.readFloat(), in.readFloat()); } this.clip = in.readBoolean(); this.traits = (TreeMap) in.readObject(); this.content = (Area) in.readObject(); }
// in src/java/org/apache/fop/area/RegionViewport.java
private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeFloat((float) viewArea.getX()); out.writeFloat((float) viewArea.getY()); out.writeFloat((float) viewArea.getWidth()); out.writeFloat((float) viewArea.getHeight()); out.writeBoolean(clip); out.writeObject((TreeMap)traits); out.writeObject(regionReference); }
// in src/java/org/apache/fop/area/RegionViewport.java
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { viewArea = new Rectangle2D.Float(in.readFloat(), in.readFloat(), in.readFloat(), in.readFloat()); clip = in.readBoolean(); traits = (TreeMap)in.readObject(); setRegionReference((RegionReference) in.readObject()); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readLangSysTable(String tableTag, long langSysTable, String langSysTag) throws IOException { in.seekSet(langSysTable); if (log.isDebugEnabled()) { log.debug(tableTag + " lang sys table: " + langSysTag ); } // read lookup order (reorder) table offset int lo = in.readTTFUShort(); // read required feature index int rf = in.readTTFUShort(); String rfi; if ( rf != 65535 ) { rfi = "f" + rf; } else { rfi = null; } // read (non-required) feature count int nf = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " lang sys table reorder table: " + lo ); log.debug(tableTag + " lang sys table required feature index: " + rf ); log.debug(tableTag + " lang sys table non-required feature count: " + nf ); } // read (non-required) feature indices int[] fia = new int[nf]; List fl = new java.util.ArrayList(); for ( int i = 0; i < nf; i++ ) { int fi = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " lang sys table non-required feature index: " + fi ); } fia[i] = fi; fl.add ( "f" + fi ); } if ( seLanguages == null ) { seLanguages = new java.util.LinkedHashMap(); } seLanguages.put ( langSysTag, new Object[] { rfi, fl } ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readScriptTable(String tableTag, long scriptTable, String scriptTag) throws IOException { in.seekSet(scriptTable); if (log.isDebugEnabled()) { log.debug(tableTag + " script table: " + scriptTag ); } // read default language system table offset int dl = in.readTTFUShort(); String dt = defaultTag; if ( dl > 0 ) { if (log.isDebugEnabled()) { log.debug(tableTag + " default lang sys tag: " + dt ); log.debug(tableTag + " default lang sys table offset: " + dl ); } } // read language system record count int nl = in.readTTFUShort(); List ll = new java.util.ArrayList(); if ( nl > 0 ) { String[] lta = new String[nl]; int[] loa = new int[nl]; // read language system records for ( int i = 0, n = nl; i < n; i++ ) { String lt = in.readTTFString(4); int lo = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " lang sys tag: " + lt ); log.debug(tableTag + " lang sys table offset: " + lo ); } lta[i] = lt; loa[i] = lo; if ( dl == lo ) { dl = 0; dt = lt; } ll.add ( lt ); } // read non-default language system tables for ( int i = 0, n = nl; i < n; i++ ) { readLangSysTable ( tableTag, scriptTable + loa [ i ], lta [ i ] ); } } // read default language system table (if specified) if ( dl > 0 ) { readLangSysTable ( tableTag, scriptTable + dl, dt ); } else if ( dt != null ) { if (log.isDebugEnabled()) { log.debug(tableTag + " lang sys default: " + dt ); } } seScripts.put ( scriptTag, new Object[] { dt, ll, seLanguages } ); seLanguages = null; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readScriptList(String tableTag, long scriptList) throws IOException { in.seekSet(scriptList); // read script record count int ns = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " script list record count: " + ns ); } if ( ns > 0 ) { String[] sta = new String[ns]; int[] soa = new int[ns]; // read script records for ( int i = 0, n = ns; i < n; i++ ) { String st = in.readTTFString(4); int so = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " script tag: " + st ); log.debug(tableTag + " script table offset: " + so ); } sta[i] = st; soa[i] = so; } // read script tables for ( int i = 0, n = ns; i < n; i++ ) { seLanguages = null; readScriptTable ( tableTag, scriptList + soa [ i ], sta [ i ] ); } } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readFeatureTable(String tableTag, long featureTable, String featureTag, int featureIndex) throws IOException { in.seekSet(featureTable); if (log.isDebugEnabled()) { log.debug(tableTag + " feature table: " + featureTag ); } // read feature params offset int po = in.readTTFUShort(); // read lookup list indices count int nl = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " feature table parameters offset: " + po ); log.debug(tableTag + " feature table lookup list index count: " + nl ); } // read lookup table indices int[] lia = new int[nl]; List lul = new java.util.ArrayList(); for ( int i = 0; i < nl; i++ ) { int li = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " feature table lookup index: " + li ); } lia[i] = li; lul.add ( "lu" + li ); } seFeatures.put ( "f" + featureIndex, new Object[] { featureTag, lul } ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readFeatureList(String tableTag, long featureList) throws IOException { in.seekSet(featureList); // read feature record count int nf = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " feature list record count: " + nf ); } if ( nf > 0 ) { String[] fta = new String[nf]; int[] foa = new int[nf]; // read feature records for ( int i = 0, n = nf; i < n; i++ ) { String ft = in.readTTFString(4); int fo = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " feature tag: " + ft ); log.debug(tableTag + " feature table offset: " + fo ); } fta[i] = ft; foa[i] = fo; } // read feature tables for ( int i = 0, n = nf; i < n; i++ ) { if (log.isDebugEnabled()) { log.debug(tableTag + " feature index: " + i ); } readFeatureTable ( tableTag, featureList + foa [ i ], fta [ i ], i ); } } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphCoverageTable readCoverageTableFormat1(String label, long tableOffset, int coverageFormat) throws IOException { List entries = new java.util.ArrayList(); in.seekSet(tableOffset); // skip over format (already known) in.skip ( 2 ); // read glyph count int ng = in.readTTFUShort(); int[] ga = new int[ng]; for ( int i = 0, n = ng; i < n; i++ ) { int g = in.readTTFUShort(); ga[i] = g; entries.add ( Integer.valueOf(g) ); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(label + " glyphs: " + toString(ga) ); } return GlyphCoverageTable.createCoverageTable ( entries ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphCoverageTable readCoverageTableFormat2(String label, long tableOffset, int coverageFormat) throws IOException { List entries = new java.util.ArrayList(); in.seekSet(tableOffset); // skip over format (already known) in.skip ( 2 ); // read range record count int nr = in.readTTFUShort(); for ( int i = 0, n = nr; i < n; i++ ) { // read range start int s = in.readTTFUShort(); // read range end int e = in.readTTFUShort(); // read range coverage (mapping) index int m = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(label + " range[" + i + "]: [" + s + "," + e + "]: " + m ); } entries.add ( new GlyphCoverageTable.MappingRange ( s, e, m ) ); } return GlyphCoverageTable.createCoverageTable ( entries ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphCoverageTable readCoverageTable(String label, long tableOffset) throws IOException { GlyphCoverageTable gct; long cp = in.getCurrentPos(); in.seekSet(tableOffset); // read coverage table format int cf = in.readTTFUShort(); if ( cf == 1 ) { gct = readCoverageTableFormat1 ( label, tableOffset, cf ); } else if ( cf == 2 ) { gct = readCoverageTableFormat2 ( label, tableOffset, cf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported coverage table format: " + cf ); } in.seekSet ( cp ); return gct; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphClassTable readClassDefTableFormat1(String label, long tableOffset, int classFormat) throws IOException { List entries = new java.util.ArrayList(); in.seekSet(tableOffset); // skip over format (already known) in.skip ( 2 ); // read start glyph int sg = in.readTTFUShort(); entries.add ( Integer.valueOf(sg) ); // read glyph count int ng = in.readTTFUShort(); // read glyph classes int[] ca = new int[ng]; for ( int i = 0, n = ng; i < n; i++ ) { int gc = in.readTTFUShort(); ca[i] = gc; entries.add ( Integer.valueOf(gc) ); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(label + " glyph classes: " + toString(ca) ); } return GlyphClassTable.createClassTable ( entries ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphClassTable readClassDefTableFormat2(String label, long tableOffset, int classFormat) throws IOException { List entries = new java.util.ArrayList(); in.seekSet(tableOffset); // skip over format (already known) in.skip ( 2 ); // read range record count int nr = in.readTTFUShort(); for ( int i = 0, n = nr; i < n; i++ ) { // read range start int s = in.readTTFUShort(); // read range end int e = in.readTTFUShort(); // read range glyph class (mapping) index int m = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(label + " range[" + i + "]: [" + s + "," + e + "]: " + m ); } entries.add ( new GlyphClassTable.MappingRange ( s, e, m ) ); } return GlyphClassTable.createClassTable ( entries ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphClassTable readClassDefTable(String label, long tableOffset) throws IOException { GlyphClassTable gct; long cp = in.getCurrentPos(); in.seekSet(tableOffset); // read class table format int cf = in.readTTFUShort(); if ( cf == 1 ) { gct = readClassDefTableFormat1 ( label, tableOffset, cf ); } else if ( cf == 2 ) { gct = readClassDefTableFormat2 ( label, tableOffset, cf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported class definition table format: " + cf ); } in.seekSet ( cp ); return gct; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readSingleSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read delta glyph int dg = in.readTTFShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " single substitution subtable format: " + subtableFormat + " (delta)" ); log.debug(tableTag + " single substitution coverage table offset: " + co ); log.debug(tableTag + " single substitution delta: " + dg ); } // read coverage table seMapping = readCoverageTable ( tableTag + " single substitution coverage", subtableOffset + co ); seEntries.add ( Integer.valueOf ( dg ) ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readSingleSubTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read glyph count int ng = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " single substitution subtable format: " + subtableFormat + " (mapped)" ); log.debug(tableTag + " single substitution coverage table offset: " + co ); log.debug(tableTag + " single substitution glyph count: " + ng ); } // read coverage table seMapping = readCoverageTable ( tableTag + " single substitution coverage", subtableOffset + co ); // read glyph substitutions int[] gsa = new int[ng]; for ( int i = 0, n = ng; i < n; i++ ) { int gs = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " single substitution glyph[" + i + "]: " + gs ); } gsa[i] = gs; seEntries.add ( Integer.valueOf ( gs ) ); } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readSingleSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readSingleSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readSingleSubTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported single substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readMultipleSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read sequence count int ns = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " multiple substitution subtable format: " + subtableFormat + " (mapped)" ); log.debug(tableTag + " multiple substitution coverage table offset: " + co ); log.debug(tableTag + " multiple substitution sequence count: " + ns ); } // read coverage table seMapping = readCoverageTable ( tableTag + " multiple substitution coverage", subtableOffset + co ); // read sequence table offsets int[] soa = new int[ns]; for ( int i = 0, n = ns; i < n; i++ ) { soa[i] = in.readTTFUShort(); } // read sequence tables int[][] gsa = new int [ ns ] []; for ( int i = 0, n = ns; i < n; i++ ) { int so = soa[i]; int[] ga; if ( so > 0 ) { in.seekSet(subtableOffset + so); // read glyph count int ng = in.readTTFUShort(); ga = new int[ng]; for ( int j = 0; j < ng; j++ ) { ga[j] = in.readTTFUShort(); } } else { ga = null; } if (log.isDebugEnabled()) { log.debug(tableTag + " multiple substitution sequence[" + i + "]: " + toString ( ga ) ); } gsa [ i ] = ga; } seEntries.add ( gsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMultipleSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMultipleSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported multiple substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readAlternateSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read alternate set count int ns = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " alternate substitution subtable format: " + subtableFormat + " (mapped)" ); log.debug(tableTag + " alternate substitution coverage table offset: " + co ); log.debug(tableTag + " alternate substitution alternate set count: " + ns ); } // read coverage table seMapping = readCoverageTable ( tableTag + " alternate substitution coverage", subtableOffset + co ); // read alternate set table offsets int[] soa = new int[ns]; for ( int i = 0, n = ns; i < n; i++ ) { soa[i] = in.readTTFUShort(); } // read alternate set tables for ( int i = 0, n = ns; i < n; i++ ) { int so = soa[i]; in.seekSet(subtableOffset + so); // read glyph count int ng = in.readTTFUShort(); int[] ga = new int[ng]; for ( int j = 0; j < ng; j++ ) { int gs = in.readTTFUShort(); ga[j] = gs; } if (log.isDebugEnabled()) { log.debug(tableTag + " alternate substitution alternate set[" + i + "]: " + toString ( ga ) ); } seEntries.add ( ga ); } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readAlternateSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readAlternateSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported alternate substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readLigatureSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read ligature set count int ns = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " ligature substitution subtable format: " + subtableFormat + " (mapped)" ); log.debug(tableTag + " ligature substitution coverage table offset: " + co ); log.debug(tableTag + " ligature substitution ligature set count: " + ns ); } // read coverage table seMapping = readCoverageTable ( tableTag + " ligature substitution coverage", subtableOffset + co ); // read ligature set table offsets int[] soa = new int[ns]; for ( int i = 0, n = ns; i < n; i++ ) { soa[i] = in.readTTFUShort(); } // read ligature set tables for ( int i = 0, n = ns; i < n; i++ ) { int so = soa[i]; in.seekSet(subtableOffset + so); // read ligature table count int nl = in.readTTFUShort(); int[] loa = new int[nl]; for ( int j = 0; j < nl; j++ ) { loa[j] = in.readTTFUShort(); } List ligs = new java.util.ArrayList(); for ( int j = 0; j < nl; j++ ) { int lo = loa[j]; in.seekSet(subtableOffset + so + lo); // read ligature glyph id int lg = in.readTTFUShort(); // read ligature (input) component count int nc = in.readTTFUShort(); int[] ca = new int [ nc - 1 ]; // read ligature (input) component glyph ids for ( int k = 0; k < nc - 1; k++ ) { ca[k] = in.readTTFUShort(); } if (log.isDebugEnabled()) { log.debug(tableTag + " ligature substitution ligature set[" + i + "]: ligature(" + lg + "), components: " + toString ( ca ) ); } ligs.add ( new GlyphSubstitutionTable.Ligature ( lg, ca ) ); } seEntries.add ( new GlyphSubstitutionTable.LigatureSet ( ligs ) ); } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readLigatureSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readLigatureSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported ligature substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphTable.RuleLookup[] readRuleLookups(int numLookups, String header) throws IOException { GlyphTable.RuleLookup[] la = new GlyphTable.RuleLookup [ numLookups ]; for ( int i = 0, n = numLookups; i < n; i++ ) { int sequenceIndex = in.readTTFUShort(); int lookupIndex = in.readTTFUShort(); la [ i ] = new GlyphTable.RuleLookup ( sequenceIndex, lookupIndex ); // dump info if debugging and header is non-null if ( log.isDebugEnabled() && ( header != null ) ) { log.debug(header + "lookup[" + i + "]: " + la[i]); } } return la; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readContextualSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read rule set count int nrs = in.readTTFUShort(); // read rule set offsets int[] rsoa = new int [ nrs ]; for ( int i = 0; i < nrs; i++ ) { rsoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " contextual substitution format: " + subtableFormat + " (glyphs)" ); log.debug(tableTag + " contextual substitution coverage table offset: " + co ); log.debug(tableTag + " contextual substitution rule set count: " + nrs ); for ( int i = 0; i < nrs; i++ ) { log.debug(tableTag + " contextual substitution rule set offset[" + i + "]: " + rsoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " contextual substitution coverage", subtableOffset + co ); } else { ct = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ nrs ]; String header = null; for ( int i = 0; i < nrs; i++ ) { GlyphTable.RuleSet rs; int rso = rsoa [ i ]; if ( rso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + rso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { GlyphTable.GlyphSequenceRule r; int ro = roa [ j ]; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + rso + ro ); // read glyph count int ng = in.readTTFUShort(); // read rule lookup count int nl = in.readTTFUShort(); // read glyphs int[] glyphs = new int [ ng - 1 ]; for ( int k = 0, nk = glyphs.length; k < nk; k++ ) { glyphs [ k ] = in.readTTFUShort(); } // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual substitution lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.GlyphSequenceRule ( lookups, ng, glyphs ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readContextualSubTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read class def table offset int cdo = in.readTTFUShort(); // read class rule set count int ngc = in.readTTFUShort(); // read class rule set offsets int[] csoa = new int [ ngc ]; for ( int i = 0; i < ngc; i++ ) { csoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " contextual substitution format: " + subtableFormat + " (glyph classes)" ); log.debug(tableTag + " contextual substitution coverage table offset: " + co ); log.debug(tableTag + " contextual substitution class set count: " + ngc ); for ( int i = 0; i < ngc; i++ ) { log.debug(tableTag + " contextual substitution class set offset[" + i + "]: " + csoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " contextual substitution coverage", subtableOffset + co ); } else { ct = null; } // read class definition table GlyphClassTable cdt; if ( cdo > 0 ) { cdt = readClassDefTable ( tableTag + " contextual substitution class definition", subtableOffset + cdo ); } else { cdt = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ ngc ]; String header = null; for ( int i = 0; i < ngc; i++ ) { int cso = csoa [ i ]; GlyphTable.RuleSet rs; if ( cso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + cso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { int ro = roa [ j ]; GlyphTable.ClassSequenceRule r; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + cso + ro ); // read glyph count int ng = in.readTTFUShort(); // read rule lookup count int nl = in.readTTFUShort(); // read classes int[] classes = new int [ ng - 1 ]; for ( int k = 0, nk = classes.length; k < nk; k++ ) { classes [ k ] = in.readTTFUShort(); } // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual substitution lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.ClassSequenceRule ( lookups, ng, classes ); } else { assert ro > 0 : "unexpected null subclass rule offset"; r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( cdt ); seEntries.add ( Integer.valueOf ( ngc ) ); seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readContextualSubTableFormat3(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read glyph (input sequence length) count int ng = in.readTTFUShort(); // read substitution lookup count int nl = in.readTTFUShort(); // read glyph coverage offsets, one per glyph input sequence length count int[] gcoa = new int [ ng ]; for ( int i = 0; i < ng; i++ ) { gcoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " contextual substitution format: " + subtableFormat + " (glyph sets)" ); log.debug(tableTag + " contextual substitution glyph input sequence length count: " + ng ); log.debug(tableTag + " contextual substitution lookup count: " + nl ); for ( int i = 0; i < ng; i++ ) { log.debug(tableTag + " contextual substitution coverage table offset[" + i + "]: " + gcoa[i] ); } } // read coverage tables GlyphCoverageTable[] gca = new GlyphCoverageTable [ ng ]; for ( int i = 0; i < ng; i++ ) { int gco = gcoa [ i ]; GlyphCoverageTable gct; if ( gco > 0 ) { gct = readCoverageTable ( tableTag + " contextual substitution coverage[" + i + "]", subtableOffset + gco ); } else { gct = null; } gca [ i ] = gct; } // read rule lookups String header = null; if (log.isDebugEnabled()) { header = tableTag + " contextual substitution lookups: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); // construct rule, rule set, and rule set array GlyphTable.Rule r = new GlyphTable.CoverageSequenceRule ( lookups, ng, gca ); GlyphTable.RuleSet rs = new GlyphTable.HomogeneousRuleSet ( new GlyphTable.Rule[] {r} ); GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet[] {rs}; // store results assert ( gca != null ) && ( gca.length > 0 ); seMapping = gca[0]; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readContextualSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readContextualSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readContextualSubTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readContextualSubTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported contextual substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readChainedContextualSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read rule set count int nrs = in.readTTFUShort(); // read rule set offsets int[] rsoa = new int [ nrs ]; for ( int i = 0; i < nrs; i++ ) { rsoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " chained contextual substitution format: " + subtableFormat + " (glyphs)" ); log.debug(tableTag + " chained contextual substitution coverage table offset: " + co ); log.debug(tableTag + " chained contextual substitution rule set count: " + nrs ); for ( int i = 0; i < nrs; i++ ) { log.debug(tableTag + " chained contextual substitution rule set offset[" + i + "]: " + rsoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " chained contextual substitution coverage", subtableOffset + co ); } else { ct = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ nrs ]; String header = null; for ( int i = 0; i < nrs; i++ ) { GlyphTable.RuleSet rs; int rso = rsoa [ i ]; if ( rso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + rso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { GlyphTable.ChainedGlyphSequenceRule r; int ro = roa [ j ]; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + rso + ro ); // read backtrack glyph count int nbg = in.readTTFUShort(); // read backtrack glyphs int[] backtrackGlyphs = new int [ nbg ]; for ( int k = 0, nk = backtrackGlyphs.length; k < nk; k++ ) { backtrackGlyphs [ k ] = in.readTTFUShort(); } // read input glyph count int nig = in.readTTFUShort(); // read glyphs int[] glyphs = new int [ nig - 1 ]; for ( int k = 0, nk = glyphs.length; k < nk; k++ ) { glyphs [ k ] = in.readTTFUShort(); } // read lookahead glyph count int nlg = in.readTTFUShort(); // read lookahead glyphs int[] lookaheadGlyphs = new int [ nlg ]; for ( int k = 0, nk = lookaheadGlyphs.length; k < nk; k++ ) { lookaheadGlyphs [ k ] = in.readTTFUShort(); } // read rule lookup count int nl = in.readTTFUShort(); // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual substitution lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.ChainedGlyphSequenceRule ( lookups, nig, glyphs, backtrackGlyphs, lookaheadGlyphs ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readChainedContextualSubTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read backtrack class def table offset int bcdo = in.readTTFUShort(); // read input class def table offset int icdo = in.readTTFUShort(); // read lookahead class def table offset int lcdo = in.readTTFUShort(); // read class set count int ngc = in.readTTFUShort(); // read class set offsets int[] csoa = new int [ ngc ]; for ( int i = 0; i < ngc; i++ ) { csoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " chained contextual substitution format: " + subtableFormat + " (glyph classes)" ); log.debug(tableTag + " chained contextual substitution coverage table offset: " + co ); log.debug(tableTag + " chained contextual substitution class set count: " + ngc ); for ( int i = 0; i < ngc; i++ ) { log.debug(tableTag + " chained contextual substitution class set offset[" + i + "]: " + csoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " chained contextual substitution coverage", subtableOffset + co ); } else { ct = null; } // read backtrack class definition table GlyphClassTable bcdt; if ( bcdo > 0 ) { bcdt = readClassDefTable ( tableTag + " contextual substitution backtrack class definition", subtableOffset + bcdo ); } else { bcdt = null; } // read input class definition table GlyphClassTable icdt; if ( icdo > 0 ) { icdt = readClassDefTable ( tableTag + " contextual substitution input class definition", subtableOffset + icdo ); } else { icdt = null; } // read lookahead class definition table GlyphClassTable lcdt; if ( lcdo > 0 ) { lcdt = readClassDefTable ( tableTag + " contextual substitution lookahead class definition", subtableOffset + lcdo ); } else { lcdt = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ ngc ]; String header = null; for ( int i = 0; i < ngc; i++ ) { int cso = csoa [ i ]; GlyphTable.RuleSet rs; if ( cso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + cso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { int ro = roa [ j ]; GlyphTable.ChainedClassSequenceRule r; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + cso + ro ); // read backtrack glyph class count int nbc = in.readTTFUShort(); // read backtrack glyph classes int[] backtrackClasses = new int [ nbc ]; for ( int k = 0, nk = backtrackClasses.length; k < nk; k++ ) { backtrackClasses [ k ] = in.readTTFUShort(); } // read input glyph class count int nic = in.readTTFUShort(); // read input glyph classes int[] classes = new int [ nic - 1 ]; for ( int k = 0, nk = classes.length; k < nk; k++ ) { classes [ k ] = in.readTTFUShort(); } // read lookahead glyph class count int nlc = in.readTTFUShort(); // read lookahead glyph classes int[] lookaheadClasses = new int [ nlc ]; for ( int k = 0, nk = lookaheadClasses.length; k < nk; k++ ) { lookaheadClasses [ k ] = in.readTTFUShort(); } // read rule lookup count int nl = in.readTTFUShort(); // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual substitution lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.ChainedClassSequenceRule ( lookups, nic, classes, backtrackClasses, lookaheadClasses ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( icdt ); seEntries.add ( bcdt ); seEntries.add ( lcdt ); seEntries.add ( Integer.valueOf ( ngc ) ); seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readChainedContextualSubTableFormat3(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read backtrack glyph count int nbg = in.readTTFUShort(); // read backtrack glyph coverage offsets int[] bgcoa = new int [ nbg ]; for ( int i = 0; i < nbg; i++ ) { bgcoa [ i ] = in.readTTFUShort(); } // read input glyph count int nig = in.readTTFUShort(); // read input glyph coverage offsets int[] igcoa = new int [ nig ]; for ( int i = 0; i < nig; i++ ) { igcoa [ i ] = in.readTTFUShort(); } // read lookahead glyph count int nlg = in.readTTFUShort(); // read lookahead glyph coverage offsets int[] lgcoa = new int [ nlg ]; for ( int i = 0; i < nlg; i++ ) { lgcoa [ i ] = in.readTTFUShort(); } // read substitution lookup count int nl = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " chained contextual substitution format: " + subtableFormat + " (glyph sets)" ); log.debug(tableTag + " chained contextual substitution backtrack glyph count: " + nbg ); for ( int i = 0; i < nbg; i++ ) { log.debug(tableTag + " chained contextual substitution backtrack coverage table offset[" + i + "]: " + bgcoa[i] ); } log.debug(tableTag + " chained contextual substitution input glyph count: " + nig ); for ( int i = 0; i < nig; i++ ) { log.debug(tableTag + " chained contextual substitution input coverage table offset[" + i + "]: " + igcoa[i] ); } log.debug(tableTag + " chained contextual substitution lookahead glyph count: " + nlg ); for ( int i = 0; i < nlg; i++ ) { log.debug(tableTag + " chained contextual substitution lookahead coverage table offset[" + i + "]: " + lgcoa[i] ); } log.debug(tableTag + " chained contextual substitution lookup count: " + nl ); } // read backtrack coverage tables GlyphCoverageTable[] bgca = new GlyphCoverageTable[nbg]; for ( int i = 0; i < nbg; i++ ) { int bgco = bgcoa [ i ]; GlyphCoverageTable bgct; if ( bgco > 0 ) { bgct = readCoverageTable ( tableTag + " chained contextual substitution backtrack coverage[" + i + "]", subtableOffset + bgco ); } else { bgct = null; } bgca[i] = bgct; } // read input coverage tables GlyphCoverageTable[] igca = new GlyphCoverageTable[nig]; for ( int i = 0; i < nig; i++ ) { int igco = igcoa [ i ]; GlyphCoverageTable igct; if ( igco > 0 ) { igct = readCoverageTable ( tableTag + " chained contextual substitution input coverage[" + i + "]", subtableOffset + igco ); } else { igct = null; } igca[i] = igct; } // read lookahead coverage tables GlyphCoverageTable[] lgca = new GlyphCoverageTable[nlg]; for ( int i = 0; i < nlg; i++ ) { int lgco = lgcoa [ i ]; GlyphCoverageTable lgct; if ( lgco > 0 ) { lgct = readCoverageTable ( tableTag + " chained contextual substitution lookahead coverage[" + i + "]", subtableOffset + lgco ); } else { lgct = null; } lgca[i] = lgct; } // read rule lookups String header = null; if (log.isDebugEnabled()) { header = tableTag + " chained contextual substitution lookups: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); // construct rule, rule set, and rule set array GlyphTable.Rule r = new GlyphTable.ChainedCoverageSequenceRule ( lookups, nig, igca, bgca, lgca ); GlyphTable.RuleSet rs = new GlyphTable.HomogeneousRuleSet ( new GlyphTable.Rule[] {r} ); GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet[] {rs}; // store results assert ( igca != null ) && ( igca.length > 0 ); seMapping = igca[0]; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readChainedContextualSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readChainedContextualSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readChainedContextualSubTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readChainedContextualSubTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported chained contextual substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readExtensionSubTableFormat1(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read extension lookup type int lt = in.readTTFUShort(); // read extension offset long eo = in.readTTFULong(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " extension substitution subtable format: " + subtableFormat ); log.debug(tableTag + " extension substitution lookup type: " + lt ); log.debug(tableTag + " extension substitution lookup table offset: " + eo ); } // read referenced subtable from extended offset readGSUBSubtable ( lt, lookupFlags, lookupSequence, subtableSequence, subtableOffset + eo ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readExtensionSubTable(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readExtensionSubTableFormat1 ( lookupType, lookupFlags, lookupSequence, subtableSequence, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported extension substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readReverseChainedSingleSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read backtrack glyph count int nbg = in.readTTFUShort(); // read backtrack glyph coverage offsets int[] bgcoa = new int [ nbg ]; for ( int i = 0; i < nbg; i++ ) { bgcoa [ i ] = in.readTTFUShort(); } // read lookahead glyph count int nlg = in.readTTFUShort(); // read backtrack glyph coverage offsets int[] lgcoa = new int [ nlg ]; for ( int i = 0; i < nlg; i++ ) { lgcoa [ i ] = in.readTTFUShort(); } // read substitution (output) glyph count int ng = in.readTTFUShort(); // read substitution (output) glyphs int[] glyphs = new int [ ng ]; for ( int i = 0, n = ng; i < n; i++ ) { glyphs [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " reverse chained contextual substitution format: " + subtableFormat ); log.debug(tableTag + " reverse chained contextual substitution coverage table offset: " + co ); log.debug(tableTag + " reverse chained contextual substitution backtrack glyph count: " + nbg ); for ( int i = 0; i < nbg; i++ ) { log.debug(tableTag + " reverse chained contextual substitution backtrack coverage table offset[" + i + "]: " + bgcoa[i] ); } log.debug(tableTag + " reverse chained contextual substitution lookahead glyph count: " + nlg ); for ( int i = 0; i < nlg; i++ ) { log.debug(tableTag + " reverse chained contextual substitution lookahead coverage table offset[" + i + "]: " + lgcoa[i] ); } log.debug(tableTag + " reverse chained contextual substitution glyphs: " + toString(glyphs) ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " reverse chained contextual substitution coverage", subtableOffset + co ); // read backtrack coverage tables GlyphCoverageTable[] bgca = new GlyphCoverageTable[nbg]; for ( int i = 0; i < nbg; i++ ) { int bgco = bgcoa[i]; GlyphCoverageTable bgct; if ( bgco > 0 ) { bgct = readCoverageTable ( tableTag + " reverse chained contextual substitution backtrack coverage[" + i + "]", subtableOffset + bgco ); } else { bgct = null; } bgca[i] = bgct; } // read lookahead coverage tables GlyphCoverageTable[] lgca = new GlyphCoverageTable[nlg]; for ( int i = 0; i < nlg; i++ ) { int lgco = lgcoa[i]; GlyphCoverageTable lgct; if ( lgco > 0 ) { lgct = readCoverageTable ( tableTag + " reverse chained contextual substitution lookahead coverage[" + i + "]", subtableOffset + lgco ); } else { lgct = null; } lgca[i] = lgct; } // store results seMapping = ct; seEntries.add ( bgca ); seEntries.add ( lgca ); seEntries.add ( glyphs ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readReverseChainedSingleSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readReverseChainedSingleSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported reverse chained single substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGSUBSubtable(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset) throws IOException { initATSubState(); int subtableFormat = -1; switch ( lookupType ) { case GSUBLookupType.SINGLE: subtableFormat = readSingleSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.MULTIPLE: subtableFormat = readMultipleSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.ALTERNATE: subtableFormat = readAlternateSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.LIGATURE: subtableFormat = readLigatureSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.CONTEXTUAL: subtableFormat = readContextualSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.CHAINED_CONTEXTUAL: subtableFormat = readChainedContextualSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.REVERSE_CHAINED_SINGLE: subtableFormat = readReverseChainedSingleSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.EXTENSION: subtableFormat = readExtensionSubTable ( lookupType, lookupFlags, lookupSequence, subtableSequence, subtableOffset ); break; default: break; } extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_SUBSTITUTION, lookupType, lookupFlags, lookupSequence, subtableSequence, subtableFormat ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphPositioningTable.DeviceTable readPosDeviceTable(long subtableOffset, long deviceTableOffset) throws IOException { long cp = in.getCurrentPos(); in.seekSet(subtableOffset + deviceTableOffset); // read start size int ss = in.readTTFUShort(); // read end size int es = in.readTTFUShort(); // read delta format int df = in.readTTFUShort(); int s1; int m1; int dm; int dd; int s2; if ( df == 1 ) { s1 = 14; m1 = 0x3; dm = 1; dd = 4; s2 = 2; } else if ( df == 2 ) { s1 = 12; m1 = 0xF; dm = 7; dd = 16; s2 = 4; } else if ( df == 3 ) { s1 = 8; m1 = 0xFF; dm = 127; dd = 256; s2 = 8; } else { log.debug ( "unsupported device table delta format: " + df + ", ignoring device table" ); return null; } // read deltas int n = ( es - ss ) + 1; if ( n < 0 ) { log.debug ( "invalid device table delta count: " + n + ", ignoring device table" ); return null; } int[] da = new int [ n ]; for ( int i = 0; ( i < n ) && ( s2 > 0 );) { int p = in.readTTFUShort(); for ( int j = 0, k = 16 / s2; j < k; j++ ) { int d = ( p >> s1 ) & m1; if ( d > dm ) { d -= dd; } if ( i < n ) { da [ i++ ] = d; } else { break; } p <<= s2; } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphPositioningTable.Value readPosValue(long subtableOffset, int valueFormat) throws IOException { // XPlacement int xp; if ( ( valueFormat & GlyphPositioningTable.Value.X_PLACEMENT ) != 0 ) { xp = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); } else { xp = 0; } // YPlacement int yp; if ( ( valueFormat & GlyphPositioningTable.Value.Y_PLACEMENT ) != 0 ) { yp = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); } else { yp = 0; } // XAdvance int xa; if ( ( valueFormat & GlyphPositioningTable.Value.X_ADVANCE ) != 0 ) { xa = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); } else { xa = 0; } // YAdvance int ya; if ( ( valueFormat & GlyphPositioningTable.Value.Y_ADVANCE ) != 0 ) { ya = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); } else { ya = 0; } // XPlaDevice GlyphPositioningTable.DeviceTable xpd; if ( ( valueFormat & GlyphPositioningTable.Value.X_PLACEMENT_DEVICE ) != 0 ) { int xpdo = in.readTTFUShort(); xpd = readPosDeviceTable ( subtableOffset, xpdo ); } else { xpd = null; } // YPlaDevice GlyphPositioningTable.DeviceTable ypd; if ( ( valueFormat & GlyphPositioningTable.Value.Y_PLACEMENT_DEVICE ) != 0 ) { int ypdo = in.readTTFUShort(); ypd = readPosDeviceTable ( subtableOffset, ypdo ); } else { ypd = null; } // XAdvDevice GlyphPositioningTable.DeviceTable xad; if ( ( valueFormat & GlyphPositioningTable.Value.X_ADVANCE_DEVICE ) != 0 ) { int xado = in.readTTFUShort(); xad = readPosDeviceTable ( subtableOffset, xado ); } else { xad = null; } // YAdvDevice GlyphPositioningTable.DeviceTable yad; if ( ( valueFormat & GlyphPositioningTable.Value.Y_ADVANCE_DEVICE ) != 0 ) { int yado = in.readTTFUShort(); yad = readPosDeviceTable ( subtableOffset, yado ); } else { yad = null; } return new GlyphPositioningTable.Value ( xp, yp, xa, ya, xpd, ypd, xad, yad ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readSinglePosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read value format int vf = in.readTTFUShort(); // read value GlyphPositioningTable.Value v = readPosValue ( subtableOffset, vf ); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " single positioning subtable format: " + subtableFormat + " (delta)" ); log.debug(tableTag + " single positioning coverage table offset: " + co ); log.debug(tableTag + " single positioning value: " + v ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " single positioning coverage", subtableOffset + co ); // store results seMapping = ct; seEntries.add ( v ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readSinglePosTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read value format int vf = in.readTTFUShort(); // read value count int nv = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " single positioning subtable format: " + subtableFormat + " (mapped)" ); log.debug(tableTag + " single positioning coverage table offset: " + co ); log.debug(tableTag + " single positioning value count: " + nv ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " single positioning coverage", subtableOffset + co ); // read positioning values GlyphPositioningTable.Value[] pva = new GlyphPositioningTable.Value[nv]; for ( int i = 0, n = nv; i < n; i++ ) { GlyphPositioningTable.Value pv = readPosValue ( subtableOffset, vf ); if (log.isDebugEnabled()) { log.debug(tableTag + " single positioning value[" + i + "]: " + pv ); } pva[i] = pv; } // store results seMapping = ct; seEntries.add ( pva ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readSinglePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positionining subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readSinglePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readSinglePosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported single positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphPositioningTable.PairValues readPosPairValues(long subtableOffset, boolean hasGlyph, int vf1, int vf2) throws IOException { // read glyph (if present) int glyph; if ( hasGlyph ) { glyph = in.readTTFUShort(); } else { glyph = 0; } // read first value (if present) GlyphPositioningTable.Value v1; if ( vf1 != 0 ) { v1 = readPosValue ( subtableOffset, vf1 ); } else { v1 = null; } // read second value (if present) GlyphPositioningTable.Value v2; if ( vf2 != 0 ) { v2 = readPosValue ( subtableOffset, vf2 ); } else { v2 = null; } return new GlyphPositioningTable.PairValues ( glyph, v1, v2 ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphPositioningTable.PairValues[] readPosPairSetTable(long subtableOffset, int pairSetTableOffset, int vf1, int vf2) throws IOException { String tableTag = "GPOS"; long cp = in.getCurrentPos(); in.seekSet(subtableOffset + pairSetTableOffset); // read pair values count int npv = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " pair set table offset: " + pairSetTableOffset ); log.debug(tableTag + " pair set table values count: " + npv ); } // read pair values GlyphPositioningTable.PairValues[] pva = new GlyphPositioningTable.PairValues [ npv ]; for ( int i = 0, n = npv; i < n; i++ ) { GlyphPositioningTable.PairValues pv = readPosPairValues ( subtableOffset, true, vf1, vf2 ); pva [ i ] = pv; if (log.isDebugEnabled()) { log.debug(tableTag + " pair set table value[" + i + "]: " + pv); } } in.seekSet(cp); return pva; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readPairPosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read value format for first glyph int vf1 = in.readTTFUShort(); // read value format for second glyph int vf2 = in.readTTFUShort(); // read number (count) of pair sets int nps = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " pair positioning subtable format: " + subtableFormat + " (glyphs)" ); log.debug(tableTag + " pair positioning coverage table offset: " + co ); log.debug(tableTag + " pair positioning value format #1: " + vf1 ); log.debug(tableTag + " pair positioning value format #2: " + vf2 ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " pair positioning coverage", subtableOffset + co ); // read pair value matrix GlyphPositioningTable.PairValues[][] pvm = new GlyphPositioningTable.PairValues [ nps ][]; for ( int i = 0, n = nps; i < n; i++ ) { // read pair set offset int pso = in.readTTFUShort(); // read pair set table at offset pvm [ i ] = readPosPairSetTable ( subtableOffset, pso, vf1, vf2 ); } // store results seMapping = ct; seEntries.add ( pvm ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readPairPosTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read value format for first glyph int vf1 = in.readTTFUShort(); // read value format for second glyph int vf2 = in.readTTFUShort(); // read class def 1 offset int cd1o = in.readTTFUShort(); // read class def 2 offset int cd2o = in.readTTFUShort(); // read number (count) of classes in class def 1 table int nc1 = in.readTTFUShort(); // read number (count) of classes in class def 2 table int nc2 = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " pair positioning subtable format: " + subtableFormat + " (glyph classes)" ); log.debug(tableTag + " pair positioning coverage table offset: " + co ); log.debug(tableTag + " pair positioning value format #1: " + vf1 ); log.debug(tableTag + " pair positioning value format #2: " + vf2 ); log.debug(tableTag + " pair positioning class def table #1 offset: " + cd1o ); log.debug(tableTag + " pair positioning class def table #2 offset: " + cd2o ); log.debug(tableTag + " pair positioning class #1 count: " + nc1 ); log.debug(tableTag + " pair positioning class #2 count: " + nc2 ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " pair positioning coverage", subtableOffset + co ); // read class definition table #1 GlyphClassTable cdt1 = readClassDefTable ( tableTag + " pair positioning class definition #1", subtableOffset + cd1o ); // read class definition table #2 GlyphClassTable cdt2 = readClassDefTable ( tableTag + " pair positioning class definition #2", subtableOffset + cd2o ); // read pair value matrix GlyphPositioningTable.PairValues[][] pvm = new GlyphPositioningTable.PairValues [ nc1 ] [ nc2 ]; for ( int i = 0; i < nc1; i++ ) { for ( int j = 0; j < nc2; j++ ) { GlyphPositioningTable.PairValues pv = readPosPairValues ( subtableOffset, false, vf1, vf2 ); pvm [ i ] [ j ] = pv; if (log.isDebugEnabled()) { log.debug(tableTag + " pair set table value[" + i + "][" + j + "]: " + pv); } } } // store results seMapping = ct; seEntries.add ( cdt1 ); seEntries.add ( cdt2 ); seEntries.add ( Integer.valueOf ( nc1 ) ); seEntries.add ( Integer.valueOf ( nc2 ) ); seEntries.add ( pvm ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readPairPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readPairPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readPairPosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported pair positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphPositioningTable.Anchor readPosAnchor(long anchorTableOffset) throws IOException { GlyphPositioningTable.Anchor a; long cp = in.getCurrentPos(); in.seekSet(anchorTableOffset); // read anchor table format int af = in.readTTFUShort(); if ( af == 1 ) { // read x coordinate int x = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read y coordinate int y = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); a = new GlyphPositioningTable.Anchor ( x, y ); } else if ( af == 2 ) { // read x coordinate int x = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read y coordinate int y = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read anchor point index int ap = in.readTTFUShort(); a = new GlyphPositioningTable.Anchor ( x, y, ap ); } else if ( af == 3 ) { // read x coordinate int x = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read y coordinate int y = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read x device table offset int xdo = in.readTTFUShort(); // read y device table offset int ydo = in.readTTFUShort(); // read x device table (if present) GlyphPositioningTable.DeviceTable xd; if ( xdo != 0 ) { xd = readPosDeviceTable ( cp, xdo ); } else { xd = null; } // read y device table (if present) GlyphPositioningTable.DeviceTable yd; if ( ydo != 0 ) { yd = readPosDeviceTable ( cp, ydo ); } else { yd = null; } a = new GlyphPositioningTable.Anchor ( x, y, xd, yd ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported positioning anchor format: " + af ); } in.seekSet(cp); return a; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readCursivePosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read entry/exit count int ec = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " cursive positioning subtable format: " + subtableFormat ); log.debug(tableTag + " cursive positioning coverage table offset: " + co ); log.debug(tableTag + " cursive positioning entry/exit count: " + ec ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " cursive positioning coverage", subtableOffset + co ); // read entry/exit records GlyphPositioningTable.Anchor[] aa = new GlyphPositioningTable.Anchor [ ec * 2 ]; for ( int i = 0, n = ec; i < n; i++ ) { // read entry anchor offset int eno = in.readTTFUShort(); // read exit anchor offset int exo = in.readTTFUShort(); // read entry anchor GlyphPositioningTable.Anchor ena; if ( eno > 0 ) { ena = readPosAnchor ( subtableOffset + eno ); } else { ena = null; } // read exit anchor GlyphPositioningTable.Anchor exa; if ( exo > 0 ) { exa = readPosAnchor ( subtableOffset + exo ); } else { exa = null; } aa [ ( i * 2 ) + 0 ] = ena; aa [ ( i * 2 ) + 1 ] = exa; if (log.isDebugEnabled()) { if ( ena != null ) { log.debug(tableTag + " cursive entry anchor [" + i + "]: " + ena ); } if ( exa != null ) { log.debug(tableTag + " cursive exit anchor [" + i + "]: " + exa ); } } } // store results seMapping = ct; seEntries.add ( aa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readCursivePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readCursivePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported cursive positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readMarkToBasePosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read mark coverage offset int mco = in.readTTFUShort(); // read base coverage offset int bco = in.readTTFUShort(); // read mark class count int nmc = in.readTTFUShort(); // read mark array offset int mao = in.readTTFUShort(); // read base array offset int bao = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-base positioning subtable format: " + subtableFormat ); log.debug(tableTag + " mark-to-base positioning mark coverage table offset: " + mco ); log.debug(tableTag + " mark-to-base positioning base coverage table offset: " + bco ); log.debug(tableTag + " mark-to-base positioning mark class count: " + nmc ); log.debug(tableTag + " mark-to-base positioning mark array offset: " + mao ); log.debug(tableTag + " mark-to-base positioning base array offset: " + bao ); } // read mark coverage table GlyphCoverageTable mct = readCoverageTable ( tableTag + " mark-to-base positioning mark coverage", subtableOffset + mco ); // read base coverage table GlyphCoverageTable bct = readCoverageTable ( tableTag + " mark-to-base positioning base coverage", subtableOffset + bco ); // read mark anchor array // seek to mark array in.seekSet(subtableOffset + mao); // read mark count int nm = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-base positioning mark count: " + nm ); } // read mark anchor array, where i:{0...markCount} GlyphPositioningTable.MarkAnchor[] maa = new GlyphPositioningTable.MarkAnchor [ nm ]; for ( int i = 0; i < nm; i++ ) { // read mark class int mc = in.readTTFUShort(); // read mark anchor offset int ao = in.readTTFUShort(); GlyphPositioningTable.Anchor a; if ( ao > 0 ) { a = readPosAnchor ( subtableOffset + mao + ao ); } else { a = null; } GlyphPositioningTable.MarkAnchor ma; if ( a != null ) { ma = new GlyphPositioningTable.MarkAnchor ( mc, a ); } else { ma = null; } maa [ i ] = ma; if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-base positioning mark anchor[" + i + "]: " + ma); } } // read base anchor matrix // seek to base array in.seekSet(subtableOffset + bao); // read base count int nb = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-base positioning base count: " + nb ); } // read anchor matrix, where i:{0...baseCount - 1}, j:{0...markClassCount - 1} GlyphPositioningTable.Anchor[][] bam = new GlyphPositioningTable.Anchor [ nb ] [ nmc ]; for ( int i = 0; i < nb; i++ ) { for ( int j = 0; j < nmc; j++ ) { // read base anchor offset int ao = in.readTTFUShort(); GlyphPositioningTable.Anchor a; if ( ao > 0 ) { a = readPosAnchor ( subtableOffset + bao + ao ); } else { a = null; } bam [ i ] [ j ] = a; if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-base positioning base anchor[" + i + "][" + j + "]: " + a); } } } // store results seMapping = mct; seEntries.add ( bct ); seEntries.add ( Integer.valueOf ( nmc ) ); seEntries.add ( maa ); seEntries.add ( bam ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMarkToBasePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMarkToBasePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark-to-base positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readMarkToLigaturePosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read mark coverage offset int mco = in.readTTFUShort(); // read ligature coverage offset int lco = in.readTTFUShort(); // read mark class count int nmc = in.readTTFUShort(); // read mark array offset int mao = in.readTTFUShort(); // read ligature array offset int lao = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-ligature positioning subtable format: " + subtableFormat ); log.debug(tableTag + " mark-to-ligature positioning mark coverage table offset: " + mco ); log.debug(tableTag + " mark-to-ligature positioning ligature coverage table offset: " + lco ); log.debug(tableTag + " mark-to-ligature positioning mark class count: " + nmc ); log.debug(tableTag + " mark-to-ligature positioning mark array offset: " + mao ); log.debug(tableTag + " mark-to-ligature positioning ligature array offset: " + lao ); } // read mark coverage table GlyphCoverageTable mct = readCoverageTable ( tableTag + " mark-to-ligature positioning mark coverage", subtableOffset + mco ); // read ligature coverage table GlyphCoverageTable lct = readCoverageTable ( tableTag + " mark-to-ligature positioning ligature coverage", subtableOffset + lco ); // read mark anchor array // seek to mark array in.seekSet(subtableOffset + mao); // read mark count int nm = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-ligature positioning mark count: " + nm ); } // read mark anchor array, where i:{0...markCount} GlyphPositioningTable.MarkAnchor[] maa = new GlyphPositioningTable.MarkAnchor [ nm ]; for ( int i = 0; i < nm; i++ ) { // read mark class int mc = in.readTTFUShort(); // read mark anchor offset int ao = in.readTTFUShort(); GlyphPositioningTable.Anchor a; if ( ao > 0 ) { a = readPosAnchor ( subtableOffset + mao + ao ); } else { a = null; } GlyphPositioningTable.MarkAnchor ma; if ( a != null ) { ma = new GlyphPositioningTable.MarkAnchor ( mc, a ); } else { ma = null; } maa [ i ] = ma; if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-ligature positioning mark anchor[" + i + "]: " + ma); } } // read ligature anchor matrix // seek to ligature array in.seekSet(subtableOffset + lao); // read ligature count int nl = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-ligature positioning ligature count: " + nl ); } // read ligature attach table offsets int[] laoa = new int [ nl ]; for ( int i = 0; i < nl; i++ ) { laoa [ i ] = in.readTTFUShort(); } // iterate over ligature attach tables, recording maximum component count int mxc = 0; for ( int i = 0; i < nl; i++ ) { int lato = laoa [ i ]; in.seekSet ( subtableOffset + lao + lato ); // read component count int cc = in.readTTFUShort(); if ( cc > mxc ) { mxc = cc; } } if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-ligature positioning maximum component count: " + mxc ); } // read anchor matrix, where i:{0...ligatureCount - 1}, j:{0...maxComponentCount - 1}, k:{0...markClassCount - 1} GlyphPositioningTable.Anchor[][][] lam = new GlyphPositioningTable.Anchor [ nl ][][]; for ( int i = 0; i < nl; i++ ) { int lato = laoa [ i ]; // seek to ligature attach table for ligature[i] in.seekSet ( subtableOffset + lao + lato ); // read component count int cc = in.readTTFUShort(); GlyphPositioningTable.Anchor[][] lcm = new GlyphPositioningTable.Anchor [ cc ] [ nmc ]; for ( int j = 0; j < cc; j++ ) { for ( int k = 0; k < nmc; k++ ) { // read ligature anchor offset int ao = in.readTTFUShort(); GlyphPositioningTable.Anchor a; if ( ao > 0 ) { a = readPosAnchor ( subtableOffset + lao + lato + ao ); } else { a = null; } lcm [ j ] [ k ] = a; if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-ligature positioning ligature anchor[" + i + "][" + j + "][" + k + "]: " + a); } } } lam [ i ] = lcm; } // store results seMapping = mct; seEntries.add ( lct ); seEntries.add ( Integer.valueOf ( nmc ) ); seEntries.add ( Integer.valueOf ( mxc ) ); seEntries.add ( maa ); seEntries.add ( lam ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMarkToLigaturePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMarkToLigaturePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark-to-ligature positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readMarkToMarkPosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read mark #1 coverage offset int m1co = in.readTTFUShort(); // read mark #2 coverage offset int m2co = in.readTTFUShort(); // read mark class count int nmc = in.readTTFUShort(); // read mark #1 array offset int m1ao = in.readTTFUShort(); // read mark #2 array offset int m2ao = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-mark positioning subtable format: " + subtableFormat ); log.debug(tableTag + " mark-to-mark positioning mark #1 coverage table offset: " + m1co ); log.debug(tableTag + " mark-to-mark positioning mark #2 coverage table offset: " + m2co ); log.debug(tableTag + " mark-to-mark positioning mark class count: " + nmc ); log.debug(tableTag + " mark-to-mark positioning mark #1 array offset: " + m1ao ); log.debug(tableTag + " mark-to-mark positioning mark #2 array offset: " + m2ao ); } // read mark #1 coverage table GlyphCoverageTable mct1 = readCoverageTable ( tableTag + " mark-to-mark positioning mark #1 coverage", subtableOffset + m1co ); // read mark #2 coverage table GlyphCoverageTable mct2 = readCoverageTable ( tableTag + " mark-to-mark positioning mark #2 coverage", subtableOffset + m2co ); // read mark #1 anchor array // seek to mark array in.seekSet(subtableOffset + m1ao); // read mark count int nm1 = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-mark positioning mark #1 count: " + nm1 ); } // read mark anchor array, where i:{0...mark1Count} GlyphPositioningTable.MarkAnchor[] maa = new GlyphPositioningTable.MarkAnchor [ nm1 ]; for ( int i = 0; i < nm1; i++ ) { // read mark class int mc = in.readTTFUShort(); // read mark anchor offset int ao = in.readTTFUShort(); GlyphPositioningTable.Anchor a; if ( ao > 0 ) { a = readPosAnchor ( subtableOffset + m1ao + ao ); } else { a = null; } GlyphPositioningTable.MarkAnchor ma; if ( a != null ) { ma = new GlyphPositioningTable.MarkAnchor ( mc, a ); } else { ma = null; } maa [ i ] = ma; if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-mark positioning mark #1 anchor[" + i + "]: " + ma); } } // read mark #2 anchor matrix // seek to mark #2 array in.seekSet(subtableOffset + m2ao); // read mark #2 count int nm2 = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-mark positioning mark #2 count: " + nm2 ); } // read anchor matrix, where i:{0...mark2Count - 1}, j:{0...markClassCount - 1} GlyphPositioningTable.Anchor[][] mam = new GlyphPositioningTable.Anchor [ nm2 ] [ nmc ]; for ( int i = 0; i < nm2; i++ ) { for ( int j = 0; j < nmc; j++ ) { // read mark anchor offset int ao = in.readTTFUShort(); GlyphPositioningTable.Anchor a; if ( ao > 0 ) { a = readPosAnchor ( subtableOffset + m2ao + ao ); } else { a = null; } mam [ i ] [ j ] = a; if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-mark positioning mark #2 anchor[" + i + "][" + j + "]: " + a); } } } // store results seMapping = mct1; seEntries.add ( mct2 ); seEntries.add ( Integer.valueOf ( nmc ) ); seEntries.add ( maa ); seEntries.add ( mam ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMarkToMarkPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMarkToMarkPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark-to-mark positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readContextualPosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read rule set count int nrs = in.readTTFUShort(); // read rule set offsets int[] rsoa = new int [ nrs ]; for ( int i = 0; i < nrs; i++ ) { rsoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " contextual positioning subtable format: " + subtableFormat + " (glyphs)" ); log.debug(tableTag + " contextual positioning coverage table offset: " + co ); log.debug(tableTag + " contextual positioning rule set count: " + nrs ); for ( int i = 0; i < nrs; i++ ) { log.debug(tableTag + " contextual positioning rule set offset[" + i + "]: " + rsoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " contextual positioning coverage", subtableOffset + co ); } else { ct = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ nrs ]; String header = null; for ( int i = 0; i < nrs; i++ ) { GlyphTable.RuleSet rs; int rso = rsoa [ i ]; if ( rso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + rso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { GlyphTable.GlyphSequenceRule r; int ro = roa [ j ]; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + rso + ro ); // read glyph count int ng = in.readTTFUShort(); // read rule lookup count int nl = in.readTTFUShort(); // read glyphs int[] glyphs = new int [ ng - 1 ]; for ( int k = 0, nk = glyphs.length; k < nk; k++ ) { glyphs [ k ] = in.readTTFUShort(); } // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual positioning lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.GlyphSequenceRule ( lookups, ng, glyphs ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readContextualPosTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read class def table offset int cdo = in.readTTFUShort(); // read class rule set count int ngc = in.readTTFUShort(); // read class rule set offsets int[] csoa = new int [ ngc ]; for ( int i = 0; i < ngc; i++ ) { csoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " contextual positioning subtable format: " + subtableFormat + " (glyph classes)" ); log.debug(tableTag + " contextual positioning coverage table offset: " + co ); log.debug(tableTag + " contextual positioning class set count: " + ngc ); for ( int i = 0; i < ngc; i++ ) { log.debug(tableTag + " contextual positioning class set offset[" + i + "]: " + csoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " contextual positioning coverage", subtableOffset + co ); } else { ct = null; } // read class definition table GlyphClassTable cdt; if ( cdo > 0 ) { cdt = readClassDefTable ( tableTag + " contextual positioning class definition", subtableOffset + cdo ); } else { cdt = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ ngc ]; String header = null; for ( int i = 0; i < ngc; i++ ) { int cso = csoa [ i ]; GlyphTable.RuleSet rs; if ( cso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + cso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { int ro = roa [ j ]; GlyphTable.ClassSequenceRule r; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + cso + ro ); // read glyph count int ng = in.readTTFUShort(); // read rule lookup count int nl = in.readTTFUShort(); // read classes int[] classes = new int [ ng - 1 ]; for ( int k = 0, nk = classes.length; k < nk; k++ ) { classes [ k ] = in.readTTFUShort(); } // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual positioning lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.ClassSequenceRule ( lookups, ng, classes ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( cdt ); seEntries.add ( Integer.valueOf ( ngc ) ); seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readContextualPosTableFormat3(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read glyph (input sequence length) count int ng = in.readTTFUShort(); // read positioning lookup count int nl = in.readTTFUShort(); // read glyph coverage offsets, one per glyph input sequence length count int[] gcoa = new int [ ng ]; for ( int i = 0; i < ng; i++ ) { gcoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " contextual positioning subtable format: " + subtableFormat + " (glyph sets)" ); log.debug(tableTag + " contextual positioning glyph input sequence length count: " + ng ); log.debug(tableTag + " contextual positioning lookup count: " + nl ); for ( int i = 0; i < ng; i++ ) { log.debug(tableTag + " contextual positioning coverage table offset[" + i + "]: " + gcoa[i] ); } } // read coverage tables GlyphCoverageTable[] gca = new GlyphCoverageTable [ ng ]; for ( int i = 0; i < ng; i++ ) { int gco = gcoa [ i ]; GlyphCoverageTable gct; if ( gco > 0 ) { gct = readCoverageTable ( tableTag + " contextual positioning coverage[" + i + "]", subtableOffset + gcoa[i] ); } else { gct = null; } gca [ i ] = gct; } // read rule lookups String header = null; if (log.isDebugEnabled()) { header = tableTag + " contextual positioning lookups: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); // construct rule, rule set, and rule set array GlyphTable.Rule r = new GlyphTable.CoverageSequenceRule ( lookups, ng, gca ); GlyphTable.RuleSet rs = new GlyphTable.HomogeneousRuleSet ( new GlyphTable.Rule[] {r} ); GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet[] {rs}; // store results assert ( gca != null ) && ( gca.length > 0 ); seMapping = gca[0]; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readContextualPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readContextualPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readContextualPosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readContextualPosTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported contextual positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readChainedContextualPosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read rule set count int nrs = in.readTTFUShort(); // read rule set offsets int[] rsoa = new int [ nrs ]; for ( int i = 0; i < nrs; i++ ) { rsoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " chained contextual positioning subtable format: " + subtableFormat + " (glyphs)" ); log.debug(tableTag + " chained contextual positioning coverage table offset: " + co ); log.debug(tableTag + " chained contextual positioning rule set count: " + nrs ); for ( int i = 0; i < nrs; i++ ) { log.debug(tableTag + " chained contextual positioning rule set offset[" + i + "]: " + rsoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " chained contextual positioning coverage", subtableOffset + co ); } else { ct = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ nrs ]; String header = null; for ( int i = 0; i < nrs; i++ ) { GlyphTable.RuleSet rs; int rso = rsoa [ i ]; if ( rso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + rso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { GlyphTable.ChainedGlyphSequenceRule r; int ro = roa [ j ]; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + rso + ro ); // read backtrack glyph count int nbg = in.readTTFUShort(); // read backtrack glyphs int[] backtrackGlyphs = new int [ nbg ]; for ( int k = 0, nk = backtrackGlyphs.length; k < nk; k++ ) { backtrackGlyphs [ k ] = in.readTTFUShort(); } // read input glyph count int nig = in.readTTFUShort(); // read glyphs int[] glyphs = new int [ nig - 1 ]; for ( int k = 0, nk = glyphs.length; k < nk; k++ ) { glyphs [ k ] = in.readTTFUShort(); } // read lookahead glyph count int nlg = in.readTTFUShort(); // read lookahead glyphs int[] lookaheadGlyphs = new int [ nlg ]; for ( int k = 0, nk = lookaheadGlyphs.length; k < nk; k++ ) { lookaheadGlyphs [ k ] = in.readTTFUShort(); } // read rule lookup count int nl = in.readTTFUShort(); // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual positioning lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.ChainedGlyphSequenceRule ( lookups, nig, glyphs, backtrackGlyphs, lookaheadGlyphs ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readChainedContextualPosTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read backtrack class def table offset int bcdo = in.readTTFUShort(); // read input class def table offset int icdo = in.readTTFUShort(); // read lookahead class def table offset int lcdo = in.readTTFUShort(); // read class set count int ngc = in.readTTFUShort(); // read class set offsets int[] csoa = new int [ ngc ]; for ( int i = 0; i < ngc; i++ ) { csoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " chained contextual positioning subtable format: " + subtableFormat + " (glyph classes)" ); log.debug(tableTag + " chained contextual positioning coverage table offset: " + co ); log.debug(tableTag + " chained contextual positioning class set count: " + ngc ); for ( int i = 0; i < ngc; i++ ) { log.debug(tableTag + " chained contextual positioning class set offset[" + i + "]: " + csoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " chained contextual positioning coverage", subtableOffset + co ); } else { ct = null; } // read backtrack class definition table GlyphClassTable bcdt; if ( bcdo > 0 ) { bcdt = readClassDefTable ( tableTag + " contextual positioning backtrack class definition", subtableOffset + bcdo ); } else { bcdt = null; } // read input class definition table GlyphClassTable icdt; if ( icdo > 0 ) { icdt = readClassDefTable ( tableTag + " contextual positioning input class definition", subtableOffset + icdo ); } else { icdt = null; } // read lookahead class definition table GlyphClassTable lcdt; if ( lcdo > 0 ) { lcdt = readClassDefTable ( tableTag + " contextual positioning lookahead class definition", subtableOffset + lcdo ); } else { lcdt = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ ngc ]; String header = null; for ( int i = 0; i < ngc; i++ ) { int cso = csoa [ i ]; GlyphTable.RuleSet rs; if ( cso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + cso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { GlyphTable.ChainedClassSequenceRule r; int ro = roa [ j ]; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + cso + ro ); // read backtrack glyph class count int nbc = in.readTTFUShort(); // read backtrack glyph classes int[] backtrackClasses = new int [ nbc ]; for ( int k = 0, nk = backtrackClasses.length; k < nk; k++ ) { backtrackClasses [ k ] = in.readTTFUShort(); } // read input glyph class count int nic = in.readTTFUShort(); // read input glyph classes int[] classes = new int [ nic - 1 ]; for ( int k = 0, nk = classes.length; k < nk; k++ ) { classes [ k ] = in.readTTFUShort(); } // read lookahead glyph class count int nlc = in.readTTFUShort(); // read lookahead glyph classes int[] lookaheadClasses = new int [ nlc ]; for ( int k = 0, nk = lookaheadClasses.length; k < nk; k++ ) { lookaheadClasses [ k ] = in.readTTFUShort(); } // read rule lookup count int nl = in.readTTFUShort(); // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual positioning lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.ChainedClassSequenceRule ( lookups, nic, classes, backtrackClasses, lookaheadClasses ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( icdt ); seEntries.add ( bcdt ); seEntries.add ( lcdt ); seEntries.add ( Integer.valueOf ( ngc ) ); seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readChainedContextualPosTableFormat3(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read backtrack glyph count int nbg = in.readTTFUShort(); // read backtrack glyph coverage offsets int[] bgcoa = new int [ nbg ]; for ( int i = 0; i < nbg; i++ ) { bgcoa [ i ] = in.readTTFUShort(); } // read input glyph count int nig = in.readTTFUShort(); // read backtrack glyph coverage offsets int[] igcoa = new int [ nig ]; for ( int i = 0; i < nig; i++ ) { igcoa [ i ] = in.readTTFUShort(); } // read lookahead glyph count int nlg = in.readTTFUShort(); // read backtrack glyph coverage offsets int[] lgcoa = new int [ nlg ]; for ( int i = 0; i < nlg; i++ ) { lgcoa [ i ] = in.readTTFUShort(); } // read positioning lookup count int nl = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " chained contextual positioning subtable format: " + subtableFormat + " (glyph sets)" ); log.debug(tableTag + " chained contextual positioning backtrack glyph count: " + nbg ); for ( int i = 0; i < nbg; i++ ) { log.debug(tableTag + " chained contextual positioning backtrack coverage table offset[" + i + "]: " + bgcoa[i] ); } log.debug(tableTag + " chained contextual positioning input glyph count: " + nig ); for ( int i = 0; i < nig; i++ ) { log.debug(tableTag + " chained contextual positioning input coverage table offset[" + i + "]: " + igcoa[i] ); } log.debug(tableTag + " chained contextual positioning lookahead glyph count: " + nlg ); for ( int i = 0; i < nlg; i++ ) { log.debug(tableTag + " chained contextual positioning lookahead coverage table offset[" + i + "]: " + lgcoa[i] ); } log.debug(tableTag + " chained contextual positioning lookup count: " + nl ); } // read backtrack coverage tables GlyphCoverageTable[] bgca = new GlyphCoverageTable[nbg]; for ( int i = 0; i < nbg; i++ ) { int bgco = bgcoa [ i ]; GlyphCoverageTable bgct; if ( bgco > 0 ) { bgct = readCoverageTable ( tableTag + " chained contextual positioning backtrack coverage[" + i + "]", subtableOffset + bgco ); } else { bgct = null; } bgca[i] = bgct; } // read input coverage tables GlyphCoverageTable[] igca = new GlyphCoverageTable[nig]; for ( int i = 0; i < nig; i++ ) { int igco = igcoa [ i ]; GlyphCoverageTable igct; if ( igco > 0 ) { igct = readCoverageTable ( tableTag + " chained contextual positioning input coverage[" + i + "]", subtableOffset + igco ); } else { igct = null; } igca[i] = igct; } // read lookahead coverage tables GlyphCoverageTable[] lgca = new GlyphCoverageTable[nlg]; for ( int i = 0; i < nlg; i++ ) { int lgco = lgcoa [ i ]; GlyphCoverageTable lgct; if ( lgco > 0 ) { lgct = readCoverageTable ( tableTag + " chained contextual positioning lookahead coverage[" + i + "]", subtableOffset + lgco ); } else { lgct = null; } lgca[i] = lgct; } // read rule lookups String header = null; if (log.isDebugEnabled()) { header = tableTag + " chained contextual positioning lookups: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); // construct rule, rule set, and rule set array GlyphTable.Rule r = new GlyphTable.ChainedCoverageSequenceRule ( lookups, nig, igca, bgca, lgca ); GlyphTable.RuleSet rs = new GlyphTable.HomogeneousRuleSet ( new GlyphTable.Rule[] {r} ); GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet[] {rs}; // store results assert ( igca != null ) && ( igca.length > 0 ); seMapping = igca[0]; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readChainedContextualPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readChainedContextualPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readChainedContextualPosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readChainedContextualPosTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported chained contextual positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readExtensionPosTableFormat1(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read extension lookup type int lt = in.readTTFUShort(); // read extension offset long eo = in.readTTFULong(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " extension positioning subtable format: " + subtableFormat ); log.debug(tableTag + " extension positioning lookup type: " + lt ); log.debug(tableTag + " extension positioning lookup table offset: " + eo ); } // read referenced subtable from extended offset readGPOSSubtable ( lt, lookupFlags, lookupSequence, subtableSequence, subtableOffset + eo ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readExtensionPosTable(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readExtensionPosTableFormat1 ( lookupType, lookupFlags, lookupSequence, subtableSequence, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported extension positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGPOSSubtable(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset) throws IOException { initATSubState(); int subtableFormat = -1; switch ( lookupType ) { case GPOSLookupType.SINGLE: subtableFormat = readSinglePosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.PAIR: subtableFormat = readPairPosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.CURSIVE: subtableFormat = readCursivePosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.MARK_TO_BASE: subtableFormat = readMarkToBasePosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.MARK_TO_LIGATURE: subtableFormat = readMarkToLigaturePosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.MARK_TO_MARK: subtableFormat = readMarkToMarkPosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.CONTEXTUAL: subtableFormat = readContextualPosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.CHAINED_CONTEXTUAL: subtableFormat = readChainedContextualPosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.EXTENSION: subtableFormat = readExtensionPosTable ( lookupType, lookupFlags, lookupSequence, subtableSequence, subtableOffset ); break; default: break; } extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_POSITIONING, lookupType, lookupFlags, lookupSequence, subtableSequence, subtableFormat ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readLookupTable(String tableTag, int lookupSequence, long lookupTable) throws IOException { boolean isGSUB = tableTag.equals ( "GSUB" ); boolean isGPOS = tableTag.equals ( "GPOS" ); in.seekSet(lookupTable); // read lookup type int lt = in.readTTFUShort(); // read lookup flags int lf = in.readTTFUShort(); // read sub-table count int ns = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { String lts; if ( isGSUB ) { lts = GSUBLookupType.toString ( lt ); } else if ( isGPOS ) { lts = GPOSLookupType.toString ( lt ); } else { lts = "?"; } log.debug(tableTag + " lookup table type: " + lt + " (" + lts + ")" ); log.debug(tableTag + " lookup table flags: " + lf + " (" + LookupFlag.toString ( lf ) + ")" ); log.debug(tableTag + " lookup table subtable count: " + ns ); } // read subtable offsets int[] soa = new int[ns]; for ( int i = 0; i < ns; i++ ) { int so = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " lookup table subtable offset: " + so ); } soa[i] = so; } // read mark filtering set if ( ( lf & LookupFlag.USE_MARK_FILTERING_SET ) != 0 ) { // read mark filtering set int fs = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " lookup table mark filter set: " + fs ); } } // read subtables for ( int i = 0; i < ns; i++ ) { int so = soa[i]; if ( isGSUB ) { readGSUBSubtable ( lt, lf, lookupSequence, i, lookupTable + so ); } else if ( isGPOS ) { readGPOSSubtable ( lt, lf, lookupSequence, i, lookupTable + so ); } } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readLookupList(String tableTag, long lookupList) throws IOException { in.seekSet(lookupList); // read lookup record count int nl = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " lookup list record count: " + nl ); } if ( nl > 0 ) { int[] loa = new int[nl]; // read lookup records for ( int i = 0, n = nl; i < n; i++ ) { int lo = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " lookup table offset: " + lo ); } loa[i] = lo; } // read lookup tables for ( int i = 0, n = nl; i < n; i++ ) { if (log.isDebugEnabled()) { log.debug(tableTag + " lookup index: " + i ); } readLookupTable ( tableTag, i, lookupList + loa [ i ] ); } } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readCommonLayoutTables(String tableTag, long scriptList, long featureList, long lookupList) throws IOException { if ( scriptList > 0 ) { readScriptList ( tableTag, scriptList ); } if ( featureList > 0 ) { readFeatureList ( tableTag, featureList ); } if ( lookupList > 0 ) { readLookupList ( tableTag, lookupList ); } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFClassDefTable(String tableTag, int lookupSequence, long subtableOffset) throws IOException { initATSubState(); in.seekSet(subtableOffset); // subtable is a bare class definition table GlyphClassTable ct = readClassDefTable ( tableTag + " glyph class definition table", subtableOffset ); // store results seMapping = ct; // extract subtable extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_DEFINITION, GDEFLookupType.GLYPH_CLASS, 0, lookupSequence, 0, 1 ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFAttachmentTable(String tableTag, int lookupSequence, long subtableOffset) throws IOException { initATSubState(); in.seekSet(subtableOffset); // read coverage offset int co = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " attachment point coverage table offset: " + co ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " attachment point coverage", subtableOffset + co ); // store results seMapping = ct; // extract subtable extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_DEFINITION, GDEFLookupType.ATTACHMENT_POINT, 0, lookupSequence, 0, 1 ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFLigatureCaretTable(String tableTag, int lookupSequence, long subtableOffset) throws IOException { initATSubState(); in.seekSet(subtableOffset); // read coverage offset int co = in.readTTFUShort(); // read ligature glyph count int nl = in.readTTFUShort(); // read ligature glyph table offsets int[] lgto = new int [ nl ]; for ( int i = 0; i < nl; i++ ) { lgto [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " ligature caret coverage table offset: " + co ); log.debug(tableTag + " ligature caret ligature glyph count: " + nl ); for ( int i = 0; i < nl; i++ ) { log.debug(tableTag + " ligature glyph table offset[" + i + "]: " + lgto[i] ); } } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " ligature caret coverage", subtableOffset + co ); // store results seMapping = ct; // extract subtable extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_DEFINITION, GDEFLookupType.LIGATURE_CARET, 0, lookupSequence, 0, 1 ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFMarkAttachmentTable(String tableTag, int lookupSequence, long subtableOffset) throws IOException { initATSubState(); in.seekSet(subtableOffset); // subtable is a bare class definition table GlyphClassTable ct = readClassDefTable ( tableTag + " glyph class definition table", subtableOffset ); // store results seMapping = ct; // extract subtable extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_DEFINITION, GDEFLookupType.MARK_ATTACHMENT, 0, lookupSequence, 0, 1 ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFMarkGlyphsTableFormat1(String tableTag, int lookupSequence, long subtableOffset, int subtableFormat) throws IOException { initATSubState(); in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read mark set class count int nmc = in.readTTFUShort(); long[] mso = new long [ nmc ]; // read mark set coverage offsets for ( int i = 0; i < nmc; i++ ) { mso [ i ] = in.readTTFULong(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " mark set subtable format: " + subtableFormat + " (glyph sets)" ); log.debug(tableTag + " mark set class count: " + nmc ); for ( int i = 0; i < nmc; i++ ) { log.debug(tableTag + " mark set coverage table offset[" + i + "]: " + mso[i] ); } } // read mark set coverage tables, one per class GlyphCoverageTable[] msca = new GlyphCoverageTable[nmc]; for ( int i = 0; i < nmc; i++ ) { msca[i] = readCoverageTable ( tableTag + " mark set coverage[" + i + "]", subtableOffset + mso[i] ); } // create combined class table from per-class coverage tables GlyphClassTable ct = GlyphClassTable.createClassTable ( Arrays.asList ( msca ) ); // store results seMapping = ct; // extract subtable extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_DEFINITION, GDEFLookupType.MARK_ATTACHMENT, 0, lookupSequence, 0, 1 ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFMarkGlyphsTable(String tableTag, int lookupSequence, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read mark set subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readGDEFMarkGlyphsTableFormat1 ( tableTag, lookupSequence, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark glyph sets subtable format: " + sf ); } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEF() throws IOException { String tableTag = "GDEF"; // Initialize temporary state initATState(); // Read glyph definition (GDEF) table TTFDirTabEntry dirTab = ttf.getDirectoryEntry ( tableTag ); if ( gdef != null ) { if (log.isDebugEnabled()) { log.debug(tableTag + ": ignoring duplicate table"); } } else if (dirTab != null) { ttf.seekTab(in, tableTag, 0); long version = in.readTTFULong(); if (log.isDebugEnabled()) { log.debug(tableTag + " version: " + ( version / 65536 ) + "." + ( version % 65536 )); } // glyph class definition table offset (may be null) int cdo = in.readTTFUShort(); // attach point list offset (may be null) int apo = in.readTTFUShort(); // ligature caret list offset (may be null) int lco = in.readTTFUShort(); // mark attach class definition table offset (may be null) int mao = in.readTTFUShort(); // mark glyph sets definition table offset (may be null) int mgo; if ( version >= 0x00010002 ) { mgo = in.readTTFUShort(); } else { mgo = 0; } if (log.isDebugEnabled()) { log.debug(tableTag + " glyph class definition table offset: " + cdo ); log.debug(tableTag + " attachment point list offset: " + apo ); log.debug(tableTag + " ligature caret list offset: " + lco ); log.debug(tableTag + " mark attachment class definition table offset: " + mao ); log.debug(tableTag + " mark glyph set definitions table offset: " + mgo ); } // initialize subtable sequence number int seqno = 0; // obtain offset to start of gdef table long to = dirTab.getOffset(); // (optionally) read glyph class definition subtable if ( cdo != 0 ) { readGDEFClassDefTable ( tableTag, seqno++, to + cdo ); } // (optionally) read glyph attachment point subtable if ( apo != 0 ) { readGDEFAttachmentTable ( tableTag, seqno++, to + apo ); } // (optionally) read ligature caret subtable if ( lco != 0 ) { readGDEFLigatureCaretTable ( tableTag, seqno++, to + lco ); } // (optionally) read mark attachment class subtable if ( mao != 0 ) { readGDEFMarkAttachmentTable ( tableTag, seqno++, to + mao ); } // (optionally) read mark glyph sets subtable if ( mgo != 0 ) { readGDEFMarkGlyphsTable ( tableTag, seqno++, to + mgo ); } GlyphDefinitionTable gdef; if ( ( gdef = constructGDEF() ) != null ) { this.gdef = gdef; } } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGSUB() throws IOException { String tableTag = "GSUB"; // Initialize temporary state initATState(); // Read glyph substitution (GSUB) table TTFDirTabEntry dirTab = ttf.getDirectoryEntry ( tableTag ); if ( gpos != null ) { if (log.isDebugEnabled()) { log.debug(tableTag + ": ignoring duplicate table"); } } else if (dirTab != null) { ttf.seekTab(in, tableTag, 0); int version = in.readTTFLong(); if (log.isDebugEnabled()) { log.debug(tableTag + " version: " + ( version / 65536 ) + "." + ( version % 65536 )); } int slo = in.readTTFUShort(); int flo = in.readTTFUShort(); int llo = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " script list offset: " + slo ); log.debug(tableTag + " feature list offset: " + flo ); log.debug(tableTag + " lookup list offset: " + llo ); } long to = dirTab.getOffset(); readCommonLayoutTables ( tableTag, to + slo, to + flo, to + llo ); GlyphSubstitutionTable gsub; if ( ( gsub = constructGSUB() ) != null ) { this.gsub = gsub; } } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGPOS() throws IOException { String tableTag = "GPOS"; // Initialize temporary state initATState(); // Read glyph positioning (GPOS) table TTFDirTabEntry dirTab = ttf.getDirectoryEntry ( tableTag ); if ( gpos != null ) { if (log.isDebugEnabled()) { log.debug(tableTag + ": ignoring duplicate table"); } } else if (dirTab != null) { ttf.seekTab(in, tableTag, 0); int version = in.readTTFLong(); if (log.isDebugEnabled()) { log.debug(tableTag + " version: " + ( version / 65536 ) + "." + ( version % 65536 )); } int slo = in.readTTFUShort(); int flo = in.readTTFUShort(); int llo = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " script list offset: " + slo ); log.debug(tableTag + " feature list offset: " + flo ); log.debug(tableTag + " lookup list offset: " + llo ); } long to = dirTab.getOffset(); readCommonLayoutTables ( tableTag, to + slo, to + flo, to + llo ); GlyphPositioningTable gpos; if ( ( gpos = constructGPOS() ) != null ) { this.gpos = gpos; } } }
// in src/java/org/apache/fop/util/DataURLUtil.java
public static String createDataURL(InputStream in, String mediatype) throws IOException { return org.apache.xmlgraphics.util.uri.DataURLUtil.createDataURL(in, mediatype); }
// in src/java/org/apache/fop/util/DataURLUtil.java
public static void writeDataURL(InputStream in, String mediatype, Writer writer) throws IOException { org.apache.xmlgraphics.util.uri.DataURLUtil.writeDataURL(in, mediatype, writer); }
// in src/java/org/apache/fop/util/WriterOutputStream.java
public void close() throws IOException { writerOutputStream.close(); }
// in src/java/org/apache/fop/util/WriterOutputStream.java
public void flush() throws IOException { writerOutputStream.flush(); }
// in src/java/org/apache/fop/util/WriterOutputStream.java
public void write(byte[] buf, int offset, int length) throws IOException { writerOutputStream.write(buf, offset, length); }
// in src/java/org/apache/fop/util/WriterOutputStream.java
public void write(byte[] buf) throws IOException { writerOutputStream.write(buf); }
// in src/java/org/apache/fop/util/WriterOutputStream.java
public void write(int b) throws IOException { writerOutputStream.write(b); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (entityResolver != null) { return entityResolver.resolveEntity(publicId, systemId); } else { return null; } }
// in src/java/org/apache/fop/util/CloseBlockerOutputStream.java
public void close() throws IOException { try { flush(); } catch (IOException ioe) { //ignore } }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
public ImageInfo preloadImage(String uri, Source src, ImageContext context) throws IOException { if (!ImageUtil.hasInputStream(src)) { return null; } ImageInfo info = null; if (batikAvailable) { try { Loader loader = new Loader(); info = loader.getImage(uri, src, context); } catch (NoClassDefFoundError e) { batikAvailable = false; log.warn("Batik not in class path", e); return null; } } if (info != null) { ImageUtil.closeQuietly(src); //Image is fully read } return info; }
// in src/java/org/apache/fop/image/loader/batik/ImageLoaderSVG.java
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!MimeConstants.MIME_SVG.equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from an SVG image"); } Image img = info.getOriginalImage(); if (!(img instanceof ImageXMLDOM)) { throw new IllegalArgumentException( "ImageInfo was expected to contain the SVG document as DOM"); } ImageXMLDOM svgImage = (ImageXMLDOM)img; if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(svgImage.getRootNamespace())) { throw new IllegalArgumentException( "The Image is not in the SVG namespace: " + svgImage.getRootNamespace()); } return svgImage; }
// in src/java/org/apache/fop/image/loader/batik/ImageLoaderWMF.java
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!ImageWMF.MIME_WMF.equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from a WMF image"); } Image img = info.getOriginalImage(); if (!(img instanceof ImageWMF)) { throw new IllegalArgumentException( "ImageInfo was expected to contain the Windows Metafile (WMF)"); } ImageWMF wmfImage = (ImageWMF)img; return wmfImage; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
public ImageInfo preloadImage(String uri, Source src, ImageContext context) throws IOException { ImageInfo info = null; if (batikAvailable) { try { Loader loader = new Loader(); if (!loader.isSupportedSource(src)) { return null; } info = loader.getImage(uri, src, context); } catch (NoClassDefFoundError e) { batikAvailable = false; log.warn("Batik not in class path", e); return null; } } if (info != null) { ImageUtil.closeQuietly(src); //Image is fully read } return info; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
public boolean parse(String[] args) throws FOPException, IOException { boolean optionsParsed = true; try { optionsParsed = parseOptions(args); if (optionsParsed) { if (showConfiguration == Boolean.TRUE) { dumpConfiguration(); } checkSettings(); setUserConfig(); if (flushCache) { flushCache(); } //Factory config is set up, now we can create the user agent foUserAgent = factory.newFOUserAgent(); foUserAgent.getRendererOptions().putAll(renderingOptions); if (targetResolution != 0) { foUserAgent.setTargetResolution(targetResolution); } addXSLTParameter("fop-output-format", getOutputFormat()); addXSLTParameter("fop-version", Version.getVersion()); foUserAgent.setConserveMemoryPolicy(conserveMemoryPolicy); if (!useComplexScriptFeatures) { foUserAgent.setComplexScriptFeaturesEnabled(false); } } else { return false; } } catch (FOPException e) { printUsage(System.err); throw e; } catch (java.io.FileNotFoundException e) { printUsage(System.err); throw e; } inputHandler = createInputHandler(); if (MimeConstants.MIME_FOP_AWT_PREVIEW.equals(outputmode)) { //set the system look&feel for the preview dialog try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println("Couldn't set system look & feel!"); } AWTRenderer renderer = new AWTRenderer(foUserAgent, inputHandler, true, true); foUserAgent.setRendererOverride(renderer); } else if (MimeConstants.MIME_FOP_AREA_TREE.equals(outputmode) && mimicRenderer != null) { // render from FO to Intermediate Format Renderer targetRenderer = foUserAgent.getRendererFactory().createRenderer( foUserAgent, mimicRenderer); XMLRenderer xmlRenderer = new XMLRenderer(foUserAgent); //Tell the XMLRenderer to mimic the target renderer xmlRenderer.mimicRenderer(targetRenderer); //Make sure the prepared XMLRenderer is used foUserAgent.setRendererOverride(xmlRenderer); } else if (MimeConstants.MIME_FOP_IF.equals(outputmode) && mimicRenderer != null) { // render from FO to Intermediate Format IFSerializer serializer = new IFSerializer(); serializer.setContext(new IFContext(foUserAgent)); IFDocumentHandler targetHandler = foUserAgent.getRendererFactory().createDocumentHandler( foUserAgent, mimicRenderer); serializer.mimicDocumentHandler(targetHandler); //Make sure the prepared serializer is used foUserAgent.setDocumentHandlerOverride(serializer); } return true; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setUserConfig() throws FOPException, IOException { if (userConfigFile == null) { return; } try { factory.setUserConfig(userConfigFile); } catch (SAXException e) { throw new FOPException(e); } }
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void writeGenerated(Writer w) throws IOException { w.write("<!-- !!! THIS IS A GENERATED FILE !!! -->\n"); w.write("<!-- If updates are needed, then: -->\n"); w.write("<!-- * run 'ant codegen-hyphenation-classes', -->\n"); w.write("<!-- which will generate a new file classes.xml -->\n"); w.write("<!-- in 'src/java/org/apache/fop/hyphenation' -->\n"); w.write("<!-- * commit the changed file -->\n"); }
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void fromJava(boolean hexcode, String outfilePath) throws IOException { File f = new File(outfilePath); if (f.exists()) { f.delete(); } f.createNewFile(); FileOutputStream fw = new FileOutputStream(f); OutputStreamWriter ow = new OutputStreamWriter(fw, "utf-8"); int maxChar; maxChar = Character.MAX_VALUE; ow.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); License.writeXMLLicenseId(ow); ow.write("\n"); writeGenerated(ow); ow.write("\n"); ow.write("<classes>\n"); // loop over the first Unicode plane for (int code = Character.MIN_VALUE; code <= maxChar; ++code) { // skip surrogate area if (code == Character.MIN_SURROGATE) { code = Character.MAX_SURROGATE; continue; } // we are only interested in LC, UC and TC letters which are their own LC, // and in 'other letters' if (!(((Character.isLowerCase(code) || Character.isUpperCase(code) || Character.isTitleCase(code)) && code == Character.toLowerCase(code)) || Character.getType(code) == Character.OTHER_LETTER)) { continue; } // skip a number of blocks Character.UnicodeBlock ubi = Character.UnicodeBlock.of(code); if (ubi.equals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS) || ubi.equals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS) || ubi.equals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS) || ubi.equals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) || ubi.equals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) || ubi.equals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A) || ubi.equals(Character.UnicodeBlock.HANGUL_SYLLABLES)) { continue; } int uppercode = Character.toUpperCase(code); int titlecode = Character.toTitleCase(code); StringBuilder s = new StringBuilder(); if (hexcode) { s.append("0x" + Integer.toHexString(code) + " "); } s.append(Character.toChars(code)); if (uppercode != code) { s.append(Character.toChars(uppercode)); } if (titlecode != code && titlecode != uppercode) { s.append(Character.toChars(titlecode)); } ow.write(s.toString() + "\n"); } ow.write("</classes>\n"); ow.flush(); ow.close(); }
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void fromUCD(boolean hexcode, String unidataPath, String outfilePath) throws IOException, URISyntaxException { URI unidata; if (unidataPath.endsWith("/")) { unidata = new URI(unidataPath); } else { unidata = new URI(unidataPath + "/"); } String scheme = unidata.getScheme(); if (scheme == null || !(scheme.equals("file") || scheme.equals("http"))) { throw new FileNotFoundException ("URI with file or http scheme required for UNIDATA input directory"); } File f = new File(outfilePath); if (f.exists()) { f.delete(); } f.createNewFile(); FileOutputStream fw = new FileOutputStream(f); OutputStreamWriter ow = new OutputStreamWriter(fw, "utf-8"); URI inuri = unidata.resolve("Blocks.txt"); InputStream inis = null; if (scheme.equals("file")) { File in = new File(inuri); inis = new FileInputStream(in); } else if (scheme.equals("http")) { inis = inuri.toURL().openStream(); } InputStreamReader insr = new InputStreamReader(inis, "utf-8"); BufferedReader inbr = new BufferedReader(insr); Map blocks = new HashMap(); for (String line = inbr.readLine(); line != null; line = inbr.readLine()) { if (line.startsWith("#") || line.matches("^\\s*$")) { continue; } String[] parts = line.split(";"); String block = parts[1].trim(); String[] indices = parts[0].split("\\.\\."); int[] ind = {Integer.parseInt(indices[0], 16), Integer.parseInt(indices[1], 16)}; blocks.put(block, ind); } inbr.close(); inuri = unidata.resolve("UnicodeData.txt"); if (scheme.equals("file")) { File in = new File(inuri); inis = new FileInputStream(in); } else if (scheme.equals("http")) { inis = inuri.toURL().openStream(); } insr = new InputStreamReader(inis, "utf-8"); inbr = new BufferedReader(insr); int maxChar; maxChar = Character.MAX_VALUE; ow.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); License.writeXMLLicenseId(ow); ow.write("\n"); writeGenerated(ow); ow.write("\n"); ow.write("<classes>\n"); for (String line = inbr.readLine(); line != null; line = inbr.readLine()) { String[] fields = line.split(";", NUM_FIELDS); int code = Integer.parseInt(fields[UNICODE], 16); if (code > maxChar) { break; } if (((fields[GENERAL_CATEGORY].equals("Ll") || fields[GENERAL_CATEGORY].equals("Lu") || fields[GENERAL_CATEGORY].equals("Lt")) && ("".equals(fields[SIMPLE_LOWERCASE_MAPPING]) || fields[UNICODE].equals(fields[SIMPLE_LOWERCASE_MAPPING]))) || fields[GENERAL_CATEGORY].equals("Lo")) { String[] blockNames = {"Superscripts and Subscripts", "Letterlike Symbols", "Alphabetic Presentation Forms", "Halfwidth and Fullwidth Forms", "CJK Unified Ideographs", "CJK Unified Ideographs Extension A", "Hangul Syllables"}; int j; for (j = 0; j < blockNames.length; ++j) { int[] ind = (int[]) blocks.get(blockNames[j]); if (code >= ind[0] && code <= ind[1]) { break; } } if (j < blockNames.length) { continue; } int uppercode = -1; int titlecode = -1; if (!"".equals(fields[SIMPLE_UPPERCASE_MAPPING])) { uppercode = Integer.parseInt(fields[SIMPLE_UPPERCASE_MAPPING], 16); } if (!"".equals(fields[SIMPLE_TITLECASE_MAPPING])) { titlecode = Integer.parseInt(fields[SIMPLE_TITLECASE_MAPPING], 16); } StringBuilder s = new StringBuilder(); if (hexcode) { s.append("0x" + fields[UNICODE].replaceFirst("^0+", "").toLowerCase() + " "); } s.append(Character.toChars(code)); if (uppercode != -1 && uppercode != code) { s.append(Character.toChars(uppercode)); } if (titlecode != -1 && titlecode != code && titlecode != uppercode) { s.append(Character.toChars(titlecode)); } ow.write(s.toString() + "\n"); } } ow.write("</classes>\n"); ow.flush(); ow.close(); inbr.close(); }
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void fromTeX(boolean hexcode, String lettersPath, String outfilePath) throws IOException { File in = new File(lettersPath); File f = new File(outfilePath); if (f.exists()) { f.delete(); } f.createNewFile(); FileOutputStream fw = new FileOutputStream(f); OutputStreamWriter ow = new OutputStreamWriter(fw, "utf-8"); FileInputStream inis = new FileInputStream(in); InputStreamReader insr = new InputStreamReader(inis, "utf-8"); BufferedReader inbr = new BufferedReader(insr); ow.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); License.writeXMLLicenseId(ow); ow.write("\n"); writeGenerated(ow); ow.write("\n"); ow.write("<classes>\n"); for (String line = inbr.readLine(); line != null; line = inbr.readLine()) { String[] codes = line.split("\\s+"); if (!(codes[0].equals("\\L") || codes[0].equals("\\l"))) { continue; } if (codes.length == 3) { ow.write("\"" + line + "\" has two codes"); continue; } if (codes[0].equals("\\l") && codes.length != 2) { ow.write("\"" + line + "\" should have one code"); continue; } else if (codes[0].equals("\\L") && codes.length != 4) { ow.write("\"" + line + "\" should have three codes"); continue; } if (codes[0].equals("\\l") || (codes[0].equals("\\L") && codes[1].equals(codes[3]))) { StringBuilder s = new StringBuilder(); if (hexcode) { s.append("0x" + codes[1].replaceFirst("^0+", "").toLowerCase() + " "); } s.append(Character.toChars(Integer.parseInt(codes[1], 16))); if (codes[0].equals("\\L")) { s.append(Character.toChars(Integer.parseInt(codes[2], 16))); } ow.write(s.toString() + "\n"); } } ow.write("</classes>\n"); ow.flush(); ow.close(); inbr.close(); }
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void main(String[] args) throws IOException, URISyntaxException { String type = "ucd"; String prefix = "--"; String infile = null; String outfile = null; boolean hexcode = false; int i; for (i = 0; i < args.length && args[i].startsWith(prefix); ++i) { String option = args[i].substring(prefix.length()); if (option.equals("java") || option.equals("ucd") || option.equals("tex")) { type = option; } else if (option.equals("hexcode")) { hexcode = true; } else { System.err.println("Unknown option: " + option); System.exit(1); } } if (i < args.length) { outfile = args[i]; } else { System.err.println("Output file is required; aborting"); System.exit(1); } if (++i < args.length) { infile = args[i]; } if (type.equals("java") && infile != null) { System.err.println("Type java does not allow an infile"); System.exit(1); } else if (type.equals("ucd") && infile == null) { infile = UNICODE_DIR; } else if (type.equals("tex") && infile == null) { System.err.println("Type tex requires an input file"); System.exit(1); } if (type.equals("java")) { fromJava(hexcode, outfile); } else if (type.equals("ucd")) { fromUCD(hexcode, infile, outfile); } else if (type.equals("tex")) { fromTeX(hexcode, infile, outfile); } else { System.err.println("Unknown type: " + type + ", nothing done"); System.exit(1); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int readType ( String line, BufferedReader b, List lines ) throws IOException { lines.add ( line ); return 0; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int readLevels ( String line, BufferedReader b, List lines ) throws IOException { boolean done = false; int n = 0; lines.add ( line ); while ( ! done ) { switch ( testPrefix ( b, PFX_LEVELS ) ) { case 0: // within current levels if ( ( line = b.readLine() ) != null ) { n++; if ( ( line.length() > 0 ) && ! line.startsWith("#") ) { lines.add ( line ); } } else { done = true; } break; case 1: // end of current levels case -1: // eof default: done = true; break; } } return n; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int testPrefix ( BufferedReader b, String pfx ) throws IOException { int rv = 0; int pfxLen = pfx.length(); b.mark ( pfxLen ); for ( int i = 0, n = pfxLen; i < n; i++ ) { int c = b.read(); if ( c < 0 ) { rv = -1; break; } else if ( c != pfx.charAt ( i ) ) { rv = 0; break; } else { rv = 1; } } b.reset(); return rv; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void dumpData ( PrintWriter out, String outFileName ) throws IOException { File f = new File ( outFileName ); File p = f.getParentFile(); if ( td != null ) { String pfxTD = "TD"; dumpResourcesDescriptor ( out, pfxTD, td.length ); dumpResourcesData ( p, f.getName(), pfxTD, td ); } if ( ld != null ) { String pfxTD = "LD"; dumpResourcesDescriptor ( out, pfxTD, ld.length ); dumpResourcesData ( p, f.getName(), pfxTD, ld ); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void dumpResourcesData ( File btcDir, String btcName, String prefix, int[][] data ) throws IOException { String btdName = extractDataFileName ( btcName ); for ( int i = 0, n = data.length; i < n; i++ ) { File f = new File ( btcDir, btdName + "$" + prefix + i + ".ser" ); ObjectOutputStream os = new ObjectOutputStream ( new FileOutputStream ( f ) ); os.writeObject ( data[i] ); os.close(); } }
// in src/codegen/unicode/java/org/apache/fop/util/License.java
public static void writeJavaLicenseId(Writer w) throws IOException { w.write("/*\n"); for (int i = 0; i < LICENSE.length; ++i) { if (LICENSE[i].equals("")) { w.write(" *\n"); } else { w.write(" * " + LICENSE[i] + "\n"); } } w.write(" */\n"); w.write("\n"); w.write("/* " + ID + " */\n"); }
// in src/codegen/unicode/java/org/apache/fop/util/License.java
public static void writeXMLLicenseId(Writer w) throws IOException { for (int i = 0; i < LICENSE.length; ++i) { w.write(String.format("<!-- %-" + maxLength + "s -->\n", new Object[] {LICENSE[i]})); } w.write("\n"); w.write("<!-- " + ID + " -->\n"); }
// in src/codegen/unicode/java/org/apache/fop/util/License.java
public static void main(String[] args) throws IOException { StringWriter w = new StringWriter(); if (args.length == 0 || args[0].equals("--java")) { writeJavaLicenseId(w); } else if (args[0].equals("--xml")) { writeXMLLicenseId(w); } System.out.println(w.toString()); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
protected void updateTranslationFile(File modelFile) throws IOException { try { boolean resultExists = getTranslationFile().exists(); SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); //Generate fresh generated translation file as template Source src = new StreamSource(modelFile.toURI().toURL().toExternalForm()); StreamSource xslt1 = new StreamSource( getClass().getResourceAsStream(MODEL2TRANSLATION)); if (xslt1.getInputStream() == null) { throw new FileNotFoundException(MODEL2TRANSLATION + " not found"); } DOMResult domres = new DOMResult(); Transformer transformer = tFactory.newTransformer(xslt1); transformer.transform(src, domres); final Node generated = domres.getNode(); Node sourceDocument; if (resultExists) { //Load existing translation file into memory (because we overwrite it later) src = new StreamSource(getTranslationFile().toURI().toURL().toExternalForm()); domres = new DOMResult(); transformer = tFactory.newTransformer(); transformer.transform(src, domres); sourceDocument = domres.getNode(); } else { //Simply use generated as source document sourceDocument = generated; } //Generate translation file (with potentially new translations) src = new DOMSource(sourceDocument); //The following triggers a bug in older Xalan versions //Result res = new StreamResult(getTranslationFile()); OutputStream out = new java.io.FileOutputStream(getTranslationFile()); out = new java.io.BufferedOutputStream(out); Result res = new StreamResult(out); try { StreamSource xslt2 = new StreamSource( getClass().getResourceAsStream(MERGETRANSLATION)); if (xslt2.getInputStream() == null) { throw new FileNotFoundException(MERGETRANSLATION + " not found"); } transformer = tFactory.newTransformer(xslt2); transformer.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { if ("my:dom".equals(href)) { return new DOMSource(generated); } return null; } }); if (resultExists) { transformer.setParameter("generated-url", "my:dom"); } transformer.transform(src, res); if (resultExists) { log("Translation file updated: " + getTranslationFile()); } else { log("Translation file generated: " + getTranslationFile()); } } finally { IOUtils.closeQuietly(out); } } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
protected long processFileSets(EventProducerCollector collector) throws IOException, EventConventionException, ClassNotFoundException { long lastModified = 0; Iterator<FileSet> iter = filesets.iterator(); while (iter.hasNext()) { FileSet fs = (FileSet)iter.next(); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); String[] srcFiles = ds.getIncludedFiles(); File directory = fs.getDir(getProject()); for (int i = 0, c = srcFiles.length; i < c; i++) { String filename = srcFiles[i]; File src = new File(directory, filename); boolean eventProducerFound = collector.scanFile(src); if (eventProducerFound) { lastModified = Math.max(lastModified, src.lastModified()); } } } return lastModified; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
public boolean scanFile(File src) throws IOException, EventConventionException, ClassNotFoundException { JavaDocBuilder builder = new JavaDocBuilder(this.tagFactory); builder.addSource(src); JavaClass[] classes = builder.getClasses(); boolean eventProducerFound = false; for (int i = 0, c = classes.length; i < c; i++) { JavaClass clazz = classes[i]; if (clazz.isInterface() && implementsInterface(clazz, CLASSNAME_EVENT_PRODUCER)) { processEventProducerInterface(clazz); eventProducerFound = true; } } return eventProducerFound; }
(Lib) SAXException 38
              
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
public void startDocument() throws SAXException { log.fatal("The MIF Handler is non-functional at this time. Please help resurrect it!"); mifFile = new MIFFile(); try { mifFile.output(outStream); } catch (IOException ioe) { throw new SAXException(ioe); } }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
public void endDocument() throws SAXException { // finish all open elements mifFile.finish(true); try { mifFile.output(outStream); outStream.flush(); } catch (IOException ioe) { throw new SAXException(ioe); } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void startElement(String namespaceURI, String localName, String rawName, Attributes attlist) throws SAXException { /* the node found in the FO document */ FONode foNode; PropertyList propertyList = null; // Check to ensure first node encountered is an fo:root if (rootFObj == null) { empty = false; if (!namespaceURI.equals(FOElementMapping.URI) || !localName.equals("root")) { FOValidationEventProducer eventProducer = FOValidationEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.invalidFORoot(this, FONode.getNodeString(namespaceURI, localName), getEffectiveLocator()); } } else { // check that incoming node is valid for currentFObj if (currentFObj.getNamespaceURI().equals(FOElementMapping.URI) || currentFObj.getNamespaceURI().equals(ExtensionElementMapping.URI)) { currentFObj.validateChildNode(locator, namespaceURI, localName); } } ElementMapping.Maker fobjMaker = findFOMaker(namespaceURI, localName); try { foNode = fobjMaker.make(currentFObj); if (rootFObj == null) { rootFObj = (Root) foNode; rootFObj.setBuilderContext(builderContext); rootFObj.setFOEventHandler(foEventHandler); } propertyList = foNode.createPropertyList( currentPropertyList, foEventHandler); foNode.processNode(localName, getEffectiveLocator(), attlist, propertyList); if (foNode.getNameId() == Constants.FO_MARKER) { if (builderContext.inMarker()) { nestedMarkerDepth++; } else { builderContext.switchMarkerContext(true); } } if (foNode.getNameId() == Constants.FO_PAGE_SEQUENCE) { builderContext.getXMLWhiteSpaceHandler().reset(); } } catch (IllegalArgumentException e) { throw new SAXException(e); } ContentHandlerFactory chFactory = foNode.getContentHandlerFactory(); if (chFactory != null) { ContentHandler subHandler = chFactory.createContentHandler(); if (subHandler instanceof ObjectSource && foNode instanceof ObjectBuiltListener) { ((ObjectSource) subHandler).setObjectBuiltListener( (ObjectBuiltListener) foNode); } subHandler.startDocument(); subHandler.startElement(namespaceURI, localName, rawName, attlist); depth = 1; delegate = subHandler; } if (currentFObj != null) { currentFObj.addChildNode(foNode); } currentFObj = foNode; if (propertyList != null && !builderContext.inMarker()) { currentPropertyList = propertyList; } // fo:characters can potentially be removed during // white-space handling. // Do not notify the FOEventHandler. if (currentFObj.getNameId() != Constants.FO_CHARACTER) { currentFObj.startOfNode(); } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void endElement(String uri, String localName, String rawName) throws SAXException { if (currentFObj == null) { throw new SAXException( "endElement() called for " + rawName + " where there is no current element."); } else if (!currentFObj.getLocalName().equals(localName) || !currentFObj.getNamespaceURI().equals(uri)) { throw new SAXException("Mismatch: " + currentFObj.getLocalName() + " (" + currentFObj.getNamespaceURI() + ") vs. " + localName + " (" + uri + ")"); } // fo:characters can potentially be removed during // white-space handling. // Do not notify the FOEventHandler. if (currentFObj.getNameId() != Constants.FO_CHARACTER) { currentFObj.endOfNode(); } if (currentPropertyList != null && currentPropertyList.getFObj() == currentFObj && !builderContext.inMarker()) { currentPropertyList = currentPropertyList.getParentPropertyList(); } if (currentFObj.getNameId() == Constants.FO_MARKER) { if (nestedMarkerDepth == 0) { builderContext.switchMarkerContext(false); } else { nestedMarkerDepth--; } } if (currentFObj.getParent() == null) { LOG.debug("endElement for top-level " + currentFObj.getName()); } currentFObj = currentFObj.getParent(); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (doc == null) { TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } String version = atts.getValue("version"); DOMImplementation domImplementation = getDOMImplementation(version); doc = domImplementation.createDocument(uri, qName, null); // It's easier to work with an empty document, so remove the // root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); setDelegateContentHandler(handler); setDelegateLexicalHandler(handler); setDelegateDTDHandler(handler); handler.startDocument(); } super.startElement(uri, localName, qName, atts); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
protected void getExternalClasses() throws SAXException { XMLReader mainParser = parser; parser = createParser(); parser.setContentHandler(this); parser.setErrorHandler(this); InputStream stream = this.getClass().getResourceAsStream("classes.xml"); InputSource source = new InputSource(stream); try { parser.parse(source); } catch (IOException ioe) { throw new SAXException(ioe.getMessage()); } finally { parser = mainParser; } }
// in src/java/org/apache/fop/svg/FOPSAXSVGDocumentFactory.java
public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (this.additionalResolver != null) { try { InputSource result = this.additionalResolver.resolveEntity(publicId, systemId); if (result != null) { return result; } } catch (IOException ioe) { /**@todo Batik's SAXSVGDocumentFactory should throw IOException, * so we don't have to handle it here. */ throw new SAXException(ioe); } } return super.resolveEntity(publicId, systemId); }
// in src/java/org/apache/fop/fonts/FontReader.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("font-metrics")) { if ("TYPE0".equals(attributes.getValue("type"))) { multiFont = new MultiByteFont(); returnFont = multiFont; isCID = true; TTFReader.checkMetricsVersion(attributes); } else if ("TRUETYPE".equals(attributes.getValue("type"))) { singleFont = new SingleByteFont(); singleFont.setFontType(FontType.TRUETYPE); returnFont = singleFont; isCID = false; TTFReader.checkMetricsVersion(attributes); } else { singleFont = new SingleByteFont(); singleFont.setFontType(FontType.TYPE1); returnFont = singleFont; isCID = false; } } else if ("embed".equals(localName)) { returnFont.setEmbedFileName(attributes.getValue("file")); returnFont.setEmbedResourceName(attributes.getValue("class")); } else if ("cid-widths".equals(localName)) { cidWidthIndex = getInt(attributes.getValue("start-index")); cidWidths = new ArrayList<Integer>(); } else if ("kerning".equals(localName)) { currentKerning = new HashMap<Integer, Integer>(); returnFont.putKerningEntry(new Integer(attributes.getValue("kpx1")), currentKerning); } else if ("bfranges".equals(localName)) { bfranges = new ArrayList<BFEntry>(); } else if ("bf".equals(localName)) { BFEntry entry = new BFEntry(getInt(attributes.getValue("us")), getInt(attributes.getValue("ue")), getInt(attributes.getValue("gi"))); bfranges.add(entry); } else if ("wx".equals(localName)) { cidWidths.add(new Integer(attributes.getValue("w"))); } else if ("widths".equals(localName)) { //singleFont.width = new int[256]; } else if ("char".equals(localName)) { try { singleFont.setWidth(Integer.parseInt(attributes.getValue("idx")), Integer.parseInt(attributes.getValue("wdt"))); } catch (NumberFormatException ne) { throw new SAXException("Malformed width in metric file: " + ne.getMessage(), ne); } } else if ("pair".equals(localName)) { currentKerning.put(new Integer(attributes.getValue("kpx2")), new Integer(attributes.getValue("kern"))); } }
// in src/java/org/apache/fop/fonts/FontReader.java
private int getInt(String str) throws SAXException { int ret = 0; try { ret = Integer.parseInt(str); } catch (Exception e) { throw new SAXException("Error while parsing integer value: " + str, e); } return ret; }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
public static void checkMetricsVersion(Attributes attr) throws SAXException { String err = null; final String str = attr.getValue(METRICS_VERSION_ATTR); if (str == null) { err = "Missing " + METRICS_VERSION_ATTR + " attribute"; } else { int version = 0; try { version = Integer.parseInt(str); if (version < METRICS_VERSION) { err = "Incompatible " + METRICS_VERSION_ATTR + " value (" + version + ", should be " + METRICS_VERSION + ")"; } } catch (NumberFormatException e) { err = "Invalid " + METRICS_VERSION_ATTR + " attribute value (" + str + ")"; } } if (err != null) { throw new SAXException( err + " - please regenerate the font metrics file with " + "a more recent version of FOP." ); } }
// in src/java/org/apache/fop/render/pdf/extensions/PDFExtensionHandler.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (PDFExtensionAttachment.CATEGORY.equals(uri)) { lastAttributes = new AttributesImpl(attributes); handled = false; if (localName.equals(PDFEmbeddedFileExtensionAttachment.ELEMENT)) { //handled in endElement handled = true; } } if (!handled) { if (PDFExtensionAttachment.CATEGORY.equals(uri)) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateDepth++; delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if (NAMESPACE.equals(uri)) { if (localName.equals(EL_PAGE_SEQUENCE) && userAgent.isAccessibilityEnabled()) { pageSequenceAttributes = new AttributesImpl(attributes); Locale language = getLanguage(attributes); structureTreeHandler = new StructureTreeHandler( userAgent.getStructureTreeEventHandler(), language); } else if (localName.equals(EL_STRUCTURE_TREE)) { if (userAgent.isAccessibilityEnabled()) { String type = attributes.getValue("type"); structureTreeHandler.startStructureTree(type); delegate = structureTreeHandler; } else { /* Delegate to a handler that does nothing */ delegate = new DefaultHandler(); } delegateDepth++; delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { if (pageSequenceAttributes != null) { /* * This means that no structure-element tag was * found in the XML, otherwise a * StructureTreeBuilderWrapper object would have * been created, which would have reset the * pageSequenceAttributes field. */ AccessibilityEventProducer.Provider .get(userAgent.getEventBroadcaster()) .noStructureTreeInXML(this); } handled = startIFElement(localName, attributes); } } else if (DocumentNavigationExtensionConstants.NAMESPACE.equals(uri)) { if (this.navParser == null) { this.navParser = new DocumentNavigationHandler( this.documentHandler.getDocumentNavigationHandler(), structureTreeElements); } delegate = this.navParser; delegateDepth++; delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { ContentHandlerFactoryRegistry registry = userAgent.getFactory().getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory == null) { DOMImplementation domImplementation = elementMappingRegistry.getDOMImplementationForNamespace(uri); if (domImplementation == null) { domImplementation = ElementMapping.getDefaultDOMImplementation(); /* throw new SAXException("No DOMImplementation could be" + " identified to handle namespace: " + uri); */ } factory = new DOMBuilderContentHandlerFactory(uri, domImplementation); } delegate = factory.createContentHandler(); delegateDepth++; delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
private void handleIFException(IFException ife) throws SAXException { if (ife.getCause() instanceof SAXException) { //unwrap throw (SAXException)ife.getCause(); } else { //wrap throw new SAXException(ife); } }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (NAMESPACE.equals(uri)) { if (BOOKMARK_TREE.getLocalName().equals(localName)) { if (!objectStack.isEmpty()) { throw new SAXException(localName + " must be the root element!"); } BookmarkTree bookmarkTree = new BookmarkTree(); objectStack.push(bookmarkTree); } else if (BOOKMARK.getLocalName().equals(localName)) { String title = attributes.getValue("title"); String s = attributes.getValue("starting-state"); boolean show = !"hide".equals(s); Bookmark b = new Bookmark(title, show, null); Object o = objectStack.peek(); if (o instanceof AbstractAction) { AbstractAction action = (AbstractAction)objectStack.pop(); o = objectStack.peek(); ((Bookmark)o).setAction(action); } if (o instanceof BookmarkTree) { ((BookmarkTree)o).addBookmark(b); } else { ((Bookmark)o).addChildBookmark(b); } objectStack.push(b); } else if (NAMED_DESTINATION.getLocalName().equals(localName)) { if (!objectStack.isEmpty()) { throw new SAXException(localName + " must be the root element!"); } String name = attributes.getValue("name"); NamedDestination dest = new NamedDestination(name, null); objectStack.push(dest); } else if (LINK.getLocalName().equals(localName)) { if (!objectStack.isEmpty()) { throw new SAXException(localName + " must be the root element!"); } Rectangle targetRect = XMLUtil.getAttributeAsRectangle(attributes, "rect"); structureTreeElement = structureTreeElements.get(attributes.getValue( InternalElementMapping.URI, InternalElementMapping.STRUCT_REF)); Link link = new Link(null, targetRect); objectStack.push(link); } else if (GOTO_XY.getLocalName().equals(localName)) { String idref = attributes.getValue("idref"); GoToXYAction action; if (idref != null) { action = new GoToXYAction(idref); } else { String id = attributes.getValue("id"); int pageIndex = XMLUtil.getAttributeAsInt(attributes, "page-index"); final Point location; if (pageIndex < 0) { location = null; } else { final int x = XMLUtil .getAttributeAsInt(attributes, "x"); final int y = XMLUtil .getAttributeAsInt(attributes, "y"); location = new Point(x, y); } action = new GoToXYAction(id, pageIndex, location); } if (structureTreeElement != null) { action.setStructureTreeElement(structureTreeElement); } objectStack.push(action); } else if (GOTO_URI.getLocalName().equals(localName)) { String id = attributes.getValue("id"); String gotoURI = attributes.getValue("uri"); String showDestination = attributes.getValue("show-destination"); boolean newWindow = "new".equals(showDestination); URIAction action = new URIAction(gotoURI, newWindow); if (id != null) { action.setID(id); } if (structureTreeElement != null) { action.setStructureTreeElement(structureTreeElement); } objectStack.push(action); } else { throw new SAXException( "Invalid element '" + localName + "' in namespace: " + uri); } handled = true; } if (!handled) { if (NAMESPACE.equals(uri)) { throw new SAXException("Unhandled element '" + localName + "' in namespace: " + uri); } else { log.warn("Unhandled element '" + localName + "' in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
public void endElement(String uri, String localName, String qName) throws SAXException { if (NAMESPACE.equals(uri)) { try { if (BOOKMARK_TREE.getLocalName().equals(localName)) { BookmarkTree tree = (BookmarkTree)objectStack.pop(); if (hasNavigation()) { this.navHandler.renderBookmarkTree(tree); } } else if (BOOKMARK.getLocalName().equals(localName)) { if (objectStack.peek() instanceof AbstractAction) { AbstractAction action = (AbstractAction)objectStack.pop(); Bookmark b = (Bookmark)objectStack.pop(); b.setAction(action); } else { objectStack.pop(); } } else if (NAMED_DESTINATION.getLocalName().equals(localName)) { AbstractAction action = (AbstractAction)objectStack.pop(); NamedDestination dest = (NamedDestination)objectStack.pop(); dest.setAction(action); if (hasNavigation()) { this.navHandler.renderNamedDestination(dest); } } else if (LINK.getLocalName().equals(localName)) { AbstractAction action = (AbstractAction)objectStack.pop(); Link link = (Link)objectStack.pop(); link.setAction(action); if (hasNavigation()) { this.navHandler.renderLink(link); } } else if (localName.startsWith("goto-")) { if (objectStack.size() == 1) { //Stand-alone action AbstractAction action = (AbstractAction)objectStack.pop(); if (hasNavigation()) { this.navHandler.addResolvedAction(action); } } } } catch (IFException ife) { throw new SAXException(ife); } } content.setLength(0); // Reset text buffer (see characters()) }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startDocument() throws SAXException { // TODO sections should be created try { rtfFile = new RtfFile(new OutputStreamWriter(os)); docArea = rtfFile.startDocumentArea(); } catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endDocument() throws SAXException { try { rtfFile.flush(); } catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (AFPExtensionAttachment.CATEGORY.equals(uri)) { lastAttributes = new AttributesImpl(attributes); handled = true; if (localName.equals(AFPElementMapping.NO_OPERATION) || localName.equals(AFPElementMapping.TAG_LOGICAL_ELEMENT) || localName.equals(AFPElementMapping.INCLUDE_PAGE_OVERLAY) || localName.equals(AFPElementMapping.INCLUDE_PAGE_SEGMENT) || localName.equals(AFPElementMapping.INCLUDE_FORM_MAP) || localName.equals(AFPElementMapping.INVOKE_MEDIUM_MAP)) { //handled in endElement } else { handled = false; } } if (!handled) { if (AFPExtensionAttachment.CATEGORY.equals(uri)) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
Override public void endElement(String uri, String localName, String qName) throws SAXException { if (AFPExtensionAttachment.CATEGORY.equals(uri)) { if (AFPElementMapping.INCLUDE_FORM_MAP.equals(localName)) { AFPIncludeFormMap formMap = new AFPIncludeFormMap(); String name = lastAttributes.getValue("name"); formMap.setName(name); String src = lastAttributes.getValue("src"); try { formMap.setSrc(new URI(src)); } catch (URISyntaxException e) { throw new SAXException("Invalid URI: " + src, e); } this.returnedObject = formMap; } else if (AFPElementMapping.INCLUDE_PAGE_OVERLAY.equals(localName)) { this.returnedObject = new AFPPageOverlay(); String name = lastAttributes.getValue("name"); if (name != null) { returnedObject.setName(name); } } else if (AFPElementMapping.INCLUDE_PAGE_SEGMENT.equals(localName)) { AFPPageSegmentSetup pageSetupExtn = null; pageSetupExtn = new AFPPageSegmentSetup(localName); this.returnedObject = pageSetupExtn; String name = lastAttributes.getValue("name"); if (name != null) { returnedObject.setName(name); } String value = lastAttributes.getValue("value"); if (value != null && pageSetupExtn != null) { pageSetupExtn.setValue(value); } String resourceSrc = lastAttributes.getValue("resource-file"); if (resourceSrc != null && pageSetupExtn != null) { pageSetupExtn.setResourceSrc(resourceSrc); } if (content.length() > 0 && pageSetupExtn != null) { pageSetupExtn.setContent(content.toString()); content.setLength(0); //Reset text buffer (see characters()) } } else { AFPPageSetup pageSetupExtn = null; if (AFPElementMapping.INVOKE_MEDIUM_MAP.equals(localName)) { this.returnedObject = new AFPInvokeMediumMap(); } else { pageSetupExtn = new AFPPageSetup(localName); this.returnedObject = pageSetupExtn; } String name = lastAttributes.getValue(AFPPageSetup.ATT_NAME); if (name != null) { returnedObject.setName(name); } String value = lastAttributes.getValue(AFPPageSetup.ATT_VALUE); if (value != null && pageSetupExtn != null) { pageSetupExtn.setValue(value); } String placement = lastAttributes.getValue(AFPPageSetup.ATT_PLACEMENT); if (placement != null && placement.length() > 0) { pageSetupExtn.setPlacement(ExtensionPlacement.fromXMLValue(placement)); } if (content.length() > 0 && pageSetupExtn != null) { pageSetupExtn.setContent(content.toString()); content.setLength(0); //Reset text buffer (see characters()) } } } }
// in src/java/org/apache/fop/render/ps/extensions/PSExtensionHandler.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (PSExtensionAttachment.CATEGORY.equals(uri)) { lastAttributes = new AttributesImpl(attributes); handled = false; if (localName.equals(PSSetupCode.ELEMENT) || localName.equals(PSPageTrailerCodeBefore.ELEMENT) || localName.equals(PSSetPageDevice.ELEMENT) || localName.equals(PSCommentBefore.ELEMENT) || localName.equals(PSCommentAfter.ELEMENT)) { //handled in endElement handled = true; } } if (!handled) { if (PSExtensionAttachment.CATEGORY.equals(uri)) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/events/model/EventModelParser.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { try { if ("event-model".equals(localName)) { if (objectStack.size() > 0) { throw new SAXException("event-model must be the root element"); } objectStack.push(model); } else if ("producer".equals(localName)) { EventProducerModel producer = new EventProducerModel( attributes.getValue("name")); EventModel parent = (EventModel)objectStack.peek(); parent.addProducer(producer); objectStack.push(producer); } else if ("method".equals(localName)) { EventSeverity severity = EventSeverity.valueOf(attributes.getValue("severity")); String ex = attributes.getValue("exception"); EventMethodModel method = new EventMethodModel( attributes.getValue("name"), severity); if (ex != null && ex.length() > 0) { method.setExceptionClass(ex); } EventProducerModel parent = (EventProducerModel)objectStack.peek(); parent.addMethod(method); objectStack.push(method); } else if ("parameter".equals(localName)) { String className = attributes.getValue("type"); Class type; try { type = Class.forName(className); } catch (ClassNotFoundException e) { throw new SAXException("Could not find Class for: " + className, e); } String name = attributes.getValue("name"); EventMethodModel parent = (EventMethodModel)objectStack.peek(); objectStack.push(parent.addParameter(type, name)); } else { throw new SAXException("Invalid element: " + qName); } } catch (ClassCastException cce) { throw new SAXException("XML format error: " + qName, cce); } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getFactory().getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) throws SAXException { String ns = attributes.getValue("ns"); domImplementation = elementMappingRegistry.getDOMImplementationForNamespace(ns); if (domImplementation == null) { throw new SAXException("No DOMImplementation could be" + " identified to handle namespace: " + ns); } ForeignObject foreign = new ForeignObject(ns); transferForeignObjects(attributes, foreign); setAreaAttributes(attributes, foreign); setTraits(attributes, foreign, SUBSET_COMMON); getCurrentViewport().setContent(foreign); areaStack.push(foreign); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
Override public void endDocument() throws SAXException { // render any pages that had unresolved ids checkPreparedPages(null, true); processOffDocumentItems(pendingODI); pendingODI.clear(); processOffDocumentItems(endDocODI); try { renderer.stopRenderer(); } catch (IOException ex) { throw new SAXException(ex); } }
// in src/java/org/apache/fop/util/XMLUtil.java
public static int getAttributeAsInt(Attributes attributes, String name) throws SAXException { String s = attributes.getValue(name); if (s == null) { throw new SAXException("Attribute '" + name + "' is missing"); } else { return Integer.parseInt(s); } }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { super.startElement(uri, localName, qName, atts); QName elementName = new QName(uri, qName); if (isOwnNamespace(uri)) { if (CATALOGUE.equals(localName)) { //nop } else if (MESSAGE.equals(localName)) { if (!CATALOGUE.equals(getParentElementName().getLocalName())) { throw new SAXException(MESSAGE + " must be a child of " + CATALOGUE); } this.currentKey = atts.getValue("key"); } else { throw new SAXException("Invalid element name: " + elementName); } } else { //ignore } this.valueBuffer.setLength(0); elementStack.push(elementName); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); elementStack.pop(); if (isOwnNamespace(uri)) { if (CATALOGUE.equals(localName)) { //nop } else if (MESSAGE.equals(localName)) { if (this.currentKey == null) { throw new SAXException( "current key is null (attribute 'key' might be mistyped)"); } resources.put(this.currentKey, this.valueBuffer.toString()); this.currentKey = null; } } else { //ignore } this.valueBuffer.setLength(0); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (doc == null) { TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } doc = domImplementation.createDocument(namespaceURI, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); setDelegateContentHandler(handler); setDelegateLexicalHandler(handler); setDelegateDTDHandler(handler); handler.startDocument(); } super.startElement(uri, localName, qName, atts); }
17
              
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
catch (IllegalArgumentException e) { throw new SAXException(e); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new SAXException(ioe.getMessage()); }
// in src/java/org/apache/fop/svg/FOPSAXSVGDocumentFactory.java
catch (IOException ioe) { /**@todo Batik's SAXSVGDocumentFactory should throw IOException, * so we don't have to handle it here. */ throw new SAXException(ioe); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (NumberFormatException ne) { throw new SAXException("Malformed width in metric file: " + ne.getMessage(), ne); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new SAXException("Error while parsing integer value: " + str, e); }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
catch (IFException ife) { throw new SAXException(ife); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
catch (URISyntaxException e) { throw new SAXException("Invalid URI: " + src, e); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassNotFoundException e) { throw new SAXException("Could not find Class for: " + className, e); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassCastException cce) { throw new SAXException("XML format error: " + qName, cce); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException ex) { throw new SAXException(ex); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
202
              
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void leaveTextMode() throws SAXException { assert this.mode == MODE_TEXT; handler.endElement("g"); this.mode = MODE_NORMAL; }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void establish(int newMode) throws SAXException { switch (newMode) { case MODE_TEXT: enterTextMode(); break; default: if (this.mode == MODE_TEXT) { leaveTextMode(); } } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void enterTextMode() throws SAXException { if (state.isFontChanged() && this.mode == MODE_TEXT) { leaveTextMode(); } if (this.mode != MODE_TEXT) { startTextGroup(); this.mode = MODE_TEXT; } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void startTextGroup() throws SAXException { AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "font-family", "'" + state.getFontFamily() + "'"); XMLUtil.addAttribute(atts, "font-style", state.getFontStyle()); XMLUtil.addAttribute(atts, "font-weight", Integer.toString(state.getFontWeight())); XMLUtil.addAttribute(atts, "font-variant", state.getFontVariant()); XMLUtil.addAttribute(atts, "font-size", SVGUtil.formatMptToPt(state.getFontSize())); XMLUtil.addAttribute(atts, "fill", toString(state.getTextColor())); handler.startElement("g", atts); state.resetFontChanged(); }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
public void handleImage(RenderingContext context, Image image, final Rectangle pos) throws IOException { SVGRenderingContext svgContext = (SVGRenderingContext)context; ImageXMLDOM svg = (ImageXMLDOM)image; ContentHandler handler = svgContext.getContentHandler(); AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "x", "x", CDATA, SVGUtil.formatMptToPt(pos.x)); atts.addAttribute("", "y", "y", CDATA, SVGUtil.formatMptToPt(pos.y)); atts.addAttribute("", "width", "width", CDATA, SVGUtil.formatMptToPt(pos.width)); atts.addAttribute("", "height", "height", CDATA, SVGUtil.formatMptToPt(pos.height)); try { Document doc = (Document)svg.getDocument(); Element svgEl = (Element)doc.getDocumentElement(); if (svgEl.getAttribute("viewBox").length() == 0) { log.warn("SVG doesn't have a viewBox. The result might not be scaled correctly!"); } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource src = new DOMSource(svg.getDocument()); SAXResult res = new SAXResult(new DelegatingFragmentContentHandler(handler) { private boolean topLevelSVGFound = false; private void setAttribute(AttributesImpl atts, String localName, String value) { int index; index = atts.getIndex("", localName); if (index < 0) { atts.addAttribute("", localName, localName, CDATA, value); } else { atts.setAttribute(index, "", localName, localName, CDATA, value); } } public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { if (!topLevelSVGFound && SVG_ELEMENT.getNamespaceURI().equals(uri) && SVG_ELEMENT.getLocalName().equals(localName)) { topLevelSVGFound = true; AttributesImpl modAtts = new AttributesImpl(atts); setAttribute(modAtts, "x", SVGUtil.formatMptToPt(pos.x)); setAttribute(modAtts, "y", SVGUtil.formatMptToPt(pos.y)); setAttribute(modAtts, "width", SVGUtil.formatMptToPt(pos.width)); setAttribute(modAtts, "height", SVGUtil.formatMptToPt(pos.height)); super.startElement(uri, localName, name, modAtts); } else { super.startElement(uri, localName, name, atts); } } }); transformer.transform(src, res); } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { if (!topLevelSVGFound && SVG_ELEMENT.getNamespaceURI().equals(uri) && SVG_ELEMENT.getLocalName().equals(localName)) { topLevelSVGFound = true; AttributesImpl modAtts = new AttributesImpl(atts); setAttribute(modAtts, "x", SVGUtil.formatMptToPt(pos.x)); setAttribute(modAtts, "y", SVGUtil.formatMptToPt(pos.y)); setAttribute(modAtts, "width", SVGUtil.formatMptToPt(pos.width)); setAttribute(modAtts, "height", SVGUtil.formatMptToPt(pos.height)); super.startElement(uri, localName, name, modAtts); } else { super.startElement(uri, localName, name, atts); } }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
public void startDocument() throws SAXException { log.fatal("The MIF Handler is non-functional at this time. Please help resurrect it!"); mifFile = new MIFFile(); try { mifFile.output(outStream); } catch (IOException ioe) { throw new SAXException(ioe); } }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
public void endDocument() throws SAXException { // finish all open elements mifFile.finish(true); try { mifFile.output(outStream); outStream.flush(); } catch (IOException ioe) { throw new SAXException(ioe); } }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setUserConfig(File userConfigFile) throws SAXException, IOException { config.setUserConfig(userConfigFile); }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setUserConfig(String uri) throws SAXException, IOException { config.setUserConfig(uri); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(File userConfigFile) throws SAXException, IOException { try { DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); setUserConfig(cfgBuilder.buildFromFile(userConfigFile)); } catch (ConfigurationException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(String uri) throws SAXException, IOException { try { DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); setUserConfig(cfgBuilder.build(uri)); } catch (ConfigurationException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void prepare() throws SAXException, IOException { if (this.configFile != null) { fopFactory.setUserConfig(this.configFile); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void generateXML(SortedMap fontFamilies, File outFile, String singleFamily) throws TransformerConfigurationException, SAXException, IOException { SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler handler; if (this.mode == GENERATE_XML) { handler = tFactory.newTransformerHandler(); } else { URL url = getClass().getResource("fonts2fo.xsl"); if (url == null) { throw new FileNotFoundException("Did not find resource: fonts2fo.xsl"); } handler = tFactory.newTransformerHandler(new StreamSource(url.toExternalForm())); } if (singleFamily != null) { Transformer transformer = handler.getTransformer(); transformer.setParameter("single-family", singleFamily); } OutputStream out = new java.io.FileOutputStream(outFile); out = new java.io.BufferedOutputStream(out); if (this.mode == GENERATE_RENDERED) { handler.setResult(new SAXResult(getFOPContentHandler(out))); } else { handler.setResult(new StreamResult(out)); } try { GenerationHelperContentHandler helper = new GenerationHelperContentHandler( handler, null); FontListSerializer serializer = new FontListSerializer(); serializer.generateSAX(fontFamilies, singleFamily, helper); } finally { IOUtils.closeQuietly(out); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void writeToConsole(SortedMap fontFamilies) throws TransformerConfigurationException, SAXException, IOException { Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String firstFamilyName = (String)entry.getKey(); System.out.println(firstFamilyName + ":"); List list = (List)entry.getValue(); Iterator fonts = list.iterator(); while (fonts.hasNext()) { FontSpec f = (FontSpec)fonts.next(); System.out.println(" " + f.getKey() + " " + f.getFamilyNames()); Iterator triplets = f.getTriplets().iterator(); while (triplets.hasNext()) { FontTriplet triplet = (FontTriplet)triplets.next(); System.out.println(" " + triplet.toString()); } } } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void writeOutput(SortedMap fontFamilies) throws TransformerConfigurationException, SAXException, IOException { if (this.outputFile.isDirectory()) { System.out.println("Creating one file for each family..."); Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String familyName = (String)entry.getKey(); System.out.println("Creating output file for " + familyName + "..."); String filename; switch(this.mode) { case GENERATE_RENDERED: filename = familyName + ".pdf"; break; case GENERATE_FO: filename = familyName + ".fo"; break; case GENERATE_XML: filename = familyName + ".xml"; break; default: throw new IllegalStateException("Unsupported mode"); } File outFile = new File(this.outputFile, filename); generateXML(fontFamilies, outFile, familyName); } } else { System.out.println("Creating output file..."); generateXML(fontFamilies, this.outputFile, this.singleFamilyFilter); } System.out.println(this.outputFile + " written."); }
// in src/java/org/apache/fop/tools/fontlist/FontListSerializer.java
public void generateSAX(SortedMap fontFamilies, GenerationHelperContentHandler handler) throws SAXException { generateSAX(fontFamilies, null, handler); }
// in src/java/org/apache/fop/tools/fontlist/FontListSerializer.java
public void generateSAX(SortedMap fontFamilies, String singleFamily, GenerationHelperContentHandler handler) throws SAXException { handler.startDocument(); AttributesImpl atts = new AttributesImpl(); handler.startElement(FONTS, atts); Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String familyName = (String)entry.getKey(); if (singleFamily != null && familyName != singleFamily) { continue; } atts.clear(); atts.addAttribute(null, NAME, NAME, CDATA, familyName); atts.addAttribute(null, STRIPPED_NAME, STRIPPED_NAME, CDATA, stripQuotes(familyName)); handler.startElement(FAMILY, atts); List containers = (List)entry.getValue(); generateXMLForFontContainers(handler, containers); handler.endElement(FAMILY); } handler.endElement(FONTS); handler.endDocument(); }
// in src/java/org/apache/fop/tools/fontlist/FontListSerializer.java
private void generateXMLForFontContainers(GenerationHelperContentHandler handler, List containers) throws SAXException { AttributesImpl atts = new AttributesImpl(); Iterator fontIter = containers.iterator(); while (fontIter.hasNext()) { FontSpec cont = (FontSpec)fontIter.next(); atts.clear(); atts.addAttribute(null, KEY, KEY, CDATA, cont.getKey()); atts.addAttribute(null, TYPE, TYPE, CDATA, cont.getFontMetrics().getFontType().getName()); handler.startElement(FONT, atts); generateXMLForTriplets(handler, cont.getTriplets()); handler.endElement(FONT); } }
// in src/java/org/apache/fop/tools/fontlist/FontListSerializer.java
private void generateXMLForTriplets(GenerationHelperContentHandler handler, Collection triplets) throws SAXException { AttributesImpl atts = new AttributesImpl(); atts.clear(); handler.startElement(TRIPLETS, atts); Iterator iter = triplets.iterator(); while (iter.hasNext()) { FontTriplet triplet = (FontTriplet)iter.next(); atts.clear(); atts.addAttribute(null, NAME, NAME, CDATA, triplet.getName()); atts.addAttribute(null, STYLE, STYLE, CDATA, triplet.getStyle()); atts.addAttribute(null, WEIGHT, WEIGHT, CDATA, Integer.toString(triplet.getWeight())); handler.element(TRIPLET, atts); } handler.endElement(TRIPLETS); }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void characters(char[] data, int start, int length) throws SAXException { delegate.characters(data, start, length); }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void startDocument() throws SAXException { if (used) { throw new IllegalStateException("FOTreeBuilder (and the Fop class) cannot be reused." + " Please instantiate a new instance."); } used = true; empty = true; rootFObj = null; // allows FOTreeBuilder to be reused if (LOG.isDebugEnabled()) { LOG.debug("Building formatting object tree"); } foEventHandler.startDocument(); this.mainFOHandler = new MainFOHandler(); this.mainFOHandler.startDocument(); this.delegate = this.mainFOHandler; }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void endDocument() throws SAXException { this.delegate.endDocument(); if (this.rootFObj == null && empty) { FOValidationEventProducer eventProducer = FOValidationEventProducer.Provider.get(userAgent.getEventBroadcaster()); eventProducer.emptyDocument(this); } rootFObj = null; if (LOG.isDebugEnabled()) { LOG.debug("Parsing of document complete"); } foEventHandler.endDocument(); }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void startElement(String namespaceURI, String localName, String rawName, Attributes attlist) throws SAXException { this.depth++; delegate.startElement(namespaceURI, localName, rawName, attlist); }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void endElement(String uri, String localName, String rawName) throws SAXException { this.delegate.endElement(uri, localName, rawName); this.depth--; if (depth == 0) { if (delegate != mainFOHandler) { //Return from sub-handler back to main handler delegate.endDocument(); delegate = mainFOHandler; delegate.endElement(uri, localName, rawName); } } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void fatalError(SAXParseException e) throws SAXException { LOG.error(e.toString()); throw e; }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void startElement(String namespaceURI, String localName, String rawName, Attributes attlist) throws SAXException { /* the node found in the FO document */ FONode foNode; PropertyList propertyList = null; // Check to ensure first node encountered is an fo:root if (rootFObj == null) { empty = false; if (!namespaceURI.equals(FOElementMapping.URI) || !localName.equals("root")) { FOValidationEventProducer eventProducer = FOValidationEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.invalidFORoot(this, FONode.getNodeString(namespaceURI, localName), getEffectiveLocator()); } } else { // check that incoming node is valid for currentFObj if (currentFObj.getNamespaceURI().equals(FOElementMapping.URI) || currentFObj.getNamespaceURI().equals(ExtensionElementMapping.URI)) { currentFObj.validateChildNode(locator, namespaceURI, localName); } } ElementMapping.Maker fobjMaker = findFOMaker(namespaceURI, localName); try { foNode = fobjMaker.make(currentFObj); if (rootFObj == null) { rootFObj = (Root) foNode; rootFObj.setBuilderContext(builderContext); rootFObj.setFOEventHandler(foEventHandler); } propertyList = foNode.createPropertyList( currentPropertyList, foEventHandler); foNode.processNode(localName, getEffectiveLocator(), attlist, propertyList); if (foNode.getNameId() == Constants.FO_MARKER) { if (builderContext.inMarker()) { nestedMarkerDepth++; } else { builderContext.switchMarkerContext(true); } } if (foNode.getNameId() == Constants.FO_PAGE_SEQUENCE) { builderContext.getXMLWhiteSpaceHandler().reset(); } } catch (IllegalArgumentException e) { throw new SAXException(e); } ContentHandlerFactory chFactory = foNode.getContentHandlerFactory(); if (chFactory != null) { ContentHandler subHandler = chFactory.createContentHandler(); if (subHandler instanceof ObjectSource && foNode instanceof ObjectBuiltListener) { ((ObjectSource) subHandler).setObjectBuiltListener( (ObjectBuiltListener) foNode); } subHandler.startDocument(); subHandler.startElement(namespaceURI, localName, rawName, attlist); depth = 1; delegate = subHandler; } if (currentFObj != null) { currentFObj.addChildNode(foNode); } currentFObj = foNode; if (propertyList != null && !builderContext.inMarker()) { currentPropertyList = propertyList; } // fo:characters can potentially be removed during // white-space handling. // Do not notify the FOEventHandler. if (currentFObj.getNameId() != Constants.FO_CHARACTER) { currentFObj.startOfNode(); } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void endElement(String uri, String localName, String rawName) throws SAXException { if (currentFObj == null) { throw new SAXException( "endElement() called for " + rawName + " where there is no current element."); } else if (!currentFObj.getLocalName().equals(localName) || !currentFObj.getNamespaceURI().equals(uri)) { throw new SAXException("Mismatch: " + currentFObj.getLocalName() + " (" + currentFObj.getNamespaceURI() + ") vs. " + localName + " (" + uri + ")"); } // fo:characters can potentially be removed during // white-space handling. // Do not notify the FOEventHandler. if (currentFObj.getNameId() != Constants.FO_CHARACTER) { currentFObj.endOfNode(); } if (currentPropertyList != null && currentPropertyList.getFObj() == currentFObj && !builderContext.inMarker()) { currentPropertyList = currentPropertyList.getParentPropertyList(); } if (currentFObj.getNameId() == Constants.FO_MARKER) { if (nestedMarkerDepth == 0) { builderContext.switchMarkerContext(false); } else { nestedMarkerDepth--; } } if (currentFObj.getParent() == null) { LOG.debug("endElement for top-level " + currentFObj.getName()); } currentFObj = currentFObj.getParent(); }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void endDocument() throws SAXException { currentFObj = null; }
// in src/java/org/apache/fop/fo/DelegatingFOEventHandler.java
Override public void startDocument() throws SAXException { delegate.startDocument(); }
// in src/java/org/apache/fop/fo/DelegatingFOEventHandler.java
Override public void endDocument() throws SAXException { delegate.endDocument(); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
public ContentHandler createContentHandler() throws SAXException { return new Handler(); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
public void startDocument() throws SAXException { // Suppress startDocument() call if doc has not been set, yet. It // will be done later. if (doc != null) { super.startDocument(); } }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (doc == null) { TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } String version = atts.getValue("version"); DOMImplementation domImplementation = getDOMImplementation(version); doc = domImplementation.createDocument(uri, qName, null); // It's easier to work with an empty document, so remove the // root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); setDelegateContentHandler(handler); setDelegateLexicalHandler(handler); setDelegateDTDHandler(handler); handler.startDocument(); } super.startElement(uri, localName, qName, atts); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
public void endDocument() throws SAXException { super.endDocument(); if (obListener != null) { obListener.notifyObjectBuilt(getObject()); } }
// in src/java/org/apache/fop/fo/extensions/xmp/XMPMetadata.java
public void toSAX(ContentHandler handler) throws SAXException { getMetadata().toSAX(handler); }
// in src/java/org/apache/fop/fo/extensions/xmp/XMPContentHandlerFactory.java
public ContentHandler createContentHandler() throws SAXException { return new FOPXMPHandler(); }
// in src/java/org/apache/fop/fo/extensions/xmp/XMPContentHandlerFactory.java
public void endDocument() throws SAXException { if (obListener != null) { obListener.notifyObjectBuilt(getObject()); } }
// in src/java/org/apache/fop/fo/FOEventHandler.java
public void startDocument() throws SAXException { }
// in src/java/org/apache/fop/fo/FOEventHandler.java
public void endDocument() throws SAXException { }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
protected void getExternalClasses() throws SAXException { XMLReader mainParser = parser; parser = createParser(); parser.setContentHandler(this); parser.setErrorHandler(this); InputStream stream = this.getClass().getResourceAsStream("classes.xml"); InputSource source = new InputSource(stream); try { parser.parse(source); } catch (IOException ioe) { throw new SAXException(ioe.getMessage()); } finally { parser = mainParser; } }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void startElement(String uri, String local, String raw, Attributes attrs) throws SAXException { if (local.equals("hyphen-char")) { String h = attrs.getValue("value"); if (h != null && h.length() == 1) { hyphenChar = h.charAt(0); } } else if (local.equals("classes")) { currElement = ELEM_CLASSES; } else if (local.equals("patterns")) { if (!hasClasses) { getExternalClasses(); } currElement = ELEM_PATTERNS; } else if (local.equals("exceptions")) { if (!hasClasses) { getExternalClasses(); } currElement = ELEM_EXCEPTIONS; exception = new ArrayList(); } else if (local.equals("hyphen")) { if (token.length() > 0) { exception.add(token.toString()); } exception.add(new Hyphen(attrs.getValue("pre"), attrs.getValue("no"), attrs.getValue("post"))); currElement = ELEM_HYPHEN; } token.setLength(0); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void fatalError(SAXParseException ex) throws SAXException { errMsg = "[Fatal Error] " + getLocationString(ex) + ": " + ex.getMessage(); throw ex; }
// in src/java/org/apache/fop/svg/FOPSAXSVGDocumentFactory.java
public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (this.additionalResolver != null) { try { InputSource result = this.additionalResolver.resolveEntity(publicId, systemId); if (result != null) { return result; } } catch (IOException ioe) { /**@todo Batik's SAXSVGDocumentFactory should throw IOException, * so we don't have to handle it here. */ throw new SAXException(ioe); } } return super.resolveEntity(publicId, systemId); }
// in src/java/org/apache/fop/fonts/FontReader.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("font-metrics")) { if ("TYPE0".equals(attributes.getValue("type"))) { multiFont = new MultiByteFont(); returnFont = multiFont; isCID = true; TTFReader.checkMetricsVersion(attributes); } else if ("TRUETYPE".equals(attributes.getValue("type"))) { singleFont = new SingleByteFont(); singleFont.setFontType(FontType.TRUETYPE); returnFont = singleFont; isCID = false; TTFReader.checkMetricsVersion(attributes); } else { singleFont = new SingleByteFont(); singleFont.setFontType(FontType.TYPE1); returnFont = singleFont; isCID = false; } } else if ("embed".equals(localName)) { returnFont.setEmbedFileName(attributes.getValue("file")); returnFont.setEmbedResourceName(attributes.getValue("class")); } else if ("cid-widths".equals(localName)) { cidWidthIndex = getInt(attributes.getValue("start-index")); cidWidths = new ArrayList<Integer>(); } else if ("kerning".equals(localName)) { currentKerning = new HashMap<Integer, Integer>(); returnFont.putKerningEntry(new Integer(attributes.getValue("kpx1")), currentKerning); } else if ("bfranges".equals(localName)) { bfranges = new ArrayList<BFEntry>(); } else if ("bf".equals(localName)) { BFEntry entry = new BFEntry(getInt(attributes.getValue("us")), getInt(attributes.getValue("ue")), getInt(attributes.getValue("gi"))); bfranges.add(entry); } else if ("wx".equals(localName)) { cidWidths.add(new Integer(attributes.getValue("w"))); } else if ("widths".equals(localName)) { //singleFont.width = new int[256]; } else if ("char".equals(localName)) { try { singleFont.setWidth(Integer.parseInt(attributes.getValue("idx")), Integer.parseInt(attributes.getValue("wdt"))); } catch (NumberFormatException ne) { throw new SAXException("Malformed width in metric file: " + ne.getMessage(), ne); } } else if ("pair".equals(localName)) { currentKerning.put(new Integer(attributes.getValue("kpx2")), new Integer(attributes.getValue("kern"))); } }
// in src/java/org/apache/fop/fonts/FontReader.java
private int getInt(String str) throws SAXException { int ret = 0; try { ret = Integer.parseInt(str); } catch (Exception e) { throw new SAXException("Error while parsing integer value: " + str, e); } return ret; }
// in src/java/org/apache/fop/fonts/FontReader.java
public void endElement(String uri, String localName, String qName) throws SAXException { String content = text.toString().trim(); if ("font-name".equals(localName)) { returnFont.setFontName(content); } else if ("full-name".equals(localName)) { returnFont.setFullName(content); } else if ("family-name".equals(localName)) { Set<String> s = new HashSet<String>(); s.add(content); returnFont.setFamilyNames(s); } else if ("ttc-name".equals(localName) && isCID) { multiFont.setTTCName(content); } else if ("encoding".equals(localName)) { if (singleFont != null && singleFont.getFontType() == FontType.TYPE1) { singleFont.setEncoding(content); } } else if ("cap-height".equals(localName)) { returnFont.setCapHeight(getInt(content)); } else if ("x-height".equals(localName)) { returnFont.setXHeight(getInt(content)); } else if ("ascender".equals(localName)) { returnFont.setAscender(getInt(content)); } else if ("descender".equals(localName)) { returnFont.setDescender(getInt(content)); } else if ("left".equals(localName)) { int[] bbox = returnFont.getFontBBox(); bbox[0] = getInt(content); returnFont.setFontBBox(bbox); } else if ("bottom".equals(localName)) { int[] bbox = returnFont.getFontBBox(); bbox[1] = getInt(content); returnFont.setFontBBox(bbox); } else if ("right".equals(localName)) { int[] bbox = returnFont.getFontBBox(); bbox[2] = getInt(content); returnFont.setFontBBox(bbox); } else if ("top".equals(localName)) { int[] bbox = returnFont.getFontBBox(); bbox[3] = getInt(content); returnFont.setFontBBox(bbox); } else if ("first-char".equals(localName)) { returnFont.setFirstChar(getInt(content)); } else if ("last-char".equals(localName)) { returnFont.setLastChar(getInt(content)); } else if ("flags".equals(localName)) { returnFont.setFlags(getInt(content)); } else if ("stemv".equals(localName)) { returnFont.setStemV(getInt(content)); } else if ("italic-angle".equals(localName)) { returnFont.setItalicAngle(getInt(content)); } else if ("missing-width".equals(localName)) { returnFont.setMissingWidth(getInt(content)); } else if ("cid-type".equals(localName)) { multiFont.setCIDType(CIDFontType.byName(content)); } else if ("default-width".equals(localName)) { multiFont.setDefaultWidth(getInt(content)); } else if ("cid-widths".equals(localName)) { int[] wds = new int[cidWidths.size()]; int j = 0; for (int count = 0; count < cidWidths.size(); count++) { wds[j++] = cidWidths.get(count).intValue(); } //multiFont.addCIDWidthEntry(cidWidthIndex, wds); multiFont.setWidthArray(wds); } else if ("bfranges".equals(localName)) { multiFont.setBFEntries(bfranges.toArray(new BFEntry[0])); } text.setLength(0); //Reset text buffer (see characters()) }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
public static void checkMetricsVersion(Attributes attr) throws SAXException { String err = null; final String str = attr.getValue(METRICS_VERSION_ATTR); if (str == null) { err = "Missing " + METRICS_VERSION_ATTR + " attribute"; } else { int version = 0; try { version = Integer.parseInt(str); if (version < METRICS_VERSION) { err = "Incompatible " + METRICS_VERSION_ATTR + " value (" + version + ", should be " + METRICS_VERSION + ")"; } } catch (NumberFormatException e) { err = "Invalid " + METRICS_VERSION_ATTR + " attribute value (" + str + ")"; } } if (err != null) { throw new SAXException( err + " - please regenerate the font metrics file with " + "a more recent version of FOP." ); } }
// in src/java/org/apache/fop/render/pdf/extensions/PDFEmbeddedFileExtensionAttachment.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (filename != null && filename.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", filename); } if (src != null && src.length() > 0) { atts.addAttribute(null, ATT_SRC, ATT_SRC, "CDATA", src); } if (desc != null && desc.length() > 0) { atts.addAttribute(null, ATT_DESC, ATT_DESC, "CDATA", desc); } String element = getElement(); handler.startElement(CATEGORY, element, element, atts); handler.endElement(CATEGORY, element, element); }
// in src/java/org/apache/fop/render/pdf/extensions/PDFExtensionHandler.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (PDFExtensionAttachment.CATEGORY.equals(uri)) { lastAttributes = new AttributesImpl(attributes); handled = false; if (localName.equals(PDFEmbeddedFileExtensionAttachment.ELEMENT)) { //handled in endElement handled = true; } } if (!handled) { if (PDFExtensionAttachment.CATEGORY.equals(uri)) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/pdf/extensions/PDFExtensionHandler.java
public void endElement(String uri, String localName, String qName) throws SAXException { if (PDFExtensionAttachment.CATEGORY.equals(uri)) { if (PDFEmbeddedFileExtensionAttachment.ELEMENT.equals(localName)) { String name = lastAttributes.getValue("name"); String src = lastAttributes.getValue("src"); String desc = lastAttributes.getValue("description"); this.returnedObject = new PDFEmbeddedFileExtensionAttachment(name, src, desc); } } }
// in src/java/org/apache/fop/render/pdf/extensions/PDFExtensionHandler.java
public void endDocument() throws SAXException { if (listener != null) { listener.notifyObjectBuilt(getObject()); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endDocument() throws SAXException { startIFElement(EL_PAGE_SEQUENCE, pageSequenceAttributes); pageSequenceAttributes = null; }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (!"structure-tree".equals(localName)) { if (localName.equals("marked-content")) { localName = "#PCDATA"; } String structID = attributes.getValue(InternalElementMapping.URI, InternalElementMapping.STRUCT_ID); if (structID == null) { structureTreeEventHandler.startNode(localName, attributes); } else if (localName.equals("external-graphic") || localName.equals("instream-foreign-object")) { StructureTreeElement structureTreeElement = structureTreeEventHandler.startImageNode(localName, attributes); structureTreeElements.put(structID, structureTreeElement); } else { StructureTreeElement structureTreeElement = structureTreeEventHandler .startReferencedNode(localName, attributes); structureTreeElements.put(structID, structureTreeElement); } } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
Override public void endElement(String uri, String localName, String arqNameg2) throws SAXException { if (!"structure-tree".equals(localName)) { structureTreeEventHandler.endNode(localName); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateDepth++; delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if (NAMESPACE.equals(uri)) { if (localName.equals(EL_PAGE_SEQUENCE) && userAgent.isAccessibilityEnabled()) { pageSequenceAttributes = new AttributesImpl(attributes); Locale language = getLanguage(attributes); structureTreeHandler = new StructureTreeHandler( userAgent.getStructureTreeEventHandler(), language); } else if (localName.equals(EL_STRUCTURE_TREE)) { if (userAgent.isAccessibilityEnabled()) { String type = attributes.getValue("type"); structureTreeHandler.startStructureTree(type); delegate = structureTreeHandler; } else { /* Delegate to a handler that does nothing */ delegate = new DefaultHandler(); } delegateDepth++; delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { if (pageSequenceAttributes != null) { /* * This means that no structure-element tag was * found in the XML, otherwise a * StructureTreeBuilderWrapper object would have * been created, which would have reset the * pageSequenceAttributes field. */ AccessibilityEventProducer.Provider .get(userAgent.getEventBroadcaster()) .noStructureTreeInXML(this); } handled = startIFElement(localName, attributes); } } else if (DocumentNavigationExtensionConstants.NAMESPACE.equals(uri)) { if (this.navParser == null) { this.navParser = new DocumentNavigationHandler( this.documentHandler.getDocumentNavigationHandler(), structureTreeElements); } delegate = this.navParser; delegateDepth++; delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { ContentHandlerFactoryRegistry registry = userAgent.getFactory().getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory == null) { DOMImplementation domImplementation = elementMappingRegistry.getDOMImplementationForNamespace(uri); if (domImplementation == null) { domImplementation = ElementMapping.getDefaultDOMImplementation(); /* throw new SAXException("No DOMImplementation could be" + " identified to handle namespace: " + uri); */ } factory = new DOMBuilderContentHandlerFactory(uri, domImplementation); } delegate = factory.createContentHandler(); delegateDepth++; delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
private boolean startIFElement(String localName, Attributes attributes) throws SAXException { lastAttributes = new AttributesImpl(attributes); ElementHandler elementHandler = elementHandlers.get(localName); content.setLength(0); ignoreCharacters = true; if (elementHandler != null) { ignoreCharacters = elementHandler.ignoreCharacters(); try { elementHandler.startElement(attributes); } catch (IFException ife) { handleIFException(ife); } return true; } else { return false; } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
private void handleIFException(IFException ife) throws SAXException { if (ife.getCause() instanceof SAXException) { //unwrap throw (SAXException)ife.getCause(); } else { //wrap throw new SAXException(ife); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement(String uri, String localName, String qName) throws SAXException { if (delegate != null) { delegate.endElement(uri, localName, qName); delegateDepth--; if (delegateDepth == 0) { delegate.endDocument(); if (delegate instanceof ContentHandlerFactory.ObjectSource) { Object obj = ((ContentHandlerFactory.ObjectSource)delegate).getObject(); if (inForeignObject) { this.foreignObject = (Document)obj; } else { handleExternallyGeneratedObject(obj); } } delegate = null; //Sub-document is processed, return to normal processing } } else { if (NAMESPACE.equals(uri)) { ElementHandler elementHandler = elementHandlers.get(localName); if (elementHandler != null) { try { elementHandler.endElement(); } catch (IFException ife) { handleIFException(ife); } content.setLength(0); } ignoreCharacters = true; } else { if (log.isTraceEnabled()) { log.trace("Ignoring " + localName + " in namespace: " + uri); } } } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException, SAXException { //nop }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
Override public void startElement(Attributes attributes) throws IFException, SAXException { String id = attributes.getValue("name"); documentHandler.getContext().setID(id); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
protected void handleExternallyGeneratedObject(Object obj) throws SAXException { try { documentHandler.handleExtensionObject(obj); } catch (IFException ife) { handleIFException(ife); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void characters(char[] ch, int start, int length) throws SAXException { if (delegate != null) { delegate.characters(ch, start, length); } else if (!ignoreCharacters) { this.content.append(ch, start, length); } }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void characters(char[] arg0, int arg1, int arg2) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void endDocument() throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void endElement(String arg0, String arg1, String arg2) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void endPrefixMapping(String arg0) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void ignorableWhitespace(char[] arg0, int arg1, int arg2) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void processingInstruction(String arg0, String arg1) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void skippedEntity(String arg0) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void startDocument() throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void startPrefixMapping(String arg0, String arg1) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override void replay(ContentHandler handler) throws SAXException { handler.startElement(uri, localName, qName, attributes); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override void replay(ContentHandler handler) throws SAXException { handler.endElement(uri, localName, qName); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override void replay(ContentHandler handler) throws SAXException { handler.startPrefixMapping(prefix, uri); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override void replay(ContentHandler handler) throws SAXException { handler.endPrefixMapping(prefix); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { events.add(new StartElement(uri, localName, qName, attributes)); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override public void endElement(String uri, String localName, String qName) throws SAXException { events.add(new EndElement(uri, localName, qName)); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override public void startPrefixMapping(String prefix, String uri) throws SAXException { events.add(new StartPrefixMapping(prefix, uri)); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override public void endPrefixMapping(String prefix) throws SAXException { events.add(new EndPrefixMapping(prefix)); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
public void replay(ContentHandler handler) throws SAXException { for (SAXEventRecorder.Event e : events) { e.replay(handler); } }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
public void replayEventsForPageSequence(ContentHandler handler, int pageSequenceIndex) throws SAXException { pageSequenceEventRecorders.get(pageSequenceIndex).replay(handler); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void addForeignAttributes(AttributesImpl atts) throws SAXException { Map foreignAttributes = getContext().getForeignAttributes(); if (!foreignAttributes.isEmpty()) { Iterator iter = foreignAttributes.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); addAttribute(atts, (QName)entry.getKey(), entry.getValue().toString()); } } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void addAttribute(AttributesImpl atts, org.apache.xmlgraphics.util.QName attribute, String value) throws SAXException { handler.startPrefixMapping(attribute.getPrefix(), attribute.getNamespaceURI()); XMLUtil.addAttribute(atts, attribute, value); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void addID() throws SAXException { String id = getContext().getID(); if (!currentID.equals(id)) { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "name", id); handler.startElement(EL_ID, atts); handler.endElement(EL_ID); currentID = id; } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void serializeBookmark(Bookmark bookmark) throws SAXException, IFException { noteAction(bookmark.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute(null, "title", "title", XMLUtil.CDATA, bookmark.getTitle()); atts.addAttribute(null, "starting-state", "starting-state", XMLUtil.CDATA, bookmark.isShown() ? "show" : "hide"); handler.startElement(DocumentNavigationExtensionConstants.BOOKMARK, atts); serializeXMLizable(bookmark.getAction()); Iterator iter = bookmark.getChildBookmarks().iterator(); while (iter.hasNext()) { Bookmark b = (Bookmark)iter.next(); if (b.getAction() != null) { serializeBookmark(b); } } handler.endElement(DocumentNavigationExtensionConstants.BOOKMARK); }
// in src/java/org/apache/fop/render/intermediate/DelegatingFragmentContentHandler.java
public void startDocument() throws SAXException { //nop/ignore }
// in src/java/org/apache/fop/render/intermediate/DelegatingFragmentContentHandler.java
public void endDocument() throws SAXException { //nop/ignore }
// in src/java/org/apache/fop/render/intermediate/extensions/GoToXYAction.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (this.isCompleteExceptTargetLocation()) { final Point reportedTargetLocation = this.getTargetLocation(); atts.addAttribute(null, "id", "id", XMLUtil.CDATA, getID()); atts.addAttribute(null, "page-index", "page-index", XMLUtil.CDATA, Integer.toString(pageIndex)); atts.addAttribute(null, "x", "x", XMLUtil.CDATA, Integer.toString(reportedTargetLocation.x)); atts.addAttribute(null, "y", "y", XMLUtil.CDATA, Integer.toString(reportedTargetLocation.y)); } else { atts.addAttribute(null, "idref", "idref", XMLUtil.CDATA, getID()); } handler.startElement(GOTO_XY.getNamespaceURI(), GOTO_XY.getLocalName(), GOTO_XY.getQName(), atts); handler.endElement(GOTO_XY.getNamespaceURI(), GOTO_XY.getLocalName(), GOTO_XY.getQName()); }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (NAMESPACE.equals(uri)) { if (BOOKMARK_TREE.getLocalName().equals(localName)) { if (!objectStack.isEmpty()) { throw new SAXException(localName + " must be the root element!"); } BookmarkTree bookmarkTree = new BookmarkTree(); objectStack.push(bookmarkTree); } else if (BOOKMARK.getLocalName().equals(localName)) { String title = attributes.getValue("title"); String s = attributes.getValue("starting-state"); boolean show = !"hide".equals(s); Bookmark b = new Bookmark(title, show, null); Object o = objectStack.peek(); if (o instanceof AbstractAction) { AbstractAction action = (AbstractAction)objectStack.pop(); o = objectStack.peek(); ((Bookmark)o).setAction(action); } if (o instanceof BookmarkTree) { ((BookmarkTree)o).addBookmark(b); } else { ((Bookmark)o).addChildBookmark(b); } objectStack.push(b); } else if (NAMED_DESTINATION.getLocalName().equals(localName)) { if (!objectStack.isEmpty()) { throw new SAXException(localName + " must be the root element!"); } String name = attributes.getValue("name"); NamedDestination dest = new NamedDestination(name, null); objectStack.push(dest); } else if (LINK.getLocalName().equals(localName)) { if (!objectStack.isEmpty()) { throw new SAXException(localName + " must be the root element!"); } Rectangle targetRect = XMLUtil.getAttributeAsRectangle(attributes, "rect"); structureTreeElement = structureTreeElements.get(attributes.getValue( InternalElementMapping.URI, InternalElementMapping.STRUCT_REF)); Link link = new Link(null, targetRect); objectStack.push(link); } else if (GOTO_XY.getLocalName().equals(localName)) { String idref = attributes.getValue("idref"); GoToXYAction action; if (idref != null) { action = new GoToXYAction(idref); } else { String id = attributes.getValue("id"); int pageIndex = XMLUtil.getAttributeAsInt(attributes, "page-index"); final Point location; if (pageIndex < 0) { location = null; } else { final int x = XMLUtil .getAttributeAsInt(attributes, "x"); final int y = XMLUtil .getAttributeAsInt(attributes, "y"); location = new Point(x, y); } action = new GoToXYAction(id, pageIndex, location); } if (structureTreeElement != null) { action.setStructureTreeElement(structureTreeElement); } objectStack.push(action); } else if (GOTO_URI.getLocalName().equals(localName)) { String id = attributes.getValue("id"); String gotoURI = attributes.getValue("uri"); String showDestination = attributes.getValue("show-destination"); boolean newWindow = "new".equals(showDestination); URIAction action = new URIAction(gotoURI, newWindow); if (id != null) { action.setID(id); } if (structureTreeElement != null) { action.setStructureTreeElement(structureTreeElement); } objectStack.push(action); } else { throw new SAXException( "Invalid element '" + localName + "' in namespace: " + uri); } handled = true; } if (!handled) { if (NAMESPACE.equals(uri)) { throw new SAXException("Unhandled element '" + localName + "' in namespace: " + uri); } else { log.warn("Unhandled element '" + localName + "' in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
public void endElement(String uri, String localName, String qName) throws SAXException { if (NAMESPACE.equals(uri)) { try { if (BOOKMARK_TREE.getLocalName().equals(localName)) { BookmarkTree tree = (BookmarkTree)objectStack.pop(); if (hasNavigation()) { this.navHandler.renderBookmarkTree(tree); } } else if (BOOKMARK.getLocalName().equals(localName)) { if (objectStack.peek() instanceof AbstractAction) { AbstractAction action = (AbstractAction)objectStack.pop(); Bookmark b = (Bookmark)objectStack.pop(); b.setAction(action); } else { objectStack.pop(); } } else if (NAMED_DESTINATION.getLocalName().equals(localName)) { AbstractAction action = (AbstractAction)objectStack.pop(); NamedDestination dest = (NamedDestination)objectStack.pop(); dest.setAction(action); if (hasNavigation()) { this.navHandler.renderNamedDestination(dest); } } else if (LINK.getLocalName().equals(localName)) { AbstractAction action = (AbstractAction)objectStack.pop(); Link link = (Link)objectStack.pop(); link.setAction(action); if (hasNavigation()) { this.navHandler.renderLink(link); } } else if (localName.startsWith("goto-")) { if (objectStack.size() == 1) { //Stand-alone action AbstractAction action = (AbstractAction)objectStack.pop(); if (hasNavigation()) { this.navHandler.addResolvedAction(action); } } } } catch (IFException ife) { throw new SAXException(ife); } } content.setLength(0); // Reset text buffer (see characters()) }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
public void characters(char[] ch, int start, int length) throws SAXException { content.append(ch, start, length); }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
public void endDocument() throws SAXException { assert objectStack.isEmpty(); }
// in src/java/org/apache/fop/render/intermediate/extensions/URIAction.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (hasID()) { atts.addAttribute(null, "id", "id", XMLUtil.CDATA, getID()); } atts.addAttribute(null, "uri", "uri", XMLUtil.CDATA, getURI()); if (isNewWindow()) { atts.addAttribute(null, "show-destination", "show-destination", XMLUtil.CDATA, "new"); } handler.startElement(GOTO_URI.getNamespaceURI(), GOTO_URI.getLocalName(), GOTO_URI.getQName(), atts); handler.endElement(GOTO_URI.getNamespaceURI(), GOTO_URI.getLocalName(), GOTO_URI.getQName()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startDocument() throws SAXException { // TODO sections should be created try { rtfFile = new RtfFile(new OutputStreamWriter(os)); docArea = rtfFile.startDocumentArea(); } catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endDocument() throws SAXException { try { rtfFile.flush(); } catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageOverlay.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } handler.startElement(CATEGORY, elementName, elementName, atts); handler.endElement(CATEGORY, elementName, elementName); }
// in src/java/org/apache/fop/render/afp/extensions/AFPInvokeMediumMap.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } handler.startElement(CATEGORY, elementName, elementName, atts); handler.endElement(CATEGORY, elementName, elementName); }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSetup.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } if (value != null && value.length() > 0) { atts.addAttribute(null, ATT_VALUE, ATT_VALUE, "CDATA", value); } if (this.placement != ExtensionPlacement.DEFAULT) { atts.addAttribute(null, ATT_PLACEMENT, ATT_PLACEMENT, "CDATA", placement.getXMLValue()); } handler.startElement(CATEGORY, elementName, elementName, atts); if (content != null && content.length() > 0) { char[] chars = content.toCharArray(); handler.characters(chars, 0, chars.length); } handler.endElement(CATEGORY, elementName, elementName); }
// in src/java/org/apache/fop/render/afp/extensions/AFPIncludeFormMap.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } if (this.src != null) { atts.addAttribute(null, ATT_SRC, ATT_SRC, "CDATA", this.src.toASCIIString()); } handler.startElement(CATEGORY, elementName, elementName, atts); handler.endElement(CATEGORY, elementName, elementName); }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (AFPExtensionAttachment.CATEGORY.equals(uri)) { lastAttributes = new AttributesImpl(attributes); handled = true; if (localName.equals(AFPElementMapping.NO_OPERATION) || localName.equals(AFPElementMapping.TAG_LOGICAL_ELEMENT) || localName.equals(AFPElementMapping.INCLUDE_PAGE_OVERLAY) || localName.equals(AFPElementMapping.INCLUDE_PAGE_SEGMENT) || localName.equals(AFPElementMapping.INCLUDE_FORM_MAP) || localName.equals(AFPElementMapping.INVOKE_MEDIUM_MAP)) { //handled in endElement } else { handled = false; } } if (!handled) { if (AFPExtensionAttachment.CATEGORY.equals(uri)) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
Override public void endElement(String uri, String localName, String qName) throws SAXException { if (AFPExtensionAttachment.CATEGORY.equals(uri)) { if (AFPElementMapping.INCLUDE_FORM_MAP.equals(localName)) { AFPIncludeFormMap formMap = new AFPIncludeFormMap(); String name = lastAttributes.getValue("name"); formMap.setName(name); String src = lastAttributes.getValue("src"); try { formMap.setSrc(new URI(src)); } catch (URISyntaxException e) { throw new SAXException("Invalid URI: " + src, e); } this.returnedObject = formMap; } else if (AFPElementMapping.INCLUDE_PAGE_OVERLAY.equals(localName)) { this.returnedObject = new AFPPageOverlay(); String name = lastAttributes.getValue("name"); if (name != null) { returnedObject.setName(name); } } else if (AFPElementMapping.INCLUDE_PAGE_SEGMENT.equals(localName)) { AFPPageSegmentSetup pageSetupExtn = null; pageSetupExtn = new AFPPageSegmentSetup(localName); this.returnedObject = pageSetupExtn; String name = lastAttributes.getValue("name"); if (name != null) { returnedObject.setName(name); } String value = lastAttributes.getValue("value"); if (value != null && pageSetupExtn != null) { pageSetupExtn.setValue(value); } String resourceSrc = lastAttributes.getValue("resource-file"); if (resourceSrc != null && pageSetupExtn != null) { pageSetupExtn.setResourceSrc(resourceSrc); } if (content.length() > 0 && pageSetupExtn != null) { pageSetupExtn.setContent(content.toString()); content.setLength(0); //Reset text buffer (see characters()) } } else { AFPPageSetup pageSetupExtn = null; if (AFPElementMapping.INVOKE_MEDIUM_MAP.equals(localName)) { this.returnedObject = new AFPInvokeMediumMap(); } else { pageSetupExtn = new AFPPageSetup(localName); this.returnedObject = pageSetupExtn; } String name = lastAttributes.getValue(AFPPageSetup.ATT_NAME); if (name != null) { returnedObject.setName(name); } String value = lastAttributes.getValue(AFPPageSetup.ATT_VALUE); if (value != null && pageSetupExtn != null) { pageSetupExtn.setValue(value); } String placement = lastAttributes.getValue(AFPPageSetup.ATT_PLACEMENT); if (placement != null && placement.length() > 0) { pageSetupExtn.setPlacement(ExtensionPlacement.fromXMLValue(placement)); } if (content.length() > 0 && pageSetupExtn != null) { pageSetupExtn.setContent(content.toString()); content.setLength(0); //Reset text buffer (see characters()) } } } }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
Override public void characters(char[] ch, int start, int length) throws SAXException { content.append(ch, start, length); }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
Override public void endDocument() throws SAXException { if (listener != null) { listener.notifyObjectBuilt(getObject()); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSegmentElement.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } if (value != null && value.length() > 0) { atts.addAttribute(null, ATT_VALUE, ATT_VALUE, "CDATA", value); } if (resourceSrc != null && resourceSrc.length() > 0) { atts.addAttribute(null, ATT_RESOURCE_SRC, ATT_RESOURCE_SRC, "CDATA", resourceSrc); } handler.startElement(CATEGORY, elementName, elementName, atts); if (content != null && content.length() > 0) { char[] chars = content.toCharArray(); handler.characters(chars, 0, chars.length); } handler.endElement(CATEGORY, elementName, elementName); }
// in src/java/org/apache/fop/render/ps/extensions/PSSetupCode.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } String element = getElement(); handler.startElement(CATEGORY, element, element, atts); if (content != null && content.length() > 0) { char[] chars = content.toCharArray(); handler.characters(chars, 0, chars.length); } handler.endElement(CATEGORY, element, element); }
// in src/java/org/apache/fop/render/ps/extensions/PSExtensionAttachment.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); String element = getElement(); handler.startElement(CATEGORY, element, element, atts); if (content != null && content.length() > 0) { char[] chars = content.toCharArray(); handler.characters(chars, 0, chars.length); } handler.endElement(CATEGORY, element, element); }
// in src/java/org/apache/fop/render/ps/extensions/PSSetPageDevice.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } String element = getElement(); handler.startElement(CATEGORY, element, element, atts); if (content != null && content.length() > 0) { char[] chars = content.toCharArray(); handler.characters(chars, 0, chars.length); } handler.endElement(CATEGORY, element, element); }
// in src/java/org/apache/fop/render/ps/extensions/PSExtensionHandler.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (PSExtensionAttachment.CATEGORY.equals(uri)) { lastAttributes = new AttributesImpl(attributes); handled = false; if (localName.equals(PSSetupCode.ELEMENT) || localName.equals(PSPageTrailerCodeBefore.ELEMENT) || localName.equals(PSSetPageDevice.ELEMENT) || localName.equals(PSCommentBefore.ELEMENT) || localName.equals(PSCommentAfter.ELEMENT)) { //handled in endElement handled = true; } } if (!handled) { if (PSExtensionAttachment.CATEGORY.equals(uri)) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/ps/extensions/PSExtensionHandler.java
public void endElement(String uri, String localName, String qName) throws SAXException { if (PSExtensionAttachment.CATEGORY.equals(uri)) { if (PSSetupCode.ELEMENT.equals(localName)) { String name = lastAttributes.getValue("name"); this.returnedObject = new PSSetupCode(name, content.toString()); } else if (PSSetPageDevice.ELEMENT.equals(localName)) { String name = lastAttributes.getValue("name"); this.returnedObject = new PSSetPageDevice(name, content.toString()); } else if (PSCommentBefore.ELEMENT.equals(localName)) { this.returnedObject = new PSCommentBefore(content.toString()); } else if (PSCommentAfter.ELEMENT.equals(localName)) { this.returnedObject = new PSCommentAfter(content.toString()); } else if (PSPageTrailerCodeBefore.ELEMENT.equals(localName)) { this.returnedObject = new PSPageTrailerCodeBefore(content.toString()); } } content.setLength(0); //Reset text buffer (see characters()) }
// in src/java/org/apache/fop/render/ps/extensions/PSExtensionHandler.java
public void characters(char[] ch, int start, int length) throws SAXException { content.append(ch, start, length); }
// in src/java/org/apache/fop/render/ps/extensions/PSExtensionHandler.java
public void endDocument() throws SAXException { if (listener != null) { listener.notifyObjectBuilt(getObject()); } }
// in src/java/org/apache/fop/events/model/EventModelParser.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { try { if ("event-model".equals(localName)) { if (objectStack.size() > 0) { throw new SAXException("event-model must be the root element"); } objectStack.push(model); } else if ("producer".equals(localName)) { EventProducerModel producer = new EventProducerModel( attributes.getValue("name")); EventModel parent = (EventModel)objectStack.peek(); parent.addProducer(producer); objectStack.push(producer); } else if ("method".equals(localName)) { EventSeverity severity = EventSeverity.valueOf(attributes.getValue("severity")); String ex = attributes.getValue("exception"); EventMethodModel method = new EventMethodModel( attributes.getValue("name"), severity); if (ex != null && ex.length() > 0) { method.setExceptionClass(ex); } EventProducerModel parent = (EventProducerModel)objectStack.peek(); parent.addMethod(method); objectStack.push(method); } else if ("parameter".equals(localName)) { String className = attributes.getValue("type"); Class type; try { type = Class.forName(className); } catch (ClassNotFoundException e) { throw new SAXException("Could not find Class for: " + className, e); } String name = attributes.getValue("name"); EventMethodModel parent = (EventMethodModel)objectStack.peek(); objectStack.push(parent.addParameter(type, name)); } else { throw new SAXException("Invalid element: " + qName); } } catch (ClassCastException cce) { throw new SAXException("XML format error: " + qName, cce); } }
// in src/java/org/apache/fop/events/model/EventModelParser.java
public void endElement(String uri, String localName, String qName) throws SAXException { objectStack.pop(); }
// in src/java/org/apache/fop/events/model/EventModel.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); String elName = "event-model"; handler.startElement("", elName, elName, atts); Iterator iter = getProducers(); while (iter.hasNext()) { ((XMLizable)iter.next()).toSAX(handler); } handler.endElement("", elName, elName); }
// in src/java/org/apache/fop/events/model/EventProducerModel.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "name", "name", "CDATA", getInterfaceName()); String elName = "producer"; handler.startElement("", elName, elName, atts); Iterator iter = getMethods(); while (iter.hasNext()) { ((XMLizable)iter.next()).toSAX(handler); } handler.endElement("", elName, elName); }
// in src/java/org/apache/fop/events/model/EventMethodModel.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "name", "name", "CDATA", getMethodName()); atts.addAttribute("", "severity", "severity", "CDATA", getSeverity().getName()); if (getExceptionClass() != null) { atts.addAttribute("", "exception", "exception", "CDATA", getExceptionClass()); } String elName = "method"; handler.startElement("", elName, elName, atts); Iterator iter = this.params.iterator(); while (iter.hasNext()) { ((XMLizable)iter.next()).toSAX(handler); } handler.endElement("", elName, elName); }
// in src/java/org/apache/fop/events/model/EventMethodModel.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "type", "type", "CDATA", getType().getName()); atts.addAttribute("", "name", "name", "CDATA", getName()); String elName = "parameter"; handler.startElement("", elName, elName, atts); handler.endElement("", elName, elName); }
// in src/java/org/apache/fop/area/AreaTreeHandler.java
Override public void startDocument() throws SAXException { // Initialize statistics if (statistics != null) { statistics.start(); } }
// in src/java/org/apache/fop/area/AreaTreeHandler.java
Override public void endDocument() throws SAXException { finishPrevPageSequence(null); // process fox:destination elements if (rootFObj != null) { List<Destination> destinationList = rootFObj.getDestinationList(); if (destinationList != null) { while (destinationList.size() > 0) { Destination destination = destinationList.remove(0); DestinationData destinationData = new DestinationData(destination); addOffDocumentItem(destinationData); } } // process fo:bookmark-tree BookmarkTree bookmarkTree = rootFObj.getBookmarkTree(); if (bookmarkTree != null) { BookmarkData data = new BookmarkData(bookmarkTree); addOffDocumentItem(data); if (!data.isResolved()) { // bookmarks did not fully resolve, add anyway. (hacky? yeah) model.handleOffDocumentItem(data); } } idTracker.signalIDProcessed(rootFObj.getId()); } model.endDocument(); if (statistics != null) { statistics.logResults(); } }
// in src/java/org/apache/fop/area/AreaTreeModel.java
public void endDocument() throws SAXException { }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
Override public void endDocument() throws SAXException { super.endDocument(); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getFactory().getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
private boolean startAreaTreeElement(String localName, Attributes attributes) throws SAXException { lastAttributes = new AttributesImpl(attributes); Maker maker = makers.get(localName); content.clear(); ignoreCharacters = true; if (maker != null) { ignoreCharacters = maker.ignoreCharacters(); maker.startElement(attributes); } else if ("extension-attachments".equals(localName)) { //TODO implement me } else { return false; } return true; }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void endElement(String uri, String localName, String qName) throws SAXException { if (delegate != null) { delegate.endElement(uri, localName, qName); delegateStack.pop(); if (delegateStack.size() == 0) { delegate.endDocument(); if (delegate instanceof ContentHandlerFactory.ObjectSource) { Object obj = ((ContentHandlerFactory.ObjectSource)delegate).getObject(); handleExternallyGeneratedObject(obj); } delegate = null; //Sub-document is processed, return to normal processing } } else { if ("".equals(uri)) { Maker maker = makers.get(localName); if (maker != null) { maker.endElement(); content.clear(); } ignoreCharacters = true; } else { //log.debug("Ignoring " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) throws SAXException { //nop }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) throws SAXException { String ns = attributes.getValue("ns"); domImplementation = elementMappingRegistry.getDOMImplementationForNamespace(ns); if (domImplementation == null) { throw new SAXException("No DOMImplementation could be" + " identified to handle namespace: " + ns); } ForeignObject foreign = new ForeignObject(ns); transferForeignObjects(attributes, foreign); setAreaAttributes(attributes, foreign); setTraits(attributes, foreign, SUBSET_COMMON); getCurrentViewport().setContent(foreign); areaStack.push(foreign); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void characters(char[] ch, int start, int length) throws SAXException { if (delegate != null) { delegate.characters(ch, start, length); } else if (!ignoreCharacters) { int maxLength = this.content.capacity() - this.content.position(); if (maxLength < length) { // allocate a larger buffer and transfer content CharBuffer newContent = CharBuffer.allocate(this.content.position() + length); this.content.flip(); newContent.put(this.content); this.content = newContent; } // make sure the full capacity is used this.content.limit(this.content.capacity()); // add characters to the buffer this.content.put(ch, start, length); // decrease the limit, if necessary if (this.content.position() < this.content.limit()) { this.content.limit(this.content.position()); } } }
// in src/java/org/apache/fop/area/RenderPagesModel.java
Override public void endDocument() throws SAXException { // render any pages that had unresolved ids checkPreparedPages(null, true); processOffDocumentItems(pendingODI); pendingODI.clear(); processOffDocumentItems(endDocODI); try { renderer.stopRenderer(); } catch (IOException ex) { throw new SAXException(ex); } }
// in src/java/org/apache/fop/accessibility/fo/StructureTreeEventTrigger.java
Override public void startDocument() throws SAXException { }
// in src/java/org/apache/fop/accessibility/fo/StructureTreeEventTrigger.java
Override public void endDocument() throws SAXException { }
// in src/java/org/apache/fop/accessibility/fo/FO2StructureTreeConverter.java
Override public void startDocument() throws SAXException { converter.startDocument(); super.startDocument(); }
// in src/java/org/apache/fop/accessibility/fo/FO2StructureTreeConverter.java
Override public void endDocument() throws SAXException { converter.endDocument(); super.endDocument(); }
// in src/java/org/apache/fop/util/DOM2SAX.java
public void writeDocument(Document doc, boolean fragment) throws SAXException { if (!fragment) { contentHandler.startDocument(); } for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) { writeNode(n); } if (!fragment) { contentHandler.endDocument(); } }
// in src/java/org/apache/fop/util/DOM2SAX.java
public void writeFragment(Node node) throws SAXException { writeNode(node); }
// in src/java/org/apache/fop/util/DOM2SAX.java
private boolean startPrefixMapping(String prefix, String uri) throws SAXException { boolean pushed = true; Stack uriStack = (Stack)prefixes.get(prefix); if (uriStack != null) { if (uriStack.isEmpty()) { contentHandler.startPrefixMapping(prefix, uri); uriStack.push(uri); } else { final String lastUri = (String) uriStack.peek(); if (!lastUri.equals(uri)) { contentHandler.startPrefixMapping(prefix, uri); uriStack.push(uri); } else { pushed = false; } } } else { contentHandler.startPrefixMapping(prefix, uri); uriStack = new Stack(); prefixes.put(prefix, uriStack); uriStack.push(uri); } return pushed; }
// in src/java/org/apache/fop/util/DOM2SAX.java
private void endPrefixMapping(String prefix) throws SAXException { final Stack uriStack = (Stack)prefixes.get(prefix); if (uriStack != null) { contentHandler.endPrefixMapping(prefix); uriStack.pop(); } }
// in src/java/org/apache/fop/util/DOM2SAX.java
private void writeNode(Node node) throws SAXException { if (node == null) { return; } switch (node.getNodeType()) { case Node.ATTRIBUTE_NODE: // handled by ELEMENT_NODE case Node.DOCUMENT_FRAGMENT_NODE: case Node.DOCUMENT_TYPE_NODE: case Node.ENTITY_NODE: case Node.ENTITY_REFERENCE_NODE: case Node.NOTATION_NODE: // These node types are ignored!!! break; case Node.CDATA_SECTION_NODE: final String cdata = node.getNodeValue(); if (lexicalHandler != null) { lexicalHandler.startCDATA(); contentHandler.characters(cdata.toCharArray(), 0, cdata.length()); lexicalHandler.endCDATA(); } else { // in the case where there is no lex handler, we still // want the text of the cdate to make its way through. contentHandler.characters(cdata.toCharArray(), 0, cdata.length()); } break; case Node.COMMENT_NODE: // should be handled!!! if (lexicalHandler != null) { final String value = node.getNodeValue(); lexicalHandler.comment(value.toCharArray(), 0, value.length()); } break; case Node.DOCUMENT_NODE: contentHandler.startDocument(); Node next = node.getFirstChild(); while (next != null) { writeNode(next); next = next.getNextSibling(); } contentHandler.endDocument(); break; case Node.ELEMENT_NODE: String prefix; List pushedPrefixes = new java.util.ArrayList(); final AttributesImpl attrs = new AttributesImpl(); final NamedNodeMap map = node.getAttributes(); final int length = map.getLength(); // Process all namespace declarations for (int i = 0; i < length; i++) { final Node attr = map.item(i); final String qnameAttr = attr.getNodeName(); // Ignore everything but NS declarations here if (qnameAttr.startsWith(XMLNS_PREFIX)) { final String uriAttr = attr.getNodeValue(); final int colon = qnameAttr.lastIndexOf(':'); prefix = (colon > 0) ? qnameAttr.substring(colon + 1) : EMPTYSTRING; if (startPrefixMapping(prefix, uriAttr)) { pushedPrefixes.add(prefix); } } } // Process all other attributes for (int i = 0; i < length; i++) { final Node attr = map.item(i); final String qnameAttr = attr.getNodeName(); // Ignore NS declarations here if (!qnameAttr.startsWith(XMLNS_PREFIX)) { final String uriAttr = attr.getNamespaceURI(); // Uri may be implicitly declared if (uriAttr != null) { final int colon = qnameAttr.lastIndexOf(':'); prefix = (colon > 0) ? qnameAttr.substring(0, colon) : EMPTYSTRING; if (startPrefixMapping(prefix, uriAttr)) { pushedPrefixes.add(prefix); } } // Add attribute to list attrs.addAttribute(attr.getNamespaceURI(), getLocalName(attr), qnameAttr, XMLUtil.CDATA, attr .getNodeValue()); } } // Now process the element itself final String qname = node.getNodeName(); final String uri = node.getNamespaceURI(); final String localName = getLocalName(node); // Uri may be implicitly declared if (uri != null) { final int colon = qname.lastIndexOf(':'); prefix = (colon > 0) ? qname.substring(0, colon) : EMPTYSTRING; if (startPrefixMapping(prefix, uri)) { pushedPrefixes.add(prefix); } } // Generate SAX event to start element contentHandler.startElement(uri, localName, qname, attrs); // Traverse all child nodes of the element (if any) next = node.getFirstChild(); while (next != null) { writeNode(next); next = next.getNextSibling(); } // Generate SAX event to close element contentHandler.endElement(uri, localName, qname); // Generate endPrefixMapping() for all pushed prefixes final int nPushedPrefixes = pushedPrefixes.size(); for (int i = 0; i < nPushedPrefixes; i++) { endPrefixMapping((String)pushedPrefixes.get(i)); } break; case Node.PROCESSING_INSTRUCTION_NODE: contentHandler.processingInstruction(node.getNodeName(), node.getNodeValue()); break; case Node.TEXT_NODE: final String data = node.getNodeValue(); contentHandler.characters(data.toCharArray(), 0, data.length()); break; default: //nop } }
// in src/java/org/apache/fop/util/XMLUtil.java
public static int getAttributeAsInt(Attributes attributes, String name) throws SAXException { String s = attributes.getValue(name); if (s == null) { throw new SAXException("Attribute '" + name + "' is missing"); } else { return Integer.parseInt(s); } }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { super.startElement(uri, localName, qName, atts); QName elementName = new QName(uri, qName); if (isOwnNamespace(uri)) { if (CATALOGUE.equals(localName)) { //nop } else if (MESSAGE.equals(localName)) { if (!CATALOGUE.equals(getParentElementName().getLocalName())) { throw new SAXException(MESSAGE + " must be a child of " + CATALOGUE); } this.currentKey = atts.getValue("key"); } else { throw new SAXException("Invalid element name: " + elementName); } } else { //ignore } this.valueBuffer.setLength(0); elementStack.push(elementName); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); elementStack.pop(); if (isOwnNamespace(uri)) { if (CATALOGUE.equals(localName)) { //nop } else if (MESSAGE.equals(localName)) { if (this.currentKey == null) { throw new SAXException( "current key is null (attribute 'key' might be mistyped)"); } resources.put(this.currentKey, this.valueBuffer.toString()); this.currentKey = null; } } else { //ignore } this.valueBuffer.setLength(0); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); valueBuffer.append(ch, start, length); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void startElement(String localName, Attributes atts) throws SAXException { getDelegateContentHandler().startElement(getMainNamespace(), localName, localName, atts); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void startElement(String localName) throws SAXException { startElement(localName, EMPTY_ATTS); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void startElement(QName qName, Attributes atts) throws SAXException { getDelegateContentHandler().startElement(qName.getNamespaceURI(), qName.getLocalName(), qName.getQName(), atts); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void startElement(QName qName) throws SAXException { startElement(qName, EMPTY_ATTS); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void endElement(String localName) throws SAXException { getDelegateContentHandler().endElement(getMainNamespace(), localName, localName); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void endElement(QName qName) throws SAXException { getDelegateContentHandler().endElement(qName.getNamespaceURI(), qName.getLocalName(), qName.getQName()); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void element(String localName, Attributes atts) throws SAXException { getDelegateContentHandler().startElement(getMainNamespace(), localName, localName, atts); getDelegateContentHandler().endElement(getMainNamespace(), localName, localName); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void element(QName qName, Attributes atts) throws SAXException { getDelegateContentHandler().startElement(qName.getNamespaceURI(), qName.getLocalName(), qName.getQName(), atts); getDelegateContentHandler().endElement(qName.getNamespaceURI(), qName.getLocalName(), qName.getQName()); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
public ContentHandler createContentHandler() throws SAXException { return new Handler(); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
public void startDocument() throws SAXException { //Suppress startDocument() call if doc has not been set, yet. It will be done later. if (doc != null) { super.startDocument(); } }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (doc == null) { TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } doc = domImplementation.createDocument(namespaceURI, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); setDelegateContentHandler(handler); setDelegateLexicalHandler(handler); setDelegateDTDHandler(handler); handler.startDocument(); } super.startElement(uri, localName, qName, atts); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
public void endDocument() throws SAXException { super.endDocument(); if (obListener != null) { obListener.notifyObjectBuilt(getObject()); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (entityResolver != null) { return entityResolver.resolveEntity(publicId, systemId); } else { return null; } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void notationDecl(String name, String publicId, String systemId) throws SAXException { if (dtdHandler != null) { dtdHandler.notationDecl(name, publicId, systemId); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { if (dtdHandler != null) { dtdHandler.unparsedEntityDecl(name, publicId, systemId, notationName); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void startDocument() throws SAXException { delegate.startDocument(); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void endDocument() throws SAXException { delegate.endDocument(); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void startPrefixMapping(String prefix, String uri) throws SAXException { delegate.startPrefixMapping(prefix, uri); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void endPrefixMapping(String prefix) throws SAXException { delegate.endPrefixMapping(prefix); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { delegate.startElement(uri, localName, qName, atts); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void endElement(String uri, String localName, String qName) throws SAXException { delegate.endElement(uri, localName, qName); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void characters(char[] ch, int start, int length) throws SAXException { delegate.characters(ch, start, length); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { delegate.ignorableWhitespace(ch, start, length); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void processingInstruction(String target, String data) throws SAXException { delegate.processingInstruction(target, data); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void skippedEntity(String name) throws SAXException { delegate.skippedEntity(name); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void startDTD(String name, String publicId, String systemId) throws SAXException { if (lexicalHandler != null) { lexicalHandler.startDTD(name, publicId, systemId); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void endDTD() throws SAXException { if (lexicalHandler != null) { lexicalHandler.endDTD(); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void startEntity(String name) throws SAXException { if (lexicalHandler != null) { lexicalHandler.startEntity(name); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void endEntity(String name) throws SAXException { if (lexicalHandler != null) { lexicalHandler.endEntity(name); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void startCDATA() throws SAXException { if (lexicalHandler != null) { lexicalHandler.startCDATA(); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void endCDATA() throws SAXException { if (lexicalHandler != null) { lexicalHandler.endCDATA(); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void comment(char[] ch, int start, int length) throws SAXException { if (lexicalHandler != null) { lexicalHandler.comment(ch, start, length); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void warning(SAXParseException exception) throws SAXException { if (errorHandler != null) { errorHandler.warning(exception); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void error(SAXParseException exception) throws SAXException { if (errorHandler != null) { errorHandler.error(exception); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void fatalError(SAXParseException exception) throws SAXException { if (errorHandler != null) { errorHandler.fatalError(exception); } }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void startDocument() throws SAXException { transformerHandler.startDocument(); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void endDocument() throws SAXException { transformerHandler.endDocument(); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void startPrefixMapping(String prefix, String uri) throws SAXException { transformerHandler.startPrefixMapping(prefix, uri); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void endPrefixMapping(String string) throws SAXException { transformerHandler.endPrefixMapping(string); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { AttributesImpl ai = new AttributesImpl(attrs); transformerHandler.startElement(uri, localName, qName, ai); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void endElement(String uri, String localName, String qName) throws SAXException { transformerHandler.endElement(uri, localName, qName); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void characters(char[] ch, int start, int length) throws SAXException { transformerHandler.characters(ch, start, length); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { transformerHandler.ignorableWhitespace(ch, start, length); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void processingInstruction(String target, String data) throws SAXException { transformerHandler.processingInstruction(target, data); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void skippedEntity(String name) throws SAXException { transformerHandler.skippedEntity(name); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void notationDecl(String name, String publicId, String systemId) throws SAXException { transformerHandler.notationDecl(name, publicId, systemId); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { transformerHandler.unparsedEntityDecl(name, publicId, systemId, notationName); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void startDTD(String name, String pid, String lid) throws SAXException { transformerHandler.startDTD(name, pid, lid); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void endDTD() throws SAXException { transformerHandler.endDTD(); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void startEntity(String name) throws SAXException { transformerHandler.startEntity(name); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void endEntity(String name) throws SAXException { transformerHandler.endEntity(name); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void startCDATA() throws SAXException { transformerHandler.startCDATA(); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void endCDATA() throws SAXException { transformerHandler.endCDATA(); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void comment(char[] charArray, int start, int length) throws SAXException { transformerHandler.comment(charArray, start, length); }
// in src/java/org/apache/fop/cli/InputHandler.java
private XMLReader getXMLReader() throws ParserConfigurationException, SAXException { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://xml.org/sax/features/namespaces", true); spf.setFeature("http://apache.org/xml/features/xinclude", true); XMLReader xr = spf.newSAXParser().getXMLReader(); return xr; }
(Lib) NullPointerException 32
              
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(String outputFormat, FOUserAgent userAgent, OutputStream stream) throws FOPException { if (userAgent == null) { throw new NullPointerException("The userAgent parameter must not be null!"); } return new Fop(outputFormat, userAgent, stream); }
// in src/java/org/apache/fop/pdf/PDFRoot.java
public void setLanguage(Locale locale) { if (locale == null) { throw new NullPointerException("locale must not be null"); } setLanguage(LanguageTags.toLanguageTag(locale)); }
// in src/java/org/apache/fop/pdf/PDFRoot.java
public void setStructTreeRoot(PDFStructTreeRoot structTreeRoot) { if (structTreeRoot == null) { throw new NullPointerException("structTreeRoot must not be null"); } put("StructTreeRoot", structTreeRoot); }
// in src/java/org/apache/fop/pdf/ObjectStream.java
CompressedObjectReference addObject(CompressedObject obj) { if (obj == null) { throw new NullPointerException("obj must not be null"); } CompressedObjectReference reference = new CompressedObjectReference(obj.getObjectNumber(), getObjectNumber(), objects.size()); objects.add(obj); return reference; }
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
public static void setupPDFEncryption(PDFEncryptionParams params, PDFDocument pdf) { if (pdf == null) { throw new NullPointerException("PDF document must not be null"); } if (params != null) { if (!checkAvailableAlgorithms()) { if (isJCEAvailable()) { LOG.warn("PDF encryption has been requested, JCE is " + "available but there's no " + "JCE provider available that provides the " + "necessary algorithms. The PDF won't be " + "encrypted."); } else { LOG.warn("PDF encryption has been requested but JCE is " + "unavailable! The PDF won't be encrypted."); } } pdf.setEncryption(params); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void assignObjectNumber(PDFObject obj) { if (obj == null) { throw new NullPointerException("obj must not be null"); } if (obj.hasObjectNumber()) { throw new IllegalStateException( "Error registering a PDFObject: " + "PDFObject already has an object number"); } PDFDocument currentParent = obj.getDocument(); if (currentParent != null && currentParent != this) { throw new IllegalStateException( "Error registering a PDFObject: " + "PDFObject already has a parent PDFDocument"); } obj.setObjectNumber(++this.objectcount); if (currentParent == null) { obj.setDocument(this); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void addObject(PDFObject obj) { if (obj == null) { throw new NullPointerException("obj must not be null"); } if (!obj.hasObjectNumber()) { throw new IllegalStateException( "Error adding a PDFObject: " + "PDFObject doesn't have an object number"); } //Add object to list this.objects.add(obj); //Add object to special lists where necessary if (obj instanceof PDFFunction) { this.functions.add((PDFFunction) obj); } if (obj instanceof PDFShading) { final String shadingName = "Sh" + (++this.shadingCount); ((PDFShading)obj).setName(shadingName); this.shadings.add((PDFShading) obj); } if (obj instanceof PDFPattern) { final String patternName = "Pa" + (++this.patternCount); ((PDFPattern)obj).setName(patternName); this.patterns.add((PDFPattern) obj); } if (obj instanceof PDFFont) { final PDFFont font = (PDFFont)obj; this.fontMap.put(font.getName(), font); } if (obj instanceof PDFGState) { this.gstates.add((PDFGState) obj); } if (obj instanceof PDFPage) { this.pages.notifyKidRegistered((PDFPage)obj); } if (obj instanceof PDFLaunch) { this.launches.add((PDFLaunch) obj); } if (obj instanceof PDFLink) { this.links.add((PDFLink) obj); } if (obj instanceof PDFFileSpec) { this.filespecs.add((PDFFileSpec) obj); } if (obj instanceof PDFGoToRemote) { this.gotoremotes.add((PDFGoToRemote) obj); } }
// in src/java/org/apache/fop/fo/properties/DimensionPropertyMaker.java
public void setExtraCorresponding(int[][] extraCorresponding) { if ( extraCorresponding == null ) { throw new NullPointerException(); } for ( int i = 0; i < extraCorresponding.length; i++ ) { int[] eca = extraCorresponding[i]; if ( ( eca == null ) || ( eca.length != 4 ) ) { throw new IllegalArgumentException ( "bad sub-array @ [" + i + "]" ); } } this.extraCorresponding = extraCorresponding; }
// in src/java/org/apache/fop/fo/FObj.java
void addExtensionAttachment(ExtensionAttachment attachment) { if (attachment == null) { throw new NullPointerException( "Parameter attachment must not be null"); } if (extensionAttachments == null) { extensionAttachments = new java.util.ArrayList<ExtensionAttachment>(); } if (log.isDebugEnabled()) { log.debug("ExtensionAttachment of category " + attachment.getCategory() + " added to " + getName() + ": " + attachment); } extensionAttachments.add(attachment); }
// in src/java/org/apache/fop/fo/FObj.java
public void addForeignAttribute(QName attributeName, String value) { /* TODO: Handle this over FOP's property mechanism so we can use * inheritance. */ if (attributeName == null) { throw new NullPointerException("Parameter attributeName must not be null"); } if (foreignAttributes == null) { foreignAttributes = new java.util.HashMap<QName, String>(); } foreignAttributes.put(attributeName, value); }
// in src/java/org/apache/fop/fonts/EmbedFontInfo.java
public void setEncodingMode(EncodingMode mode) { if (mode == null) { throw new NullPointerException("mode must not be null"); } this.encodingMode = mode; }
// in src/java/org/apache/fop/render/pdf/CTMHelper.java
public static String toPDFString(CTM sourceMatrix) { if (null == sourceMatrix) { throw new NullPointerException("sourceMatrix must not be null"); } final double[] matrix = toPDFArray(sourceMatrix); return constructPDFArray(matrix); }
// in src/java/org/apache/fop/render/pdf/CTMHelper.java
public static String toPDFString(AffineTransform transform, boolean convertMillipoints) { if (null == transform) { throw new NullPointerException("transform must not be null"); } final double[] matrix = new double[6]; transform.getMatrix(matrix); if (convertMillipoints) { //Convert from millipoints to points matrix[4] /= 1000; matrix[5] /= 1000; } return constructPDFArray(matrix); }
// in src/java/org/apache/fop/render/pdf/CTMHelper.java
public static CTM toPDFCTM(CTM sourceMatrix) { if (null == sourceMatrix) { throw new NullPointerException("sourceMatrix must not be null"); } final double[] matrix = toPDFArray(sourceMatrix); return new CTM(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); }
// in src/java/org/apache/fop/render/pdf/CTMHelper.java
public static double[] toPDFArray(CTM sourceMatrix) { if (null == sourceMatrix) { throw new NullPointerException("sourceMatrix must not be null"); } final double[] matrix = sourceMatrix.toArray(); return new double[]{matrix[0], matrix[1], matrix[2], matrix[3], matrix[4] / 1000.0, matrix[5] / 1000.0}; }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
private Typeface getTypeface(String fontName) { if (fontName == null) { throw new NullPointerException("fontName must not be null"); } Typeface tf = getFontInfo().getFonts().get(fontName); if (tf instanceof LazyFont) { tf = ((LazyFont)tf).getRealFont(); } return tf; }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void noteAction(AbstractAction action) { if (action == null) { throw new NullPointerException("action must not be null"); } if (!action.isComplete()) { assert action.hasID(); incompleteActions.put(action.getID(), action); } }
// in src/java/org/apache/fop/render/intermediate/extensions/GoToXYAction.java
public boolean isSame(AbstractAction other) { if (other == null) { throw new NullPointerException("other must not be null"); } if (!(other instanceof GoToXYAction)) { return false; } GoToXYAction otherAction = (GoToXYAction)other; if (this.pageIndex != otherAction.pageIndex) { return false; } if (this.targetLocation == null || otherAction.targetLocation == null) { return false; } if (!getTargetLocation().equals(otherAction.getTargetLocation())) { return false; } return true; }
// in src/java/org/apache/fop/render/intermediate/extensions/URIAction.java
public boolean isSame(AbstractAction other) { if (other == null) { throw new NullPointerException("other must not be null"); } if (!(other instanceof URIAction)) { return false; } URIAction otherAction = (URIAction)other; if (!getURI().equals(otherAction.getURI())) { return false; } if (isNewWindow() != otherAction.isNewWindow()) { return false; } return true; }
// in src/java/org/apache/fop/render/ps/PSPainter.java
private Typeface getTypeface(String fontName) { if (fontName == null) { throw new NullPointerException("fontName must not be null"); } Typeface tf = (Typeface)getFontInfo().getFonts().get(fontName); if (tf instanceof LazyFont) { tf = ((LazyFont)tf).getRealFont(); } return tf; }
// in src/java/org/apache/fop/area/AreaTreeModel.java
public void startPageSequence(PageSequence pageSequence) { if (pageSequence == null) { throw new NullPointerException("pageSequence must not be null"); } if (currentPageSequence != null) { currentPageIndex += currentPageSequence.getPageCount(); } this.currentPageSequence = pageSequence; pageSequenceList.add(currentPageSequence); }
// in src/java/org/apache/fop/layoutmgr/ElementListObserver.java
public static void observe(List elementList, String category, String id) { if (isObservationActive()) { if (category == null) { throw new NullPointerException("category must not be null"); } Iterator i = activeObservers.iterator(); while (i.hasNext()) { ((Observer)i.next()).observe(elementList, category, id); } } }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public static ResourceBundle getXMLBundle(String baseName, Locale locale, ClassLoader loader) throws MissingResourceException { if (loader == null) { throw new NullPointerException("loader must not be null"); } if (baseName == null) { throw new NullPointerException("baseName must not be null"); } assert locale != null; ResourceBundle bundle; if (!locale.equals(Locale.getDefault())) { bundle = handleGetXMLBundle(baseName, "_" + locale, false, loader); if (bundle != null) { return bundle; } } bundle = handleGetXMLBundle(baseName, "_" + Locale.getDefault(), true, loader); if (bundle != null) { return bundle; } throw new MissingResourceException( baseName + " (" + locale + ")", baseName + '_' + locale, null); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
protected Object handleGetObject(String key) { if (key == null) { throw new NullPointerException("key must not be null"); } return resources.get(key); }
// in src/java/org/apache/fop/util/text/AdvancedMessageFormat.java
public void addChild(Part part) { if (part == null) { throw new NullPointerException("part must not be null"); } if (hasSections) { CompositePart composite = (CompositePart) this.parts.get(this.parts.size() - 1); composite.addChild(part); } else { this.parts.add(part); } }
0 0
(Lib) Exception 30
              
// in src/java/org/apache/fop/render/rtf/rtflib/tools/BuilderContext.java
public void replaceContainer(RtfContainer oldC, RtfContainer newC) throws Exception { // treating the Stack as a Vector allows such manipulations (yes, I hear you screaming ;-) final int index = containers.indexOf(oldC); if (index < 0) { throw new Exception("container to replace not found:" + oldC); } containers.setElementAt(newC, index); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static void readBidiClassProperties(String bidiFileName) throws Exception { // read property names BufferedReader b = new BufferedReader(new InputStreamReader(new URL(bidiFileName).openStream())); String line; int lineNumber = 0; TreeSet intervals = new TreeSet(); while ( ( line = b.readLine() ) != null ) { lineNumber++; if ( line.startsWith("#") ) { continue; } else if ( line.length() == 0 ) { continue; } else { if ( line.indexOf ( "#" ) != -1 ) { line = ( line.split ( "#" ) ) [ 0 ]; } String[] fa = line.split ( ";" ); if ( fa.length == 2 ) { int[] interval = parseInterval ( fa[0].trim() ); byte bidiClass = (byte) parseBidiClass ( fa[1].trim() ); if ( interval[1] == interval[0] ) { // singleton int c = interval[0]; if ( c <= 0x00FF ) { if ( bcL1 [ c - 0x0000 ] == 0 ) { bcL1 [ c - 0x0000 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + c ); } } else if ( ( c >= 0x0590 ) && ( c <= 0x06FF ) ) { if ( bcR1 [ c - 0x0590 ] == 0 ) { bcR1 [ c - 0x0590 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + c ); } } else { addInterval ( intervals, c, c, bidiClass ); } } else { // non-singleton int s = interval[0]; int e = interval[1]; // inclusive if ( s <= 0x00FF ) { for ( int i = s; i <= e; i++ ) { if ( i <= 0x00FF ) { if ( bcL1 [ i - 0x0000 ] == 0 ) { bcL1 [ i - 0x0000 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + i ); } } else { addInterval ( intervals, i, e, bidiClass ); break; } } } else if ( ( s >= 0x0590 ) && ( s <= 0x06FF ) ) { for ( int i = s; i <= e; i++ ) { if ( i <= 0x06FF ) { if ( bcR1 [ i - 0x0590 ] == 0 ) { bcR1 [ i - 0x0590 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + i ); } } else { addInterval ( intervals, i, e, bidiClass ); break; } } } else { addInterval ( intervals, s, e, bidiClass ); } } } else { throw new Exception ( "bad syntax, line(" + lineNumber + "): " + line ); } } } // compile interval search data int ivIndex = 0; int niv = intervals.size(); bcS1 = new int [ niv ]; bcE1 = new int [ niv ]; bcC1 = new byte [ niv ]; for ( Iterator it = intervals.iterator(); it.hasNext(); ivIndex++ ) { Interval iv = (Interval) it.next(); bcS1[ivIndex] = iv.start; bcE1[ivIndex] = iv.end; bcC1[ivIndex] = (byte) iv.bidiClass; } // test data test(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static int[] parseInterval ( String interval ) throws Exception { int s; int e; String[] fa = interval.split("\\.\\."); if ( fa.length == 1 ) { s = Integer.parseInt ( fa[0], 16 ); e = s; } else if ( fa.length == 2 ) { s = Integer.parseInt ( fa[0], 16 ); e = Integer.parseInt ( fa[1], 16 ); } else { throw new Exception ( "bad interval syntax: " + interval ); } if ( e < s ) { throw new Exception ( "bad interval, start must be less than or equal to end: " + interval ); } return new int[] {s, e}; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static void test() throws Exception { for ( int i = 0, n = testData.length / 2; i < n; i++ ) { int ch = testData [ i * 2 + 0 ]; int tc = testData [ i * 2 + 1 ]; int bc = getBidiClass ( ch ); if ( bc != tc ) { throw new Exception ( "test mapping failed for character (0x" + Integer.toHexString(ch) + "): expected " + tc + ", got " + bc ); } } }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
private static void convertLineBreakProperties( // CSOK: MethodLength String lineBreakFileName, String propertyValueFileName, String breakPairFileName, String outFileName) throws Exception { readLineBreakProperties(lineBreakFileName, propertyValueFileName); // read break pair table int lineBreakPropertyValueCount = lineBreakPropertyValues.size(); int tableSize = lineBreakPropertyValueCount - NOT_IN_PAIR_TABLE.length; Map notInPairTableMap = new HashMap(NOT_IN_PAIR_TABLE.length); for (int i = 0; i < NOT_IN_PAIR_TABLE.length; i++) { Object v = lineBreakPropertyValues.get(NOT_IN_PAIR_TABLE[i]); if (v == null) { throw new Exception("'not in pair table' property not found: " + NOT_IN_PAIR_TABLE[i]); } notInPairTableMap.put(NOT_IN_PAIR_TABLE[i], v); } byte[][] pairTable = new byte[tableSize][]; byte[] columnHeader = new byte[tableSize]; byte[] rowHeader = new byte[tableSize]; byte[] columnMap = new byte[lineBreakPropertyValueCount + 1]; Arrays.fill(columnMap, (byte)255); byte[] rowMap = new byte[lineBreakPropertyValueCount + 1]; Arrays.fill(rowMap, (byte)255); BufferedReader b = new BufferedReader(new FileReader(breakPairFileName)); String line = b.readLine(); int lineNumber = 1; String[] lineTokens; String name; // read header if (line != null) { lineTokens = line.split("\\s+"); byte columnNumber = 0; for (int i = 0; i < lineTokens.length; ++i) { name = lineTokens[i]; if (name.length() > 0) { if (columnNumber >= columnHeader.length) { throw new Exception(breakPairFileName + ':' + lineNumber + ": unexpected column header " + name); } if (notInPairTableMap.get(name) != null) { throw new Exception(breakPairFileName + ':' + lineNumber + ": invalid column header " + name); } Byte v = (Byte)lineBreakPropertyValues.get(name); if (v != null) { byte vv = v.byteValue(); columnHeader[columnNumber] = vv; columnMap[vv] = columnNumber; } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": unknown column header " + name); } columnNumber++; } } if (columnNumber < columnHeader.length) { StringBuffer missing = new StringBuffer(); for (int j = 0; j < lineBreakPropertyShortNames.size(); j++) { boolean found = false; for (int k = 0; k < columnNumber; k++) { if (columnHeader[k] == j + 1) { found = true; break; } } if (!found) { if (missing.length() > 0) { missing.append(", "); } missing.append((String)lineBreakPropertyShortNames.get(j)); } } throw new Exception( breakPairFileName + ':' + lineNumber + ": missing column for properties: " + missing.toString()); } } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": can't read table header"); } line = b.readLine().trim(); lineNumber++; byte rowNumber = 0; while (line != null && line.length() > 0) { if (rowNumber >= rowHeader.length) { throw new Exception(breakPairFileName + ':' + lineNumber + ": unexpected row " + line); } pairTable[rowNumber] = new byte[tableSize]; lineTokens = line.split("\\s+"); if (lineTokens.length > 0) { name = lineTokens[0]; if (notInPairTableMap.get(name) != null) { throw new Exception(breakPairFileName + ':' + lineNumber + ": invalid row header " + name); } Byte v = (Byte)lineBreakPropertyValues.get(name); if (v != null) { byte vv = v.byteValue(); rowHeader[rowNumber] = vv; rowMap[vv] = rowNumber; } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": unknown row header " + name); } } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": can't read row header"); } int columnNumber = 0; String token; for (int i = 1; i < lineTokens.length; ++i) { token = lineTokens[i]; if (token.length() == 1) { byte tokenBreakClass = (byte)BREAK_CLASS_TOKENS.indexOf(token.charAt(0)); if (tokenBreakClass >= 0) { pairTable[rowNumber][columnNumber] = tokenBreakClass; } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": unexpected token: " + token); } } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": token too long: " + token); } columnNumber++; } line = b.readLine().trim(); lineNumber++; rowNumber++; } if (rowNumber < rowHeader.length) { StringBuffer missing = new StringBuffer(); for (int j = 0; j < lineBreakPropertyShortNames.size(); j++) { boolean found = false; for (int k = 0; k < rowNumber; k++) { if (rowHeader[k] == j + 1) { found = true; break; } } if (!found) { if (missing.length() > 0) { missing.append(", "); } missing.append((String)lineBreakPropertyShortNames.get(j)); } } throw new Exception( breakPairFileName + ':' + lineNumber + ": missing row for properties: " + missing.toString()); } // generate class int rowsize = 512; int blocksize = lineBreakProperties.length / rowsize; byte[][] row = new byte[rowsize][]; int idx = 0; StringBuffer doStaticLinkCode = new StringBuffer(); PrintWriter out = new PrintWriter(new FileWriter(outFileName)); License.writeJavaLicenseId(out); out.println(); out.println("package org.apache.fop.text.linebreak;"); out.println(); out.println("/*"); out.println(" * !!! THIS IS A GENERATED FILE !!!"); out.println(" * If updates to the source are needed, then:"); out.println(" * - apply the necessary modifications to"); out.println(" * 'src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java'"); out.println(" * - run 'ant codegen-unicode', which will generate a new LineBreakUtils.java"); out.println(" * in 'src/java/org/apache/fop/text/linebreak'"); out.println(" * - commit BOTH changed files"); out.println(" */"); out.println(); out.println("// CSOFF: WhitespaceAfterCheck"); out.println("// CSOFF: LineLengthCheck"); out.println(); out.println("/** Line breaking utilities. */"); out.println("public final class LineBreakUtils {"); out.println(); out.println(" private LineBreakUtils() {"); out.println(" }"); out.println(); out.println(" /** Break class constant */"); out.println(" public static final byte DIRECT_BREAK = " + DIRECT_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte INDIRECT_BREAK = " + INDIRECT_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte COMBINING_INDIRECT_BREAK = " + COMBINING_INDIRECT_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte COMBINING_PROHIBITED_BREAK = " + COMBINING_PROHIBITED_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte PROHIBITED_BREAK = " + PROHIBITED_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte EXPLICIT_BREAK = " + EXPLICIT_BREAK + ';'); out.println(); out.println(" private static final byte[][] PAIR_TABLE = {"); boolean printComma = false; for (int i = 1; i <= lineBreakPropertyValueCount; i++) { if (printComma) { out.println(","); } else { printComma = true; } out.print(" {"); boolean localPrintComma = false; for (int j = 1; j <= lineBreakPropertyValueCount; j++) { if (localPrintComma) { out.print(", "); } else { localPrintComma = true; } if (columnMap[j] != -1 && rowMap[i] != -1) { out.print(pairTable[rowMap[i]][columnMap[j]]); } else { out.print('0'); } } out.print('}'); } out.println("};"); out.println(); out.println(" private static byte[][] lineBreakProperties = new byte[" + rowsize + "][];"); out.println(); out.println(" private static void init0() {"); int rowsPrinted = 0; int initSections = 0; for (int i = 0; i < rowsize; i++) { boolean found = false; for (int j = 0; j < i; j++) { if (row[j] != null) { boolean matched = true; for (int k = 0; k < blocksize; k++) { if (row[j][k] != lineBreakProperties[idx + k]) { matched = false; break; } } if (matched) { found = true; doStaticLinkCode.append(" lineBreakProperties["); doStaticLinkCode.append(i); doStaticLinkCode.append("] = lineBreakProperties["); doStaticLinkCode.append(j); doStaticLinkCode.append("];\n"); break; } } } if (!found) { if (rowsPrinted >= 64) { out.println(" }"); out.println(); initSections++; out.println(" private static void init" + initSections + "() {"); rowsPrinted = 0; } row[i] = new byte[blocksize]; boolean printLocalComma = false; out.print(" lineBreakProperties[" + i + "] = new byte[] { "); for (int k = 0; k < blocksize; k++) { row[i][k] = lineBreakProperties[idx + k]; if (printLocalComma) { out.print(", "); } else { printLocalComma = true; } out.print(row[i][k]); } out.println("};"); rowsPrinted++; } idx += blocksize; } out.println(" }"); out.println(); out.println(" static {"); for (int i = 0; i <= initSections; i++) { out.println(" init" + i + "();"); } out.print(doStaticLinkCode); out.println(" }"); out.println(); for (int i = 0; i < lineBreakPropertyShortNames.size(); i++) { String shortName = (String)lineBreakPropertyShortNames.get(i); out.println(" /** Linebreak property constant */"); out.print(" public static final byte LINE_BREAK_PROPERTY_"); out.print(shortName); out.print(" = "); out.print(i + 1); out.println(';'); } out.println(); final String shortNamePrefix = " private static String[] lineBreakPropertyShortNames = {"; out.print(shortNamePrefix); int lineLength = shortNamePrefix.length(); printComma = false; for (int i = 0; i < lineBreakPropertyShortNames.size(); i++) { name = (String)lineBreakPropertyShortNames.get(i); if (printComma) { if (lineLength <= MAX_LINE_LENGTH - 2) { out.print(", "); } else { out.print(","); } // count the space anyway to force a linebreak if the comma causes lineLength == MAX_LINE_LENGTH lineLength += 2; } else { printComma = true; } if (lineLength > MAX_LINE_LENGTH) { out.println(); out.print(" "); lineLength = 8; } out.print('"'); out.print(name); out.print('"'); lineLength += (2 + name.length()); } out.println("};"); out.println(); final String longNamePrefix = " private static String[] lineBreakPropertyLongNames = {"; out.print(longNamePrefix); lineLength = longNamePrefix.length(); printComma = false; for (int i = 0; i < lineBreakPropertyLongNames.size(); i++) { name = (String)lineBreakPropertyLongNames.get(i); if (printComma) { out.print(','); lineLength++; } else { printComma = true; } if (lineLength > MAX_LINE_LENGTH) { out.println(); out.print(" "); lineLength = 8; } out.print('"'); out.print(name); out.print('"'); lineLength += (2 + name.length()); } out.println("};"); out.println(); out.println(" /**"); out.println(" * Return the short name for the linebreak property corresponding"); out.println(" * to the given symbolic constant."); out.println(" *"); out.println(" * @param i the numeric value of the linebreak property"); out.println(" * @return the short name of the linebreak property"); out.println(" */"); out.println(" public static String getLineBreakPropertyShortName(byte i) {"); out.println(" if (i > 0 && i <= lineBreakPropertyShortNames.length) {"); out.println(" return lineBreakPropertyShortNames[i - 1];"); out.println(" } else {"); out.println(" return null;"); out.println(" }"); out.println(" }"); out.println(); out.println(" /**"); out.println(" * Return the long name for the linebreak property corresponding"); out.println(" * to the given symbolic constant."); out.println(" *"); out.println(" * @param i the numeric value of the linebreak property"); out.println(" * @return the long name of the linebreak property"); out.println(" */"); out.println(" public static String getLineBreakPropertyLongName(byte i) {"); out.println(" if (i > 0 && i <= lineBreakPropertyLongNames.length) {"); out.println(" return lineBreakPropertyLongNames[i - 1];"); out.println(" } else {"); out.println(" return null;"); out.println(" }"); out.println(" }"); out.println(); out.println(" /**"); out.println(" * Return the linebreak property constant for the given <code>char</code>"); out.println(" *"); out.println(" * @param c the <code>char</code> whose linebreak property to return"); out.println(" * @return the constant representing the linebreak property"); out.println(" */"); out.println(" public static byte getLineBreakProperty(char c) {"); out.println(" return lineBreakProperties[c / " + blocksize + "][c % " + blocksize + "];"); out.println(" }"); out.println(); out.println(" /**"); out.println(" * Return the break class constant for the given pair of linebreak"); out.println(" * property constants."); out.println(" *"); out.println(" * @param lineBreakPropertyBefore the linebreak property for the first character"); out.println(" * in a two-character sequence"); out.println(" * @param lineBreakPropertyAfter the linebreak property for the second character"); out.println(" * in a two-character sequence"); out.println(" * @return the constant representing the break class"); out.println(" */"); out.println( " public static byte getLineBreakPairProperty(int lineBreakPropertyBefore, int lineBreakPropertyAfter) {"); out.println(" return PAIR_TABLE[lineBreakPropertyBefore - 1][lineBreakPropertyAfter - 1];"); out.println(" }"); out.println(); out.println("}"); out.flush(); out.close(); }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
private static void readLineBreakProperties(String lineBreakFileName, String propertyValueFileName) throws Exception { // read property names BufferedReader b = new BufferedReader(new InputStreamReader(new URL(propertyValueFileName).openStream())); String line = b.readLine(); int lineNumber = 1; byte propertyIndex = 1; byte indexForUnknown = 0; while (line != null) { if (line.startsWith("lb")) { String shortName; String longName = null; int semi = line.indexOf(';'); if (semi < 0) { throw new Exception( propertyValueFileName + ':' + lineNumber + ": missing property short name in " + line); } line = line.substring(semi + 1); semi = line.indexOf(';'); if (semi > 0) { shortName = line.substring(0, semi).trim(); longName = line.substring(semi + 1).trim(); semi = longName.indexOf(';'); if (semi > 0) { longName = longName.substring(0, semi).trim(); } } else { shortName = line.trim(); } if (shortName.equals("XX")) { indexForUnknown = propertyIndex; } lineBreakPropertyValues.put(shortName, new Byte((byte)propertyIndex)); lineBreakPropertyShortNames.add(shortName); lineBreakPropertyLongNames.add(longName); propertyIndex++; if (propertyIndex <= 0) { throw new Exception(propertyValueFileName + ':' + lineNumber + ": property rolled over in " + line); } } line = b.readLine(); lineNumber++; } if (indexForUnknown == 0) { throw new Exception("index for XX (unknown) line break property value not found"); } // read property values Arrays.fill(lineBreakProperties, (byte)0); b = new BufferedReader(new InputStreamReader(new URL(lineBreakFileName).openStream())); line = b.readLine(); lineNumber = 1; while (line != null) { int idx = line.indexOf('#'); if (idx >= 0) { line = line.substring(0, idx); } line = line.trim(); if (line.length() > 0) { idx = line.indexOf(';'); if (idx <= 0) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": No field delimiter in " + line); } Byte v = (Byte)lineBreakPropertyValues.get(line.substring(idx + 1).trim()); if (v == null) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Unknown property value in " + line); } String codepoint = line.substring(0, idx); int low; int high; idx = codepoint.indexOf(".."); try { if (idx >= 0) { low = Integer.parseInt(codepoint.substring(0, idx), 16); high = Integer.parseInt(codepoint.substring(idx + 2), 16); } else { low = Integer.parseInt(codepoint, 16); high = low; } } catch (NumberFormatException e) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Invalid codepoint number in " + line); } if (high > 0xFFFF) { // ignore non-baseplane characters for now } else { if (low < 0 || high < 0) { throw new Exception( lineBreakFileName + ':' + lineNumber + ": Negative codepoint(s) in " + line); } byte vv = v.byteValue(); for (int i = low; i <= high; i++) { if (lineBreakProperties[i] != 0) { throw new Exception( lineBreakFileName + ':' + lineNumber + ": Property already set for " + ((char)i) + " in " + line); } lineBreakProperties[i] = vv; } } } line = b.readLine(); lineNumber++; } }
1
              
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
catch (NumberFormatException e) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Invalid codepoint number in " + line); }
21
              
// in src/sandbox/org/apache/fop/render/svg/SVGSVGHandler.java
public void handleXML(RendererContext context, org.w3c.dom.Document doc, String ns) throws Exception { if (getNamespace().equals(ns)) { if (!(doc instanceof SVGDocument)) { DOMImplementation impl = SVGDOMImplementation.getDOMImplementation(); doc = DOMUtilities.deepCloneDocument(doc, impl); } SVGSVGElement svg = ((SVGDocument) doc).getRootElement(); SVGDocument targetDoc = (SVGDocument)context.getProperty(SVG_DOCUMENT); SVGElement currentPageG = (SVGElement)context.getProperty(SVG_PAGE_G); Element view = targetDoc.createElementNS(getNamespace(), "svg"); Node newsvg = targetDoc.importNode(svg, true); //view.setAttributeNS(null, "viewBox", "0 0 "); int xpos = ((Integer)context.getProperty(XPOS)).intValue(); int ypos = ((Integer)context.getProperty(YPOS)).intValue(); view.setAttributeNS(null, "x", "" + xpos / 1000f); view.setAttributeNS(null, "y", "" + ypos / 1000f); // this fixes a problem where the xmlns is repeated sometimes Element ele = (Element) newsvg; ele.setAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI, "xmlns", getNamespace()); if (ele.hasAttributeNS(null, "xmlns")) { ele.removeAttributeNS(null, "xmlns"); } view.appendChild(newsvg); currentPageG.appendChild(view); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void generate() throws Exception { prepare(); FontEventListener listener = new FontEventListener() { public void fontLoadingErrorAtAutoDetection(Object source, String fontURL, Exception e) { System.err.println("Could not load " + fontURL + " (" + e.getLocalizedMessage() + ")"); } public void fontSubstituted(Object source, FontTriplet requested, FontTriplet effective) { //ignore } public void glyphNotAvailable(Object source, char ch, String fontName) { //ignore } public void fontDirectoryNotFound(Object source, String msg) { //ignore } public void svgTextStrokedAsShapes(Object source, String fontFamily) { // ignore } }; FontListGenerator listGenerator = new FontListGenerator(); SortedMap fontFamilies = listGenerator.listFonts(fopFactory, configMime, listener); if (this.mode == GENERATE_CONSOLE) { writeToConsole(fontFamilies); } else { writeOutput(fontFamilies); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
private void renderInputHandler(InputHandler inputHandler, File outFile, String outputFormat) throws Exception { OutputStream out = null; try { out = new java.io.FileOutputStream(outFile); out = new BufferedOutputStream(out); } catch (Exception ex) { throw new BuildException("Failed to open " + outFile, ex); } boolean success = false; try { FOUserAgent userAgent = fopFactory.newFOUserAgent(); userAgent.setBaseURL(this.baseURL); inputHandler.renderTo(userAgent, outputFormat, out); success = true; } catch (Exception ex) { if (task.getThrowexceptions()) { throw new BuildException(ex); } throw ex; } finally { try { out.close(); } catch (IOException ioe) { logger.error("Error closing output file", ioe); } if (!success) { outFile.delete(); } } }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
public static void main(String[] argv) throws Exception { HyphenationTree ht = null; int minCharCount = 2; BufferedReader in = new BufferedReader(new java.io.InputStreamReader(System.in)); while (true) { System.out.print("l:\tload patterns from XML\n" + "L:\tload patterns from serialized object\n" + "s:\tset minimum character count\n" + "w:\twrite hyphenation tree to object file\n" + "h:\thyphenate\n" + "f:\tfind pattern\n" + "b:\tbenchmark\n" + "q:\tquit\n\n" + "Command:"); String token = in.readLine().trim(); if (token.equals("f")) { System.out.print("Pattern: "); token = in.readLine().trim(); System.out.println("Values: " + ht.findPattern(token)); } else if (token.equals("s")) { System.out.print("Minimun value: "); token = in.readLine().trim(); minCharCount = Integer.parseInt(token); } else if (token.equals("l")) { ht = new HyphenationTree(); System.out.print("XML file name: "); token = in.readLine().trim(); ht.loadPatterns(token); } else if (token.equals("L")) { ObjectInputStream ois = null; System.out.print("Object file name: "); token = in.readLine().trim(); try { ois = new ObjectInputStream(new FileInputStream(token)); ht = (HyphenationTree)ois.readObject(); } catch (Exception e) { e.printStackTrace(); } finally { if (ois != null) { try { ois.close(); } catch (IOException e) { //ignore } } } } else if (token.equals("w")) { System.out.print("Object file name: "); token = in.readLine().trim(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream(token)); oos.writeObject(ht); } catch (Exception e) { e.printStackTrace(); } finally { if (oos != null) { try { oos.flush(); } catch (IOException e) { //ignore } try { oos.close(); } catch (IOException e) { //ignore } } } } else if (token.equals("h")) { System.out.print("Word: "); token = in.readLine().trim(); System.out.print("Hyphenation points: "); System.out.println(ht.hyphenate(token, minCharCount, minCharCount)); } else if (token.equals("b")) { if (ht == null) { System.out.println("No patterns have been loaded."); break; } System.out.print("Word list filename: "); token = in.readLine().trim(); long starttime = 0; int counter = 0; try { BufferedReader reader = new BufferedReader(new FileReader(token)); String line; starttime = System.currentTimeMillis(); while ((line = reader.readLine()) != null) { // System.out.print("\nline: "); Hyphenation hyp = ht.hyphenate(line, minCharCount, minCharCount); if (hyp != null) { String hword = hyp.toString(); // System.out.println(line); // System.out.println(hword); } else { // System.out.println("No hyphenation"); } counter++; } } catch (Exception ioe) { System.out.println("Exception " + ioe); ioe.printStackTrace(); } long endtime = System.currentTimeMillis(); long result = endtime - starttime; System.out.println(counter + " words in " + result + " Milliseconds hyphenated"); } else if (token.equals("q")) { break; } } }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public static void main(String[] args) throws Exception { if (args.length > 0) { PatternParser pp = new PatternParser(); PrintStream p = null; if (args.length > 1) { FileOutputStream f = new FileOutputStream(args[1]); p = new PrintStream(f, false, "utf-8"); pp.setTestOut(p); } pp.parse(args[0]); if (pp != null) { pp.closeTestOut(); } } }
// in src/java/org/apache/fop/hyphenation/TernaryTree.java
public static void main(String[] args) throws Exception { TernaryTree tt = new TernaryTree(); tt.insert("Carlos", 'C'); tt.insert("Car", 'r'); tt.insert("palos", 'l'); tt.insert("pa", 'p'); tt.trimToSize(); System.out.println((char)tt.find("Car")); System.out.println((char)tt.find("Carlos")); System.out.println((char)tt.find("alto")); tt.printStats(); }
// in src/java/org/apache/fop/render/xml/XMLXMLHandler.java
public void handleXML(RendererContext context, org.w3c.dom.Document doc, String ns) throws Exception { ContentHandler handler = (ContentHandler) context.getProperty(HANDLER); new DOM2SAX(handler).writeDocument(doc, true); }
// in src/java/org/apache/fop/render/AbstractGenericSVGHandler.java
public void handleXML(RendererContext context, Document doc, String ns) throws Exception { if (SVGDOMImplementation.SVG_NAMESPACE_URI.equals(ns)) { renderSVGDocument(context, doc); } }
// in src/java/org/apache/fop/render/rtf/rtflib/tools/BuilderContext.java
public void replaceContainer(RtfContainer oldC, RtfContainer newC) throws Exception { // treating the Stack as a Vector allows such manipulations (yes, I hear you screaming ;-) final int index = containers.indexOf(oldC); if (index < 0) { throw new Exception("container to replace not found:" + oldC); } containers.setElementAt(newC, index); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public static void main(String[] args) throws Exception { Writer w = null; if (args.length != 0) { final String outFile = args[0]; System.err.println("Outputting RTF to file '" + outFile + "'"); w = new BufferedWriter(new FileWriter(outFile)); } else { System.err.println("Outputting RTF code to standard output"); w = new BufferedWriter(new OutputStreamWriter(System.out)); } final RtfFile f = new RtfFile(w); final RtfSection sect = f.startDocumentArea().newSection(); final RtfParagraph p = sect.newParagraph(); p.newText("Hello, RTF world.\n", null); final RtfAttributes attr = new RtfAttributes(); attr.set(RtfText.ATTR_BOLD); attr.set(RtfText.ATTR_ITALIC); attr.set(RtfText.ATTR_FONT_SIZE, 36); p.newText("This is bold, italic, 36 points", attr); f.flush(); System.err.println("RtfFile test: all done."); }
// in src/java/org/apache/fop/render/afp/AFPSVGHandler.java
public void handleXML(RendererContext context, Document doc, String ns) throws Exception { if (SVGDOMImplementation.SVG_NAMESPACE_URI.equals(ns)) { renderSVGDocument(context, doc); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void convertBidiTestData(String ucdFileName, String bidiFileName, String outFileName) throws Exception { // read type data from UCD if ignoring deprecated type data if ( ignoreDeprecatedTypeData ) { readBidiTypeData(ucdFileName); } // read bidi test data readBidiTestData(bidiFileName); // generate class PrintWriter out = new PrintWriter(new FileWriter(outFileName)); License.writeJavaLicenseId(out); out.println(); out.println("package org.apache.fop.complexscripts.bidi;"); out.println(); out.println("import java.io.IOException;"); out.println("import java.io.InputStream;"); out.println("import java.io.ObjectInputStream;"); out.println(); out.println("// CSOFF: WhitespaceAfterCheck"); out.println(); out.println("/*"); out.println(" * !!! THIS IS A GENERATED FILE !!!"); out.println(" * If updates to the source are needed, then:"); out.println(" * - apply the necessary modifications to"); out.println(" * 'src/codegen/unicode/java/org/apache/fop/text/bidi/GenerateBidiTestData.java'"); out.println(" * - run 'ant codegen-unicode', which will generate a new BidiTestData.java"); out.println(" * in 'test/java/org/apache/fop/complexscripts/bidi'"); out.println(" * - commit BOTH changed files"); out.println(" */"); out.println(); out.println("/** Bidirectional test data. */"); out.println("public final class BidiTestData {"); out.println(); out.println(" private BidiTestData() {"); out.println(" }"); out.println(); dumpData ( out, outFileName ); out.println(" public static final int NUM_TEST_SEQUENCES = " + numTestSpecs + ";"); out.println(); out.println(" public static int[] readTestData ( String prefix, int index ) {"); out.println(" int[] data = null;"); out.println(" InputStream is = null;"); out.println(" Class btc = BidiTestData.class;"); out.println(" String name = btc.getSimpleName() + \"$\" + prefix + index + \".ser\";"); out.println(" try {"); out.println(" if ( ( is = btc.getResourceAsStream ( name ) ) != null ) {"); out.println(" ObjectInputStream ois = new ObjectInputStream ( is );"); out.println(" data = (int[]) ois.readObject();"); out.println(" ois.close();"); out.println(" }"); out.println(" } catch ( IOException e ) {"); out.println(" data = null;"); out.println(" } catch ( ClassNotFoundException e ) {"); out.println(" data = null;"); out.println(" } finally {"); out.println(" if ( is != null ) {"); out.println(" try { is.close(); } catch ( Exception e ) {}"); out.println(" }"); out.println(" }"); out.println(" return data;"); out.println(" }"); out.println("}"); out.flush(); out.close(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void readBidiTypeData(String ucdFileName) throws Exception { BufferedReader b = new BufferedReader(new InputStreamReader(new URL(ucdFileName).openStream())); String line; int n; // singleton map - derived from single char entry Map/*<Integer,List>*/ sm = new HashMap/*<Integer,List>*/(); // interval map - derived from pair of block endpoint entries Map/*<String,int[3]>*/ im = new HashMap/*<String,int[3]>*/(); if ( verbose ) { System.out.print("Reading bidi type data..."); } for ( lineNumber = 0; ( line = b.readLine() ) != null; ) { lineNumber++; if ( line.length() == 0 ) { continue; } else if ( line.startsWith("#") ) { continue; } else { parseTypeProperties ( line, sm, im ); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void readBidiTestData(String bidiFileName) throws Exception { BufferedReader b = new BufferedReader(new InputStreamReader(new URL(bidiFileName).openStream())); String line; int n; List tdl = new ArrayList(); List ldl = new ArrayList(); if ( verbose ) { System.out.print("Reading bidi test data..."); } for ( lineNumber = 0; ( line = b.readLine() ) != null; ) { lineNumber++; if ( line.length() == 0 ) { continue; } else if ( line.startsWith("#") ) { continue; } else if ( line.startsWith(PFX_TYPE) && ! ignoreDeprecatedTypeData ) { List lines = new ArrayList(); if ( ( n = readType ( line, b, lines ) ) < 0 ) { break; } else { lineNumber += n; tdl.add ( parseType ( lines ) ); } } else if ( line.startsWith(PFX_LEVELS) ) { List lines = new ArrayList(); if ( ( n = readLevels ( line, b, lines ) ) < 0 ) { break; } else { lineNumber += n; ldl.add ( parseLevels ( lines ) ); } } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static void convertBidiClassProperties(String bidiFileName, String outFileName) throws Exception { readBidiClassProperties(bidiFileName); // generate class PrintWriter out = new PrintWriter(new FileWriter(outFileName)); License.writeJavaLicenseId(out); out.println(); out.println("package org.apache.fop.complexscripts.bidi;"); out.println(); out.println("import java.util.Arrays;"); out.println("import org.apache.fop.complexscripts.bidi.BidiConstants;"); out.println(); out.println("// CSOFF: WhitespaceAfterCheck"); out.println("// CSOFF: LineLengthCheck"); out.println(); out.println("/*"); out.println(" * !!! THIS IS A GENERATED FILE !!!"); out.println(" * If updates to the source are needed, then:"); out.println(" * - apply the necessary modifications to"); out.println(" * 'src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java'"); out.println(" * - run 'ant codegen-unicode', which will generate a new BidiClass.java"); out.println(" * in 'src/java/org/apache/fop/complexscripts/bidi'"); out.println(" * - commit BOTH changed files"); out.println(" */"); out.println(); out.println("/** Bidirectional class utilities. */"); out.println("public final class BidiClass {"); out.println(); out.println("private BidiClass() {"); out.println("}"); out.println(); dumpData(out); out.println ("/**"); out.println (" * Lookup bidi class for character expressed as unicode scalar value."); out.println (" * @param ch a unicode scalar value"); out.println (" * @return bidi class"); out.println (" */"); out.println("public static int getBidiClass ( int ch ) {"); out.println(" if ( ch <= 0x00FF ) {"); out.println(" return bcL1 [ ch - 0x0000 ];"); out.println(" } else if ( ( ch >= 0x0590 ) && ( ch <= 0x06FF ) ) {"); out.println(" return bcR1 [ ch - 0x0590 ];"); out.println(" } else {"); out.println(" return getBidiClass ( ch, bcS1, bcE1, bcC1 );"); out.println(" }"); out.println("}"); out.println(); out.println("private static int getBidiClass ( int ch, int[] sa, int[] ea, byte[] ca ) {"); out.println(" int k = Arrays.binarySearch ( sa, ch );"); out.println(" if ( k >= 0 ) {"); out.println(" return ca [ k ];"); out.println(" } else {"); out.println(" k = - ( k + 1 );"); out.println(" if ( k == 0 ) {"); out.println(" return BidiConstants.L;"); out.println(" } else if ( ch <= ea [ k - 1 ] ) {"); out.println(" return ca [ k - 1 ];"); out.println(" } else {"); out.println(" return BidiConstants.L;"); out.println(" }"); out.println(" }"); out.println("}"); out.println(); out.println("}"); out.flush(); out.close(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static void readBidiClassProperties(String bidiFileName) throws Exception { // read property names BufferedReader b = new BufferedReader(new InputStreamReader(new URL(bidiFileName).openStream())); String line; int lineNumber = 0; TreeSet intervals = new TreeSet(); while ( ( line = b.readLine() ) != null ) { lineNumber++; if ( line.startsWith("#") ) { continue; } else if ( line.length() == 0 ) { continue; } else { if ( line.indexOf ( "#" ) != -1 ) { line = ( line.split ( "#" ) ) [ 0 ]; } String[] fa = line.split ( ";" ); if ( fa.length == 2 ) { int[] interval = parseInterval ( fa[0].trim() ); byte bidiClass = (byte) parseBidiClass ( fa[1].trim() ); if ( interval[1] == interval[0] ) { // singleton int c = interval[0]; if ( c <= 0x00FF ) { if ( bcL1 [ c - 0x0000 ] == 0 ) { bcL1 [ c - 0x0000 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + c ); } } else if ( ( c >= 0x0590 ) && ( c <= 0x06FF ) ) { if ( bcR1 [ c - 0x0590 ] == 0 ) { bcR1 [ c - 0x0590 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + c ); } } else { addInterval ( intervals, c, c, bidiClass ); } } else { // non-singleton int s = interval[0]; int e = interval[1]; // inclusive if ( s <= 0x00FF ) { for ( int i = s; i <= e; i++ ) { if ( i <= 0x00FF ) { if ( bcL1 [ i - 0x0000 ] == 0 ) { bcL1 [ i - 0x0000 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + i ); } } else { addInterval ( intervals, i, e, bidiClass ); break; } } } else if ( ( s >= 0x0590 ) && ( s <= 0x06FF ) ) { for ( int i = s; i <= e; i++ ) { if ( i <= 0x06FF ) { if ( bcR1 [ i - 0x0590 ] == 0 ) { bcR1 [ i - 0x0590 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + i ); } } else { addInterval ( intervals, i, e, bidiClass ); break; } } } else { addInterval ( intervals, s, e, bidiClass ); } } } else { throw new Exception ( "bad syntax, line(" + lineNumber + "): " + line ); } } } // compile interval search data int ivIndex = 0; int niv = intervals.size(); bcS1 = new int [ niv ]; bcE1 = new int [ niv ]; bcC1 = new byte [ niv ]; for ( Iterator it = intervals.iterator(); it.hasNext(); ivIndex++ ) { Interval iv = (Interval) it.next(); bcS1[ivIndex] = iv.start; bcE1[ivIndex] = iv.end; bcC1[ivIndex] = (byte) iv.bidiClass; } // test data test(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static int[] parseInterval ( String interval ) throws Exception { int s; int e; String[] fa = interval.split("\\.\\."); if ( fa.length == 1 ) { s = Integer.parseInt ( fa[0], 16 ); e = s; } else if ( fa.length == 2 ) { s = Integer.parseInt ( fa[0], 16 ); e = Integer.parseInt ( fa[1], 16 ); } else { throw new Exception ( "bad interval syntax: " + interval ); } if ( e < s ) { throw new Exception ( "bad interval, start must be less than or equal to end: " + interval ); } return new int[] {s, e}; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static void test() throws Exception { for ( int i = 0, n = testData.length / 2; i < n; i++ ) { int ch = testData [ i * 2 + 0 ]; int tc = testData [ i * 2 + 1 ]; int bc = getBidiClass ( ch ); if ( bc != tc ) { throw new Exception ( "test mapping failed for character (0x" + Integer.toHexString(ch) + "): expected " + tc + ", got " + bc ); } } }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
private static void convertLineBreakProperties( // CSOK: MethodLength String lineBreakFileName, String propertyValueFileName, String breakPairFileName, String outFileName) throws Exception { readLineBreakProperties(lineBreakFileName, propertyValueFileName); // read break pair table int lineBreakPropertyValueCount = lineBreakPropertyValues.size(); int tableSize = lineBreakPropertyValueCount - NOT_IN_PAIR_TABLE.length; Map notInPairTableMap = new HashMap(NOT_IN_PAIR_TABLE.length); for (int i = 0; i < NOT_IN_PAIR_TABLE.length; i++) { Object v = lineBreakPropertyValues.get(NOT_IN_PAIR_TABLE[i]); if (v == null) { throw new Exception("'not in pair table' property not found: " + NOT_IN_PAIR_TABLE[i]); } notInPairTableMap.put(NOT_IN_PAIR_TABLE[i], v); } byte[][] pairTable = new byte[tableSize][]; byte[] columnHeader = new byte[tableSize]; byte[] rowHeader = new byte[tableSize]; byte[] columnMap = new byte[lineBreakPropertyValueCount + 1]; Arrays.fill(columnMap, (byte)255); byte[] rowMap = new byte[lineBreakPropertyValueCount + 1]; Arrays.fill(rowMap, (byte)255); BufferedReader b = new BufferedReader(new FileReader(breakPairFileName)); String line = b.readLine(); int lineNumber = 1; String[] lineTokens; String name; // read header if (line != null) { lineTokens = line.split("\\s+"); byte columnNumber = 0; for (int i = 0; i < lineTokens.length; ++i) { name = lineTokens[i]; if (name.length() > 0) { if (columnNumber >= columnHeader.length) { throw new Exception(breakPairFileName + ':' + lineNumber + ": unexpected column header " + name); } if (notInPairTableMap.get(name) != null) { throw new Exception(breakPairFileName + ':' + lineNumber + ": invalid column header " + name); } Byte v = (Byte)lineBreakPropertyValues.get(name); if (v != null) { byte vv = v.byteValue(); columnHeader[columnNumber] = vv; columnMap[vv] = columnNumber; } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": unknown column header " + name); } columnNumber++; } } if (columnNumber < columnHeader.length) { StringBuffer missing = new StringBuffer(); for (int j = 0; j < lineBreakPropertyShortNames.size(); j++) { boolean found = false; for (int k = 0; k < columnNumber; k++) { if (columnHeader[k] == j + 1) { found = true; break; } } if (!found) { if (missing.length() > 0) { missing.append(", "); } missing.append((String)lineBreakPropertyShortNames.get(j)); } } throw new Exception( breakPairFileName + ':' + lineNumber + ": missing column for properties: " + missing.toString()); } } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": can't read table header"); } line = b.readLine().trim(); lineNumber++; byte rowNumber = 0; while (line != null && line.length() > 0) { if (rowNumber >= rowHeader.length) { throw new Exception(breakPairFileName + ':' + lineNumber + ": unexpected row " + line); } pairTable[rowNumber] = new byte[tableSize]; lineTokens = line.split("\\s+"); if (lineTokens.length > 0) { name = lineTokens[0]; if (notInPairTableMap.get(name) != null) { throw new Exception(breakPairFileName + ':' + lineNumber + ": invalid row header " + name); } Byte v = (Byte)lineBreakPropertyValues.get(name); if (v != null) { byte vv = v.byteValue(); rowHeader[rowNumber] = vv; rowMap[vv] = rowNumber; } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": unknown row header " + name); } } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": can't read row header"); } int columnNumber = 0; String token; for (int i = 1; i < lineTokens.length; ++i) { token = lineTokens[i]; if (token.length() == 1) { byte tokenBreakClass = (byte)BREAK_CLASS_TOKENS.indexOf(token.charAt(0)); if (tokenBreakClass >= 0) { pairTable[rowNumber][columnNumber] = tokenBreakClass; } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": unexpected token: " + token); } } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": token too long: " + token); } columnNumber++; } line = b.readLine().trim(); lineNumber++; rowNumber++; } if (rowNumber < rowHeader.length) { StringBuffer missing = new StringBuffer(); for (int j = 0; j < lineBreakPropertyShortNames.size(); j++) { boolean found = false; for (int k = 0; k < rowNumber; k++) { if (rowHeader[k] == j + 1) { found = true; break; } } if (!found) { if (missing.length() > 0) { missing.append(", "); } missing.append((String)lineBreakPropertyShortNames.get(j)); } } throw new Exception( breakPairFileName + ':' + lineNumber + ": missing row for properties: " + missing.toString()); } // generate class int rowsize = 512; int blocksize = lineBreakProperties.length / rowsize; byte[][] row = new byte[rowsize][]; int idx = 0; StringBuffer doStaticLinkCode = new StringBuffer(); PrintWriter out = new PrintWriter(new FileWriter(outFileName)); License.writeJavaLicenseId(out); out.println(); out.println("package org.apache.fop.text.linebreak;"); out.println(); out.println("/*"); out.println(" * !!! THIS IS A GENERATED FILE !!!"); out.println(" * If updates to the source are needed, then:"); out.println(" * - apply the necessary modifications to"); out.println(" * 'src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java'"); out.println(" * - run 'ant codegen-unicode', which will generate a new LineBreakUtils.java"); out.println(" * in 'src/java/org/apache/fop/text/linebreak'"); out.println(" * - commit BOTH changed files"); out.println(" */"); out.println(); out.println("// CSOFF: WhitespaceAfterCheck"); out.println("// CSOFF: LineLengthCheck"); out.println(); out.println("/** Line breaking utilities. */"); out.println("public final class LineBreakUtils {"); out.println(); out.println(" private LineBreakUtils() {"); out.println(" }"); out.println(); out.println(" /** Break class constant */"); out.println(" public static final byte DIRECT_BREAK = " + DIRECT_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte INDIRECT_BREAK = " + INDIRECT_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte COMBINING_INDIRECT_BREAK = " + COMBINING_INDIRECT_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte COMBINING_PROHIBITED_BREAK = " + COMBINING_PROHIBITED_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte PROHIBITED_BREAK = " + PROHIBITED_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte EXPLICIT_BREAK = " + EXPLICIT_BREAK + ';'); out.println(); out.println(" private static final byte[][] PAIR_TABLE = {"); boolean printComma = false; for (int i = 1; i <= lineBreakPropertyValueCount; i++) { if (printComma) { out.println(","); } else { printComma = true; } out.print(" {"); boolean localPrintComma = false; for (int j = 1; j <= lineBreakPropertyValueCount; j++) { if (localPrintComma) { out.print(", "); } else { localPrintComma = true; } if (columnMap[j] != -1 && rowMap[i] != -1) { out.print(pairTable[rowMap[i]][columnMap[j]]); } else { out.print('0'); } } out.print('}'); } out.println("};"); out.println(); out.println(" private static byte[][] lineBreakProperties = new byte[" + rowsize + "][];"); out.println(); out.println(" private static void init0() {"); int rowsPrinted = 0; int initSections = 0; for (int i = 0; i < rowsize; i++) { boolean found = false; for (int j = 0; j < i; j++) { if (row[j] != null) { boolean matched = true; for (int k = 0; k < blocksize; k++) { if (row[j][k] != lineBreakProperties[idx + k]) { matched = false; break; } } if (matched) { found = true; doStaticLinkCode.append(" lineBreakProperties["); doStaticLinkCode.append(i); doStaticLinkCode.append("] = lineBreakProperties["); doStaticLinkCode.append(j); doStaticLinkCode.append("];\n"); break; } } } if (!found) { if (rowsPrinted >= 64) { out.println(" }"); out.println(); initSections++; out.println(" private static void init" + initSections + "() {"); rowsPrinted = 0; } row[i] = new byte[blocksize]; boolean printLocalComma = false; out.print(" lineBreakProperties[" + i + "] = new byte[] { "); for (int k = 0; k < blocksize; k++) { row[i][k] = lineBreakProperties[idx + k]; if (printLocalComma) { out.print(", "); } else { printLocalComma = true; } out.print(row[i][k]); } out.println("};"); rowsPrinted++; } idx += blocksize; } out.println(" }"); out.println(); out.println(" static {"); for (int i = 0; i <= initSections; i++) { out.println(" init" + i + "();"); } out.print(doStaticLinkCode); out.println(" }"); out.println(); for (int i = 0; i < lineBreakPropertyShortNames.size(); i++) { String shortName = (String)lineBreakPropertyShortNames.get(i); out.println(" /** Linebreak property constant */"); out.print(" public static final byte LINE_BREAK_PROPERTY_"); out.print(shortName); out.print(" = "); out.print(i + 1); out.println(';'); } out.println(); final String shortNamePrefix = " private static String[] lineBreakPropertyShortNames = {"; out.print(shortNamePrefix); int lineLength = shortNamePrefix.length(); printComma = false; for (int i = 0; i < lineBreakPropertyShortNames.size(); i++) { name = (String)lineBreakPropertyShortNames.get(i); if (printComma) { if (lineLength <= MAX_LINE_LENGTH - 2) { out.print(", "); } else { out.print(","); } // count the space anyway to force a linebreak if the comma causes lineLength == MAX_LINE_LENGTH lineLength += 2; } else { printComma = true; } if (lineLength > MAX_LINE_LENGTH) { out.println(); out.print(" "); lineLength = 8; } out.print('"'); out.print(name); out.print('"'); lineLength += (2 + name.length()); } out.println("};"); out.println(); final String longNamePrefix = " private static String[] lineBreakPropertyLongNames = {"; out.print(longNamePrefix); lineLength = longNamePrefix.length(); printComma = false; for (int i = 0; i < lineBreakPropertyLongNames.size(); i++) { name = (String)lineBreakPropertyLongNames.get(i); if (printComma) { out.print(','); lineLength++; } else { printComma = true; } if (lineLength > MAX_LINE_LENGTH) { out.println(); out.print(" "); lineLength = 8; } out.print('"'); out.print(name); out.print('"'); lineLength += (2 + name.length()); } out.println("};"); out.println(); out.println(" /**"); out.println(" * Return the short name for the linebreak property corresponding"); out.println(" * to the given symbolic constant."); out.println(" *"); out.println(" * @param i the numeric value of the linebreak property"); out.println(" * @return the short name of the linebreak property"); out.println(" */"); out.println(" public static String getLineBreakPropertyShortName(byte i) {"); out.println(" if (i > 0 && i <= lineBreakPropertyShortNames.length) {"); out.println(" return lineBreakPropertyShortNames[i - 1];"); out.println(" } else {"); out.println(" return null;"); out.println(" }"); out.println(" }"); out.println(); out.println(" /**"); out.println(" * Return the long name for the linebreak property corresponding"); out.println(" * to the given symbolic constant."); out.println(" *"); out.println(" * @param i the numeric value of the linebreak property"); out.println(" * @return the long name of the linebreak property"); out.println(" */"); out.println(" public static String getLineBreakPropertyLongName(byte i) {"); out.println(" if (i > 0 && i <= lineBreakPropertyLongNames.length) {"); out.println(" return lineBreakPropertyLongNames[i - 1];"); out.println(" } else {"); out.println(" return null;"); out.println(" }"); out.println(" }"); out.println(); out.println(" /**"); out.println(" * Return the linebreak property constant for the given <code>char</code>"); out.println(" *"); out.println(" * @param c the <code>char</code> whose linebreak property to return"); out.println(" * @return the constant representing the linebreak property"); out.println(" */"); out.println(" public static byte getLineBreakProperty(char c) {"); out.println(" return lineBreakProperties[c / " + blocksize + "][c % " + blocksize + "];"); out.println(" }"); out.println(); out.println(" /**"); out.println(" * Return the break class constant for the given pair of linebreak"); out.println(" * property constants."); out.println(" *"); out.println(" * @param lineBreakPropertyBefore the linebreak property for the first character"); out.println(" * in a two-character sequence"); out.println(" * @param lineBreakPropertyAfter the linebreak property for the second character"); out.println(" * in a two-character sequence"); out.println(" * @return the constant representing the break class"); out.println(" */"); out.println( " public static byte getLineBreakPairProperty(int lineBreakPropertyBefore, int lineBreakPropertyAfter) {"); out.println(" return PAIR_TABLE[lineBreakPropertyBefore - 1][lineBreakPropertyAfter - 1];"); out.println(" }"); out.println(); out.println("}"); out.flush(); out.close(); }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
private static void readLineBreakProperties(String lineBreakFileName, String propertyValueFileName) throws Exception { // read property names BufferedReader b = new BufferedReader(new InputStreamReader(new URL(propertyValueFileName).openStream())); String line = b.readLine(); int lineNumber = 1; byte propertyIndex = 1; byte indexForUnknown = 0; while (line != null) { if (line.startsWith("lb")) { String shortName; String longName = null; int semi = line.indexOf(';'); if (semi < 0) { throw new Exception( propertyValueFileName + ':' + lineNumber + ": missing property short name in " + line); } line = line.substring(semi + 1); semi = line.indexOf(';'); if (semi > 0) { shortName = line.substring(0, semi).trim(); longName = line.substring(semi + 1).trim(); semi = longName.indexOf(';'); if (semi > 0) { longName = longName.substring(0, semi).trim(); } } else { shortName = line.trim(); } if (shortName.equals("XX")) { indexForUnknown = propertyIndex; } lineBreakPropertyValues.put(shortName, new Byte((byte)propertyIndex)); lineBreakPropertyShortNames.add(shortName); lineBreakPropertyLongNames.add(longName); propertyIndex++; if (propertyIndex <= 0) { throw new Exception(propertyValueFileName + ':' + lineNumber + ": property rolled over in " + line); } } line = b.readLine(); lineNumber++; } if (indexForUnknown == 0) { throw new Exception("index for XX (unknown) line break property value not found"); } // read property values Arrays.fill(lineBreakProperties, (byte)0); b = new BufferedReader(new InputStreamReader(new URL(lineBreakFileName).openStream())); line = b.readLine(); lineNumber = 1; while (line != null) { int idx = line.indexOf('#'); if (idx >= 0) { line = line.substring(0, idx); } line = line.trim(); if (line.length() > 0) { idx = line.indexOf(';'); if (idx <= 0) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": No field delimiter in " + line); } Byte v = (Byte)lineBreakPropertyValues.get(line.substring(idx + 1).trim()); if (v == null) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Unknown property value in " + line); } String codepoint = line.substring(0, idx); int low; int high; idx = codepoint.indexOf(".."); try { if (idx >= 0) { low = Integer.parseInt(codepoint.substring(0, idx), 16); high = Integer.parseInt(codepoint.substring(idx + 2), 16); } else { low = Integer.parseInt(codepoint, 16); high = low; } } catch (NumberFormatException e) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Invalid codepoint number in " + line); } if (high > 0xFFFF) { // ignore non-baseplane characters for now } else { if (low < 0 || high < 0) { throw new Exception( lineBreakFileName + ':' + lineNumber + ": Negative codepoint(s) in " + line); } byte vv = v.byteValue(); for (int i = low; i <= high; i++) { if (lineBreakProperties[i] != 0) { throw new Exception( lineBreakFileName + ':' + lineNumber + ": Property already set for " + ((char)i) + " in " + line); } lineBreakProperties[i] = vv; } } } line = b.readLine(); lineNumber++; } }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
private static void optimizeBlocks(String lineBreakFileName, String propertyValueFileName) throws Exception { readLineBreakProperties(lineBreakFileName, propertyValueFileName); for (int i = 0; i < 16; i++) { int rowsize = 1 << i; int blocksize = lineBreakProperties.length / (rowsize); byte[][] row = new byte[rowsize][]; int idx = 0; int nrOfDistinctBlocks = 0; for (int j = 0; j < rowsize; j++) { byte[] block = new byte[blocksize]; for (int k = 0; k < blocksize; k++) { block[k] = lineBreakProperties[idx]; idx++; } boolean found = false; for (int k = 0; k < j; k++) { if (row[k] != null) { boolean matched = true; for (int l = 0; l < blocksize; l++) { if (row[k][l] != block[l]) { matched = false; break; } } if (matched) { found = true; break; } } } if (!found) { row[j] = block; nrOfDistinctBlocks++; } else { row[j] = null; } } int size = rowsize * 4 + nrOfDistinctBlocks * blocksize; System.out.println( "i=" + i + " blocksize=" + blocksize + " blocks=" + nrOfDistinctBlocks + " size=" + size); } }
(Domain) PDFConformanceException 24
              
// in src/java/org/apache/fop/pdf/PDFProfile.java
protected void validateProfileCombination() { if (pdfAMode != PDFAMode.DISABLED) { if (pdfAMode == PDFAMode.PDFA_1B) { if (pdfXMode != PDFXMode.DISABLED && pdfXMode != PDFXMode.PDFX_3_2003) { throw new PDFConformanceException( pdfAMode + " and " + pdfXMode + " are not compatible!"); } } } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyEncryptionAllowed() { final String err = "{0} doesn't allow encrypted PDFs"; if (isPDFAActive()) { throw new PDFConformanceException(format(err, getPDFAMode())); } if (isPDFXActive()) { throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyPSXObjectsAllowed() { final String err = "PostScript XObjects are prohibited when {0}" + " is active. Convert EPS graphics to another format."; if (isPDFAActive()) { throw new PDFConformanceException(format(err, getPDFAMode())); } if (isPDFXActive()) { throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyTransparencyAllowed(String context) { final String err = "{0} does not allow the use of transparency. ({1})"; if (isPDFAActive()) { throw new PDFConformanceException(MessageFormat.format(err, new Object[] {getPDFAMode(), context})); } if (isPDFXActive()) { throw new PDFConformanceException(MessageFormat.format(err, new Object[] {getPDFXMode(), context})); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyPDFVersion() { final String err = "PDF version must be 1.4 for {0}"; if (getPDFAMode().isPDFA1LevelB() && !Version.V1_4.equals(getDocument().getPDFVersion())) { throw new PDFConformanceException(format(err, getPDFAMode())); } if (getPDFXMode() == PDFXMode.PDFX_3_2003 && !Version.V1_4.equals(getDocument().getPDFVersion())) { throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyTaggedPDF() { if (getPDFAMode().isPDFA1LevelA()) { final String err = "{0} requires the {1} dictionary entry to be set"; PDFDictionary markInfo = getDocument().getRoot().getMarkInfo(); if (markInfo == null) { throw new PDFConformanceException(format( "{0} requires the MarkInfo dictionary to be present", getPDFAMode())); } if (!Boolean.TRUE.equals(markInfo.get("Marked"))) { throw new PDFConformanceException(format(err, new Object[] {getPDFAMode(), "Marked"})); } if (getDocument().getRoot().getStructTreeRoot() == null) { throw new PDFConformanceException(format(err, new Object[] {getPDFAMode(), "StructTreeRoot"})); } if (getDocument().getRoot().getLanguage() == null) { throw new PDFConformanceException(format(err, new Object[] {getPDFAMode(), "Lang"})); } } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyTitleAbsent() { if (isPDFXActive()) { final String err = "{0} requires the title to be set."; throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyAnnotAllowed() { if (!isAnnotationAllowed()) { final String err = "{0} does not allow annotations inside the printable area."; //Note: this rule is simplified. Refer to the standard for details. throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyActionAllowed() { if (isPDFXActive()) { final String err = "{0} does not allow Actions."; throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyEmbeddedFilesAllowed() { final String err = "{0} does not allow embedded files."; if (isPDFAActive()) { throw new PDFConformanceException(format(err, getPDFAMode())); } if (isPDFXActive()) { //Implicit since file specs are forbidden throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFFont.java
protected void validate() { if (getDocumentSafely().getProfile().isFontEmbeddingRequired()) { if (this.getClass() == PDFFont.class) { throw new PDFConformanceException("For " + getDocumentSafely().getProfile() + ", all fonts, even the base 14" + " fonts, have to be embedded! Offending font: " + getBaseFont()); } } }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
protected void populateStreamDict(Object lengthEntry) { final String filterEntry = getFilterList().buildFilterDictEntries(); if (getDocumentSafely().getProfile().getPDFAMode().isPDFA1LevelB() && filterEntry != null && filterEntry.length() > 0) { throw new PDFConformanceException( "The Filter key is prohibited when PDF/A-1 is active"); } put("Type", new PDFName("Metadata")); put("Subtype", new PDFName("XML")); super.populateStreamDict(lengthEntry); }
// in src/java/org/apache/fop/pdf/PDFFontNonBase14.java
protected void validate() { if (getDocumentSafely().getProfile().isFontEmbeddingRequired()) { if (this.getDescriptor().getFontFile() == null) { throw new PDFConformanceException("For " + getDocumentSafely().getProfile() + ", all fonts have to be embedded! Offending font: " + getBaseFont()); } } }
// in src/java/org/apache/fop/svg/PDFGraphics2D.java
protected void applyColor(Color col, boolean fill) { preparePainting(); //TODO Handle this in PDFColorHandler by automatically converting the color. //This won't work properly anyway after the redesign of ColorExt if (col.getColorSpace().getType() == ColorSpace.TYPE_CMYK) { if (pdfDoc.getProfile().getPDFAMode().isPDFA1LevelB()) { //See PDF/A-1, ISO 19005:1:2005(E), 6.2.3.3 //FOP is currently restricted to DeviceRGB if PDF/A-1 is active. throw new PDFConformanceException( "PDF/A-1 does not allow mixing DeviceRGB and DeviceCMYK."); } } boolean doWrite = false; if (fill) { if (paintingState.setBackColor(col)) { doWrite = true; } } else { if (paintingState.setColor(col)) { doWrite = true; } } if (doWrite) { StringBuffer sb = new StringBuffer(); colorHandler.establishColor(sb, col, fill); currentStream.write(sb.toString()); } }
// in src/java/org/apache/fop/render/pdf/AbstractImageAdapter.java
public void setup(PDFDocument doc) { ICC_Profile prof = getEffectiveICCProfile(); PDFDeviceColorSpace pdfCS = toPDFColorSpace(getImageColorSpace()); if (prof != null) { pdfICCStream = setupColorProfile(doc, prof, pdfCS); } if (doc.getProfile().getPDFAMode().isPDFA1LevelB()) { if (pdfCS != null && pdfCS.getColorSpace() != PDFDeviceColorSpace.DEVICE_RGB && pdfCS.getColorSpace() != PDFDeviceColorSpace.DEVICE_GRAY && prof == null) { //See PDF/A-1, ISO 19005:1:2005(E), 6.2.3.3 //FOP is currently restricted to DeviceRGB if PDF/A-1 is active. throw new PDFConformanceException( "PDF/A-1 does not allow mixing DeviceRGB and DeviceCMYK: " + image.getInfo()); } } }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addPDFXOutputIntent() throws IOException { addDefaultOutputProfile(); String desc = ColorProfileUtil.getICCProfileDescription(this.outputProfile.getICCProfile()); int deviceClass = this.outputProfile.getICCProfile().getProfileClass(); if (deviceClass != ICC_Profile.CLASS_OUTPUT) { throw new PDFConformanceException(pdfDoc.getProfile().getPDFXMode() + " requires that" + " the DestOutputProfile be an Output Device Profile. " + desc + " does not match that requirement."); } PDFOutputIntent outputIntent = pdfDoc.getFactory().makeOutputIntent(); outputIntent.setSubtype(PDFOutputIntent.GTS_PDFX); outputIntent.setDestOutputProfile(this.outputProfile); outputIntent.setOutputConditionIdentifier(desc); outputIntent.setInfo(outputIntent.getOutputConditionIdentifier()); pdfDoc.getRoot().addOutputIntent(outputIntent); }
0 0
(Lib) IndexOutOfBoundsException 20
              
// in src/java/org/apache/fop/fo/FOText.java
public int bidiLevelAt ( int position ) throws IndexOutOfBoundsException { if ( ( position < 0 ) || ( position >= length() ) ) { throw new IndexOutOfBoundsException(); } else if ( bidiLevels != null ) { return bidiLevels [ position ]; } else { return -1; } }
// in src/java/org/apache/fop/fonts/SingleByteFont.java
public SimpleSingleByteEncoding getAdditionalEncoding(int index) throws IndexOutOfBoundsException { if (hasAdditionalEncodings()) { return this.additionalEncodings.get(index); } else { throw new IndexOutOfBoundsException("No additional encodings available"); } }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException { try { if (pageIndex >= getNumberOfPages()) { return null; } PageFormat pageFormat = new PageFormat(); Paper paper = new Paper(); Rectangle2D dim = getPageViewport(pageIndex).getViewArea(); double width = dim.getWidth(); double height = dim.getHeight(); // if the width is greater than the height assume landscape mode // and swap the width and height values in the paper format if (width > height) { paper.setImageableArea(0, 0, height / 1000d, width / 1000d); paper.setSize(height / 1000d, width / 1000d); pageFormat.setOrientation(PageFormat.LANDSCAPE); } else { paper.setImageableArea(0, 0, width / 1000d, height / 1000d); paper.setSize(width / 1000d, height / 1000d); pageFormat.setOrientation(PageFormat.PORTRAIT); } pageFormat.setPaper(paper); return pageFormat; } catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); } }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException { try { if (pageIndex >= getNumberOfPages()) { return null; } PageFormat pageFormat = new PageFormat(); Paper paper = new Paper(); Rectangle2D dim = getPageViewport(pageIndex).getViewArea(); double width = dim.getWidth(); double height = dim.getHeight(); // if the width is greater than the height assume lanscape mode // and swap the width and height values in the paper format if (width > height) { paper.setImageableArea(0, 0, height / 1000d, width / 1000d); paper.setSize(height / 1000d, width / 1000d); pageFormat.setOrientation(PageFormat.LANDSCAPE); } else { paper.setImageableArea(0, 0, width / 1000d, height / 1000d); paper.setSize(width / 1000d, height / 1000d); pageFormat.setOrientation(PageFormat.PORTRAIT); } pageFormat.setPaper(paper); return pageFormat; } catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); } }
// in src/java/org/apache/fop/area/inline/WordArea.java
public int bidiLevelAt ( int position ) { if ( position > word.length() ) { throw new IndexOutOfBoundsException(); } else if ( levels != null ) { return levels [ position ]; } else { return -1; } }
// in src/java/org/apache/fop/area/inline/WordArea.java
public int[] glyphPositionAdjustmentsAt ( int position ) { if ( position > word.length() ) { throw new IndexOutOfBoundsException(); } else if ( gposAdjustments != null ) { return gposAdjustments [ position ]; } else { return null; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningState.java
public boolean adjust ( GlyphPositioningTable.Value v, int offset ) { assert v != null; if ( ( index + offset ) < indexLast ) { return v.adjust ( adjustments [ index + offset ], fontSize ); } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningState.java
public int[] getAdjustment ( int offset ) throws IndexOutOfBoundsException { if ( ( index + offset ) < indexLast ) { return adjustments [ index + offset ]; } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public void setPosition ( int index ) throws IndexOutOfBoundsException { if ( ( index >= 0 ) && ( index <= indexLast ) ) { this.index = index; } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int consume ( int count ) throws IndexOutOfBoundsException { if ( ( consumed + count ) <= indexLast ) { consumed += count; return consumed; } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int getGlyph ( int offset ) throws IndexOutOfBoundsException { int i = index + offset; if ( ( i >= 0 ) && ( i < indexLast ) ) { return igs.getGlyph ( i ); } else { throw new IndexOutOfBoundsException ( "attempting index at " + i ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public void setGlyph ( int offset, int glyph ) throws IndexOutOfBoundsException { int i = index + offset; if ( ( i >= 0 ) && ( i < indexLast ) ) { igs.setGlyph ( i, glyph ); } else { throw new IndexOutOfBoundsException ( "attempting index at " + i ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation getAssociation ( int offset ) throws IndexOutOfBoundsException { int i = index + offset; if ( ( i >= 0 ) && ( i < indexLast ) ) { return igs.getAssociation ( i ); } else { throw new IndexOutOfBoundsException ( "attempting index at " + i ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphs ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { if ( count < 0 ) { count = getGlyphsAvailable ( offset, reverseOrder, ignoreTester ) [ 0 ]; } int start = index + offset; if ( start < 0 ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else if ( ! reverseOrder && ( ( start + count ) > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start + count ) ); } else if ( reverseOrder && ( ( start + 1 ) < count ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start - count ) ); } if ( glyphs == null ) { glyphs = new int [ count ]; } else if ( glyphs.length != count ) { throw new IllegalArgumentException ( "glyphs array is non-null, but its length (" + glyphs.length + "), is not equal to count (" + count + ")" ); } if ( ! reverseOrder ) { return getGlyphsForward ( start, count, ignoreTester, glyphs, counts ); } else { return getGlyphsReverse ( start, count, ignoreTester, glyphs, counts ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation[] getAssociations ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, GlyphSequence.CharAssociation[] associations, int[] counts ) throws IndexOutOfBoundsException { if ( count < 0 ) { count = getGlyphsAvailable ( offset, reverseOrder, ignoreTester ) [ 0 ]; } int start = index + offset; if ( start < 0 ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else if ( ! reverseOrder && ( ( start + count ) > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start + count ) ); } else if ( reverseOrder && ( ( start + 1 ) < count ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start - count ) ); } if ( associations == null ) { associations = new GlyphSequence.CharAssociation [ count ]; } else if ( associations.length != count ) { throw new IllegalArgumentException ( "associations array is non-null, but its length (" + associations.length + "), is not equal to count (" + count + ")" ); } if ( ! reverseOrder ) { return getAssociationsForward ( start, count, ignoreTester, associations, counts ); } else { return getAssociationsReverse ( start, count, ignoreTester, associations, counts ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int erase ( int offset, int[] glyphs ) throws IndexOutOfBoundsException { int start = index + offset; if ( ( start < 0 ) || ( start > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else { int erased = 0; for ( int i = start - index, n = indexLast - start; i < n; i++ ) { int gi = getGlyph ( i ); if ( gi == glyphs [ erased ] ) { setGlyph ( i, 65535 ); erased++; } } return erased; } }
2
              
// in src/java/org/apache/fop/render/print/PageableRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
38
              
// in src/java/org/apache/fop/fo/FOText.java
public int bidiLevelAt ( int position ) throws IndexOutOfBoundsException { if ( ( position < 0 ) || ( position >= length() ) ) { throw new IndexOutOfBoundsException(); } else if ( bidiLevels != null ) { return bidiLevels [ position ]; } else { return -1; } }
// in src/java/org/apache/fop/fonts/SingleByteFont.java
public SimpleSingleByteEncoding getAdditionalEncoding(int index) throws IndexOutOfBoundsException { if (hasAdditionalEncodings()) { return this.additionalEncodings.get(index); } else { throw new IndexOutOfBoundsException("No additional encodings available"); } }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException { try { if (pageIndex >= getNumberOfPages()) { return null; } PageFormat pageFormat = new PageFormat(); Paper paper = new Paper(); Rectangle2D dim = getPageViewport(pageIndex).getViewArea(); double width = dim.getWidth(); double height = dim.getHeight(); // if the width is greater than the height assume landscape mode // and swap the width and height values in the paper format if (width > height) { paper.setImageableArea(0, 0, height / 1000d, width / 1000d); paper.setSize(height / 1000d, width / 1000d); pageFormat.setOrientation(PageFormat.LANDSCAPE); } else { paper.setImageableArea(0, 0, width / 1000d, height / 1000d); paper.setSize(width / 1000d, height / 1000d); pageFormat.setOrientation(PageFormat.PORTRAIT); } pageFormat.setPaper(paper); return pageFormat; } catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); } }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
public Printable getPrintable(int pageIndex) throws IndexOutOfBoundsException { return this; }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException { try { if (pageIndex >= getNumberOfPages()) { return null; } PageFormat pageFormat = new PageFormat(); Paper paper = new Paper(); Rectangle2D dim = getPageViewport(pageIndex).getViewArea(); double width = dim.getWidth(); double height = dim.getHeight(); // if the width is greater than the height assume lanscape mode // and swap the width and height values in the paper format if (width > height) { paper.setImageableArea(0, 0, height / 1000d, width / 1000d); paper.setSize(height / 1000d, width / 1000d); pageFormat.setOrientation(PageFormat.LANDSCAPE); } else { paper.setImageableArea(0, 0, width / 1000d, height / 1000d); paper.setSize(width / 1000d, height / 1000d); pageFormat.setOrientation(PageFormat.PORTRAIT); } pageFormat.setPaper(paper); return pageFormat; } catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); } }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public Printable getPrintable(int pageIndex) throws IndexOutOfBoundsException { return this; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningState.java
public int[] getAdjustment ( int offset ) throws IndexOutOfBoundsException { if ( ( index + offset ) < indexLast ) { return adjustments [ index + offset ]; } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public void setPosition ( int index ) throws IndexOutOfBoundsException { if ( ( index >= 0 ) && ( index <= indexLast ) ) { this.index = index; } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int consume ( int count ) throws IndexOutOfBoundsException { if ( ( consumed + count ) <= indexLast ) { consumed += count; return consumed; } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int getGlyph ( int offset ) throws IndexOutOfBoundsException { int i = index + offset; if ( ( i >= 0 ) && ( i < indexLast ) ) { return igs.getGlyph ( i ); } else { throw new IndexOutOfBoundsException ( "attempting index at " + i ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int getGlyph() throws IndexOutOfBoundsException { return getGlyph ( 0 ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public void setGlyph ( int offset, int glyph ) throws IndexOutOfBoundsException { int i = index + offset; if ( ( i >= 0 ) && ( i < indexLast ) ) { igs.setGlyph ( i, glyph ); } else { throw new IndexOutOfBoundsException ( "attempting index at " + i ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation getAssociation ( int offset ) throws IndexOutOfBoundsException { int i = index + offset; if ( ( i >= 0 ) && ( i < indexLast ) ) { return igs.getAssociation ( i ); } else { throw new IndexOutOfBoundsException ( "attempting index at " + i ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation getAssociation() throws IndexOutOfBoundsException { return getAssociation ( 0 ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphs ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { if ( count < 0 ) { count = getGlyphsAvailable ( offset, reverseOrder, ignoreTester ) [ 0 ]; } int start = index + offset; if ( start < 0 ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else if ( ! reverseOrder && ( ( start + count ) > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start + count ) ); } else if ( reverseOrder && ( ( start + 1 ) < count ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start - count ) ); } if ( glyphs == null ) { glyphs = new int [ count ]; } else if ( glyphs.length != count ) { throw new IllegalArgumentException ( "glyphs array is non-null, but its length (" + glyphs.length + "), is not equal to count (" + count + ")" ); } if ( ! reverseOrder ) { return getGlyphsForward ( start, count, ignoreTester, glyphs, counts ); } else { return getGlyphsReverse ( start, count, ignoreTester, glyphs, counts ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
private int[] getGlyphsForward ( int start, int count, GlyphTester ignoreTester, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { int counted = 0; int ignored = 0; for ( int i = start, n = indexLast, k = 0; i < n; i++ ) { int gi = getGlyph ( i - index ); if ( gi == 65535 ) { ignored++; } else { if ( ( ignoreTester == null ) || ! ignoreTester.test ( gi, getLookupFlags() ) ) { if ( k < count ) { glyphs [ k++ ] = gi; counted++; } else { break; } } else { ignored++; } } } if ( ( counts != null ) && ( counts.length > 1 ) ) { counts[0] = counted; counts[1] = ignored; } return glyphs; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
private int[] getGlyphsReverse ( int start, int count, GlyphTester ignoreTester, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { int counted = 0; int ignored = 0; for ( int i = start, k = 0; i >= 0; i-- ) { int gi = getGlyph ( i - index ); if ( gi == 65535 ) { ignored++; } else { if ( ( ignoreTester == null ) || ! ignoreTester.test ( gi, getLookupFlags() ) ) { if ( k < count ) { glyphs [ k++ ] = gi; counted++; } else { break; } } else { ignored++; } } } if ( ( counts != null ) && ( counts.length > 1 ) ) { counts[0] = counted; counts[1] = ignored; } return glyphs; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphs ( int offset, int count, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { return getGlyphs ( offset, count, offset < 0, ignoreDefault, glyphs, counts ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphs() throws IndexOutOfBoundsException { return getGlyphs ( 0, indexLast - index, false, null, null, null ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getIgnoredGlyphs ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { return getGlyphs ( offset, count, reverseOrder, new NotGlyphTester ( ignoreTester ), glyphs, counts ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getIgnoredGlyphs ( int offset, int count ) throws IndexOutOfBoundsException { return getIgnoredGlyphs ( offset, count, offset < 0, ignoreDefault, null, null ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphsAvailable ( int offset, boolean reverseOrder, GlyphTester ignoreTester ) throws IndexOutOfBoundsException { int start = index + offset; if ( ( start < 0 ) || ( start > indexLast ) ) { return new int[] { 0, 0 }; } else if ( ! reverseOrder ) { return getGlyphsAvailableForward ( start, ignoreTester ); } else { return getGlyphsAvailableReverse ( start, ignoreTester ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
private int[] getGlyphsAvailableForward ( int start, GlyphTester ignoreTester ) throws IndexOutOfBoundsException { int counted = 0; int ignored = 0; if ( ignoreTester == null ) { counted = indexLast - start; } else { for ( int i = start, n = indexLast; i < n; i++ ) { int gi = getGlyph ( i - index ); if ( gi == 65535 ) { ignored++; } else { if ( ignoreTester.test ( gi, getLookupFlags() ) ) { ignored++; } else { counted++; } } } } return new int[] { counted, ignored }; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
private int[] getGlyphsAvailableReverse ( int start, GlyphTester ignoreTester ) throws IndexOutOfBoundsException { int counted = 0; int ignored = 0; if ( ignoreTester == null ) { counted = start + 1; } else { for ( int i = start; i >= 0; i-- ) { int gi = getGlyph ( i - index ); if ( gi == 65535 ) { ignored++; } else { if ( ignoreTester.test ( gi, getLookupFlags() ) ) { ignored++; } else { counted++; } } } } return new int[] { counted, ignored }; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphsAvailable ( int offset, boolean reverseOrder ) throws IndexOutOfBoundsException { return getGlyphsAvailable ( offset, reverseOrder, ignoreDefault ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphsAvailable ( int offset ) throws IndexOutOfBoundsException { return getGlyphsAvailable ( offset, offset < 0 ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation[] getAssociations ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, GlyphSequence.CharAssociation[] associations, int[] counts ) throws IndexOutOfBoundsException { if ( count < 0 ) { count = getGlyphsAvailable ( offset, reverseOrder, ignoreTester ) [ 0 ]; } int start = index + offset; if ( start < 0 ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else if ( ! reverseOrder && ( ( start + count ) > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start + count ) ); } else if ( reverseOrder && ( ( start + 1 ) < count ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start - count ) ); } if ( associations == null ) { associations = new GlyphSequence.CharAssociation [ count ]; } else if ( associations.length != count ) { throw new IllegalArgumentException ( "associations array is non-null, but its length (" + associations.length + "), is not equal to count (" + count + ")" ); } if ( ! reverseOrder ) { return getAssociationsForward ( start, count, ignoreTester, associations, counts ); } else { return getAssociationsReverse ( start, count, ignoreTester, associations, counts ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
private GlyphSequence.CharAssociation[] getAssociationsForward ( int start, int count, GlyphTester ignoreTester, GlyphSequence.CharAssociation[] associations, int[] counts ) throws IndexOutOfBoundsException { int counted = 0; int ignored = 0; for ( int i = start, n = indexLast, k = 0; i < n; i++ ) { int gi = getGlyph ( i - index ); if ( gi == 65535 ) { ignored++; } else { if ( ( ignoreTester == null ) || ! ignoreTester.test ( gi, getLookupFlags() ) ) { if ( k < count ) { associations [ k++ ] = getAssociation ( i - index ); counted++; } else { break; } } else { ignored++; } } } if ( ( counts != null ) && ( counts.length > 1 ) ) { counts[0] = counted; counts[1] = ignored; } return associations; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
private GlyphSequence.CharAssociation[] getAssociationsReverse ( int start, int count, GlyphTester ignoreTester, GlyphSequence.CharAssociation[] associations, int[] counts ) throws IndexOutOfBoundsException { int counted = 0; int ignored = 0; for ( int i = start, k = 0; i >= 0; i-- ) { int gi = getGlyph ( i - index ); if ( gi == 65535 ) { ignored++; } else { if ( ( ignoreTester == null ) || ! ignoreTester.test ( gi, getLookupFlags() ) ) { if ( k < count ) { associations [ k++ ] = getAssociation ( i - index ); counted++; } else { break; } } else { ignored++; } } } if ( ( counts != null ) && ( counts.length > 1 ) ) { counts[0] = counted; counts[1] = ignored; } return associations; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation[] getAssociations ( int offset, int count ) throws IndexOutOfBoundsException { return getAssociations ( offset, count, offset < 0, ignoreDefault, null, null ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation[] getIgnoredAssociations ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, GlyphSequence.CharAssociation[] associations, int[] counts ) throws IndexOutOfBoundsException { return getAssociations ( offset, count, reverseOrder, new NotGlyphTester ( ignoreTester ), associations, counts ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation[] getIgnoredAssociations ( int offset, int count ) throws IndexOutOfBoundsException { return getIgnoredAssociations ( offset, count, offset < 0, ignoreDefault, null, null ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public boolean replaceInput ( int offset, int count, GlyphSequence gs, int gsOffset, int gsCount ) throws IndexOutOfBoundsException { int nig = ( igs != null ) ? igs.getGlyphCount() : 0; int position = getPosition() + offset; if ( position < 0 ) { position = 0; } else if ( position > nig ) { position = nig; } if ( ( count < 0 ) || ( ( position + count ) > nig ) ) { count = nig - position; } int nrg = ( gs != null ) ? gs.getGlyphCount() : 0; if ( gsOffset < 0 ) { gsOffset = 0; } else if ( gsOffset > nrg ) { gsOffset = nrg; } if ( ( gsCount < 0 ) || ( ( gsOffset + gsCount ) > nrg ) ) { gsCount = nrg - gsOffset; } int ng = nig + gsCount - count; IntBuffer gb = IntBuffer.allocate ( ng ); List al = new ArrayList ( ng ); for ( int i = 0, n = position; i < n; i++ ) { gb.put ( igs.getGlyph ( i ) ); al.add ( igs.getAssociation ( i ) ); } for ( int i = gsOffset, n = gsOffset + gsCount; i < n; i++ ) { gb.put ( gs.getGlyph ( i ) ); al.add ( gs.getAssociation ( i ) ); } for ( int i = position + count, n = nig; i < n; i++ ) { gb.put ( igs.getGlyph ( i ) ); al.add ( igs.getAssociation ( i ) ); } gb.flip(); if ( igs.compareGlyphs ( gb ) != 0 ) { this.igs = new GlyphSequence ( igs.getCharacters(), gb, al ); this.indexLast = gb.limit(); return true; } else { return false; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public boolean replaceInput ( int offset, int count, GlyphSequence gs ) throws IndexOutOfBoundsException { return replaceInput ( offset, count, gs, 0, gs.getGlyphCount() ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int erase ( int offset, int[] glyphs ) throws IndexOutOfBoundsException { int start = index + offset; if ( ( start < 0 ) || ( start > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else { int erased = 0; for ( int i = start - index, n = indexLast - start; i < n; i++ ) { int gi = getGlyph ( i ); if ( gi == glyphs [ erased ] ) { setGlyph ( i, 65535 ); erased++; } } return erased; } }
// in src/java/org/apache/fop/complexscripts/util/GlyphSequence.java
public int getGlyph ( int index ) throws IndexOutOfBoundsException { return glyphs.get ( index ); }
// in src/java/org/apache/fop/complexscripts/util/GlyphSequence.java
public void setGlyph ( int index, int gi ) throws IndexOutOfBoundsException { if ( gi > 65535 ) { gi = 65535; } glyphs.put ( index, gi ); }
// in src/java/org/apache/fop/complexscripts/util/GlyphSequence.java
public CharAssociation getAssociation ( int index ) throws IndexOutOfBoundsException { return (CharAssociation) associations.get ( index ); }
(Lib) BuildException 15
              
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
protected void testNewBuild() { try { ClassLoader loader = new URLClassLoader( createUrls("build/fop.jar")); Map diff = runConverter(loader, "areatree", "reference/output/"); if (diff != null && !diff.isEmpty()) { System.out.println("===================================="); System.out.println("The following files differ:"); boolean broke = false; for (Iterator keys = diff.keySet().iterator(); keys.hasNext();) { Object fname = keys.next(); Boolean pass = (Boolean)diff.get(fname); System.out.println("file: " + fname + " - reference success: " + pass); if (pass.booleanValue()) { broke = true; } } if (broke) { throw new BuildException("Working tests have been changed."); } } } catch (MalformedURLException mue) { mue.printStackTrace(); } }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
protected void runReference() throws BuildException { // check not already done File f = new File(basedir + "/reference/output/"); // if(f.exists()) { // need to check that files have actually been created. // return; // } else { try { ClassLoader loader = new URLClassLoader(createUrls(referenceJar)); boolean failed = false; try { Class cla = Class.forName("org.apache.fop.apps.Fop", true, loader); Method get = cla.getMethod("getVersion", new Class[]{}); if (!get.invoke(null, new Object[]{}).equals(refVersion)) { throw new BuildException("Reference jar is not correct version it must be: " + refVersion); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
public void setMessagelevel(String messageLevel) { if (messageLevel.equalsIgnoreCase("info")) { messageType = Project.MSG_INFO; } else if (messageLevel.equalsIgnoreCase("verbose")) { messageType = Project.MSG_VERBOSE; } else if (messageLevel.equalsIgnoreCase("debug")) { messageType = Project.MSG_DEBUG; } else if (messageLevel.equalsIgnoreCase("err") || messageLevel.equalsIgnoreCase("error")) { messageType = Project.MSG_ERR; } else if (messageLevel.equalsIgnoreCase("warn")) { messageType = Project.MSG_WARN; } else { log("messagelevel set to unknown value \"" + messageLevel + "\"", Project.MSG_ERR); throw new BuildException("unknown messagelevel"); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
public void execute() throws BuildException { int logLevel = SimpleLog.LOG_LEVEL_INFO; switch (getMessageType()) { case Project.MSG_DEBUG : logLevel = SimpleLog.LOG_LEVEL_DEBUG; break; case Project.MSG_INFO : logLevel = SimpleLog.LOG_LEVEL_INFO; break; case Project.MSG_WARN : logLevel = SimpleLog.LOG_LEVEL_WARN; break; case Project.MSG_ERR : logLevel = SimpleLog.LOG_LEVEL_ERROR; break; case Project.MSG_VERBOSE: logLevel = SimpleLog.LOG_LEVEL_DEBUG; break; default: logLevel = SimpleLog.LOG_LEVEL_INFO; } SimpleLog logger = new SimpleLog("FOP/Anttask"); logger.setLevel(logLevel); try { FOPTaskStarter starter = new FOPTaskStarter(this); starter.setLogger(logger); starter.run(); } catch (FOPException ex) { throw new BuildException(ex); } catch (IOException ioe) { throw new BuildException(ioe); } catch (SAXException saxex) { throw new BuildException(saxex); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
public void run() throws FOPException { //Set base directory if (task.getBasedir() != null) { try { this.baseURL = task.getBasedir().toURI().toURL().toExternalForm(); } catch (MalformedURLException mfue) { logger.error("Error creating base URL from base directory", mfue); } } else { try { if (task.getFofile() != null) { this.baseURL = task.getFofile().getParentFile().toURI().toURL() .toExternalForm(); } } catch (MalformedURLException mfue) { logger.error("Error creating base URL from XSL-FO input file", mfue); } } task.log("Using base URL: " + baseURL, Project.MSG_DEBUG); String outputFormat = normalizeOutputFormat(task.getFormat()); String newExtension = determineExtension(outputFormat); // actioncount = # of fofiles actually processed through FOP int actioncount = 0; // skippedcount = # of fofiles which haven't changed (force = "false") int skippedcount = 0; // deal with single source file if (task.getFofile() != null) { if (task.getFofile().exists()) { File outf = task.getOutfile(); if (outf == null) { throw new BuildException("outfile is required when fofile is used"); } if (task.getOutdir() != null) { outf = new File(task.getOutdir(), outf.getName()); } // Render if "force" flag is set OR // OR output file doesn't exist OR // output file is older than input file if (task.getForce() || !outf.exists() || (task.getFofile().lastModified() > outf.lastModified() )) { render(task.getFofile(), outf, outputFormat); actioncount++; } else if (outf.exists() && (task.getFofile().lastModified() <= outf.lastModified() )) { skippedcount++; } } } else if (task.getXmlFile() != null && task.getXsltFile() != null) { if (task.getXmlFile().exists() && task.getXsltFile().exists()) { File outf = task.getOutfile(); if (outf == null) { throw new BuildException("outfile is required when fofile is used"); } if (task.getOutdir() != null) { outf = new File(task.getOutdir(), outf.getName()); } // Render if "force" flag is set OR // OR output file doesn't exist OR // output file is older than input file if (task.getForce() || !outf.exists() || (task.getXmlFile().lastModified() > outf.lastModified() || task.getXsltFile().lastModified() > outf.lastModified())) { render(task.getXmlFile(), task.getXsltFile(), outf, outputFormat); actioncount++; } else if (outf.exists() && (task.getXmlFile().lastModified() <= outf.lastModified() || task.getXsltFile().lastModified() <= outf.lastModified())) { skippedcount++; } } } GlobPatternMapper mapper = new GlobPatternMapper(); String inputExtension = ".fo"; File xsltFile = task.getXsltFile(); if (xsltFile != null) { inputExtension = ".xml"; } mapper.setFrom("*" + inputExtension); mapper.setTo("*" + newExtension); // deal with the filesets for (int i = 0; i < task.getFilesets().size(); i++) { FileSet fs = (FileSet) task.getFilesets().get(i); DirectoryScanner ds = fs.getDirectoryScanner(task.getProject()); String[] files = ds.getIncludedFiles(); for (int j = 0; j < files.length; j++) { File f = new File(fs.getDir(task.getProject()), files[j]); File outf = null; if (task.getOutdir() != null && files[j].endsWith(inputExtension)) { String[] sa = mapper.mapFileName(files[j]); outf = new File(task.getOutdir(), sa[0]); } else { outf = replaceExtension(f, inputExtension, newExtension); if (task.getOutdir() != null) { outf = new File(task.getOutdir(), outf.getName()); } } File dir = outf.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } try { if (task.getRelativebase()) { this.baseURL = f.getParentFile().toURI().toURL() .toExternalForm(); } if (this.baseURL == null) { this.baseURL = fs.getDir(task.getProject()).toURI().toURL() .toExternalForm(); } } catch (Exception e) { task.log("Error setting base URL", Project.MSG_DEBUG); } // Render if "force" flag is set OR // OR output file doesn't exist OR // output file is older than input file if (task.getForce() || !outf.exists() || (f.lastModified() > outf.lastModified() )) { if (xsltFile != null) { render(f, xsltFile, outf, outputFormat); } else { render(f, outf, outputFormat); } actioncount++; } else if (outf.exists() && (f.lastModified() <= outf.lastModified() )) { skippedcount++; } } } if (actioncount + skippedcount == 0) { task.log("No files processed. No files were selected by the filesets " + "and no fofile was set." , Project.MSG_WARN); } else if (skippedcount > 0) { task.log(skippedcount + " xslfo file(s) skipped (no change found" + " since last generation; set force=\"true\" to override)." , Project.MSG_INFO); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
private void renderInputHandler(InputHandler inputHandler, File outFile, String outputFormat) throws Exception { OutputStream out = null; try { out = new java.io.FileOutputStream(outFile); out = new BufferedOutputStream(out); } catch (Exception ex) { throw new BuildException("Failed to open " + outFile, ex); } boolean success = false; try { FOUserAgent userAgent = fopFactory.newFOUserAgent(); userAgent.setBaseURL(this.baseURL); inputHandler.renderTo(userAgent, outputFormat, out); success = true; } catch (Exception ex) { if (task.getThrowexceptions()) { throw new BuildException(ex); } throw ex; } finally { try { out.close(); } catch (IOException ioe) { logger.error("Error closing output file", ioe); } if (!success) { outFile.delete(); } } }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
public void execute() throws BuildException { try { EventProducerCollector collector = new EventProducerCollector(); long lastModified = processFileSets(collector); for (Iterator iter = collector.getModels().iterator(); iter.hasNext();) { EventModel model = (EventModel) iter.next(); File parentDir = getParentDir(model); if (!parentDir.exists() && !parentDir.mkdirs()) { throw new BuildException( "Could not create target directory for event model file: " + parentDir); } File modelFile = new File(parentDir, "event-model.xml"); if (!modelFile.exists() || lastModified > modelFile.lastModified()) { model.saveToXML(modelFile); log("Event model written to " + modelFile); } if (getTranslationFile() != null) { // TODO Remove translation file creation facility? if (!getTranslationFile().exists() || lastModified > getTranslationFile().lastModified()) { updateTranslationFile(modelFile); } } } } catch (ClassNotFoundException e) { throw new BuildException(e); } catch (EventConventionException ece) { throw new BuildException(ece); } catch (IOException ioe) { throw new BuildException(ioe); } }
8
              
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (FOPException ex) { throw new BuildException(ex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (IOException ioe) { throw new BuildException(ioe); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (SAXException saxex) { throw new BuildException(saxex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { throw new BuildException("Failed to open " + outFile, ex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { if (task.getThrowexceptions()) { throw new BuildException(ex); } throw ex; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (ClassNotFoundException e) { throw new BuildException(e); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (EventConventionException ece) { throw new BuildException(ece); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (IOException ioe) { throw new BuildException(ioe); }
5
              
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
public void execute() throws BuildException { runReference(); testNewBuild(); }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
protected void runReference() throws BuildException { // check not already done File f = new File(basedir + "/reference/output/"); // if(f.exists()) { // need to check that files have actually been created. // return; // } else { try { ClassLoader loader = new URLClassLoader(createUrls(referenceJar)); boolean failed = false; try { Class cla = Class.forName("org.apache.fop.apps.Fop", true, loader); Method get = cla.getMethod("getVersion", new Class[]{}); if (!get.invoke(null, new Object[]{}).equals(refVersion)) { throw new BuildException("Reference jar is not correct version it must be: " + refVersion); } }
// in src/java/org/apache/fop/tools/anttasks/FileCompare.java
public void execute() throws BuildException { boolean identical = false; File oldFile; File newFile; try { PrintWriter results = new PrintWriter(new java.io.FileWriter("results.html"), true); this.writeHeader(results); for (int i = 0; i < filenameList.length; i++) { oldFile = new File(referenceDirectory + filenameList[i]); newFile = new File(testDirectory + filenameList[i]); if (filesExist(oldFile, newFile)) { identical = compareFileSize(oldFile, newFile); if (identical) { identical = compareBytes(oldFile, newFile); } if (!identical) { System.out.println("Task Compare: \nFiles " + referenceDirectory + oldFile.getName() + " - " + testDirectory + newFile.getName() + " are *not* identical."); results.println("<tr><td><a href='" + referenceDirectory + oldFile.getName() + "'>" + oldFile.getName() + "</a> </td><td> <a href='" + testDirectory + newFile.getName() + "'>" + newFile.getName() + "</a>" + " </td><td><font color='red'>No</font></td></tr>"); } else { results.println("<tr><td><a href='" + referenceDirectory + oldFile.getName() + "'>" + oldFile.getName() + "</a> </td><td> <a href='" + testDirectory + newFile.getName() + "'>" + newFile.getName() + "</a>" + " </td><td>Yes</td></tr>"); } } } results.println("</table></html>"); } catch (IOException ioe) { System.err.println("ERROR: " + ioe); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
public void execute() throws BuildException { int logLevel = SimpleLog.LOG_LEVEL_INFO; switch (getMessageType()) { case Project.MSG_DEBUG : logLevel = SimpleLog.LOG_LEVEL_DEBUG; break; case Project.MSG_INFO : logLevel = SimpleLog.LOG_LEVEL_INFO; break; case Project.MSG_WARN : logLevel = SimpleLog.LOG_LEVEL_WARN; break; case Project.MSG_ERR : logLevel = SimpleLog.LOG_LEVEL_ERROR; break; case Project.MSG_VERBOSE: logLevel = SimpleLog.LOG_LEVEL_DEBUG; break; default: logLevel = SimpleLog.LOG_LEVEL_INFO; } SimpleLog logger = new SimpleLog("FOP/Anttask"); logger.setLevel(logLevel); try { FOPTaskStarter starter = new FOPTaskStarter(this); starter.setLogger(logger); starter.run(); } catch (FOPException ex) { throw new BuildException(ex); } catch (IOException ioe) { throw new BuildException(ioe); } catch (SAXException saxex) { throw new BuildException(saxex); } }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
public void execute() throws BuildException { try { EventProducerCollector collector = new EventProducerCollector(); long lastModified = processFileSets(collector); for (Iterator iter = collector.getModels().iterator(); iter.hasNext();) { EventModel model = (EventModel) iter.next(); File parentDir = getParentDir(model); if (!parentDir.exists() && !parentDir.mkdirs()) { throw new BuildException( "Could not create target directory for event model file: " + parentDir); } File modelFile = new File(parentDir, "event-model.xml"); if (!modelFile.exists() || lastModified > modelFile.lastModified()) { model.saveToXML(modelFile); log("Event model written to " + modelFile); } if (getTranslationFile() != null) { // TODO Remove translation file creation facility? if (!getTranslationFile().exists() || lastModified > getTranslationFile().lastModified()) { updateTranslationFile(modelFile); } } } } catch (ClassNotFoundException e) { throw new BuildException(e); } catch (EventConventionException ece) { throw new BuildException(ece); } catch (IOException ioe) { throw new BuildException(ioe); } }
(Lib) FileNotFoundException 15
              
// in src/java/org/apache/fop/pdf/PDFDocument.java
protected InputStream resolveURI(String uri) throws java.io.FileNotFoundException { try { /* TODO: Temporary hack to compile, improve later */ return new java.net.URL(uri).openStream(); } catch (Exception e) { throw new java.io.FileNotFoundException( "URI could not be resolved (" + e.getMessage() + "): " + uri); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void generateXML(SortedMap fontFamilies, File outFile, String singleFamily) throws TransformerConfigurationException, SAXException, IOException { SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler handler; if (this.mode == GENERATE_XML) { handler = tFactory.newTransformerHandler(); } else { URL url = getClass().getResource("fonts2fo.xsl"); if (url == null) { throw new FileNotFoundException("Did not find resource: fonts2fo.xsl"); } handler = tFactory.newTransformerHandler(new StreamSource(url.toExternalForm())); } if (singleFamily != null) { Transformer transformer = handler.getTransformer(); transformer.setParameter("single-family", singleFamily); } OutputStream out = new java.io.FileOutputStream(outFile); out = new java.io.BufferedOutputStream(out); if (this.mode == GENERATE_RENDERED) { handler.setResult(new SAXResult(getFOPContentHandler(out))); } else { handler.setResult(new StreamResult(out)); } try { GenerationHelperContentHandler helper = new GenerationHelperContentHandler( handler, null); FontListSerializer serializer = new FontListSerializer(); serializer.generateSAX(fontFamilies, singleFamily, helper); } finally { IOUtils.closeQuietly(out); } }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
Override protected void read() throws IOException { AFMFile afm = null; PFMFile pfm = null; InputStream afmIn = null; String afmUri = null; for (int i = 0; i < AFM_EXTENSIONS.length; i++) { try { afmUri = this.fontFileURI.substring(0, this.fontFileURI.length() - 4) + AFM_EXTENSIONS[i]; afmIn = openFontUri(resolver, afmUri); if (afmIn != null) { break; } } catch (IOException ioe) { // Ignore, AFM probably not available under the URI } } if (afmIn != null) { try { AFMParser afmParser = new AFMParser(); afm = afmParser.parse(afmIn, afmUri); } finally { IOUtils.closeQuietly(afmIn); } } String pfmUri = getPFMURI(this.fontFileURI); InputStream pfmIn = null; try { pfmIn = openFontUri(resolver, pfmUri); } catch (IOException ioe) { // Ignore, PFM probably not available under the URI } if (pfmIn != null) { try { pfm = new PFMFile(); pfm.load(pfmIn); } catch (IOException ioe) { if (afm == null) { // Ignore the exception if we have a valid PFM. PFM is only the fallback. throw ioe; } } finally { IOUtils.closeQuietly(pfmIn); } } if (afm == null && pfm == null) { throw new java.io.FileNotFoundException( "Neither an AFM nor a PFM file was found for " + this.fontFileURI); } buildFont(afm, pfm); this.loaded = true; }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
public void addEmbeddedFile(PDFEmbeddedFileExtensionAttachment embeddedFile) throws IOException { this.pdfDoc.getProfile().verifyEmbeddedFilesAllowed(); PDFNames names = this.pdfDoc.getRoot().getNames(); if (names == null) { //Add Names if not already present names = this.pdfDoc.getFactory().makeNames(); this.pdfDoc.getRoot().setNames(names); } //Create embedded file PDFEmbeddedFile file = new PDFEmbeddedFile(); this.pdfDoc.registerObject(file); Source src = getUserAgent().resolveURI(embeddedFile.getSrc()); InputStream in = ImageUtil.getInputStream(src); if (in == null) { throw new FileNotFoundException(embeddedFile.getSrc()); } try { OutputStream out = file.getBufferOutputStream(); IOUtils.copyLarge(in, out); } finally { IOUtils.closeQuietly(in); } PDFDictionary dict = new PDFDictionary(); dict.put("F", file); String filename = PDFText.toPDFString(embeddedFile.getFilename(), '_'); PDFFileSpec fileSpec = new PDFFileSpec(filename); fileSpec.setEmbeddedFile(dict); if (embeddedFile.getDesc() != null) { fileSpec.setDescription(embeddedFile.getDesc()); } this.pdfDoc.registerObject(fileSpec); //Make sure there is an EmbeddedFiles in the Names dictionary PDFEmbeddedFiles embeddedFiles = names.getEmbeddedFiles(); if (embeddedFiles == null) { embeddedFiles = new PDFEmbeddedFiles(); this.pdfDoc.assignObjectNumber(embeddedFiles); this.pdfDoc.addTrailerObject(embeddedFiles); names.setEmbeddedFiles(embeddedFiles); } //Add to EmbeddedFiles in the Names dictionary PDFArray nameArray = embeddedFiles.getNames(); if (nameArray == null) { nameArray = new PDFArray(); embeddedFiles.setNames(nameArray); } String name = PDFText.toPDFString(filename); nameArray.add(name); nameArray.add(new PDFReference(fileSpec)); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected InputStream openInputStream(ResourceAccessor accessor, String filename, AFPEventProducer eventProducer) throws IOException { URI uri; try { uri = new URI(filename.trim()); } catch (URISyntaxException e) { throw new FileNotFoundException("Invalid filename: " + filename + " (" + e.getMessage() + ")"); } if (LOG.isDebugEnabled()) { LOG.debug("Opening " + uri); } InputStream inputStream = accessor.createInputStream(uri); return inputStream; }
// in src/java/org/apache/fop/afp/util/DefaultFOPResourceAccessor.java
public InputStream createInputStream(URI uri) throws IOException { //Step 1: resolve against local base URI --> URI URI resolved = resolveAgainstBase(uri); //Step 2: resolve against the user agent --> stream String base = (this.categoryBaseURI != null ? this.categoryBaseURI : this.userAgent.getBaseURL()); Source src = userAgent.resolveURI(resolved.toASCIIString(), base); if (src == null) { throw new FileNotFoundException("Resource not found: " + uri.toASCIIString()); } else if (src instanceof StreamSource) { StreamSource ss = (StreamSource)src; InputStream in = ss.getInputStream(); if (in != null) { return in; } if (ss.getReader() != null) { //Don't support reader, retry using system ID below IOUtils.closeQuietly(ss.getReader()); } } URL url = new URL(src.getSystemId()); return url.openStream(); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void checkSettings() throws FOPException, FileNotFoundException { if (inputmode == NOT_SET) { throw new FOPException("No input file specified"); } if (outputmode == null) { throw new FOPException("No output file specified"); } if ((outputmode.equals(MimeConstants.MIME_FOP_AWT_PREVIEW) || outputmode.equals(MimeConstants.MIME_FOP_PRINT)) && outfile != null) { throw new FOPException("Output file may not be specified " + "for AWT or PRINT output"); } if (inputmode == XSLT_INPUT) { // check whether xml *and* xslt file have been set if (xmlfile == null && !this.useStdIn) { throw new FOPException("XML file must be specified for the transform mode"); } if (xsltfile == null) { throw new FOPException("XSLT file must be specified for the transform mode"); } // warning if fofile has been set in xslt mode if (fofile != null) { log.warn("Can't use fo file with transform mode! Ignoring.\n" + "Your input is " + "\n xmlfile: " + xmlfile.getAbsolutePath() + "\nxsltfile: " + xsltfile.getAbsolutePath() + "\n fofile: " + fofile.getAbsolutePath()); } if (xmlfile != null && !xmlfile.exists()) { throw new FileNotFoundException("Error: xml file " + xmlfile.getAbsolutePath() + " not found "); } if (!xsltfile.exists()) { throw new FileNotFoundException("Error: xsl file " + xsltfile.getAbsolutePath() + " not found "); } } else if (inputmode == FO_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (fofile != null && !fofile.exists()) { throw new FileNotFoundException("Error: fo file " + fofile.getAbsolutePath() + " not found "); } } else if (inputmode == AREATREE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Area Tree is used as input!"); } if (areatreefile != null && !areatreefile.exists()) { throw new FileNotFoundException("Error: area tree file " + areatreefile.getAbsolutePath() + " not found "); } } else if (inputmode == IF_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Intermediate Format" + " is used as input!"); } else if (outputmode.equals(MimeConstants.MIME_FOP_IF)) { throw new FOPException( "Intermediate Output is not available if Intermediate Format" + " is used as input!"); } if (iffile != null && !iffile.exists()) { throw new FileNotFoundException("Error: intermediate format file " + iffile.getAbsolutePath() + " not found "); } } else if (inputmode == IMAGE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (imagefile != null && !imagefile.exists()) { throw new FileNotFoundException("Error: image file " + imagefile.getAbsolutePath() + " not found "); } } }
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void fromUCD(boolean hexcode, String unidataPath, String outfilePath) throws IOException, URISyntaxException { URI unidata; if (unidataPath.endsWith("/")) { unidata = new URI(unidataPath); } else { unidata = new URI(unidataPath + "/"); } String scheme = unidata.getScheme(); if (scheme == null || !(scheme.equals("file") || scheme.equals("http"))) { throw new FileNotFoundException ("URI with file or http scheme required for UNIDATA input directory"); } File f = new File(outfilePath); if (f.exists()) { f.delete(); } f.createNewFile(); FileOutputStream fw = new FileOutputStream(f); OutputStreamWriter ow = new OutputStreamWriter(fw, "utf-8"); URI inuri = unidata.resolve("Blocks.txt"); InputStream inis = null; if (scheme.equals("file")) { File in = new File(inuri); inis = new FileInputStream(in); } else if (scheme.equals("http")) { inis = inuri.toURL().openStream(); } InputStreamReader insr = new InputStreamReader(inis, "utf-8"); BufferedReader inbr = new BufferedReader(insr); Map blocks = new HashMap(); for (String line = inbr.readLine(); line != null; line = inbr.readLine()) { if (line.startsWith("#") || line.matches("^\\s*$")) { continue; } String[] parts = line.split(";"); String block = parts[1].trim(); String[] indices = parts[0].split("\\.\\."); int[] ind = {Integer.parseInt(indices[0], 16), Integer.parseInt(indices[1], 16)}; blocks.put(block, ind); } inbr.close(); inuri = unidata.resolve("UnicodeData.txt"); if (scheme.equals("file")) { File in = new File(inuri); inis = new FileInputStream(in); } else if (scheme.equals("http")) { inis = inuri.toURL().openStream(); } insr = new InputStreamReader(inis, "utf-8"); inbr = new BufferedReader(insr); int maxChar; maxChar = Character.MAX_VALUE; ow.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); License.writeXMLLicenseId(ow); ow.write("\n"); writeGenerated(ow); ow.write("\n"); ow.write("<classes>\n"); for (String line = inbr.readLine(); line != null; line = inbr.readLine()) { String[] fields = line.split(";", NUM_FIELDS); int code = Integer.parseInt(fields[UNICODE], 16); if (code > maxChar) { break; } if (((fields[GENERAL_CATEGORY].equals("Ll") || fields[GENERAL_CATEGORY].equals("Lu") || fields[GENERAL_CATEGORY].equals("Lt")) && ("".equals(fields[SIMPLE_LOWERCASE_MAPPING]) || fields[UNICODE].equals(fields[SIMPLE_LOWERCASE_MAPPING]))) || fields[GENERAL_CATEGORY].equals("Lo")) { String[] blockNames = {"Superscripts and Subscripts", "Letterlike Symbols", "Alphabetic Presentation Forms", "Halfwidth and Fullwidth Forms", "CJK Unified Ideographs", "CJK Unified Ideographs Extension A", "Hangul Syllables"}; int j; for (j = 0; j < blockNames.length; ++j) { int[] ind = (int[]) blocks.get(blockNames[j]); if (code >= ind[0] && code <= ind[1]) { break; } } if (j < blockNames.length) { continue; } int uppercode = -1; int titlecode = -1; if (!"".equals(fields[SIMPLE_UPPERCASE_MAPPING])) { uppercode = Integer.parseInt(fields[SIMPLE_UPPERCASE_MAPPING], 16); } if (!"".equals(fields[SIMPLE_TITLECASE_MAPPING])) { titlecode = Integer.parseInt(fields[SIMPLE_TITLECASE_MAPPING], 16); } StringBuilder s = new StringBuilder(); if (hexcode) { s.append("0x" + fields[UNICODE].replaceFirst("^0+", "").toLowerCase() + " "); } s.append(Character.toChars(code)); if (uppercode != -1 && uppercode != code) { s.append(Character.toChars(uppercode)); } if (titlecode != -1 && titlecode != code && titlecode != uppercode) { s.append(Character.toChars(titlecode)); } ow.write(s.toString() + "\n"); } } ow.write("</classes>\n"); ow.flush(); ow.close(); inbr.close(); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
protected void updateTranslationFile(File modelFile) throws IOException { try { boolean resultExists = getTranslationFile().exists(); SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); //Generate fresh generated translation file as template Source src = new StreamSource(modelFile.toURI().toURL().toExternalForm()); StreamSource xslt1 = new StreamSource( getClass().getResourceAsStream(MODEL2TRANSLATION)); if (xslt1.getInputStream() == null) { throw new FileNotFoundException(MODEL2TRANSLATION + " not found"); } DOMResult domres = new DOMResult(); Transformer transformer = tFactory.newTransformer(xslt1); transformer.transform(src, domres); final Node generated = domres.getNode(); Node sourceDocument; if (resultExists) { //Load existing translation file into memory (because we overwrite it later) src = new StreamSource(getTranslationFile().toURI().toURL().toExternalForm()); domres = new DOMResult(); transformer = tFactory.newTransformer(); transformer.transform(src, domres); sourceDocument = domres.getNode(); } else { //Simply use generated as source document sourceDocument = generated; } //Generate translation file (with potentially new translations) src = new DOMSource(sourceDocument); //The following triggers a bug in older Xalan versions //Result res = new StreamResult(getTranslationFile()); OutputStream out = new java.io.FileOutputStream(getTranslationFile()); out = new java.io.BufferedOutputStream(out); Result res = new StreamResult(out); try { StreamSource xslt2 = new StreamSource( getClass().getResourceAsStream(MERGETRANSLATION)); if (xslt2.getInputStream() == null) { throw new FileNotFoundException(MERGETRANSLATION + " not found"); } transformer = tFactory.newTransformer(xslt2); transformer.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { if ("my:dom".equals(href)) { return new DOMSource(generated); } return null; } }); if (resultExists) { transformer.setParameter("generated-url", "my:dom"); } transformer.transform(src, res); if (resultExists) { log("Translation file updated: " + getTranslationFile()); } else { log("Translation file generated: " + getTranslationFile()); } } finally { IOUtils.closeQuietly(out); } } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
2
              
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (Exception e) { throw new java.io.FileNotFoundException( "URI could not be resolved (" + e.getMessage() + "): " + uri); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (URISyntaxException e) { throw new FileNotFoundException("Invalid filename: " + filename + " (" + e.getMessage() + ")"); }
2
              
// in src/java/org/apache/fop/pdf/PDFDocument.java
protected InputStream resolveURI(String uri) throws java.io.FileNotFoundException { try { /* TODO: Temporary hack to compile, improve later */ return new java.net.URL(uri).openStream(); } catch (Exception e) { throw new java.io.FileNotFoundException( "URI could not be resolved (" + e.getMessage() + "): " + uri); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void checkSettings() throws FOPException, FileNotFoundException { if (inputmode == NOT_SET) { throw new FOPException("No input file specified"); } if (outputmode == null) { throw new FOPException("No output file specified"); } if ((outputmode.equals(MimeConstants.MIME_FOP_AWT_PREVIEW) || outputmode.equals(MimeConstants.MIME_FOP_PRINT)) && outfile != null) { throw new FOPException("Output file may not be specified " + "for AWT or PRINT output"); } if (inputmode == XSLT_INPUT) { // check whether xml *and* xslt file have been set if (xmlfile == null && !this.useStdIn) { throw new FOPException("XML file must be specified for the transform mode"); } if (xsltfile == null) { throw new FOPException("XSLT file must be specified for the transform mode"); } // warning if fofile has been set in xslt mode if (fofile != null) { log.warn("Can't use fo file with transform mode! Ignoring.\n" + "Your input is " + "\n xmlfile: " + xmlfile.getAbsolutePath() + "\nxsltfile: " + xsltfile.getAbsolutePath() + "\n fofile: " + fofile.getAbsolutePath()); } if (xmlfile != null && !xmlfile.exists()) { throw new FileNotFoundException("Error: xml file " + xmlfile.getAbsolutePath() + " not found "); } if (!xsltfile.exists()) { throw new FileNotFoundException("Error: xsl file " + xsltfile.getAbsolutePath() + " not found "); } } else if (inputmode == FO_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (fofile != null && !fofile.exists()) { throw new FileNotFoundException("Error: fo file " + fofile.getAbsolutePath() + " not found "); } } else if (inputmode == AREATREE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Area Tree is used as input!"); } if (areatreefile != null && !areatreefile.exists()) { throw new FileNotFoundException("Error: area tree file " + areatreefile.getAbsolutePath() + " not found "); } } else if (inputmode == IF_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Intermediate Format" + " is used as input!"); } else if (outputmode.equals(MimeConstants.MIME_FOP_IF)) { throw new FOPException( "Intermediate Output is not available if Intermediate Format" + " is used as input!"); } if (iffile != null && !iffile.exists()) { throw new FileNotFoundException("Error: intermediate format file " + iffile.getAbsolutePath() + " not found "); } } else if (inputmode == IMAGE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (imagefile != null && !imagefile.exists()) { throw new FileNotFoundException("Error: image file " + imagefile.getAbsolutePath() + " not found "); } } }
(Lib) NoSuchElementException 13
              
// in src/java/org/apache/fop/fo/RecursiveCharIterator.java
public char nextChar() throws NoSuchElementException { if (curCharIter != null) { return curCharIter.nextChar(); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/NullCharIterator.java
public char nextChar() throws NoSuchElementException { throw new NoSuchElementException(); }
// in src/java/org/apache/fop/fo/OneCharIterator.java
public char nextChar() throws NoSuchElementException { if (bFirst) { bFirst = false; return charCode; } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/flow/Character.java
public char nextChar() { if (bFirst) { bFirst = false; return foChar.character; } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/FOText.java
public char nextChar() { if (this.currentPosition < charBuffer.limit()) { this.canRemove = true; this.canReplace = true; return charBuffer.get(currentPosition++); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/FObj.java
public Object next() { if (currentNode != null) { if (currentIndex != 0) { if (currentNode.siblings != null && currentNode.siblings[1] != null) { currentNode = currentNode.siblings[1]; } else { throw new NoSuchElementException(); } } currentIndex++; flags |= (F_SET_ALLOWED | F_REMOVE_ALLOWED); return currentNode; } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/FObj.java
public Object previous() { if (currentNode.siblings != null && currentNode.siblings[0] != null) { currentIndex--; currentNode = currentNode.siblings[0]; flags |= (F_SET_ALLOWED | F_REMOVE_ALLOWED); return currentNode; } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
public Object next() { if (log.isDebugEnabled()) { log.debug("[" + (current + 1) + "]"); } // Renders current page as image BufferedImage pageImage = null; try { pageImage = getPageImage(current++); } catch (FOPException e) { throw new NoSuchElementException(e.getMessage()); } if (COMPRESSION_CCITT_T4.equalsIgnoreCase(writerParams.getCompressionMethod()) || COMPRESSION_CCITT_T6.equalsIgnoreCase(writerParams.getCompressionMethod())) { return pageImage; } else { //Decorate the image with a packed sample model for encoding by the codec SinglePixelPackedSampleModel sppsm; sppsm = (SinglePixelPackedSampleModel)pageImage.getSampleModel(); int bands = sppsm.getNumBands(); int[] off = new int[bands]; int w = pageImage.getWidth(); int h = pageImage.getHeight(); for (int i = 0; i < bands; i++) { off[i] = i; } SampleModel sm = new PixelInterleavedSampleModel( DataBuffer.TYPE_BYTE, w, h, bands, w * bands, off); RenderedImage rimg = new FormatRed(GraphicsUtil.wrap(pageImage), sm); return rimg; } }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public LayoutManager previous() throws NoSuchElementException { if (curPos > 0) { return listLMs.get(--curPos); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public LayoutManager next() throws NoSuchElementException { if (curPos < listLMs.size()) { return listLMs.get(curPos++); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public void remove() throws NoSuchElementException { if (curPos > 0) { listLMs.remove(--curPos); // Note: doesn't actually remove it from the base! } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/layoutmgr/PositionIterator.java
public Position next() throws NoSuchElementException { if (hasNext) { Position retPos = getPos(nextObj); lookAhead(); return retPos; } else { throw new NoSuchElementException("PosIter"); } }
1
              
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
catch (FOPException e) { throw new NoSuchElementException(e.getMessage()); }
8
              
// in src/java/org/apache/fop/fo/RecursiveCharIterator.java
public char nextChar() throws NoSuchElementException { if (curCharIter != null) { return curCharIter.nextChar(); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/NullCharIterator.java
public char nextChar() throws NoSuchElementException { throw new NoSuchElementException(); }
// in src/java/org/apache/fop/fo/OneCharIterator.java
public char nextChar() throws NoSuchElementException { if (bFirst) { bFirst = false; return charCode; } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/CharIterator.java
public Object next() throws NoSuchElementException { return new Character(nextChar()); }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public LayoutManager previous() throws NoSuchElementException { if (curPos > 0) { return listLMs.get(--curPos); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public LayoutManager next() throws NoSuchElementException { if (curPos < listLMs.size()) { return listLMs.get(curPos++); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public void remove() throws NoSuchElementException { if (curPos > 0) { listLMs.remove(--curPos); // Note: doesn't actually remove it from the base! } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/layoutmgr/PositionIterator.java
public Position next() throws NoSuchElementException { if (hasNext) { Position retPos = getPos(nextObj); lookAhead(); return retPos; } else { throw new NoSuchElementException("PosIter"); } }
(Domain) FontRuntimeException 9
              
// in src/java/org/apache/fop/afp/fonts/RasterFont.java
public CharacterSet getCharacterSet(int sizeInMpt) { Integer requestedSize = Integer.valueOf(sizeInMpt); CharacterSet csm = (CharacterSet) charSets.get(requestedSize); double sizeInPt = sizeInMpt / 1000.0; if (csm != null) { return csm; } if (substitutionCharSets != null) { //Check first if a substitution has already been added csm = (CharacterSet) substitutionCharSets.get(requestedSize); } if (csm == null && !charSets.isEmpty()) { // No match or substitution found, but there exist entries // for other sizes // Get char set with nearest, smallest font size SortedMap<Integer, CharacterSet> smallerSizes = charSets.headMap(requestedSize); SortedMap<Integer, CharacterSet> largerSizes = charSets.tailMap(requestedSize); int smallerSize = smallerSizes.isEmpty() ? 0 : ((Integer)smallerSizes.lastKey()).intValue(); int largerSize = largerSizes.isEmpty() ? Integer.MAX_VALUE : ((Integer)largerSizes.firstKey()).intValue(); Integer fontSize; if (!smallerSizes.isEmpty() && (sizeInMpt - smallerSize) <= (largerSize - sizeInMpt)) { fontSize = Integer.valueOf(smallerSize); } else { fontSize = Integer.valueOf(largerSize); } csm = (CharacterSet) charSets.get(fontSize); if (csm != null) { // Add the substitute mapping, so subsequent calls will // find it immediately if (substitutionCharSets == null) { substitutionCharSets = new HashMap<Integer, CharacterSet>(); } substitutionCharSets.put(requestedSize, csm); // do not output the warning if the font size is closer to an integer less than 0.1 if (!(Math.abs(fontSize.intValue() / 1000.0 - sizeInPt) < 0.1)) { String msg = "No " + sizeInPt + "pt font " + getFontName() + " found, substituted with " + fontSize.intValue() / 1000f + "pt font"; LOG.warn(msg); } } } if (csm == null) { // Still no match -> error String msg = "No font found for font " + getFontName() + " with point size " + sizeInPt; LOG.error(msg); throw new FontRuntimeException(msg); } return csm; }
// in src/java/org/apache/fop/afp/fonts/RasterFont.java
public int getFirstChar() { Iterator<CharacterSet> it = charSets.values().iterator(); if (it.hasNext()) { CharacterSet csm = it.next(); return csm.getFirstChar(); } else { String msg = "getFirstChar() - No character set found for font:" + getFontName(); LOG.error(msg); throw new FontRuntimeException(msg); } }
// in src/java/org/apache/fop/afp/fonts/RasterFont.java
public int getLastChar() { Iterator<CharacterSet> it = charSets.values().iterator(); if (it.hasNext()) { CharacterSet csm = it.next(); return csm.getLastChar(); } else { String msg = "getLastChar() - No character set found for font:" + getFontName(); LOG.error(msg); throw new FontRuntimeException(msg); } }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
public void addFont(int fontReference, AFPFont font, int size, int orientation) throws MaximumSizeExceededException { FontDefinition fontDefinition = new FontDefinition(); fontDefinition.fontReferenceKey = BinaryUtils.convert(fontReference)[0]; switch (orientation) { case 90: fontDefinition.orientation = 0x2D; break; case 180: fontDefinition.orientation = 0x5A; break; case 270: fontDefinition.orientation = (byte) 0x87; break; default: fontDefinition.orientation = 0x00; break; } try { if (font instanceof RasterFont) { RasterFont raster = (RasterFont) font; CharacterSet cs = raster.getCharacterSet(size); if (cs == null) { String msg = "Character set not found for font " + font.getFontName() + " with point size " + size; LOG.error(msg); throw new FontRuntimeException(msg); } fontDefinition.characterSet = cs.getNameBytes(); if (fontDefinition.characterSet.length != 8) { throw new IllegalArgumentException("The character set " + new String(fontDefinition.characterSet, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof OutlineFont) { OutlineFont outline = (OutlineFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof DoubleByteFont) { DoubleByteFont outline = (DoubleByteFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); //TODO Relax requirement for 8 characters if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else { String msg = "Font of type " + font.getClass().getName() + " not recognized."; LOG.error(msg); throw new FontRuntimeException(msg); } if (fontList.size() > 253) { // Throw an exception if the size is exceeded throw new MaximumSizeExceededException(); } else { fontList.add(fontDefinition); } } catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); } }
// in src/java/org/apache/fop/afp/util/DTDEntityResolver.java
public InputSource resolveEntity(String publicId, String systemId) throws IOException { URL resource = null; if ( AFP_DTD_1_2_ID.equals(publicId) ) { resource = getResource( AFP_DTD_1_2_RESOURCE ); } else if ( AFP_DTD_1_1_ID.equals(publicId) ) { resource = getResource( AFP_DTD_1_1_RESOURCE ); } else if ( AFP_DTD_1_0_ID.equals(publicId) ) { throw new FontRuntimeException( "The AFP Installed Font Definition 1.0 DTD is not longer supported" ); } else if (systemId != null && systemId.indexOf("afp-fonts.dtd") >= 0 ) { throw new FontRuntimeException( "The AFP Installed Font Definition DTD must be specified using the public id" ); } else { return null; } InputSource inputSource = new InputSource( resource.openStream() ); inputSource.setPublicId( publicId ); inputSource.setSystemId( systemId ); return inputSource; }
// in src/java/org/apache/fop/afp/util/DTDEntityResolver.java
private URL getResource(String resourcePath) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } URL resource = cl.getResource( resourcePath ); if (resource == null) { throw new FontRuntimeException( "Resource " + resourcePath + "could not be found on the classpath" ); } return resource; }
1
              
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); }
0
(Domain) HyphenationException 5
              
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
public void loadPatterns(String filename) throws HyphenationException { File f = new File(filename); try { InputSource src = new InputSource(f.toURI().toURL().toExternalForm()); loadPatterns(src); } catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + f + "' to a URL: " + e.getMessage()); } }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void parse(File file) throws HyphenationException { try { InputSource src = new InputSource(file.toURI().toURL().toExternalForm()); parse(src); } catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + file + "' to a URL: " + e.getMessage()); } }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void parse(InputSource source) throws HyphenationException { try { parser.parse(source); } catch (FileNotFoundException fnfe) { throw new HyphenationException("File not found: " + fnfe.getMessage()); } catch (IOException ioe) { throw new HyphenationException(ioe.getMessage()); } catch (SAXException e) { throw new HyphenationException(errMsg); } }
5
              
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + f + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + file + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (FileNotFoundException fnfe) { throw new HyphenationException("File not found: " + fnfe.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new HyphenationException(ioe.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (SAXException e) { throw new HyphenationException(errMsg); }
7
              
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
public void loadPatterns(String filename) throws HyphenationException { File f = new File(filename); try { InputSource src = new InputSource(f.toURI().toURL().toExternalForm()); loadPatterns(src); } catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + f + "' to a URL: " + e.getMessage()); } }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
public void loadPatterns(InputSource source) throws HyphenationException { PatternParser pp = new PatternParser(this); ivalues = new TernaryTree(); pp.parse(source); // patterns/values should be now in the tree // let's optimize a bit trimToSize(); vspace.trimToSize(); classmap.trimToSize(); // get rid of the auxiliary map ivalues = null; }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void parse(String filename) throws HyphenationException { parse(new File(filename)); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void parse(File file) throws HyphenationException { try { InputSource src = new InputSource(file.toURI().toURL().toExternalForm()); parse(src); } catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + file + "' to a URL: " + e.getMessage()); } }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void parse(InputSource source) throws HyphenationException { try { parser.parse(source); } catch (FileNotFoundException fnfe) { throw new HyphenationException("File not found: " + fnfe.getMessage()); } catch (IOException ioe) { throw new HyphenationException(ioe.getMessage()); } catch (SAXException e) { throw new HyphenationException(errMsg); } }
(Domain) ExternalGraphicException 4
              
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
protected void writeRtfContentWithException() throws IOException { if (writer == null) { return; } if (url == null && imagedata == null) { throw new ExternalGraphicException( "No image data is available (neither URL, nor in-memory)"); } String linkToRoot = System.getProperty("jfor_link_to_root"); if (url != null && linkToRoot != null) { writer.write("{\\field {\\* \\fldinst { INCLUDEPICTURE \""); writer.write(linkToRoot); File urlFile = new File(url.getFile()); writer.write(urlFile.getName()); writer.write("\" \\\\* MERGEFORMAT \\\\d }}}"); return; } // getRtfFile ().getLog ().logInfo ("Writing image '" + url + "'."); if (imagedata == null) { try { final InputStream in = url.openStream(); try { imagedata = IOUtils.toByteArray(url.openStream()); } finally { IOUtils.closeQuietly(in); } } catch (Exception e) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + url + "' (" + e + ")"); } } if (imagedata == null) { return; } // Determine image file format String file = (url != null ? url.getFile() : "<unknown>"); imageformat = FormatBase.determineFormat(imagedata); if (imageformat != null) { imageformat = imageformat.convert(imageformat, imagedata); } if (imageformat == null || imageformat.getType() == ImageConstants.I_NOT_SUPPORTED || "".equals(imageformat.getRtfTag())) { throw new ExternalGraphicException("The tag <fo:external-graphic> " + "does not support " + file.substring(file.lastIndexOf(".") + 1) + " - image type."); } // Writes the beginning of the rtf image writeGroupMark(true); writeStarControlWord("shppict"); writeGroupMark(true); writeControlWord("pict"); StringBuffer buf = new StringBuffer(imagedata.length * 3); writeControlWord(imageformat.getRtfTag()); computeImageSize(); writeSizeInfo(); writeAttributes(getRtfAttributes(), null); for (int i = 0; i < imagedata.length; i++) { int iData = imagedata [i]; // Make positive byte if (iData < 0) { iData += 256; } if (iData < 16) { // Set leading zero and append buf.append('0'); } buf.append(Integer.toHexString(iData)); } int len = buf.length(); char[] chars = new char[len]; buf.getChars(0, len, chars, 0); writer.write(chars); // Writes the end of RTF image writeGroupMark(false); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
public void setURL(String urlString) throws IOException { URL tmpUrl = null; try { tmpUrl = new URL (urlString); } catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } } this.url = tmpUrl; }
2
              
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (Exception e) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + url + "' (" + e + ")"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); }
0
(Lib) MissingResourceException 4
              
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
private static EventModel loadModel(Class resourceBaseClass) { String resourceName = "event-model.xml"; InputStream in = resourceBaseClass.getResourceAsStream(resourceName); if (in == null) { throw new MissingResourceException( "File " + resourceName + " not found", DefaultEventBroadcaster.class.getName(), ""); } try { return EventModelParser.parse(new StreamSource(in)); } catch (TransformerException e) { throw new MissingResourceException( "Error reading " + resourceName + ": " + e.getMessage(), DefaultEventBroadcaster.class.getName(), ""); } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public static ResourceBundle getXMLBundle(String baseName, Locale locale, ClassLoader loader) throws MissingResourceException { if (loader == null) { throw new NullPointerException("loader must not be null"); } if (baseName == null) { throw new NullPointerException("baseName must not be null"); } assert locale != null; ResourceBundle bundle; if (!locale.equals(Locale.getDefault())) { bundle = handleGetXMLBundle(baseName, "_" + locale, false, loader); if (bundle != null) { return bundle; } } bundle = handleGetXMLBundle(baseName, "_" + Locale.getDefault(), true, loader); if (bundle != null) { return bundle; } throw new MissingResourceException( baseName + " (" + locale + ")", baseName + '_' + locale, null); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
private static ResourceBundle handleGetXMLBundle(String base, String locale, boolean loadBase, final ClassLoader loader) { XMLResourceBundle bundle = null; String bundleName = base + locale; Object cacheKey = loader != null ? (Object) loader : (Object) "null"; Hashtable loaderCache; //<String, ResourceBundle> synchronized (cache) { loaderCache = (Hashtable)cache.get(cacheKey); if (loaderCache == null) { loaderCache = new Hashtable(); cache.put(cacheKey, loaderCache); } } ResourceBundle result = (ResourceBundle)loaderCache.get(bundleName); if (result != null) { if (result == MISSINGBASE) { return null; } if (result == MISSING) { if (!loadBase) { return null; } String extension = strip(locale); if (extension == null) { return null; } return handleGetXMLBundle(base, extension, loadBase, loader); } return result; } final String fileName = bundleName.replace('.', '/') + ".xml"; InputStream stream = (InputStream)AccessController .doPrivileged(new PrivilegedAction() { public Object run() { return loader == null ? ClassLoader.getSystemResourceAsStream(fileName) : loader.getResourceAsStream(fileName); } }); if (stream != null) { try { try { bundle = new XMLResourceBundle(stream); } finally { stream.close(); } bundle.setLocale(locale); } catch (IOException e) { throw new MissingResourceException(e.getMessage(), base, null); } } String extension = strip(locale); if (bundle != null) { if (extension != null) { ResourceBundle parent = handleGetXMLBundle(base, extension, true, loader); if (parent != null) { bundle.setParent(parent); } } loaderCache.put(bundleName, bundle); return bundle; } if (extension != null) { ResourceBundle fallback = handleGetXMLBundle(base, extension, loadBase, loader); if (fallback != null) { loaderCache.put(bundleName, fallback); return fallback; } } loaderCache.put(bundleName, loadBase ? MISSINGBASE : MISSING); return null; }
2
              
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
catch (TransformerException e) { throw new MissingResourceException( "Error reading " + resourceName + ": " + e.getMessage(), DefaultEventBroadcaster.class.getName(), ""); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (IOException e) { throw new MissingResourceException(e.getMessage(), base, null); }
2
              
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public static ResourceBundle getXMLBundle(String baseName, ClassLoader loader) throws MissingResourceException { return getXMLBundle(baseName, Locale.getDefault(), loader); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public static ResourceBundle getXMLBundle(String baseName, Locale locale, ClassLoader loader) throws MissingResourceException { if (loader == null) { throw new NullPointerException("loader must not be null"); } if (baseName == null) { throw new NullPointerException("baseName must not be null"); } assert locale != null; ResourceBundle bundle; if (!locale.equals(Locale.getDefault())) { bundle = handleGetXMLBundle(baseName, "_" + locale, false, loader); if (bundle != null) { return bundle; } } bundle = handleGetXMLBundle(baseName, "_" + Locale.getDefault(), true, loader); if (bundle != null) { return bundle; } throw new MissingResourceException( baseName + " (" + locale + ")", baseName + '_' + locale, null); }
(Lib) TranscoderException 4
              
// in src/java/org/apache/fop/svg/PDFTranscoder.java
protected void transcode(Document document, String uri, TranscoderOutput output) throws TranscoderException { graphics = new PDFDocumentGraphics2D(isTextStroked()); graphics.getPDFDocument().getInfo().setProducer("Apache FOP Version " + Version.getVersion() + ": PDF Transcoder for Batik"); if (hints.containsKey(KEY_DEVICE_RESOLUTION)) { graphics.setDeviceDPI(getDeviceResolution()); } setupImageInfrastructure(uri); try { Configuration effCfg = getEffectiveConfiguration(); if (effCfg != null) { PDFDocumentGraphics2DConfigurator configurator = new PDFDocumentGraphics2DConfigurator(); boolean useComplexScriptFeatures = false; //TODO - FIX ME configurator.configure(graphics, effCfg, useComplexScriptFeatures); } else { graphics.setupDefaultFontInfo(); } } catch (Exception e) { throw new TranscoderException( "Error while setting up PDFDocumentGraphics2D", e); } super.transcode(document, uri, output); if (getLogger().isTraceEnabled()) { getLogger().trace("document size: " + width + " x " + height); } // prepare the image to be painted UnitProcessor.Context uctx = UnitProcessor.createContext(ctx, document.getDocumentElement()); float widthInPt = UnitProcessor.userSpaceToSVG(width, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int w = (int)(widthInPt + 0.5); float heightInPt = UnitProcessor.userSpaceToSVG(height, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int h = (int)(heightInPt + 0.5); if (getLogger().isTraceEnabled()) { getLogger().trace("document size: " + w + "pt x " + h + "pt"); } // prepare the image to be painted //int w = (int)(width + 0.5); //int h = (int)(height + 0.5); try { OutputStream out = output.getOutputStream(); if (!(out instanceof BufferedOutputStream)) { out = new BufferedOutputStream(out); } graphics.setupDocument(out, w, h); graphics.setSVGDimension(width, height); if (hints.containsKey(ImageTranscoder.KEY_BACKGROUND_COLOR)) { graphics.setBackgroundColor ((Color)hints.get(ImageTranscoder.KEY_BACKGROUND_COLOR)); } graphics.setGraphicContext (new org.apache.xmlgraphics.java2d.GraphicContext()); graphics.preparePainting(); graphics.transform(curTxf); graphics.setRenderingHint (RenderingHintsKeyExt.KEY_TRANSCODING, RenderingHintsKeyExt.VALUE_TRANSCODING_VECTOR); this.root.paint(graphics); graphics.finish(); } catch (IOException ex) { throw new TranscoderException(ex); } }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
protected void transcode(Document document, String uri, TranscoderOutput output) throws TranscoderException { graphics = createDocumentGraphics2D(); if (!isTextStroked()) { try { boolean useComplexScriptFeatures = false; //TODO - FIX ME this.fontInfo = PDFDocumentGraphics2DConfigurator.createFontInfo( getEffectiveConfiguration(), useComplexScriptFeatures); graphics.setCustomTextHandler(new NativeTextHandler(graphics, fontInfo)); } catch (FOPException fe) { throw new TranscoderException(fe); } } super.transcode(document, uri, output); getLogger().trace("document size: " + width + " x " + height); // prepare the image to be painted UnitProcessor.Context uctx = UnitProcessor.createContext(ctx, document.getDocumentElement()); float widthInPt = UnitProcessor.userSpaceToSVG(width, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int w = (int)(widthInPt + 0.5); float heightInPt = UnitProcessor.userSpaceToSVG(height, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int h = (int)(heightInPt + 0.5); getLogger().trace("document size: " + w + "pt x " + h + "pt"); try { OutputStream out = output.getOutputStream(); if (!(out instanceof BufferedOutputStream)) { out = new BufferedOutputStream(out); } graphics.setupDocument(out, w, h); graphics.setViewportDimension(width, height); if (hints.containsKey(ImageTranscoder.KEY_BACKGROUND_COLOR)) { graphics.setBackgroundColor ((Color)hints.get(ImageTranscoder.KEY_BACKGROUND_COLOR)); } graphics.setGraphicContext (new org.apache.xmlgraphics.java2d.GraphicContext()); graphics.setTransform(curTxf); this.root.paint(graphics); graphics.finish(); } catch (IOException ex) { throw new TranscoderException(ex); } }
4
              
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (Exception e) { throw new TranscoderException( "Error while setting up PDFDocumentGraphics2D", e); }
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (FOPException fe) { throw new TranscoderException(fe); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
5
              
// in src/java/org/apache/fop/svg/PDFTranscoder.java
protected void transcode(Document document, String uri, TranscoderOutput output) throws TranscoderException { graphics = new PDFDocumentGraphics2D(isTextStroked()); graphics.getPDFDocument().getInfo().setProducer("Apache FOP Version " + Version.getVersion() + ": PDF Transcoder for Batik"); if (hints.containsKey(KEY_DEVICE_RESOLUTION)) { graphics.setDeviceDPI(getDeviceResolution()); } setupImageInfrastructure(uri); try { Configuration effCfg = getEffectiveConfiguration(); if (effCfg != null) { PDFDocumentGraphics2DConfigurator configurator = new PDFDocumentGraphics2DConfigurator(); boolean useComplexScriptFeatures = false; //TODO - FIX ME configurator.configure(graphics, effCfg, useComplexScriptFeatures); } else { graphics.setupDefaultFontInfo(); } } catch (Exception e) { throw new TranscoderException( "Error while setting up PDFDocumentGraphics2D", e); } super.transcode(document, uri, output); if (getLogger().isTraceEnabled()) { getLogger().trace("document size: " + width + " x " + height); } // prepare the image to be painted UnitProcessor.Context uctx = UnitProcessor.createContext(ctx, document.getDocumentElement()); float widthInPt = UnitProcessor.userSpaceToSVG(width, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int w = (int)(widthInPt + 0.5); float heightInPt = UnitProcessor.userSpaceToSVG(height, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int h = (int)(heightInPt + 0.5); if (getLogger().isTraceEnabled()) { getLogger().trace("document size: " + w + "pt x " + h + "pt"); } // prepare the image to be painted //int w = (int)(width + 0.5); //int h = (int)(height + 0.5); try { OutputStream out = output.getOutputStream(); if (!(out instanceof BufferedOutputStream)) { out = new BufferedOutputStream(out); } graphics.setupDocument(out, w, h); graphics.setSVGDimension(width, height); if (hints.containsKey(ImageTranscoder.KEY_BACKGROUND_COLOR)) { graphics.setBackgroundColor ((Color)hints.get(ImageTranscoder.KEY_BACKGROUND_COLOR)); } graphics.setGraphicContext (new org.apache.xmlgraphics.java2d.GraphicContext()); graphics.preparePainting(); graphics.transform(curTxf); graphics.setRenderingHint (RenderingHintsKeyExt.KEY_TRANSCODING, RenderingHintsKeyExt.VALUE_TRANSCODING_VECTOR); this.root.paint(graphics); graphics.finish(); } catch (IOException ex) { throw new TranscoderException(ex); } }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
public void error(TranscoderException te) throws TranscoderException { getLogger().error(te.getMessage()); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
public void fatalError(TranscoderException te) throws TranscoderException { throw te; }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
public void warning(TranscoderException te) throws TranscoderException { getLogger().warn(te.getMessage()); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
protected void transcode(Document document, String uri, TranscoderOutput output) throws TranscoderException { graphics = createDocumentGraphics2D(); if (!isTextStroked()) { try { boolean useComplexScriptFeatures = false; //TODO - FIX ME this.fontInfo = PDFDocumentGraphics2DConfigurator.createFontInfo( getEffectiveConfiguration(), useComplexScriptFeatures); graphics.setCustomTextHandler(new NativeTextHandler(graphics, fontInfo)); } catch (FOPException fe) { throw new TranscoderException(fe); } } super.transcode(document, uri, output); getLogger().trace("document size: " + width + " x " + height); // prepare the image to be painted UnitProcessor.Context uctx = UnitProcessor.createContext(ctx, document.getDocumentElement()); float widthInPt = UnitProcessor.userSpaceToSVG(width, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int w = (int)(widthInPt + 0.5); float heightInPt = UnitProcessor.userSpaceToSVG(height, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int h = (int)(heightInPt + 0.5); getLogger().trace("document size: " + w + "pt x " + h + "pt"); try { OutputStream out = output.getOutputStream(); if (!(out instanceof BufferedOutputStream)) { out = new BufferedOutputStream(out); } graphics.setupDocument(out, w, h); graphics.setViewportDimension(width, height); if (hints.containsKey(ImageTranscoder.KEY_BACKGROUND_COLOR)) { graphics.setBackgroundColor ((Color)hints.get(ImageTranscoder.KEY_BACKGROUND_COLOR)); } graphics.setGraphicContext (new org.apache.xmlgraphics.java2d.GraphicContext()); graphics.setTransform(curTxf); this.root.paint(graphics); graphics.finish(); } catch (IOException ex) { throw new TranscoderException(ex); } }
(Lib) TransformerException 4
              
// in src/java/org/apache/fop/apps/FOURIResolver.java
private void handleException(Exception e, String errorStr, boolean strict) throws TransformerException { if (strict) { throw new TransformerException(errorStr, e); } log.error(e.getMessage()); }
// in src/java/org/apache/fop/servlet/ServletContextURIResolver.java
protected Source resolveServletContextURI(String path) throws TransformerException { while (path.startsWith("//")) { path = path.substring(1); } try { URL url = this.servletContext.getResource(path); InputStream in = this.servletContext.getResourceAsStream(path); if (in != null) { if (url != null) { return new StreamSource(in, url.toExternalForm()); } else { return new StreamSource(in); } } else { throw new TransformerException("Resource does not exist. \"" + path + "\" is not accessible through the servlet context."); } } catch (MalformedURLException mfue) { throw new TransformerException( "Error accessing resource using servlet context: " + path, mfue); } }
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
public void writeFontXML(org.w3c.dom.Document doc, File target) throws TransformerException { log.info("Writing xml font file " + target + "..."); try { OutputStream out = new java.io.FileOutputStream(target); out = new java.io.BufferedOutputStream(out); try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.transform( new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(out)); } finally { out.close(); } } catch (IOException ioe) { throw new TransformerException("Error writing the output file", ioe); } }
2
              
// in src/java/org/apache/fop/servlet/ServletContextURIResolver.java
catch (MalformedURLException mfue) { throw new TransformerException( "Error accessing resource using servlet context: " + path, mfue); }
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
catch (IOException ioe) { throw new TransformerException("Error writing the output file", ioe); }
19
              
// in src/java/org/apache/fop/apps/FOURIResolver.java
private void handleException(Exception e, String errorStr, boolean strict) throws TransformerException { if (strict) { throw new TransformerException(errorStr, e); } log.error(e.getMessage()); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
public Source resolve(String href, String base) throws TransformerException { Source source = null; // data URLs can be quite long so evaluate early and don't try to build a File // (can lead to problems) source = commonURIResolver.resolve(href, base); // Custom uri resolution if (source == null && uriResolver != null) { source = uriResolver.resolve(href, base); } // Fallback to default resolution mechanism if (source == null) { URL absoluteURL = null; int hashPos = href.indexOf('#'); String fileURL; String fragment; if (hashPos >= 0) { fileURL = href.substring(0, hashPos); fragment = href.substring(hashPos); } else { fileURL = href; fragment = null; } File file = new File(fileURL); if (file.canRead() && file.isFile()) { try { if (fragment != null) { absoluteURL = new URL(file.toURI().toURL().toExternalForm() + fragment); } else { absoluteURL = file.toURI().toURL(); } } catch (MalformedURLException mfue) { handleException(mfue, "Could not convert filename '" + href + "' to URL", throwExceptions); } } else { // no base provided if (base == null) { // We don't have a valid file protocol based URL try { absoluteURL = new URL(href); } catch (MalformedURLException mue) { try { // the above failed, we give it another go in case // the href contains only a path then file: is // assumed absoluteURL = new URL("file:" + href); } catch (MalformedURLException mfue) { handleException(mfue, "Error with URL '" + href + "'", throwExceptions); } } // try and resolve from context of base } else { URL baseURL = null; try { baseURL = new URL(base); } catch (MalformedURLException mfue) { handleException(mfue, "Error with base URL '" + base + "'", throwExceptions); } /* * This piece of code is based on the following statement in * RFC2396 section 5.2: * * 3) If the scheme component is defined, indicating that * the reference starts with a scheme name, then the * reference is interpreted as an absolute URI and we are * done. Otherwise, the reference URI's scheme is inherited * from the base URI's scheme component. * * Due to a loophole in prior specifications [RFC1630], some * parsers allow the scheme name to be present in a relative * URI if it is the same as the base URI scheme. * Unfortunately, this can conflict with the correct parsing * of non-hierarchical URI. For backwards compatibility, an * implementation may work around such references by * removing the scheme if it matches that of the base URI * and the scheme is known to always use the <hier_part> * syntax. * * The URL class does not implement this work around, so we * do. */ assert (baseURL != null); String scheme = baseURL.getProtocol() + ":"; if (href.startsWith(scheme) && "file:".equals(scheme)) { href = href.substring(scheme.length()); int colonPos = href.indexOf(':'); int slashPos = href.indexOf('/'); if (slashPos >= 0 && colonPos >= 0 && colonPos < slashPos) { href = "/" + href; // Absolute file URL doesn't // have a leading slash } } try { absoluteURL = new URL(baseURL, href); } catch (MalformedURLException mfue) { handleException(mfue, "Error with URL; base '" + base + "' " + "href '" + href + "'", throwExceptions); } } } if (absoluteURL != null) { String effURL = absoluteURL.toExternalForm(); try { URLConnection connection = absoluteURL.openConnection(); connection.setAllowUserInteraction(false); connection.setDoInput(true); updateURLConnection(connection, href); connection.connect(); return new StreamSource(connection.getInputStream(), effURL); } catch (FileNotFoundException fnfe) { // Note: This is on "debug" level since the caller is // supposed to handle this log.debug("File not found: " + effURL); } catch (java.io.IOException ioe) { log.error("Error with opening URL '" + effURL + "': " + ioe.getMessage()); } } } return source; }
// in src/java/org/apache/fop/servlet/FopPrintServlet.java
protected void render(Source src, Transformer transformer, HttpServletResponse response) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_FOP_PRINT, foUserAgent); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer.transform(src, res); //Return the result reportOK(response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void renderFO(String fo, HttpServletResponse response) throws FOPException, TransformerException, IOException { //Setup source Source foSrc = convertString2Source(fo); //Setup the identity transformation Transformer transformer = this.transFactory.newTransformer(); transformer.setURIResolver(this.uriResolver); //Start transformation and rendering process render(foSrc, transformer, response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void renderXML(String xml, String xslt, HttpServletResponse response) throws FOPException, TransformerException, IOException { //Setup sources Source xmlSrc = convertString2Source(xml); Source xsltSrc = convertString2Source(xslt); //Setup the XSL transformation Transformer transformer = this.transFactory.newTransformer(xsltSrc); transformer.setURIResolver(this.uriResolver); //Start transformation and rendering process render(xmlSrc, transformer, response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void render(Source src, Transformer transformer, HttpServletResponse response) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(); //Setup output ByteArrayOutputStream out = new ByteArrayOutputStream(); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer.transform(src, res); //Return the result sendPDF(out.toByteArray(), response); }
// in src/java/org/apache/fop/servlet/ServletContextURIResolver.java
public Source resolve(String href, String base) throws TransformerException { if (href.startsWith(SERVLET_CONTEXT_PROTOCOL)) { return resolveServletContextURI(href.substring(SERVLET_CONTEXT_PROTOCOL.length())); } else { if (base != null && base.startsWith(SERVLET_CONTEXT_PROTOCOL) && (href.indexOf(':') < 0)) { String abs = base + href; return resolveServletContextURI( abs.substring(SERVLET_CONTEXT_PROTOCOL.length())); } else { return null; } } }
// in src/java/org/apache/fop/servlet/ServletContextURIResolver.java
protected Source resolveServletContextURI(String path) throws TransformerException { while (path.startsWith("//")) { path = path.substring(1); } try { URL url = this.servletContext.getResource(path); InputStream in = this.servletContext.getResourceAsStream(path); if (in != null) { if (url != null) { return new StreamSource(in, url.toExternalForm()); } else { return new StreamSource(in); } } else { throw new TransformerException("Resource does not exist. \"" + path + "\" is not accessible through the servlet context."); } } catch (MalformedURLException mfue) { throw new TransformerException( "Error accessing resource using servlet context: " + path, mfue); } }
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
public void writeFontXML(org.w3c.dom.Document doc, String target) throws TransformerException { writeFontXML(doc, new File(target)); }
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
public void writeFontXML(org.w3c.dom.Document doc, File target) throws TransformerException { log.info("Writing xml font file " + target + "..."); try { OutputStream out = new java.io.FileOutputStream(target); out = new java.io.BufferedOutputStream(out); try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.transform( new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(out)); } finally { out.close(); } } catch (IOException ioe) { throw new TransformerException("Error writing the output file", ioe); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void parse(Source src, IFDocumentHandler documentHandler, FOUserAgent userAgent) throws TransformerException, IFException { try { Transformer transformer = tFactory.newTransformer(); transformer.setErrorListener(new DefaultErrorListener(log)); SAXResult res = new SAXResult(getContentHandler(documentHandler, userAgent)); transformer.transform(src, res); } catch (TransformerException te) { //Unpack original IFException if applicable if (te.getCause() instanceof SAXException) { SAXException se = (SAXException)te.getCause(); if (se.getCause() instanceof IFException) { throw (IFException)se.getCause(); } } else if (te.getCause() instanceof IFException) { throw (IFException)te.getCause(); } throw te; } }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void appendDocument(Source src) throws TransformerException, IFException { IFParser parser = new IFParser(); parser.parse(src, new IFPageSequenceFilter(getTargetHandler()), getTargetHandler().getContext().getUserAgent()); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
public static EventModel parse(Source src) throws TransformerException { Transformer transformer = tFactory.newTransformer(); transformer.setErrorListener(new DefaultErrorListener(LOG)); EventModel model = new EventModel(); SAXResult res = new SAXResult(getContentHandler(model)); transformer.transform(src, res); return model; }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void parse(Source src, AreaTreeModel treeModel, FOUserAgent userAgent) throws TransformerException { Transformer transformer = tFactory.newTransformer(); transformer.setErrorListener(new DefaultErrorListener(log)); SAXResult res = new SAXResult(getContentHandler(treeModel, userAgent)); transformer.transform(src, res); }
// in src/java/org/apache/fop/util/DataURIResolver.java
public Source resolve(String href, String base) throws TransformerException { return newResolver.resolve(href, base); }
// in src/java/org/apache/fop/util/DefaultErrorListener.java
public void error(TransformerException exc) throws TransformerException { throw exc; }
// in src/java/org/apache/fop/util/DefaultErrorListener.java
public void fatalError(TransformerException exc) throws TransformerException { throw exc; }
// in src/java/org/apache/fop/cli/InputHandler.java
public void fatalError(TransformerException exc) throws TransformerException { throw exc; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
protected void updateTranslationFile(File modelFile) throws IOException { try { boolean resultExists = getTranslationFile().exists(); SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); //Generate fresh generated translation file as template Source src = new StreamSource(modelFile.toURI().toURL().toExternalForm()); StreamSource xslt1 = new StreamSource( getClass().getResourceAsStream(MODEL2TRANSLATION)); if (xslt1.getInputStream() == null) { throw new FileNotFoundException(MODEL2TRANSLATION + " not found"); } DOMResult domres = new DOMResult(); Transformer transformer = tFactory.newTransformer(xslt1); transformer.transform(src, domres); final Node generated = domres.getNode(); Node sourceDocument; if (resultExists) { //Load existing translation file into memory (because we overwrite it later) src = new StreamSource(getTranslationFile().toURI().toURL().toExternalForm()); domres = new DOMResult(); transformer = tFactory.newTransformer(); transformer.transform(src, domres); sourceDocument = domres.getNode(); } else { //Simply use generated as source document sourceDocument = generated; } //Generate translation file (with potentially new translations) src = new DOMSource(sourceDocument); //The following triggers a bug in older Xalan versions //Result res = new StreamResult(getTranslationFile()); OutputStream out = new java.io.FileOutputStream(getTranslationFile()); out = new java.io.BufferedOutputStream(out); Result res = new StreamResult(out); try { StreamSource xslt2 = new StreamSource( getClass().getResourceAsStream(MERGETRANSLATION)); if (xslt2.getInputStream() == null) { throw new FileNotFoundException(MERGETRANSLATION + " not found"); } transformer = tFactory.newTransformer(xslt2); transformer.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { if ("my:dom".equals(href)) { return new DOMSource(generated); } return null; } }); if (resultExists) { transformer.setParameter("generated-url", "my:dom"); } transformer.transform(src, res); if (resultExists) { log("Translation file updated: " + getTranslationFile()); } else { log("Translation file generated: " + getTranslationFile()); } } finally { IOUtils.closeQuietly(out); } } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
public Source resolve(String href, String base) throws TransformerException { if ("my:dom".equals(href)) { return new DOMSource(generated); } return null; }
(Lib) CascadingRuntimeException 3
              
// in src/java/org/apache/fop/pdf/PDFText.java
public static final String escapeText(final String text, boolean forceHexMode) { if (text != null && text.length() > 0) { boolean unicode = false; boolean hexMode = false; if (forceHexMode) { hexMode = true; } else { for (int i = 0, c = text.length(); i < c; i++) { if (text.charAt(i) >= 128) { unicode = true; hexMode = true; break; } } } if (hexMode) { final byte[] uniBytes; try { uniBytes = text.getBytes("UTF-16"); } catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); } return toHex(uniBytes); } else { final StringBuffer result = new StringBuffer(text.length() * 2); result.append("("); final int l = text.length(); if (unicode) { // byte order marker (0xfeff) result.append("\\376\\377"); for (int i = 0; i < l; i++) { final char ch = text.charAt(i); final int high = (ch & 0xff00) >>> 8; final int low = ch & 0xff; result.append("\\"); result.append(Integer.toOctalString(high)); result.append("\\"); result.append(Integer.toOctalString(low)); } } else { for (int i = 0; i < l; i++) { final char ch = text.charAt(i); if (ch < 256) { escapeStringChar(ch, result); } else { throw new IllegalStateException( "Can only treat text in 8-bit ASCII/PDFEncoding"); } } } result.append(")"); return result.toString(); } } return "()"; }
// in src/java/org/apache/fop/pdf/PDFText.java
public static final byte[] toUTF16(String text) { try { return text.getBytes("UnicodeBig"); } catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); } }
// in src/java/org/apache/fop/pdf/PDFText.java
public static final String toUnicodeHex(char c) { final StringBuffer buf = new StringBuffer(4); final byte[] uniBytes; try { final char[] a = {c}; uniBytes = new String(a).getBytes("UTF-16BE"); } catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); } for (int i = 0; i < uniBytes.length; i++) { buf.append(DIGITS[(uniBytes[i] >>> 4) & 0x0F]); buf.append(DIGITS[uniBytes[i] & 0x0F]); } return buf.toString(); }
3
              
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
0
(Lib) DSCException 3
              
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
public void process(InputStream in, OutputStream out, int pageCount, Rectangle2D documentBoundingBox) throws DSCException, IOException { DSCParser parser = new DSCParser(in); PSGenerator gen = new PSGenerator(out); parser.addListener(new DefaultNestedDocumentHandler(gen)); parser.addListener(new IncludeResourceListener(gen)); //Skip DSC header DSCHeaderComment header = DSCTools.checkAndSkipDSC30Header(parser); header.generate(gen); parser.setFilter(new DSCFilter() { private final Set filtered = new java.util.HashSet(); { //We rewrite those as part of the processing filtered.add(DSCConstants.PAGES); filtered.add(DSCConstants.BBOX); filtered.add(DSCConstants.HIRES_BBOX); filtered.add(DSCConstants.DOCUMENT_NEEDED_RESOURCES); filtered.add(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES); } public boolean accept(DSCEvent event) { if (event.isDSCComment()) { //Filter %%Pages which we add manually from a parameter return !(filtered.contains(event.asDSCComment().getName())); } else { return true; } } }); //Get PostScript language level (may be missing) while (true) { DSCEvent event = parser.nextEvent(); if (event == null) { reportInvalidDSC(); } if (DSCTools.headerCommentsEndHere(event)) { //Set number of pages DSCCommentPages pages = new DSCCommentPages(pageCount); pages.generate(gen); new DSCCommentBoundingBox(documentBoundingBox).generate(gen); new DSCCommentHiResBoundingBox(documentBoundingBox).generate(gen); PSFontUtils.determineSuppliedFonts(resTracker, fontInfo, fontInfo.getUsedFonts()); registerSuppliedForms(resTracker, globalFormResources); //Supplied Resources DSCCommentDocumentSuppliedResources supplied = new DSCCommentDocumentSuppliedResources( resTracker.getDocumentSuppliedResources()); supplied.generate(gen); //Needed Resources DSCCommentDocumentNeededResources needed = new DSCCommentDocumentNeededResources( resTracker.getDocumentNeededResources()); needed.generate(gen); //Write original comment that ends the header comments event.generate(gen); break; } if (event.isDSCComment()) { DSCComment comment = event.asDSCComment(); if (DSCConstants.LANGUAGE_LEVEL.equals(comment.getName())) { DSCCommentLanguageLevel level = (DSCCommentLanguageLevel)comment; gen.setPSLevel(level.getLanguageLevel()); } } event.generate(gen); } //Skip to the FOPFontSetup PostScriptComment fontSetupPlaceholder = parser.nextPSComment("FOPFontSetup", gen); if (fontSetupPlaceholder == null) { throw new DSCException("Didn't find %FOPFontSetup comment in stream"); } PSFontUtils.writeFontDict(gen, fontInfo, fontInfo.getUsedFonts()); generateForms(globalFormResources, gen); //Skip the prolog and to the first page DSCComment pageOrTrailer = parser.nextDSCComment(DSCConstants.PAGE, gen); if (pageOrTrailer == null) { throw new DSCException("Page expected, but none found"); } //Process individual pages (and skip as necessary) while (true) { DSCCommentPage page = (DSCCommentPage)pageOrTrailer; page.generate(gen); pageOrTrailer = DSCTools.nextPageOrTrailer(parser, gen); if (pageOrTrailer == null) { reportInvalidDSC(); } else if (!DSCConstants.PAGE.equals(pageOrTrailer.getName())) { pageOrTrailer.generate(gen); break; } } //Write the rest while (parser.hasNext()) { DSCEvent event = parser.nextEvent(); event.generate(gen); } gen.flush(); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private static void reportInvalidDSC() throws DSCException { throw new DSCException("File is not DSC-compliant: Unexpected end of file"); }
0 3
              
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
public void process(InputStream in, OutputStream out, int pageCount, Rectangle2D documentBoundingBox) throws DSCException, IOException { DSCParser parser = new DSCParser(in); PSGenerator gen = new PSGenerator(out); parser.addListener(new DefaultNestedDocumentHandler(gen)); parser.addListener(new IncludeResourceListener(gen)); //Skip DSC header DSCHeaderComment header = DSCTools.checkAndSkipDSC30Header(parser); header.generate(gen); parser.setFilter(new DSCFilter() { private final Set filtered = new java.util.HashSet(); { //We rewrite those as part of the processing filtered.add(DSCConstants.PAGES); filtered.add(DSCConstants.BBOX); filtered.add(DSCConstants.HIRES_BBOX); filtered.add(DSCConstants.DOCUMENT_NEEDED_RESOURCES); filtered.add(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES); } public boolean accept(DSCEvent event) { if (event.isDSCComment()) { //Filter %%Pages which we add manually from a parameter return !(filtered.contains(event.asDSCComment().getName())); } else { return true; } } }); //Get PostScript language level (may be missing) while (true) { DSCEvent event = parser.nextEvent(); if (event == null) { reportInvalidDSC(); } if (DSCTools.headerCommentsEndHere(event)) { //Set number of pages DSCCommentPages pages = new DSCCommentPages(pageCount); pages.generate(gen); new DSCCommentBoundingBox(documentBoundingBox).generate(gen); new DSCCommentHiResBoundingBox(documentBoundingBox).generate(gen); PSFontUtils.determineSuppliedFonts(resTracker, fontInfo, fontInfo.getUsedFonts()); registerSuppliedForms(resTracker, globalFormResources); //Supplied Resources DSCCommentDocumentSuppliedResources supplied = new DSCCommentDocumentSuppliedResources( resTracker.getDocumentSuppliedResources()); supplied.generate(gen); //Needed Resources DSCCommentDocumentNeededResources needed = new DSCCommentDocumentNeededResources( resTracker.getDocumentNeededResources()); needed.generate(gen); //Write original comment that ends the header comments event.generate(gen); break; } if (event.isDSCComment()) { DSCComment comment = event.asDSCComment(); if (DSCConstants.LANGUAGE_LEVEL.equals(comment.getName())) { DSCCommentLanguageLevel level = (DSCCommentLanguageLevel)comment; gen.setPSLevel(level.getLanguageLevel()); } } event.generate(gen); } //Skip to the FOPFontSetup PostScriptComment fontSetupPlaceholder = parser.nextPSComment("FOPFontSetup", gen); if (fontSetupPlaceholder == null) { throw new DSCException("Didn't find %FOPFontSetup comment in stream"); } PSFontUtils.writeFontDict(gen, fontInfo, fontInfo.getUsedFonts()); generateForms(globalFormResources, gen); //Skip the prolog and to the first page DSCComment pageOrTrailer = parser.nextDSCComment(DSCConstants.PAGE, gen); if (pageOrTrailer == null) { throw new DSCException("Page expected, but none found"); } //Process individual pages (and skip as necessary) while (true) { DSCCommentPage page = (DSCCommentPage)pageOrTrailer; page.generate(gen); pageOrTrailer = DSCTools.nextPageOrTrailer(parser, gen); if (pageOrTrailer == null) { reportInvalidDSC(); } else if (!DSCConstants.PAGE.equals(pageOrTrailer.getName())) { pageOrTrailer.generate(gen); break; } } //Write the rest while (parser.hasNext()) { DSCEvent event = parser.nextEvent(); event.generate(gen); } gen.flush(); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private static void reportInvalidDSC() throws DSCException { throw new DSCException("File is not DSC-compliant: Unexpected end of file"); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
public void processEvent(DSCEvent event, DSCParser parser) throws IOException, DSCException { if (event.isDSCComment() && event instanceof DSCCommentIncludeResource) { DSCCommentIncludeResource include = (DSCCommentIncludeResource)event; PSResource res = include.getResource(); if (res.getType().equals(PSResource.TYPE_FORM)) { if (inlineFormResources.containsValue(res)) { PSImageFormResource form = (PSImageFormResource) inlineFormResources.get(res); //Create an inline form //Wrap in save/restore pair to release memory gen.writeln("save"); generateFormForImage(gen, form); boolean execformFound = false; DSCEvent next = parser.nextEvent(); if (next.isLine()) { PostScriptLine line = next.asLine(); if (line.getLine().endsWith(" execform")) { line.generate(gen); execformFound = true; } } if (!execformFound) { throw new IOException( "Expected a PostScript line in the form: <form> execform"); } gen.writeln("restore"); } else { //Do nothing } parser.next(); } } }
(Domain) EventConventionException 3
              
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
private EventMethodModel createMethodModel(JavaMethod method) throws EventConventionException, ClassNotFoundException { JavaClass clazz = method.getParentClass(); //Check EventProducer conventions if (!method.getReturnType().isVoid()) { throw new EventConventionException("All methods of interface " + clazz.getFullyQualifiedName() + " must have return type 'void'!"); } String methodSig = clazz.getFullyQualifiedName() + "." + method.getCallSignature(); JavaParameter[] params = method.getParameters(); if (params.length < 1) { throw new EventConventionException("The method " + methodSig + " must have at least one parameter: 'Object source'!"); } Type firstType = params[0].getType(); if (firstType.isPrimitive() || !"source".equals(params[0].getName())) { throw new EventConventionException("The first parameter of the method " + methodSig + " must be: 'Object source'!"); } //build method model DocletTag tag = method.getTagByName("event.severity"); EventSeverity severity; if (tag != null) { severity = EventSeverity.valueOf(tag.getValue()); } else { severity = EventSeverity.INFO; } EventMethodModel methodMeta = new EventMethodModel( method.getName(), severity); if (params.length > 1) { for (int j = 1, cj = params.length; j < cj; j++) { JavaParameter p = params[j]; Class<?> type; JavaClass pClass = p.getType().getJavaClass(); if (p.getType().isPrimitive()) { type = PRIMITIVE_MAP.get(pClass.getName()); if (type == null) { throw new UnsupportedOperationException( "Primitive datatype not supported: " + pClass.getName()); } } else { String className = pClass.getFullyQualifiedName(); type = Class.forName(className); } methodMeta.addParameter(type, p.getName()); } } Type[] exceptions = method.getExceptions(); if (exceptions != null && exceptions.length > 0) { //We only use the first declared exception because that is always thrown JavaClass cl = exceptions[0].getJavaClass(); methodMeta.setExceptionClass(cl.getFullyQualifiedName()); methodMeta.setSeverity(EventSeverity.FATAL); //In case it's not set in the comments } return methodMeta; }
0 4
              
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
protected long processFileSets(EventProducerCollector collector) throws IOException, EventConventionException, ClassNotFoundException { long lastModified = 0; Iterator<FileSet> iter = filesets.iterator(); while (iter.hasNext()) { FileSet fs = (FileSet)iter.next(); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); String[] srcFiles = ds.getIncludedFiles(); File directory = fs.getDir(getProject()); for (int i = 0, c = srcFiles.length; i < c; i++) { String filename = srcFiles[i]; File src = new File(directory, filename); boolean eventProducerFound = collector.scanFile(src); if (eventProducerFound) { lastModified = Math.max(lastModified, src.lastModified()); } } } return lastModified; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
public boolean scanFile(File src) throws IOException, EventConventionException, ClassNotFoundException { JavaDocBuilder builder = new JavaDocBuilder(this.tagFactory); builder.addSource(src); JavaClass[] classes = builder.getClasses(); boolean eventProducerFound = false; for (int i = 0, c = classes.length; i < c; i++) { JavaClass clazz = classes[i]; if (clazz.isInterface() && implementsInterface(clazz, CLASSNAME_EVENT_PRODUCER)) { processEventProducerInterface(clazz); eventProducerFound = true; } } return eventProducerFound; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
protected void processEventProducerInterface(JavaClass clazz) throws EventConventionException, ClassNotFoundException { EventProducerModel prodMeta = new EventProducerModel(clazz.getFullyQualifiedName()); JavaMethod[] methods = clazz.getMethods(true); for (int i = 0, c = methods.length; i < c; i++) { JavaMethod method = methods[i]; EventMethodModel methodMeta = createMethodModel(method); prodMeta.addMethod(methodMeta); } EventModel model = new EventModel(); model.addProducer(prodMeta); models.add(model); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
private EventMethodModel createMethodModel(JavaMethod method) throws EventConventionException, ClassNotFoundException { JavaClass clazz = method.getParentClass(); //Check EventProducer conventions if (!method.getReturnType().isVoid()) { throw new EventConventionException("All methods of interface " + clazz.getFullyQualifiedName() + " must have return type 'void'!"); } String methodSig = clazz.getFullyQualifiedName() + "." + method.getCallSignature(); JavaParameter[] params = method.getParameters(); if (params.length < 1) { throw new EventConventionException("The method " + methodSig + " must have at least one parameter: 'Object source'!"); } Type firstType = params[0].getType(); if (firstType.isPrimitive() || !"source".equals(params[0].getName())) { throw new EventConventionException("The first parameter of the method " + methodSig + " must be: 'Object source'!"); } //build method model DocletTag tag = method.getTagByName("event.severity"); EventSeverity severity; if (tag != null) { severity = EventSeverity.valueOf(tag.getValue()); } else { severity = EventSeverity.INFO; } EventMethodModel methodMeta = new EventMethodModel( method.getName(), severity); if (params.length > 1) { for (int j = 1, cj = params.length; j < cj; j++) { JavaParameter p = params[j]; Class<?> type; JavaClass pClass = p.getType().getJavaClass(); if (p.getType().isPrimitive()) { type = PRIMITIVE_MAP.get(pClass.getName()); if (type == null) { throw new UnsupportedOperationException( "Primitive datatype not supported: " + pClass.getName()); } } else { String className = pClass.getFullyQualifiedName(); type = Class.forName(className); } methodMeta.addParameter(type, p.getName()); } } Type[] exceptions = method.getExceptions(); if (exceptions != null && exceptions.length > 0) { //We only use the first declared exception because that is always thrown JavaClass cl = exceptions[0].getJavaClass(); methodMeta.setExceptionClass(cl.getFullyQualifiedName()); methodMeta.setSeverity(EventSeverity.FATAL); //In case it's not set in the comments } return methodMeta; }
(Domain) MaximumSizeExceededException 3
              
// in src/java/org/apache/fop/afp/modca/MapPageSegment.java
public void addPageSegment(String name) throws MaximumSizeExceededException { if (getPageSegments().size() > MAX_SIZE) { throw new MaximumSizeExceededException(); } if (name.length() > 8) { throw new IllegalArgumentException("The name of page segment " + name + " must not be longer than 8 characters"); } if (LOG.isDebugEnabled()) { LOG.debug("addPageSegment():: adding page segment " + name); } getPageSegments().add(name); }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
public void addFont(int fontReference, AFPFont font, int size, int orientation) throws MaximumSizeExceededException { FontDefinition fontDefinition = new FontDefinition(); fontDefinition.fontReferenceKey = BinaryUtils.convert(fontReference)[0]; switch (orientation) { case 90: fontDefinition.orientation = 0x2D; break; case 180: fontDefinition.orientation = 0x5A; break; case 270: fontDefinition.orientation = (byte) 0x87; break; default: fontDefinition.orientation = 0x00; break; } try { if (font instanceof RasterFont) { RasterFont raster = (RasterFont) font; CharacterSet cs = raster.getCharacterSet(size); if (cs == null) { String msg = "Character set not found for font " + font.getFontName() + " with point size " + size; LOG.error(msg); throw new FontRuntimeException(msg); } fontDefinition.characterSet = cs.getNameBytes(); if (fontDefinition.characterSet.length != 8) { throw new IllegalArgumentException("The character set " + new String(fontDefinition.characterSet, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof OutlineFont) { OutlineFont outline = (OutlineFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof DoubleByteFont) { DoubleByteFont outline = (DoubleByteFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); //TODO Relax requirement for 8 characters if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else { String msg = "Font of type " + font.getClass().getName() + " not recognized."; LOG.error(msg); throw new FontRuntimeException(msg); } if (fontList.size() > 253) { // Throw an exception if the size is exceeded throw new MaximumSizeExceededException(); } else { fontList.add(fontDefinition); } } catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); } }
// in src/java/org/apache/fop/afp/modca/MapPageOverlay.java
public void addOverlay(String name) throws MaximumSizeExceededException { if (getOverlays().size() > MAX_SIZE) { throw new MaximumSizeExceededException(); } if (name.length() != 8) { throw new IllegalArgumentException("The name of overlay " + name + " must be 8 characters"); } if (LOG.isDebugEnabled()) { LOG.debug("addOverlay():: adding overlay " + name); } try { byte[] data = name.getBytes(AFPConstants.EBCIDIC_ENCODING); getOverlays().add(data); } catch (UnsupportedEncodingException usee) { LOG.error("addOverlay():: UnsupportedEncodingException translating the name " + name); } }
0 3
              
// in src/java/org/apache/fop/afp/modca/MapPageSegment.java
public void addPageSegment(String name) throws MaximumSizeExceededException { if (getPageSegments().size() > MAX_SIZE) { throw new MaximumSizeExceededException(); } if (name.length() > 8) { throw new IllegalArgumentException("The name of page segment " + name + " must not be longer than 8 characters"); } if (LOG.isDebugEnabled()) { LOG.debug("addPageSegment():: adding page segment " + name); } getPageSegments().add(name); }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
public void addFont(int fontReference, AFPFont font, int size, int orientation) throws MaximumSizeExceededException { FontDefinition fontDefinition = new FontDefinition(); fontDefinition.fontReferenceKey = BinaryUtils.convert(fontReference)[0]; switch (orientation) { case 90: fontDefinition.orientation = 0x2D; break; case 180: fontDefinition.orientation = 0x5A; break; case 270: fontDefinition.orientation = (byte) 0x87; break; default: fontDefinition.orientation = 0x00; break; } try { if (font instanceof RasterFont) { RasterFont raster = (RasterFont) font; CharacterSet cs = raster.getCharacterSet(size); if (cs == null) { String msg = "Character set not found for font " + font.getFontName() + " with point size " + size; LOG.error(msg); throw new FontRuntimeException(msg); } fontDefinition.characterSet = cs.getNameBytes(); if (fontDefinition.characterSet.length != 8) { throw new IllegalArgumentException("The character set " + new String(fontDefinition.characterSet, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof OutlineFont) { OutlineFont outline = (OutlineFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof DoubleByteFont) { DoubleByteFont outline = (DoubleByteFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); //TODO Relax requirement for 8 characters if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else { String msg = "Font of type " + font.getClass().getName() + " not recognized."; LOG.error(msg); throw new FontRuntimeException(msg); } if (fontList.size() > 253) { // Throw an exception if the size is exceeded throw new MaximumSizeExceededException(); } else { fontList.add(fontDefinition); } } catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); } }
// in src/java/org/apache/fop/afp/modca/MapPageOverlay.java
public void addOverlay(String name) throws MaximumSizeExceededException { if (getOverlays().size() > MAX_SIZE) { throw new MaximumSizeExceededException(); } if (name.length() != 8) { throw new IllegalArgumentException("The name of overlay " + name + " must be 8 characters"); } if (LOG.isDebugEnabled()) { LOG.debug("addOverlay():: adding overlay " + name); } try { byte[] data = name.getBytes(AFPConstants.EBCIDIC_ENCODING); getOverlays().add(data); } catch (UnsupportedEncodingException usee) { LOG.error("addOverlay():: UnsupportedEncodingException translating the name " + name); } }
(Domain) PDFFilterException 3
              
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setColors(int colors) throws PDFFilterException { if (predictor != PREDICTION_NONE) { this.colors = colors; } else { throw new PDFFilterException( "Prediction must not be PREDICTION_NONE in" + " order to set Colors"); } }
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setBitsPerComponent(int bits) throws PDFFilterException { if (predictor != PREDICTION_NONE) { bitsPerComponent = bits; } else { throw new PDFFilterException( "Prediction must not be PREDICTION_NONE in order" + " to set bitsPerComponent"); } }
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setColumns(int columns) throws PDFFilterException { if (predictor != PREDICTION_NONE) { this.columns = columns; } else { throw new PDFFilterException( "Prediction must not be PREDICTION_NONE in" + " order to set Columns"); } }
0 4
              
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setPredictor(int predictor) throws PDFFilterException { this.predictor = predictor; }
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setColors(int colors) throws PDFFilterException { if (predictor != PREDICTION_NONE) { this.colors = colors; } else { throw new PDFFilterException( "Prediction must not be PREDICTION_NONE in" + " order to set Colors"); } }
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setBitsPerComponent(int bits) throws PDFFilterException { if (predictor != PREDICTION_NONE) { bitsPerComponent = bits; } else { throw new PDFFilterException( "Prediction must not be PREDICTION_NONE in order" + " to set bitsPerComponent"); } }
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setColumns(int columns) throws PDFFilterException { if (predictor != PREDICTION_NONE) { this.columns = columns; } else { throw new PDFFilterException( "Prediction must not be PREDICTION_NONE in" + " order to set Columns"); } }
(Domain) RtfStructureException 3
              
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfHeader startHeader() throws IOException, RtfStructureException { if (header != null) { throw new RtfStructureException("startHeader called more than once"); } header = new RtfHeader(this, writer); listTableContainer = new RtfContainer(this, writer); return header; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfPageArea startPageArea() throws IOException, RtfStructureException { if (pageArea != null) { throw new RtfStructureException("startPageArea called more than once"); } // create an empty header if there was none if (header == null) { startHeader(); } header.close(); pageArea = new RtfPageArea(this, writer); addChild(pageArea); return pageArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfDocumentArea startDocumentArea() throws IOException, RtfStructureException { if (docArea != null) { throw new RtfStructureException("startDocumentArea called more than once"); } // create an empty header if there was none if (header == null) { startHeader(); } header.close(); docArea = new RtfDocumentArea(this, writer); addChild(docArea); return docArea; }
0 6
              
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfHeader startHeader() throws IOException, RtfStructureException { if (header != null) { throw new RtfStructureException("startHeader called more than once"); } header = new RtfHeader(this, writer); listTableContainer = new RtfContainer(this, writer); return header; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfPageArea startPageArea() throws IOException, RtfStructureException { if (pageArea != null) { throw new RtfStructureException("startPageArea called more than once"); } // create an empty header if there was none if (header == null) { startHeader(); } header.close(); pageArea = new RtfPageArea(this, writer); addChild(pageArea); return pageArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfPageArea getPageArea() throws IOException, RtfStructureException { if (pageArea == null) { return startPageArea(); } return pageArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfDocumentArea startDocumentArea() throws IOException, RtfStructureException { if (docArea != null) { throw new RtfStructureException("startDocumentArea called more than once"); } // create an empty header if there was none if (header == null) { startHeader(); } header.close(); docArea = new RtfDocumentArea(this, writer); addChild(docArea); return docArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfDocumentArea getDocumentArea() throws IOException, RtfStructureException { if (docArea == null) { return startDocumentArea(); } return docArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfContainer.java
protected void addChild(RtfElement e) throws RtfStructureException { if (isClosed()) { // No childs should be added to a container that has been closed final StringBuffer sb = new StringBuffer(); sb.append("addChild: container already closed (parent="); sb.append(this.getClass().getName()); sb.append(" child="); sb.append(e.getClass().getName()); sb.append(")"); final String msg = sb.toString(); // warn of this problem final RtfFile rf = getRtfFile(); // if(rf.getLog() != null) { // rf.getLog().logWarning(msg); // } // TODO this should be activated to help detect XSL-FO constructs // that we do not handle properly. /* throw new RtfStructureException(msg); */ } children.add(e); lastChild = e; }
(Lib) ConfigurationException 2
              
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java
public void configure(PDFDocumentGraphics2D graphics, Configuration cfg, boolean useComplexScriptFeatures ) throws ConfigurationException { PDFDocument pdfDoc = graphics.getPDFDocument(); //Filter map pdfDoc.setFilterMap( PDFRendererConfigurator.buildFilterMapFromConfiguration(cfg)); //Fonts try { FontInfo fontInfo = createFontInfo(cfg, useComplexScriptFeatures); graphics.setFontInfo(fontInfo); } catch (FOPException e) { throw new ConfigurationException("Error while setting up fonts", e); } }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
public static Map buildFilterMapFromConfiguration(Configuration cfg) throws ConfigurationException { Map filterMap = new java.util.HashMap(); Configuration[] filterLists = cfg.getChildren("filterList"); for (int i = 0; i < filterLists.length; i++) { Configuration filters = filterLists[i]; String type = filters.getAttribute("type", null); Configuration[] filt = filters.getChildren("value"); List filterList = new java.util.ArrayList(); for (int j = 0; j < filt.length; j++) { String name = filt[j].getValue(); filterList.add(name); } if (type == null) { type = PDFFilterList.DEFAULT_FILTER; } if (!filterList.isEmpty() && log.isDebugEnabled()) { StringBuffer debug = new StringBuffer("Adding PDF filter"); if (filterList.size() != 1) { debug.append("s"); } debug.append(" for type ").append(type).append(": "); for (int j = 0; j < filterList.size(); j++) { if (j != 0) { debug.append(", "); } debug.append(filterList.get(j)); } log.debug(debug.toString()); } if (filterMap.get(type) != null) { throw new ConfigurationException("A filterList of type '" + type + "' has already been defined"); } filterMap.put(type, filterList); } return filterMap; }
1
              
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java
catch (FOPException e) { throw new ConfigurationException("Error while setting up fonts", e); }
6
              
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java
public void configure(PDFDocumentGraphics2D graphics, Configuration cfg, boolean useComplexScriptFeatures ) throws ConfigurationException { PDFDocument pdfDoc = graphics.getPDFDocument(); //Filter map pdfDoc.setFilterMap( PDFRendererConfigurator.buildFilterMapFromConfiguration(cfg)); //Fonts try { FontInfo fontInfo = createFontInfo(cfg, useComplexScriptFeatures); graphics.setFontInfo(fontInfo); } catch (FOPException e) { throw new ConfigurationException("Error while setting up fonts", e); } }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
public void configure(Configuration cfg) throws ConfigurationException { this.cfg = cfg; }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
public static Map buildFilterMapFromConfiguration(Configuration cfg) throws ConfigurationException { Map filterMap = new java.util.HashMap(); Configuration[] filterLists = cfg.getChildren("filterList"); for (int i = 0; i < filterLists.length; i++) { Configuration filters = filterLists[i]; String type = filters.getAttribute("type", null); Configuration[] filt = filters.getChildren("value"); List filterList = new java.util.ArrayList(); for (int j = 0; j < filt.length; j++) { String name = filt[j].getValue(); filterList.add(name); } if (type == null) { type = PDFFilterList.DEFAULT_FILTER; } if (!filterList.isEmpty() && log.isDebugEnabled()) { StringBuffer debug = new StringBuffer("Adding PDF filter"); if (filterList.size() != 1) { debug.append("s"); } debug.append(" for type ").append(type).append(": "); for (int j = 0; j < filterList.size(); j++) { if (j != 0) { debug.append(", "); } debug.append(filterList.get(j)); } log.debug(debug.toString()); } if (filterMap.get(type) != null) { throw new ConfigurationException("A filterList of type '" + type + "' has already been defined"); } filterMap.put(type, filterList); } return filterMap; }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private AFPFontInfo buildFont(Configuration fontCfg, String fontPath) throws ConfigurationException { FontManager fontManager = this.userAgent.getFactory().getFontManager(); Configuration[] triple = fontCfg.getChildren("font-triplet"); List<FontTriplet> tripletList = new ArrayList<FontTriplet>(); if (triple.length == 0) { eventProducer.fontConfigMissing(this, "<font-triplet...", fontCfg.getLocation()); return null; } for (Configuration config : triple) { int weight = FontUtil.parseCSS2FontWeight(config.getAttribute("weight")); FontTriplet triplet = new FontTriplet(config.getAttribute("name"), config.getAttribute("style"), weight); tripletList.add(triplet); } //build the fonts Configuration[] config = fontCfg.getChildren("afp-font"); if (config.length == 0) { eventProducer.fontConfigMissing(this, "<afp-font...", fontCfg.getLocation()); return null; } Configuration afpFontCfg = config[0]; URI baseURI = null; String uri = afpFontCfg.getAttribute("base-uri", fontPath); if (uri == null) { //Fallback for old attribute which only supports local filenames String path = afpFontCfg.getAttribute("path", fontPath); if (path != null) { File f = new File(path); baseURI = f.toURI(); } } else { try { baseURI = new URI(uri); } catch (URISyntaxException e) { eventProducer.invalidConfiguration(this, e); return null; } } ResourceAccessor accessor = new DefaultFOPResourceAccessor( this.userAgent, fontManager.getFontBaseURL(), baseURI); AFPFont font = null; try { String type = afpFontCfg.getAttribute("type"); if (type == null) { eventProducer.fontConfigMissing(this, "type attribute", fontCfg.getLocation()); return null; } String codepage = afpFontCfg.getAttribute("codepage"); if (codepage == null) { eventProducer.fontConfigMissing(this, "codepage attribute", fontCfg.getLocation()); return null; } String encoding = afpFontCfg.getAttribute("encoding"); if (encoding == null) { eventProducer.fontConfigMissing(this, "encoding attribute", fontCfg.getLocation()); return null; } font = fontFromType(type, codepage, encoding, accessor, afpFontCfg); } catch (ConfigurationException ce) { eventProducer.invalidConfiguration(this, ce); } catch (IOException ioe) { eventProducer.invalidConfiguration(this, ioe); } catch (IllegalArgumentException iae) { eventProducer.invalidConfiguration(this, iae); } return font != null ? new AFPFontInfo(font, tripletList) : null; }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private AFPFont fontFromType(String type, String codepage, String encoding, ResourceAccessor accessor, Configuration afpFontCfg) throws ConfigurationException, IOException { if ("raster".equalsIgnoreCase(type)) { String name = afpFontCfg.getAttribute("name", "Unknown"); // Create a new font object RasterFont font = new RasterFont(name); Configuration[] rasters = afpFontCfg.getChildren("afp-raster-font"); if (rasters.length == 0) { eventProducer.fontConfigMissing(this, "<afp-raster-font...", afpFontCfg.getLocation()); return null; } for (int j = 0; j < rasters.length; j++) { Configuration rasterCfg = rasters[j]; String characterset = rasterCfg.getAttribute("characterset"); if (characterset == null) { eventProducer.fontConfigMissing(this, "characterset attribute", afpFontCfg.getLocation()); return null; } float size = rasterCfg.getAttributeAsFloat("size"); int sizeMpt = (int) (size * 1000); String base14 = rasterCfg.getAttribute("base14-font", null); if (base14 != null) { try { Class<? extends Typeface> clazz = Class.forName( "org.apache.fop.fonts.base14." + base14).asSubclass(Typeface.class); try { Typeface tf = clazz.newInstance(); font.addCharacterSet(sizeMpt, CharacterSetBuilder.getSingleByteInstance() .build(characterset, codepage, encoding, tf, eventProducer)); } catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); } } catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); } } else { font.addCharacterSet(sizeMpt, CharacterSetBuilder.getSingleByteInstance() .buildSBCS(characterset, codepage, encoding, accessor, eventProducer)); } } return font; } else if ("outline".equalsIgnoreCase(type)) { String characterset = afpFontCfg.getAttribute("characterset"); if (characterset == null) { eventProducer.fontConfigMissing(this, "characterset attribute", afpFontCfg.getLocation()); return null; } String name = afpFontCfg.getAttribute("name", characterset); CharacterSet characterSet = null; String base14 = afpFontCfg.getAttribute("base14-font", null); if (base14 != null) { try { Class<? extends Typeface> clazz = Class.forName("org.apache.fop.fonts.base14." + base14).asSubclass(Typeface.class); try { Typeface tf = clazz.newInstance(); characterSet = CharacterSetBuilder.getSingleByteInstance() .build(characterset, codepage, encoding, tf, eventProducer); } catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); } } catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); } } else { characterSet = CharacterSetBuilder.getSingleByteInstance().buildSBCS( characterset, codepage, encoding, accessor, eventProducer); } // Return new font object return new OutlineFont(name, characterSet); } else if ("CIDKeyed".equalsIgnoreCase(type)) { String characterset = afpFontCfg.getAttribute("characterset"); if (characterset == null) { eventProducer.fontConfigMissing(this, "characterset attribute", afpFontCfg.getLocation()); return null; } String name = afpFontCfg.getAttribute("name", characterset); CharacterSet characterSet = null; CharacterSetType charsetType = afpFontCfg.getAttributeAsBoolean("ebcdic-dbcs", false) ? CharacterSetType.DOUBLE_BYTE_LINE_DATA : CharacterSetType.DOUBLE_BYTE; characterSet = CharacterSetBuilder.getDoubleByteInstance().buildDBCS(characterset, codepage, encoding, charsetType, accessor, eventProducer); // Create a new font object DoubleByteFont font = new DoubleByteFont(name, characterSet); return font; } else { log.error("No or incorrect type attribute: " + type); } return null; }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private List<AFPFontInfo> buildFontListFromConfiguration(Configuration cfg, AFPEventProducer eventProducer) throws FOPException, ConfigurationException { Configuration fonts = cfg.getChild("fonts"); FontManager fontManager = this.userAgent.getFactory().getFontManager(); // General matcher FontTriplet.Matcher referencedFontsMatcher = fontManager.getReferencedFontsMatcher(); // Renderer-specific matcher FontTriplet.Matcher localMatcher = null; // Renderer-specific referenced fonts Configuration referencedFontsCfg = fonts.getChild("referenced-fonts", false); if (referencedFontsCfg != null) { localMatcher = FontManagerConfigurator.createFontsMatcher( referencedFontsCfg, this.userAgent.getFactory().validateUserConfigStrictly()); } List<AFPFontInfo> fontList = new java.util.ArrayList<AFPFontInfo>(); Configuration[] font = fonts.getChildren("font"); final String fontPath = null; for (int i = 0; i < font.length; i++) { AFPFontInfo afi = buildFont(font[i], fontPath); if (afi != null) { if (log.isDebugEnabled()) { log.debug("Adding font " + afi.getAFPFont().getFontName()); } List<FontTriplet> fontTriplets = afi.getFontTriplets(); for (int j = 0; j < fontTriplets.size(); ++j) { FontTriplet triplet = fontTriplets.get(j); if (log.isDebugEnabled()) { log.debug(" Font triplet " + triplet.getName() + ", " + triplet.getStyle() + ", " + triplet.getWeight()); } if ((referencedFontsMatcher != null && referencedFontsMatcher.matches(triplet)) || (localMatcher != null && localMatcher.matches(triplet))) { afi.getAFPFont().setEmbeddable(false); break; } } fontList.add(afi); } } return fontList; }
(Lib) MalformedURLException 2
              
// in src/java/org/apache/fop/apps/FOURIResolver.java
public String checkBaseURL(String base) throws MalformedURLException { // replace back slash with forward slash to ensure windows file:/// URLS are supported base = base.replace('\\', '/'); if (!base.endsWith("/")) { // The behavior described by RFC 3986 regarding resolution of relative // references may be misleading for normal users: // file://path/to/resources + myResource.res -> file://path/to/myResource.res // file://path/to/resources/ + myResource.res -> file://path/to/resources/myResource.res // We assume that even when the ending slash is missing, users have the second // example in mind base += "/"; } File dir = new File(base); if (dir.isDirectory()) { return dir.toURI().toASCIIString(); } else { URI baseURI; try { baseURI = new URI(base); String scheme = baseURI.getScheme(); boolean directoryExists = true; if ("file".equals(scheme)) { dir = FileUtils.toFile(baseURI.toURL()); directoryExists = dir.isDirectory(); } if (scheme == null || !directoryExists) { String message = "base " + base + " is not a valid directory"; if (throwExceptions) { throw new MalformedURLException(message); } log.error(message); } return baseURI.toASCIIString(); } catch (URISyntaxException e) { //TODO not ideal: our base URLs are actually base URIs. throw new MalformedURLException(e.getMessage()); } } }
1
              
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (URISyntaxException e) { //TODO not ideal: our base URLs are actually base URIs. throw new MalformedURLException(e.getMessage()); }
9
              
// in src/java/org/apache/fop/apps/FOURIResolver.java
public String checkBaseURL(String base) throws MalformedURLException { // replace back slash with forward slash to ensure windows file:/// URLS are supported base = base.replace('\\', '/'); if (!base.endsWith("/")) { // The behavior described by RFC 3986 regarding resolution of relative // references may be misleading for normal users: // file://path/to/resources + myResource.res -> file://path/to/myResource.res // file://path/to/resources/ + myResource.res -> file://path/to/resources/myResource.res // We assume that even when the ending slash is missing, users have the second // example in mind base += "/"; } File dir = new File(base); if (dir.isDirectory()) { return dir.toURI().toASCIIString(); } else { URI baseURI; try { baseURI = new URI(base); String scheme = baseURI.getScheme(); boolean directoryExists = true; if ("file".equals(scheme)) { dir = FileUtils.toFile(baseURI.toURL()); directoryExists = dir.isDirectory(); } if (scheme == null || !directoryExists) { String message = "base " + base + " is not a valid directory"; if (throwExceptions) { throw new MalformedURLException(message); } log.error(message); } return baseURI.toASCIIString(); } catch (URISyntaxException e) { //TODO not ideal: our base URLs are actually base URIs. throw new MalformedURLException(e.getMessage()); } } }
// in src/java/org/apache/fop/apps/FopFactory.java
Override public void setFontBaseURL(String fontBase) throws MalformedURLException { super.setFontBaseURL(getFOURIResolver().checkBaseURL(fontBase)); }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setBaseURL(String base) throws MalformedURLException { this.base = foURIResolver.checkBaseURL(base); }
// in src/java/org/apache/fop/apps/FopFactory.java
Deprecated public void setFontBaseURL(String fontBase) throws MalformedURLException { getFontManager().setFontBaseURL(fontBase); }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setHyphenBaseURL(final String hyphenBase) throws MalformedURLException { if (hyphenBase != null) { setHyphenationTreeResolver( new HyphenationTreeResolver() { public Source resolve(String href) { return resolveURI(href, hyphenBase); } }); }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
private URL[] createUrls(String mainJar) throws MalformedURLException { ArrayList urls = new ArrayList(); urls.add(new File(mainJar).toURI().toURL()); File[] libFiles = new File("lib").listFiles(); for (int i = 0; i < libFiles.length; i++) { if (libFiles[i].getPath().endsWith(".jar")) { urls.add(libFiles[i].toURI().toURL()); } } return (URL[]) urls.toArray(new URL[urls.size()]); }
// in src/java/org/apache/fop/fonts/FontManager.java
public void setFontBaseURL(String fontBase) throws MalformedURLException { this.fontBase = fontBase; }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static InputStream openFontUri(FontResolver resolver, String uri) throws IOException, MalformedURLException { InputStream in = null; if (resolver != null) { Source source = resolver.resolve(uri); if (source == null) { String err = "Cannot load font: failed to create Source for font file " + uri; throw new IOException(err); } if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null && source.getSystemId() != null) { in = new java.net.URL(source.getSystemId()).openStream(); } if (in == null) { String err = "Cannot load font: failed to create InputStream from" + " Source for font file " + uri; throw new IOException(err); } } else { in = new URL(uri).openStream(); } return in; }
// in src/java/org/apache/fop/cli/Main.java
public static URL[] getJARList() throws MalformedURLException { String fopHome = System.getProperty("fop.home"); File baseDir; if (fopHome != null) { baseDir = new File(fopHome).getAbsoluteFile(); } else { baseDir = new File(".").getAbsoluteFile().getParentFile(); } File buildDir; if ("build".equals(baseDir.getName())) { buildDir = baseDir; baseDir = baseDir.getParentFile(); } else { buildDir = new File(baseDir, "build"); } File fopJar = new File(buildDir, "fop.jar"); if (!fopJar.exists()) { fopJar = new File(baseDir, "fop.jar"); } if (!fopJar.exists()) { throw new RuntimeException("fop.jar not found in directory: " + baseDir.getAbsolutePath() + " (or below)"); } List jars = new java.util.ArrayList(); jars.add(fopJar.toURI().toURL()); File[] files; FileFilter filter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".jar"); } }; File libDir = new File(baseDir, "lib"); if (!libDir.exists()) { libDir = baseDir; } files = libDir.listFiles(filter); if (files != null) { for (int i = 0, size = files.length; i < size; i++) { jars.add(files[i].toURI().toURL()); } } String optionalLib = System.getProperty("fop.optional.lib"); if (optionalLib != null) { files = new File(optionalLib).listFiles(filter); if (files != null) { for (int i = 0, size = files.length; i < size; i++) { jars.add(files[i].toURI().toURL()); } } } URL[] urls = (URL[])jars.toArray(new URL[jars.size()]); /* for (int i = 0, c = urls.length; i < c; i++) { System.out.println(urls[i]); }*/ return urls; }
(Domain) PageProductionException 2
              
// in src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java
public SimplePageMaster getNextSimplePageMaster(boolean isOddPage, boolean isFirstPage, boolean isLastPage, boolean isBlankPage, String mainFlowName) throws PageProductionException { if (currentSubSequence == null) { currentSubSequence = getNextSubSequence(); if (currentSubSequence == null) { blockLevelEventProducer.missingSubsequencesInPageSequenceMaster(this, masterName, getLocator()); } if (currentSubSequence.isInfinite() && !currentSubSequence.canProcess(mainFlowName)) { throw new PageProductionException( "The current sub-sequence will not terminate whilst processing then main flow"); } } SimplePageMaster pageMaster = currentSubSequence .getNextPageMaster(isOddPage, isFirstPage, isLastPage, isBlankPage); boolean canRecover = true; while (pageMaster == null) { SubSequenceSpecifier nextSubSequence = getNextSubSequence(); if (nextSubSequence == null) { //Sub-sequence exhausted so attempt to reuse it blockLevelEventProducer.pageSequenceMasterExhausted(this, masterName, canRecover & currentSubSequence.isReusable(), getLocator()); currentSubSequence.reset(); if (!currentSubSequence.canProcess(mainFlowName)) { throw new PageProductionException( "The last simple-page-master does not reference the main flow"); } canRecover = false; } else { currentSubSequence = nextSubSequence; } pageMaster = currentSubSequence .getNextPageMaster(isOddPage, isFirstPage, isLastPage, isBlankPage); } return pageMaster; }
0 2
              
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
public SimplePageMaster getNextSimplePageMaster (int page, boolean isFirstPage, boolean isLastPage, boolean isBlank) throws PageProductionException { if (pageSequenceMaster == null) { return simplePageMaster; } boolean isOddPage = ((page % 2) == 1); if (log.isDebugEnabled()) { log.debug("getNextSimplePageMaster(page=" + page + " isOdd=" + isOddPage + " isFirst=" + isFirstPage + " isLast=" + isLastPage + " isBlank=" + isBlank + ")"); } return pageSequenceMaster.getNextSimplePageMaster(isOddPage, isFirstPage, isLastPage, isBlank, getMainFlow().getFlowName()); }
// in src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java
public SimplePageMaster getNextSimplePageMaster(boolean isOddPage, boolean isFirstPage, boolean isLastPage, boolean isBlankPage, String mainFlowName) throws PageProductionException { if (currentSubSequence == null) { currentSubSequence = getNextSubSequence(); if (currentSubSequence == null) { blockLevelEventProducer.missingSubsequencesInPageSequenceMaster(this, masterName, getLocator()); } if (currentSubSequence.isInfinite() && !currentSubSequence.canProcess(mainFlowName)) { throw new PageProductionException( "The current sub-sequence will not terminate whilst processing then main flow"); } } SimplePageMaster pageMaster = currentSubSequence .getNextPageMaster(isOddPage, isFirstPage, isLastPage, isBlankPage); boolean canRecover = true; while (pageMaster == null) { SubSequenceSpecifier nextSubSequence = getNextSubSequence(); if (nextSubSequence == null) { //Sub-sequence exhausted so attempt to reuse it blockLevelEventProducer.pageSequenceMasterExhausted(this, masterName, canRecover & currentSubSequence.isReusable(), getLocator()); currentSubSequence.reset(); if (!currentSubSequence.canProcess(mainFlowName)) { throw new PageProductionException( "The last simple-page-master does not reference the main flow"); } canRecover = false; } else { currentSubSequence = nextSubSequence; } pageMaster = currentSubSequence .getNextPageMaster(isOddPage, isFirstPage, isLastPage, isBlankPage); } return pageMaster; }
(Lib) ArithmeticException 1
              
// in src/java/org/apache/fop/traits/MinOptMax.java
private void checkCompatibility(int thisElasticity, int operandElasticity, String msge) { if (thisElasticity < operandElasticity) { throw new ArithmeticException( "Cannot subtract a MinOptMax from another MinOptMax that has less " + msge + " (" + thisElasticity + " < " + operandElasticity + ")"); } }
0 1
              
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax minus(MinOptMax operand) throws ArithmeticException { checkCompatibility(getShrink(), operand.getShrink(), "shrink"); checkCompatibility(getStretch(), operand.getStretch(), "stretch"); return new MinOptMax(min - operand.min, opt - operand.opt, max - operand.max); }
(Lib) AssertionError 1
              
// in src/java/org/apache/fop/fo/FONode.java
protected Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(); // Can't happen } }
1
              
// in src/java/org/apache/fop/fo/FONode.java
catch (CloneNotSupportedException e) { throw new AssertionError(); // Can't happen }
0
(Lib) EOFException 7
              
// in src/java/org/apache/fop/fonts/type1/PFMInputStream.java
public String readString() throws IOException { InputStreamReader reader = new InputStreamReader(in, "ISO-8859-1"); StringBuffer buf = new StringBuffer(); int ch = reader.read(); while (ch > 0) { buf.append((char)ch); ch = reader.read(); } if (ch == -1) { throw new EOFException("Unexpected end of stream reached"); } return buf.toString(); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public void seekSet(long offset) throws IOException { if (offset > fsize || offset < 0) { throw new java.io.EOFException("Reached EOF, file size=" + fsize + " offset=" + offset); } current = (int)offset; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public byte read() throws IOException { if (current >= fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } final byte ret = file[current++]; return ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final void writeTTFUShort(long pos, int val) throws IOException { if ((pos + 2) > fsize) { throw new java.io.EOFException("Reached EOF"); } final byte b1 = (byte)((val >> 8) & 0xff); final byte b2 = (byte)(val & 0xff); final int fileIndex = (int) pos; file[fileIndex] = b1; file[fileIndex + 1] = b2; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final String readTTFString() throws IOException { int i = current; while (file[i++] != 0) { if (i > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } } byte[] tmp = new byte[i - current]; System.arraycopy(file, current, tmp, 0, i - current); return new String(tmp, "ISO-8859-1"); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final String readTTFString(int len) throws IOException { if ((len + current) > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } byte[] tmp = new byte[len]; System.arraycopy(file, current, tmp, 0, len); current += len; final String encoding; if ((tmp.length > 0) && (tmp[0] == 0)) { encoding = "UTF-16BE"; } else { encoding = "ISO-8859-1"; } return new String(tmp, encoding); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final String readTTFString(int len, int encodingID) throws IOException { if ((len + current) > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } byte[] tmp = new byte[len]; System.arraycopy(file, current, tmp, 0, len); current += len; final String encoding; encoding = "UTF-16BE"; //Use this for all known encoding IDs for now return new String(tmp, encoding); }
0 0
(Lib) Error 1
              
// in src/java/org/apache/fop/datatypes/URISpecification.java
public static String escapeURI(String uri) { uri = getURL(uri); StringBuffer sb = new StringBuffer(); for (int i = 0, c = uri.length(); i < c; i++) { char ch = uri.charAt(i); if (ch == '%') { if (i < c - 3 && isHexDigit(uri.charAt(i + 1)) && isHexDigit(uri.charAt(i + 2))) { sb.append(ch); continue; } } if (isReserved(ch) || isUnreserved(ch)) { //Note: this may not be accurate for some very special cases. sb.append(ch); } else { try { byte[] utf8 = Character.toString(ch).getBytes("UTF-8"); for (int j = 0, cj = utf8.length; j < cj; j++) { appendEscape(sb, utf8[j]); } } catch (UnsupportedEncodingException e) { throw new Error("Incompatible JVM. UTF-8 not supported."); } } } return sb.toString(); }
1
              
// in src/java/org/apache/fop/datatypes/URISpecification.java
catch (UnsupportedEncodingException e) { throw new Error("Incompatible JVM. UTF-8 not supported."); }
0
(Lib) ImageException 1
              
// in src/java/org/apache/fop/image/loader/batik/ImageConverterSVG2G2D.java
public Image convert(final Image src, Map hints) throws ImageException { checkSourceFlavor(src); final ImageXMLDOM svg = (ImageXMLDOM)src; if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(svg.getRootNamespace())) { throw new IllegalArgumentException("XML DOM is not in the SVG namespace: " + svg.getRootNamespace()); } //Prepare float pxToMillimeter = UnitConv.IN2MM / GraphicsConstants.DEFAULT_DPI; Number ptm = (Number)hints.get(ImageProcessingHints.SOURCE_RESOLUTION); if (ptm != null) { pxToMillimeter = (float)(UnitConv.IN2MM / ptm.doubleValue()); } UserAgent ua = createBatikUserAgent(pxToMillimeter); GVTBuilder builder = new GVTBuilder(); final ImageManager imageManager = (ImageManager)hints.get( ImageProcessingHints.IMAGE_MANAGER); final ImageSessionContext sessionContext = (ImageSessionContext)hints.get( ImageProcessingHints.IMAGE_SESSION_CONTEXT); boolean useEnhancedBridgeContext = (imageManager != null && sessionContext != null); final BridgeContext ctx = (useEnhancedBridgeContext ? new GenericFOPBridgeContext(ua, null, imageManager, sessionContext) : new BridgeContext(ua)); Document doc = svg.getDocument(); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(doc); //Build the GVT tree final GraphicsNode root; try { root = builder.build(ctx, clonedDoc); } catch (Exception e) { throw new ImageException("GVT tree could not be built for SVG graphic", e); } //Create the painter int width = svg.getSize().getWidthMpt(); int height = svg.getSize().getHeightMpt(); Dimension imageSize = new Dimension(width, height); Graphics2DImagePainter painter = createPainter(ctx, root, imageSize); //Create g2d image ImageInfo imageInfo = src.getInfo(); ImageGraphics2D g2dImage = new ImageGraphics2D(imageInfo, painter); return g2dImage; }
1
              
// in src/java/org/apache/fop/image/loader/batik/ImageConverterSVG2G2D.java
catch (Exception e) { throw new ImageException("GVT tree could not be built for SVG graphic", e); }
8
              
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImageUsingImageHandler(ImageInfo info, Rectangle rect) throws ImageException, IOException { ImageManager manager = getFopFactory().getImageManager(); ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry(); //Load and convert the image to a supported format RenderingContext context = createRenderingContext(); Map hints = createDefaultImageProcessingHints(sessionContext); context.putHints(hints); ImageFlavor[] flavors = imageHandlerRegistry.getSupportedFlavors(context); org.apache.xmlgraphics.image.loader.Image img = manager.getImage( info, flavors, hints, sessionContext); try { drawImage(img, rect, context); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageWritingError(this, ioe); } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImage(Image image, Rectangle rect, RenderingContext context) throws IOException, ImageException { drawImage(image, rect, context, false, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImage(Image image, Rectangle rect, RenderingContext context, boolean convert, Map additionalHints) throws IOException, ImageException { ImageManager manager = getFopFactory().getImageManager(); ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry(); Image effImage; context.putHints(additionalHints); if (convert) { Map hints = createDefaultImageProcessingHints(getUserAgent().getImageSessionContext()); if (additionalHints != null) { hints.putAll(additionalHints); } effImage = manager.convertImage(image, imageHandlerRegistry.getSupportedFlavors(context), hints); } else { effImage = image; } //First check for a dynamically registered handler ImageHandler handler = imageHandlerRegistry.getHandler(context, effImage); if (handler == null) { throw new UnsupportedOperationException( "No ImageHandler available for image: " + effImage.getInfo() + " (" + effImage.getClass().getName() + ")"); } if (log.isTraceEnabled()) { log.trace("Using ImageHandler: " + handler.getClass().getName()); } handler.handleImage(context, effImage, rect); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
protected void drawImageUsingImageHandler(ImageInfo info, Rectangle rect) throws ImageException, IOException { if (!getPSUtil().isOptimizeResources() || PSImageUtils.isImageInlined(info, (PSRenderingContext)createRenderingContext())) { super.drawImageUsingImageHandler(info, rect); } else { if (log.isDebugEnabled()) { log.debug("Image " + info + " is embedded as a form later"); } //Don't load image at this time, just put a form placeholder in the stream PSResource form = documentHandler.getFormForImage(info.getOriginalURI()); PSImageUtils.drawForm(form, info, rect, getGenerator()); } }
// in src/java/org/apache/fop/image/loader/batik/ImageConverterSVG2G2D.java
public Image convert(final Image src, Map hints) throws ImageException { checkSourceFlavor(src); final ImageXMLDOM svg = (ImageXMLDOM)src; if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(svg.getRootNamespace())) { throw new IllegalArgumentException("XML DOM is not in the SVG namespace: " + svg.getRootNamespace()); } //Prepare float pxToMillimeter = UnitConv.IN2MM / GraphicsConstants.DEFAULT_DPI; Number ptm = (Number)hints.get(ImageProcessingHints.SOURCE_RESOLUTION); if (ptm != null) { pxToMillimeter = (float)(UnitConv.IN2MM / ptm.doubleValue()); } UserAgent ua = createBatikUserAgent(pxToMillimeter); GVTBuilder builder = new GVTBuilder(); final ImageManager imageManager = (ImageManager)hints.get( ImageProcessingHints.IMAGE_MANAGER); final ImageSessionContext sessionContext = (ImageSessionContext)hints.get( ImageProcessingHints.IMAGE_SESSION_CONTEXT); boolean useEnhancedBridgeContext = (imageManager != null && sessionContext != null); final BridgeContext ctx = (useEnhancedBridgeContext ? new GenericFOPBridgeContext(ua, null, imageManager, sessionContext) : new BridgeContext(ua)); Document doc = svg.getDocument(); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(doc); //Build the GVT tree final GraphicsNode root; try { root = builder.build(ctx, clonedDoc); } catch (Exception e) { throw new ImageException("GVT tree could not be built for SVG graphic", e); } //Create the painter int width = svg.getSize().getWidthMpt(); int height = svg.getSize().getHeightMpt(); Dimension imageSize = new Dimension(width, height); Graphics2DImagePainter painter = createPainter(ctx, root, imageSize); //Create g2d image ImageInfo imageInfo = src.getInfo(); ImageGraphics2D g2dImage = new ImageGraphics2D(imageInfo, painter); return g2dImage; }
// in src/java/org/apache/fop/image/loader/batik/ImageLoaderSVG.java
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!MimeConstants.MIME_SVG.equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from an SVG image"); } Image img = info.getOriginalImage(); if (!(img instanceof ImageXMLDOM)) { throw new IllegalArgumentException( "ImageInfo was expected to contain the SVG document as DOM"); } ImageXMLDOM svgImage = (ImageXMLDOM)img; if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(svgImage.getRootNamespace())) { throw new IllegalArgumentException( "The Image is not in the SVG namespace: " + svgImage.getRootNamespace()); } return svgImage; }
// in src/java/org/apache/fop/image/loader/batik/ImageLoaderWMF.java
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!ImageWMF.MIME_WMF.equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from a WMF image"); } Image img = info.getOriginalImage(); if (!(img instanceof ImageWMF)) { throw new IllegalArgumentException( "ImageInfo was expected to contain the Windows Metafile (WMF)"); } ImageWMF wmfImage = (ImageWMF)img; return wmfImage; }
// in src/java/org/apache/fop/image/loader/batik/ImageConverterG2D2SVG.java
public Image convert(Image src, Map hints) throws ImageException { checkSourceFlavor(src); ImageGraphics2D g2dImage = (ImageGraphics2D)src; DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); // Create an instance of org.w3c.dom.Document Document document = domImpl.createDocument( SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null); Element root = document.getDocumentElement(); // Create an SVGGeneratorContext to customize SVG generation SVGGeneratorContext genCtx = SVGGeneratorContext.createDefault(document); genCtx.setComment("Generated by Apache Batik's SVGGraphics2D"); genCtx.setEmbeddedFontsOn(true); // Create an instance of the SVG Generator SVGGraphics2D g2d = new SVGGraphics2D(genCtx, true); ImageSize size = src.getSize(); Dimension dim = size.getDimensionMpt(); g2d.setSVGCanvasSize(dim); //SVGGraphics2D doesn't generate the viewBox by itself root.setAttribute("viewBox", "0 0 " + dim.width + " " + dim.height); g2dImage.getGraphics2DImagePainter().paint(g2d, new Rectangle2D.Float(0, 0, dim.width, dim.height)); //Populate the document root with the generated SVG content. g2d.getRoot(root); //Return the generated SVG image ImageXMLDOM svgImage = new ImageXMLDOM(src.getInfo(), document, BatikImageFlavors.SVG_DOM); g2d.dispose(); return svgImage; }
(Lib) NumberFormatException 1
              
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseWithHash(String value) throws PropertyException { Color parsedColor; try { int len = value.length(); int alpha; if (len == 5 || len == 9) { alpha = Integer.parseInt( value.substring((len == 5) ? 3 : 7), 16); } else { alpha = 0xFF; } int red = 0; int green = 0; int blue = 0; if ((len == 4) || (len == 5)) { //multiply by 0x11 = 17 = 255/15 red = Integer.parseInt(value.substring(1, 2), 16) * 0x11; green = Integer.parseInt(value.substring(2, 3), 16) * 0x11; blue = Integer.parseInt(value.substring(3, 4), 16) * 0X11; } else if ((len == 7) || (len == 9)) { red = Integer.parseInt(value.substring(1, 3), 16); green = Integer.parseInt(value.substring(3, 5), 16); blue = Integer.parseInt(value.substring(5, 7), 16); } else { throw new NumberFormatException(); } parsedColor = new Color(red, green, blue, alpha); } catch (RuntimeException re) { throw new PropertyException("Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA"); } return parsedColor; }
0 0
(Domain) RtfException 1
              
// in src/java/org/apache/fop/render/rtf/rtflib/tools/BuilderContext.java
public RtfContainer getContainer(Class containerClass, boolean required, Object /*IBuilder*/ forWhichBuilder) throws RtfException { // TODO what to do if the desired container is not at the top of the stack? // close top-of-stack container? final RtfContainer result = (RtfContainer)getObjectFromStack(containers, containerClass); if (result == null && required) { throw new RtfException( "No RtfContainer of class '" + containerClass.getName() + "' available for '" + forWhichBuilder.getClass().getName() + "' builder" ); } return result; }
0 1
              
// in src/java/org/apache/fop/render/rtf/rtflib/tools/BuilderContext.java
public RtfContainer getContainer(Class containerClass, boolean required, Object /*IBuilder*/ forWhichBuilder) throws RtfException { // TODO what to do if the desired container is not at the top of the stack? // close top-of-stack container? final RtfContainer result = (RtfContainer)getObjectFromStack(containers, containerClass); if (result == null && required) { throw new RtfException( "No RtfContainer of class '" + containerClass.getName() + "' available for '" + forWhichBuilder.getClass().getName() + "' builder" ); } return result; }
(Lib) ServletException 1
              
// in src/java/org/apache/fop/servlet/FopServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { //Get parameters String foParam = request.getParameter(FO_REQUEST_PARAM); String xmlParam = request.getParameter(XML_REQUEST_PARAM); String xsltParam = request.getParameter(XSLT_REQUEST_PARAM); //Analyze parameters and decide with method to use if (foParam != null) { renderFO(foParam, response); } else if ((xmlParam != null) && (xsltParam != null)) { renderXML(xmlParam, xsltParam, response); } else { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>Error</title></head>\n" + "<body><h1>FopServlet Error</h1><h3>No 'fo' " + "request param given.</body></html>"); } } catch (Exception ex) { throw new ServletException(ex); } }
1
              
// in src/java/org/apache/fop/servlet/FopServlet.java
catch (Exception ex) { throw new ServletException(ex); }
2
              
// in src/java/org/apache/fop/servlet/FopServlet.java
public void init() throws ServletException { this.uriResolver = new ServletContextURIResolver(getServletContext()); this.transFactory = TransformerFactory.newInstance(); this.transFactory.setURIResolver(this.uriResolver); //Configure FopFactory as desired this.fopFactory = FopFactory.newInstance(); this.fopFactory.setURIResolver(this.uriResolver); configureFopFactory(); }
// in src/java/org/apache/fop/servlet/FopServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { //Get parameters String foParam = request.getParameter(FO_REQUEST_PARAM); String xmlParam = request.getParameter(XML_REQUEST_PARAM); String xsltParam = request.getParameter(XSLT_REQUEST_PARAM); //Analyze parameters and decide with method to use if (foParam != null) { renderFO(foParam, response); } else if ((xmlParam != null) && (xsltParam != null)) { renderXML(xmlParam, xsltParam, response); } else { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>Error</title></head>\n" + "<body><h1>FopServlet Error</h1><h3>No 'fo' " + "request param given.</body></html>"); } } catch (Exception ex) { throw new ServletException(ex); } }
(Domain) ValidationException 1
              
// in src/java/org/apache/fop/fo/flow/table/FixedColRowGroupBuilder.java
void endTablePart() throws ValidationException { if (rows.size() > 0) { throw new ValidationException( "A table-cell is spanning more rows than available in its parent element."); } setFlagForCols(GridUnit.LAST_IN_PART, lastRow); borderResolver.endPart(); }
0 90
              
// in src/java/org/apache/fop/fo/XMLObj.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/PropertyList.java
private String addAttributeToList(Attributes attributes, String attributeName) throws ValidationException { String attributeValue = attributes.getValue(attributeName); if ( attributeValue != null ) { convertAttributeToProperty(attributes, attributeName, attributeValue); } return attributeValue; }
// in src/java/org/apache/fop/fo/PropertyList.java
public void addAttributesToList(Attributes attributes) throws ValidationException { /* * Give writing-mode highest conversion priority. */ addAttributeToList(attributes, "writing-mode"); /* * If column-number/number-columns-spanned are specified, then we * need them before all others (possible from-table-column() on any * other property further in the list... */ addAttributeToList(attributes, "column-number"); addAttributeToList(attributes, "number-columns-spanned"); /* * If font-size is set on this FO, must set it first, since * other attributes specified in terms of "ems" depend on it. */ String checkValue = addAttributeToList(attributes, "font"); if (checkValue == null || "".equals(checkValue)) { /* * font shorthand wasn't specified, so still need to process * explicit font-size */ addAttributeToList(attributes, "font-size"); } String attributeNS; String attributeName; String attributeValue; FopFactory factory = getFObj().getUserAgent().getFactory(); for (int i = 0; i < attributes.getLength(); i++) { /* convert all attributes with the same namespace as the fo element * the "xml:lang" and "xml:base" properties are special cases */ attributeNS = attributes.getURI(i); attributeName = attributes.getQName(i); attributeValue = attributes.getValue(i); if (attributeNS == null || attributeNS.length() == 0 || "xml:lang".equals(attributeName) || "xml:base".equals(attributeName)) { convertAttributeToProperty(attributes, attributeName, attributeValue); } else if (!factory.isNamespaceIgnored(attributeNS)) { ElementMapping mapping = factory.getElementMappingRegistry().getElementMapping( attributeNS); QName attr = new QName(attributeNS, attributeName); if (mapping != null) { if (mapping.isAttributeProperty(attr) && mapping.getStandardPrefix() != null) { convertAttributeToProperty(attributes, mapping.getStandardPrefix() + ":" + attr.getLocalName(), attributeValue); } else { getFObj().addForeignAttribute(attr, attributeValue); } } else { handleInvalidProperty(attr); } } } }
// in src/java/org/apache/fop/fo/PropertyList.java
private void convertAttributeToProperty(Attributes attributes, String attributeName, String attributeValue) throws ValidationException { if (attributeName.startsWith("xmlns:") || "xmlns".equals(attributeName)) { /* Ignore namespace declarations if the XML parser/XSLT processor * reports them as 'regular' attributes */ return; } if (attributeValue != null) { /* Handle "compound" properties, ex. space-before.minimum */ String basePropertyName = findBasePropertyName(attributeName); String subPropertyName = findSubPropertyName(attributeName); int propId = FOPropertyMapping.getPropertyId(basePropertyName); int subpropId = FOPropertyMapping.getSubPropertyId(subPropertyName); if (propId == -1 || (subpropId == -1 && subPropertyName != null)) { handleInvalidProperty(new QName(null, attributeName)); } FObj parentFO = fobj.findNearestAncestorFObj(); PropertyMaker propertyMaker = findMaker(propId); if (propertyMaker == null) { log.warn("No PropertyMaker registered for " + attributeName + ". Ignoring property."); return; } try { Property prop = null; if (subPropertyName == null) { // base attribute only found /* Do nothing if the base property has already been created. * This is e.g. the case when a compound attribute was * specified before the base attribute; in these cases * the base attribute was already created in * findBaseProperty() */ if (getExplicit(propId) != null) { return; } prop = propertyMaker.make(this, attributeValue, parentFO); } else { // e.g. "leader-length.maximum" Property baseProperty = findBaseProperty(attributes, parentFO, propId, basePropertyName, propertyMaker); prop = propertyMaker.make(baseProperty, subpropId, this, attributeValue, parentFO); } if (prop != null) { putExplicit(propId, prop); } } catch (PropertyException e) { fobj.getFOValidationEventProducer().invalidPropertyValue(this, fobj.getName(), attributeName, attributeValue, e, fobj.locator); } } }
// in src/java/org/apache/fop/fo/PropertyList.java
protected void handleInvalidProperty(QName attr) throws ValidationException { if (!attr.getQName().startsWith("xmlns")) { fobj.getFOValidationEventProducer().invalidProperty(this, fobj.getName(), attr, true, fobj.locator); } }
// in src/java/org/apache/fop/fo/flow/AbstractListItemPart.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(%block;)"); } } else if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else { blockItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/ListItem.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (label != null) { nodesOutOfOrderError(loc, "fo:marker", "fo:list-item-label"); } } else if (localName.equals("list-item-label")) { if (label != null) { tooManyNodesError(loc, "fo:list-item-label"); } } else if (localName.equals("list-item-body")) { if (label == null) { nodesOutOfOrderError(loc, "fo:list-item-label", "fo:list-item-body"); } else if (body != null) { tooManyNodesError(loc, "fo:list-item-body"); } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/Float.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/PageNumber.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/Wrapper.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ("marker".equals(localName)) { if (blockOrInlineItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(#PCDATA|%inline;|%block;)"); } } else if (isBlockOrInlineItem(nsURI, localName)) { /* delegate validation to parent, but keep the error reporting * tidy. If we would simply call validateChildNode() on the * parent, the user would get a wrong impression, as only the * locator (if any) will contain a reference to the offending * fo:wrapper. */ try { FONode.validateChildNode(this.parent, loc, nsURI, localName); } catch (ValidationException vex) { invalidChildError(loc, getName(), FO_URI, localName, "rule.wrapperInvalidChildForParent"); } blockOrInlineItemFound = true; } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/InlineContainer.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(%block;)"); } } else if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else { blockItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/BasicLink.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockOrInlineItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(#PCDATA|%inline;|%block;)"); } } else if (!isBlockOrInlineItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else { blockOrInlineItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/FootnoteBody.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/Leader.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ( localName.equals("leader") || localName.equals("inline-container") || localName.equals("block-container") || localName.equals("float") || localName.equals("marker") || !isInlineItem(nsURI, localName) ) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/InitialPropertySet.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/AbstractPageNumberCitation.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/ListBlock.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (hasListItem) { nodesOutOfOrderError(loc, "fo:marker", "fo:list-item"); } } else if (localName.equals("list-item")) { hasListItem = true; } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/Inline.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockOrInlineItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(#PCDATA|%inline;|%block;)"); } } else if (!isBlockOrInlineItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else if (!canHaveBlockLevelChildren && isBlockItem(nsURI, localName) && !isNeutralItem(nsURI, localName)) { invalidChildError(loc, getName(), nsURI, localName, "rule.inlineContent"); } else { blockOrInlineItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/MultiToggle.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!isBlockOrInlineItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/InstreamForeignObject.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } else if (firstChild != null) { tooManyNodesError(loc, new QName(nsURI, null, localName)); } }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/MultiProperties.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("multi-property-set")) { if (hasWrapper) { nodesOutOfOrderError(loc, "fo:multi-property-set", "fo:wrapper"); } else { hasMultiPropertySet = true; } } else if (localName.equals("wrapper")) { if (hasWrapper) { tooManyNodesError(loc, "fo:wrapper"); } else { hasWrapper = true; } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/BlockContainer.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ("marker".equals(localName)) { if (commonAbsolutePosition.absolutePosition == EN_ABSOLUTE || commonAbsolutePosition.absolutePosition == EN_FIXED) { getFOValidationEventProducer() .markerBlockContainerAbsolutePosition(this, locator); } if (blockItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(%block;)"); } } else if (!isBlockItem(FO_URI, localName)) { invalidChildError(loc, FO_URI, localName); } else { blockItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/MultiPropertySet.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/Character.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/Footnote.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("inline")) { if (footnoteCitation != null) { tooManyNodesError(loc, "fo:inline"); } } else if (localName.equals("footnote-body")) { if (footnoteCitation == null) { nodesOutOfOrderError(loc, "fo:inline", "fo:footnote-body"); } else if (footnoteBody != null) { tooManyNodesError(loc, "fo:footnote-body"); } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/Marker.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!isBlockOrInlineItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/Marker.java
public void addAttributesToList(Attributes attributes) throws ValidationException { this.attribs = new MarkerAttribute[attributes.getLength()]; String name; String value; String namespace; String qname; for (int i = attributes.getLength(); --i >= 0;) { namespace = attributes.getURI(i); qname = attributes.getQName(i); name = attributes.getLocalName(i); value = attributes.getValue(i); this.attribs[i] = MarkerAttribute.getInstance(namespace, qname, name, value); } }
// in src/java/org/apache/fop/fo/flow/Block.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ("marker".equals(localName)) { if (blockOrInlineItemFound || initialPropertySetFound) { nodesOutOfOrderError(loc, "fo:marker", "initial-property-set? (#PCDATA|%inline;|%block;)"); } } else if ("initial-property-set".equals(localName)) { if (initialPropertySetFound) { tooManyNodesError(loc, "fo:initial-property-set"); } else if (blockOrInlineItemFound) { nodesOutOfOrderError(loc, "fo:initial-property-set", "(#PCDATA|%inline;|%block;)"); } else { initialPropertySetFound = true; } } else if (isBlockOrInlineItem(nsURI, localName)) { blockOrInlineItemFound = true; } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ("marker".equals(localName)) { if (this.firstChild != null) { //a table-cell has already been added to this row nodesOutOfOrderError(loc, "fo:marker", "(table-cell+)"); } } else if (!"table-cell".equals(localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/table/TableCell.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(%block;)"); } } else if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else { blockItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/table/VariableColRowGroupBuilder.java
void endTablePart() throws ValidationException { // TODO catch the ValidationException sooner? events.add(new Event() { public void play(RowGroupBuilder rowGroupBuilder) throws ValidationException { rowGroupBuilder.endTablePart(); } }); }
// in src/java/org/apache/fop/fo/flow/table/VariableColRowGroupBuilder.java
public void play(RowGroupBuilder rowGroupBuilder) throws ValidationException { rowGroupBuilder.endTablePart(); }
// in src/java/org/apache/fop/fo/flow/table/VariableColRowGroupBuilder.java
void endTable() throws ValidationException { RowGroupBuilder delegate = new FixedColRowGroupBuilder(table); for (Iterator eventIter = events.iterator(); eventIter.hasNext();) { ((Event) eventIter.next()).play(delegate); } delegate.endTable(); }
// in src/java/org/apache/fop/fo/flow/table/FixedColRowGroupBuilder.java
void endTablePart() throws ValidationException { if (rows.size() > 0) { throw new ValidationException( "A table-cell is spanning more rows than available in its parent element."); } setFlagForCols(GridUnit.LAST_IN_PART, lastRow); borderResolver.endPart(); }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
protected void finishLastRowGroup() throws ValidationException { if (!inMarker()) { RowGroupBuilder rowGroupBuilder = getTable().getRowGroupBuilder(); if (tableRowsFound) { rowGroupBuilder.endTableRow(); } else if (!lastCellEndsRow) { rowGroupBuilder.endRow(this); } try { rowGroupBuilder.endTablePart(); } catch (ValidationException e) { e.setLocator(locator); throw e; } } }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (tableRowsFound || tableCellsFound) { nodesOutOfOrderError(loc, "fo:marker", "(table-row+|table-cell+)"); } } else if (localName.equals("table-row")) { tableRowsFound = true; if (tableCellsFound) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noMixRowsAndCells(this, getName(), getLocator()); } } else if (localName.equals("table-cell")) { tableCellsFound = true; if (tableRowsFound) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noMixRowsAndCells(this, getName(), getLocator()); } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/table/TableColumn.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/table/TableCaption.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(%block;)"); } } else if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else { blockItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/table/Table.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ("marker".equals(localName)) { if (tableColumnFound || tableHeaderFound || tableFooterFound || tableBodyFound) { nodesOutOfOrderError(loc, "fo:marker", "(table-column*,table-header?,table-footer?,table-body+)"); } } else if ("table-column".equals(localName)) { tableColumnFound = true; if (tableHeaderFound || tableFooterFound || tableBodyFound) { nodesOutOfOrderError(loc, "fo:table-column", "(table-header?,table-footer?,table-body+)"); } } else if ("table-header".equals(localName)) { if (tableHeaderFound) { tooManyNodesError(loc, "table-header"); } else { tableHeaderFound = true; if (tableFooterFound || tableBodyFound) { nodesOutOfOrderError(loc, "fo:table-header", "(table-footer?,table-body+)"); } } } else if ("table-footer".equals(localName)) { if (tableFooterFound) { tooManyNodesError(loc, "table-footer"); } else { tableFooterFound = true; if (tableBodyFound) { if (getUserAgent().validateStrictly()) { nodesOutOfOrderError(loc, "fo:table-footer", "(table-body+)", true); } if (!isSeparateBorderModel()) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.footerOrderCannotRecover(this, getName(), getLocator()); } } } } else if ("table-body".equals(localName)) { tableBodyFound = true; } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/table/TableAndCaption.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (tableCaptionFound) { nodesOutOfOrderError(loc, "fo:marker", "fo:table-caption"); } else if (tableFound) { nodesOutOfOrderError(loc, "fo:marker", "fo:table"); } } else if (localName.equals("table-caption")) { if (tableCaptionFound) { tooManyNodesError(loc, "fo:table-caption"); } else if (tableFound) { nodesOutOfOrderError(loc, "fo:table-caption", "fo:table"); } else { tableCaptionFound = true; } } else if (localName.equals("table")) { if (tableFound) { tooManyNodesError(loc, "fo:table"); } else { tableFound = true; } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/MultiSwitch.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!localName.equals("multi-case")) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!localName.equals("simple-page-master") && !localName.equals("page-sequence-master")) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
private void checkRegionNames() throws ValidationException { // (user-entered) region-name to default region map. Map<String, String> allRegions = new java.util.HashMap<String, String>(); for (SimplePageMaster simplePageMaster : simplePageMasters.values()) { Map<String, Region> spmRegions = simplePageMaster.getRegions(); for (Region region : spmRegions.values()) { if (allRegions.containsKey(region.getRegionName())) { String defaultRegionName = allRegions.get(region.getRegionName()); if (!defaultRegionName.equals(region.getDefaultRegionName())) { getFOValidationEventProducer().regionNameMappedToMultipleRegionClasses(this, region.getRegionName(), defaultRegionName, region.getDefaultRegionName(), getLocator()); } } allRegions.put(region.getRegionName(), region.getDefaultRegionName()); } } }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
private void resolveSubSequenceReferences() throws ValidationException { for (PageSequenceMaster psm : pageSequenceMasters.values()) { for (SubSequenceSpecifier subSequenceSpecifier : psm.getSubSequenceSpecifier()) { subSequenceSpecifier.resolveReferences(this); } } }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
protected void addSimplePageMaster(SimplePageMaster sPM) throws ValidationException { // check for duplication of master-name String masterName = sPM.getMasterName(); if (existsName(masterName)) { getFOValidationEventProducer().masterNameNotUnique(this, getName(), masterName, sPM.getLocator()); } this.simplePageMasters.put(masterName, sPM); }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
protected void addPageSequenceMaster(String masterName, PageSequenceMaster pSM) throws ValidationException { // check against duplication of master-name if (existsName(masterName)) { getFOValidationEventProducer().masterNameNotUnique(this, getName(), masterName, pSM.getLocator()); } this.pageSequenceMasters.put(masterName, pSM); }
// in src/java/org/apache/fop/fo/pagination/Declarations.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!localName.equals("color-profile")) { invalidChildError(loc, nsURI, localName); } } // anything outside of XSL namespace is OK. }
// in src/java/org/apache/fop/fo/pagination/Root.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("layout-master-set")) { if (layoutMasterSet != null) { tooManyNodesError(loc, "fo:layout-master-set"); } } else if (localName.equals("declarations")) { if (layoutMasterSet == null) { nodesOutOfOrderError(loc, "fo:layout-master-set", "fo:declarations"); } else if (declarations != null) { tooManyNodesError(loc, "fo:declarations"); } else if (bookmarkTree != null) { nodesOutOfOrderError(loc, "fo:declarations", "fo:bookmark-tree"); } else if (pageSequenceFound) { nodesOutOfOrderError(loc, "fo:declarations", "fo:page-sequence"); } } else if (localName.equals("bookmark-tree")) { if (layoutMasterSet == null) { nodesOutOfOrderError(loc, "fo:layout-master-set", "fo:bookmark-tree"); } else if (bookmarkTree != null) { tooManyNodesError(loc, "fo:bookmark-tree"); } else if (pageSequenceFound) { nodesOutOfOrderError(loc, "fo:bookmark-tree", "fo:page-sequence"); } } else if (localName.equals("page-sequence")) { if (layoutMasterSet == null) { nodesOutOfOrderError(loc, "fo:layout-master-set", "fo:page-sequence"); } else { pageSequenceFound = true; } } else { invalidChildError(loc, nsURI, localName); } } else { if (FOX_URI.equals(nsURI)) { if ("external-document".equals(localName)) { pageSequenceFound = true; } } //invalidChildError(loc, nsURI, localName); //Ignore non-FO elements under root } }
// in src/java/org/apache/fop/fo/pagination/Root.java
protected void validateChildNode(Locator loc, FONode child) throws ValidationException { if (child instanceof AbstractPageSequence) { pageSequenceFound = true; } }
// in src/java/org/apache/fop/fo/pagination/SimplePageMaster.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("region-body")) { if (hasRegionBody) { tooManyNodesError(loc, "fo:region-body"); } else { hasRegionBody = true; } } else if (localName.equals("region-before")) { if (!hasRegionBody) { nodesOutOfOrderError(loc, "fo:region-body", "fo:region-before"); } else if (hasRegionBefore) { tooManyNodesError(loc, "fo:region-before"); } else if (hasRegionAfter) { nodesOutOfOrderError(loc, "fo:region-before", "fo:region-after"); } else if (hasRegionStart) { nodesOutOfOrderError(loc, "fo:region-before", "fo:region-start"); } else if (hasRegionEnd) { nodesOutOfOrderError(loc, "fo:region-before", "fo:region-end"); } else { hasRegionBefore = true; } } else if (localName.equals("region-after")) { if (!hasRegionBody) { nodesOutOfOrderError(loc, "fo:region-body", "fo:region-after"); } else if (hasRegionAfter) { tooManyNodesError(loc, "fo:region-after"); } else if (hasRegionStart) { nodesOutOfOrderError(loc, "fo:region-after", "fo:region-start"); } else if (hasRegionEnd) { nodesOutOfOrderError(loc, "fo:region-after", "fo:region-end"); } else { hasRegionAfter = true; } } else if (localName.equals("region-start")) { if (!hasRegionBody) { nodesOutOfOrderError(loc, "fo:region-body", "fo:region-start"); } else if (hasRegionStart) { tooManyNodesError(loc, "fo:region-start"); } else if (hasRegionEnd) { nodesOutOfOrderError(loc, "fo:region-start", "fo:region-end"); } else { hasRegionStart = true; } } else if (localName.equals("region-end")) { if (!hasRegionBody) { nodesOutOfOrderError(loc, "fo:region-body", "fo:region-end"); } else if (hasRegionEnd) { tooManyNodesError(loc, "fo:region-end"); } else { hasRegionEnd = true; } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/Flow.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(%block;)"); } } else if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else { blockItemFound = true; } } }
// in src/java/org/apache/fop/fo/pagination/StaticContent.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/Title.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!isInlineItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { invalidChildError(loc, nsURI, localName); }
// in src/java/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java
public void resolveReferences(LayoutMasterSet layoutMasterSet) throws ValidationException { master = layoutMasterSet.getSimplePageMaster(masterReference); if (master == null) { BlockLevelEventProducer.Provider.get( getUserAgent().getEventBroadcaster()) .noMatchingPageMaster(this, parent.getName(), masterReference, getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!localName.equals("conditional-page-master-reference")) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
public void resolveReferences(LayoutMasterSet layoutMasterSet) throws ValidationException { for (ConditionalPageMasterReference conditionalPageMasterReference : conditionalPageMasterRefs) { conditionalPageMasterReference.resolveReferences(layoutMasterSet); } }
// in src/java/org/apache/fop/fo/pagination/bookmarks/BookmarkTitle.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/pagination/bookmarks/Bookmark.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("bookmark-title")) { if (bookmarkTitle != null) { tooManyNodesError(loc, "fo:bookmark-title"); } } else if (localName.equals("bookmark")) { if (bookmarkTitle == null) { nodesOutOfOrderError(loc, "fo:bookmark-title", "fo:bookmark"); } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/bookmarks/BookmarkTree.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!localName.equals("bookmark")) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/SinglePageMasterReference.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/pagination/SinglePageMasterReference.java
public void resolveReferences(LayoutMasterSet layoutMasterSet) throws ValidationException { master = layoutMasterSet.getSimplePageMaster(masterReference); if (master == null) { BlockLevelEventProducer.Provider.get( getUserAgent().getEventBroadcaster()) .noMatchingPageMaster(this, parent.getName(), masterReference, getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/PageSequenceWrapper.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!(localName.equals("page-sequence") || localName.equals("page-sequence-wrapper"))) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/ColorProfile.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { invalidChildError(loc, nsURI, localName); }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java
public void resolveReferences(LayoutMasterSet layoutMasterSet) throws ValidationException { master = layoutMasterSet.getSimplePageMaster(masterReference); if (master == null) { BlockLevelEventProducer.Provider.get( getUserAgent().getEventBroadcaster()) .noMatchingPageMaster(this, parent.getName(), masterReference, getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/Region.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ("title".equals(localName)) { if (titleFO != null) { tooManyNodesError(loc, "fo:title"); } else if (!flowMap.isEmpty()) { nodesOutOfOrderError(loc, "fo:title", "fo:static-content"); } else if (mainFlow != null) { nodesOutOfOrderError(loc, "fo:title", "fo:flow"); } } else if ("static-content".equals(localName)) { if (mainFlow != null) { nodesOutOfOrderError(loc, "fo:static-content", "fo:flow"); } } else if ("flow".equals(localName)) { if (mainFlow != null) { tooManyNodesError(loc, "fo:flow"); } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
private void addFlow(Flow flow) throws ValidationException { String flowName = flow.getFlowName(); if (hasFlowName(flowName)) { getFOValidationEventProducer().duplicateFlowNameInPageSequence(this, flow.getName(), flowName, flow.getLocator()); } if (!getRoot().getLayoutMasterSet().regionNameExists(flowName) && !flowName.equals("xsl-before-float-separator") && !flowName.equals("xsl-footnote-separator")) { getFOValidationEventProducer().flowNameNotMapped(this, flow.getName(), flowName, flow.getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!"single-page-master-reference".equals(localName) && !"repeatable-page-master-reference".equals(localName) && !"repeatable-page-master-alternatives".equals(localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/FObj.java
private void checkId(String id) throws ValidationException { if (!inMarker() && !id.equals("")) { Set idrefs = getBuilderContext().getIDReferences(); if (!idrefs.contains(id)) { idrefs.add(id); } else { getFOValidationEventProducer().idNotUnique(this, getName(), id, true, locator); } } }
// in src/java/org/apache/fop/fo/FONode.java
protected void validateChildNode( Locator loc, String namespaceURI, String localName) throws ValidationException { //nop }
// in src/java/org/apache/fop/fo/FONode.java
protected static void validateChildNode( FONode fo, Locator loc, String namespaceURI, String localName) throws ValidationException { fo.validateChildNode(loc, namespaceURI, localName); }
// in src/java/org/apache/fop/fo/FONode.java
protected void tooManyNodesError(Locator loc, String nsURI, String lName) throws ValidationException { tooManyNodesError(loc, new QName(nsURI, lName)); }
// in src/java/org/apache/fop/fo/FONode.java
protected void tooManyNodesError(Locator loc, QName offendingNode) throws ValidationException { getFOValidationEventProducer().tooManyNodes(this, getName(), offendingNode, loc); }
// in src/java/org/apache/fop/fo/FONode.java
protected void tooManyNodesError(Locator loc, String offendingNode) throws ValidationException { tooManyNodesError(loc, new QName(FO_URI, offendingNode)); }
// in src/java/org/apache/fop/fo/FONode.java
protected void nodesOutOfOrderError(Locator loc, String tooLateNode, String tooEarlyNode) throws ValidationException { nodesOutOfOrderError(loc, tooLateNode, tooEarlyNode, false); }
// in src/java/org/apache/fop/fo/FONode.java
protected void nodesOutOfOrderError(Locator loc, String tooLateNode, String tooEarlyNode, boolean canRecover) throws ValidationException { getFOValidationEventProducer().nodeOutOfOrder(this, getName(), tooLateNode, tooEarlyNode, canRecover, loc); }
// in src/java/org/apache/fop/fo/FONode.java
protected void invalidChildError(Locator loc, String nsURI, String lName) throws ValidationException { invalidChildError(loc, getName(), nsURI, lName, null); }
// in src/java/org/apache/fop/fo/FONode.java
protected void invalidChildError(Locator loc, String parentName, String nsURI, String lName, String ruleViolated) throws ValidationException { String prefix = getNodePrefix ( nsURI ); QName qn; // qualified name of offending node if ( prefix != null ) { qn = new QName(nsURI, prefix, lName); } else { qn = new QName(nsURI, lName); } getFOValidationEventProducer().invalidChild(this, parentName, qn, ruleViolated, loc); }
// in src/java/org/apache/fop/fo/FONode.java
protected void missingChildElementError(String contentModel) throws ValidationException { getFOValidationEventProducer().missingChildElement(this, getName(), contentModel, false, locator); }
// in src/java/org/apache/fop/fo/FONode.java
protected void missingChildElementError(String contentModel, boolean canRecover) throws ValidationException { getFOValidationEventProducer().missingChildElement(this, getName(), contentModel, canRecover, locator); }
// in src/java/org/apache/fop/fo/FONode.java
protected void missingPropertyError(String propertyName) throws ValidationException { getFOValidationEventProducer().missingProperty(this, getName(), propertyName, locator); }
// in src/java/org/apache/fop/fo/extensions/ExternalDocument.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { invalidChildError(loc, nsURI, localName); }
// in src/java/org/apache/fop/fo/extensions/destination/Destination.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { invalidChildError(loc, nsURI, localName); }
// in src/java/org/apache/fop/render/afp/extensions/AbstractAFPExtensionObject.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/render/ps/extensions/AbstractPSExtensionElement.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/render/ps/extensions/AbstractPSExtensionObject.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
Explicit thrown (throw new...): 1317/1349
Explicit thrown ratio: 97.6%
Builder thrown ratio: 0.5%
Variable thrown ratio: 2.2%
Checked Runtime Total
Domain 161 195 356
Lib 76 577 653
Total 237 772

Caught Exceptions Summary

A (Domain) exception is defined in the application. A (Lib) exception is defined in the JDK or in a library. An exception can be caught, and it happens that the catch block contains a throw (e.g. for wrapping a low-level exception). Hovering over a number triggers showing code snippets from the application code.

Type Exception Caught
(directly)
Caught
with Thrown
(Lib) IOException 179
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O exception while setting up output file", ioe); }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (java.io.IOException ioe) { log.error("Error with opening URL '" + effURL + "': " + ioe.getMessage()); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (IOException e) { // won't happen. We're operating in-memory. throw new RuntimeException( "Error during base64 encodation of username/password"); }
// in src/java/org/apache/fop/pdf/PDFFactory.java
catch (IOException ioe) { log.error( "Failed to write CIDSet [" + cidFont + "] " + cidFont.getEmbedFontName(), ioe); }
// in src/java/org/apache/fop/pdf/PDFFactory.java
catch (IOException ioe) { log.error( "Failed to embed font [" + desc + "] " + desc.getEmbedFontName(), ioe); return null; }
// in src/java/org/apache/fop/pdf/PDFOutputIntent.java
catch (IOException ioe) { log.error("Ignored I/O exception", ioe); }
// in src/java/org/apache/fop/pdf/PDFStream.java
catch (IOException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/pdf/PDFStream.java
catch (IOException ex) { //TODO throw the exception and catch it elsewhere ex.printStackTrace(); }
// in src/java/org/apache/fop/pdf/PDFEmbeddedFile.java
catch (IOException ioe) { //ignore and just skip this entry as it's optional }
// in src/java/org/apache/fop/pdf/PDFInfo.java
catch (IOException ioe) { log.error("Ignored I/O exception", ioe); }
// in src/java/org/apache/fop/pdf/PDFICCBasedColorSpace.java
catch (IOException ioe) { throw new RuntimeException( "Unexpected IOException loading the sRGB profile: " + ioe.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFOutline.java
catch (IOException ioe) { log.error("Ignored I/O exception", ioe); }
// in src/java/org/apache/fop/tools/anttasks/FileCompare.java
catch (IOException ioe) { System.err.println("ERROR: " + ioe); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (IOException ioe) { throw new BuildException(ioe); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (IOException ioe) { logger.error("Error closing output file", ioe); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(fobj, uri, ioe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, url, ioe, getLocator()); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (IOException e) { //ignore }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (IOException e) { //ignore }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (IOException e) { //ignore }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new HyphenationException(ioe.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new SAXException(ioe.getMessage()); }
// in src/java/org/apache/fop/hyphenation/SerializeHyphPattern.java
catch (IOException ioe) { System.err.println("Can't write compiled pattern file: " + outfile); System.err.println(ioe); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (IOException ioe) { log.error("I/O error while loading precompiled hyphenation pattern file", ioe); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("I/O problem while trying to load " + name, ioe); } }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("I/O problem while trying to load " + name, ioe); } return null; }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/svg/FOPSAXSVGDocumentFactory.java
catch (IOException ioe) { /**@todo Batik's SAXSVGDocumentFactory should throw IOException, * so we don't have to handle it here. */ throw new SAXException(ioe); }
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
// in src/java/org/apache/fop/svg/PDFGraphics2D.java
catch (IOException ioe) { // ignore exception, will be thrown again later }
// in src/java/org/apache/fop/svg/NativeTextPainter.java
catch (IOException ioe) { //No other possibility than to use a RuntimeException throw new RuntimeException(ioe); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (IOException ioe) { userAgent.displayError(ioe); return null; }
// in src/java/org/apache/fop/svg/AbstractFOPTextPainter.java
catch (IOException ioe) { if (g2d instanceof AFPGraphics2D) { ((AFPGraphics2D)g2d).handleIOException(ioe); } }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (IOException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
catch (IOException ioe) { throw new TransformerException("Error writing the output file", ioe); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException ioe) { // We don't really care about the exception since it's just a // cache file log.warn("I/O exception while reading font cache (" + ioe.getMessage() + "). Discarding font cache file."); try { cacheFile.delete(); } catch (SecurityException ex) { log.warn("Failed to delete font cache file: " + cacheFile.getAbsolutePath()); } }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException ioe) { LogUtil.handleException(log, ioe, true); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException e) { // Should never happen, because URL must be local log.debug("IOError: " + e.getMessage()); return 0; }
// in src/java/org/apache/fop/fonts/FontDetector.java
catch (IOException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/fonts/FontDetector.java
catch (IOException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (IOException ioex) { log.error("Failed to read font metrics file " + metricsFileName, ioex); if (fail) { throw new RuntimeException(ioex.getMessage()); } }
// in src/java/org/apache/fop/fonts/autodetect/WindowsFontDirFinder.java
catch (IOException e) { // should continue if this fails }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
catch (IOException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
catch (IOException ioe) { // Ignore, AFM probably not available under the URI }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
catch (IOException ioe) { // Ignore, PFM probably not available under the URI }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
catch (IOException ioe) { if (afm == null) { // Ignore the exception if we have a valid PFM. PFM is only the fallback. throw ioe; } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
catch (IOException ioe) { System.err.println("Problem reading font: " + ioe.toString()); ioe.printStackTrace(System.err); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error flushing the PDF document", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error while drawing borders", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageWritingError(this, ioe); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); }
// in src/java/org/apache/fop/render/txt/TXTStream.java
catch (IOException e) { throw new RuntimeException(e.toString()); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding page image", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException( "I/O error while painting marks using a bitmap", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, null, ioe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding BufferedImage", ioe); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IOException ioe) { eventProducer.invalidConfiguration(this, ioe); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IOException ioe) { throw new FOPException("Could not create default external resource group file" , ioe); }
// in src/java/org/apache/fop/render/afp/AFPSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, uri); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException( "I/O error while embedding form map resource: " + formMap.getName(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Could not handle resource" + pageSegment.getURI(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("IO error while painting rectangle", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ife) { throw new IFException("IO error while painting borders", ife); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Error while embedding font resources", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
catch (IOException ioe) { //Some JPEG codecs cannot encode CMYK helper.encode(baos); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error writing the PostScript header", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageContent()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in handleExtensionObject()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in clipRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawBorderRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException e) { //Won't happen with Java2D throw new IllegalStateException("Unexpected I/O error"); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/afp/AFPGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/afp/AFPGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/afp/parser/UnparsedStructuredField.java
catch (IOException ioe) { //nop }
// in src/java/org/apache/fop/afp/svg/AFPTextHandler.java
catch (IOException ioe) { throw new RuntimeException("Error while embedding font resources", ioe); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (IOException ioe) { endPresentationTextData(); handleUnexpectedIOError(ioe); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (IOException ioe) { endPresentationTextData(); handleUnexpectedIOError(ioe); //Should not occur since we're writing to byte arrays }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (IOException ioe) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageSaveError(this, page.getPageNumberString(), ioe); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, getLocator()); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException ioe) { RendererEventProducer eventProducer = RendererEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.ioError(this, ioe); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException ex) { throw new SAXException(ex); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (IOException ioe) { getResourceEventProducer().imageIOError(this, uri, ioe, getExternalDocument().getLocator()); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( IOException e ) { resetATStateAll(); throw new AdvancedTypographicTableFormatException ( e.getMessage(), e ); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (IOException e) { throw new MissingResourceException(e.getMessage(), base, null); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (IOException ioe) { //wrap in a PropertyException throw new PropertyException(ioe); }
// in src/java/org/apache/fop/util/CloseBlockerOutputStream.java
catch (IOException ioe) { //ignore }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (NoClassDefFoundError ncdfe) { try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } batikAvailable = false; log.warn("Batik not in class path", ncdfe); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (IOException ioe) { // we're more interested in the original exception }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (IOException e) { // If the svg is invalid then it throws an IOException // so there is no way of knowing if it is an svg document log.debug("Error while trying to load stream as an WMF file: " + e.getMessage()); // assuming any exception means this document is not svg // or could not be loaded for some reason try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (IOException ioe) { // we're more interested in the original exception }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (NoClassDefFoundError ncdfe) { if (in != null) { try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } } batikAvailable = false; log.warn("Batik not in class path", ncdfe); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (IOException ioe) { // we're more interested in the original exception }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (IOException e) { // If the svg is invalid then it throws an IOException // so there is no way of knowing if it is an svg document log.debug("Error while trying to load stream as an SVG file: " + e.getMessage()); // assuming any exception means this document is not svg // or could not be loaded for some reason try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (IOException ioe) { // we're more interested in the original exception }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (IOException ioe) { throw new BuildException(ioe); }
91
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O exception while setting up output file", ioe); }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (IOException e) { // won't happen. We're operating in-memory. throw new RuntimeException( "Error during base64 encodation of username/password"); }
// in src/java/org/apache/fop/pdf/PDFStream.java
catch (IOException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/pdf/PDFICCBasedColorSpace.java
catch (IOException ioe) { throw new RuntimeException( "Unexpected IOException loading the sRGB profile: " + ioe.getMessage()); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (IOException ioe) { throw new BuildException(ioe); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new HyphenationException(ioe.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new SAXException(ioe.getMessage()); }
// in src/java/org/apache/fop/svg/FOPSAXSVGDocumentFactory.java
catch (IOException ioe) { /**@todo Batik's SAXSVGDocumentFactory should throw IOException, * so we don't have to handle it here. */ throw new SAXException(ioe); }
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
// in src/java/org/apache/fop/svg/NativeTextPainter.java
catch (IOException ioe) { //No other possibility than to use a RuntimeException throw new RuntimeException(ioe); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (IOException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
catch (IOException ioe) { throw new TransformerException("Error writing the output file", ioe); }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (IOException ioex) { log.error("Failed to read font metrics file " + metricsFileName, ioex); if (fail) { throw new RuntimeException(ioex.getMessage()); } }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
catch (IOException ioe) { if (afm == null) { // Ignore the exception if we have a valid PFM. PFM is only the fallback. throw ioe; } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error flushing the PDF document", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error while drawing borders", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe); }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); }
// in src/java/org/apache/fop/render/txt/TXTStream.java
catch (IOException e) { throw new RuntimeException(e.toString()); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding page image", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException( "I/O error while painting marks using a bitmap", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding BufferedImage", ioe); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IOException ioe) { throw new FOPException("Could not create default external resource group file" , ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException( "I/O error while embedding form map resource: " + formMap.getName(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Could not handle resource" + pageSegment.getURI(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("IO error while painting rectangle", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ife) { throw new IFException("IO error while painting borders", ife); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Error while embedding font resources", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error writing the PostScript header", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageContent()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in handleExtensionObject()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in clipRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawBorderRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException e) { //Won't happen with Java2D throw new IllegalStateException("Unexpected I/O error"); }
// in src/java/org/apache/fop/afp/svg/AFPTextHandler.java
catch (IOException ioe) { throw new RuntimeException("Error while embedding font resources", ioe); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException ex) { throw new SAXException(ex); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( IOException e ) { resetATStateAll(); throw new AdvancedTypographicTableFormatException ( e.getMessage(), e ); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (IOException e) { throw new MissingResourceException(e.getMessage(), base, null); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (IOException ioe) { //wrap in a PropertyException throw new PropertyException(ioe); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (IOException ioe) { throw new BuildException(ioe); }
(Lib) Exception 100
            
// in src/java/org/apache/fop/pdf/PDFStream.java
catch (Exception e) { //TODO throw the exception and catch it elsewhere e.printStackTrace(); return 0; }
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (Exception e) { throw new java.io.FileNotFoundException( "URI could not be resolved (" + e.getMessage() + "): " + uri); }
// in src/java/org/apache/fop/tools/TestConverter.java
catch (Exception e) { logger.error("Error while running tests", e); }
// in src/java/org/apache/fop/tools/TestConverter.java
catch (Exception e) { logger.error("Error setting base directory"); }
// in src/java/org/apache/fop/tools/TestConverter.java
catch (Exception e) { logger.error("Error while running tests", e); }
// in src/java/org/apache/fop/tools/TestConverter.java
catch (Exception e) { logger.error("Error while comparing files", e); return false; }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (Exception e) { e.printStackTrace(); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception e) { task.log("Error setting base URL", Project.MSG_DEBUG); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { throw new BuildException("Failed to open " + outFile, ex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { if (task.getThrowexceptions()) { throw new BuildException(ex); } throw ex; }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { logger.error("Error rendering fo file: " + foFile, ex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { logger.error("Error rendering xml/xslt files: " + xmlFile + ", " + xsltFile, ex); }
// in src/java/org/apache/fop/servlet/FopServlet.java
catch (Exception ex) { throw new ServletException(ex); }
// in src/java/org/apache/fop/fo/XMLObj.java
catch (Exception e) { //TODO this is ugly because there may be subsequent failures like NPEs log.error("Error while trying to instantiate a DOM Document", e); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGElement.java
catch (Exception e) { log.error("Could not set base URL for svg", e); }
// in src/java/org/apache/fop/fo/extensions/svg/BatikExtensionElementMapping.java
catch (Exception e) { return null; }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
catch (Exception e) { return SVGDOMImplementation.getDOMImplementation(); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGElementMapping.java
catch (Exception e) { return null; }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (Exception e) { e.printStackTrace(); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (Exception e) { e.printStackTrace(); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (Exception ioe) { System.out.println("Exception " + ioe); ioe.printStackTrace(); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (Exception e) { throw new RuntimeException("Couldn't create XMLReader: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (Exception e) { //ignore, fallback further down }
// in src/java/org/apache/fop/svg/SimpleSVGUserAgent.java
catch (Exception e) { return null; }
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (Exception e) { throw new TranscoderException( "Error while setting up PDFDocumentGraphics2D", e); }
// in src/java/org/apache/fop/svg/PDFANode.java
catch (Exception e) { //TODO Move this to setDestination() and throw an IllegalArgumentException e.printStackTrace(); }
// in src/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java
catch (Exception e) { ctx.getUserAgent().displayError(e); }
// in src/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java
catch (Exception e) { ctx.getUserAgent().displayError(e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new SAXException("Error while parsing integer value: " + str, e); }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
catch (Exception e) { log.error("Error while building XML font metrics file.", e); System.exit(-1); }
// in src/java/org/apache/fop/fonts/apps/PFMReader.java
catch (Exception e) { log.error("Error while building XML font metrics file", e); System.exit(-1); }
// in src/java/org/apache/fop/fonts/autodetect/FontInfoFinder.java
catch (Exception e) { if (this.eventListener != null) { this.eventListener.fontLoadingErrorAtAutoDetection(this, fontFileURL, e); } return null; }
// in src/java/org/apache/fop/fonts/autodetect/FontInfoFinder.java
catch (Exception e) { if (fontCache != null) { fontCache.registerFailedFont(embedURL, fileLastModified); } if (this.eventListener != null) { this.eventListener.fontLoadingErrorAtAutoDetection(this, embedURL, e); } continue; }
// in src/java/org/apache/fop/fonts/autodetect/FontInfoFinder.java
catch (Exception e) { if (fontCache != null) { fontCache.registerFailedFont(embedURL, fileLastModified); } if (this.eventListener != null) { this.eventListener.fontLoadingErrorAtAutoDetection(this, embedURL, e); } return null; }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/AbstractGenericSVGHandler.java
catch (Exception e) { EventBroadcaster eventBroadcaster = userAgent.getEventBroadcaster(); SVGEventProducer eventProducer = SVGEventProducer.Provider.get(eventBroadcaster); final String uri = getDocumentURI(doc); eventProducer.svgNotBuilt(this, e, uri); return null; }
// in src/java/org/apache/fop/render/AbstractRenderer.java
catch (Exception e) { // could not handle document ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( ctx.getUserAgent().getEventBroadcaster()); eventProducer.foreignXMLProcessingError(this, doc, namespace, e); }
// in src/java/org/apache/fop/render/pcl/HardcodedFonts.java
catch (Exception e) { LOG.error(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
catch (Exception e) { final String msg = "RtfTableRow.writePaddingAttributes: " + e.toString(); // getRtfFile().getLog().logWarning(msg); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (Exception e) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + url + "' (" + e + ")"); }
// in src/java/org/apache/fop/render/rtf/PageAttributesConverter.java
catch (Exception e) { log.error("Exception in convertPageAttributes: " + e.getMessage() + "- page attributes ignored"); attrib = new FOPRtfAttributes(); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startTable:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startColumn: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startLink: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnote: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("characters:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumberCitation: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("number format error: cannot convert '" + number + "' to float value"); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("Invalid font size value '" + size + "'"); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/java2d/ConfiguredFontCollection.java
catch (Exception e) { log.warn("Unable to load custom font from file '" + fontFile + "'", e); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
// in src/java/org/apache/fop/afp/apps/FontPatternExtractor.java
catch (Exception e) { e.printStackTrace(); System.exit(-1); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (Exception ex) { // Lets log at least! LOG.error(ex.getMessage()); }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageLoadError(this, pageViewport.getPageNumberString(), e); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageRenderingError(this, pageViewport.getPageNumberString(), e); if (e instanceof RuntimeException) { throw (RuntimeException)e; } }
// in src/java/org/apache/fop/util/ColorSpaceCache.java
catch (Exception e) { // Ignore exception - will be logged a bit further down // (colorSpace == null case) }
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
catch (Exception e) { //Provide a fallback if exotic formats are encountered bi = convertToGrayscale(bi, targetDimension); return converter.convertToMonochrome(bi); }
// in src/java/org/apache/fop/image/loader/batik/ImageConverterSVG2G2D.java
catch (Exception e) { throw new ImageException("GVT tree could not be built for SVG graphic", e); }
// in src/java/org/apache/fop/image/loader/batik/BatikUtil.java
catch (Exception e) { //ignore }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (Exception e) { return null; }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (Exception e) { baseURL = ""; }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (Exception e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (Exception e) { System.err.println("Couldn't set system look & feel!"); }
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { return false; }
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { System.err.println("Unable to start FOP:"); e.printStackTrace(); System.exit(-1); }
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { if (options != null) { options.getLogger().error("Exception", e); if (options.getOutputFile() != null) { options.getOutputFile().delete(); } } System.exit(1); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
catch (Exception e) { System.out.println("An unexpected error occured at line: " + lineNumber ); e.printStackTrace(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
catch (Exception e) { System.out.println("An unexpected error occured"); e.printStackTrace(); }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
catch (Exception e) { System.out.println("An unexpected error occured"); e.printStackTrace(); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (Exception e) { e.printStackTrace(); }
41
            
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (Exception e) { throw new java.io.FileNotFoundException( "URI could not be resolved (" + e.getMessage() + "): " + uri); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { throw new BuildException("Failed to open " + outFile, ex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { if (task.getThrowexceptions()) { throw new BuildException(ex); } throw ex; }
// in src/java/org/apache/fop/servlet/FopServlet.java
catch (Exception ex) { throw new ServletException(ex); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (Exception e) { throw new RuntimeException("Couldn't create XMLReader: " + e.getMessage()); }
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (Exception e) { throw new TranscoderException( "Error while setting up PDFDocumentGraphics2D", e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new SAXException("Error while parsing integer value: " + str, e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (Exception e) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + url + "' (" + e + ")"); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startTable:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startColumn: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startLink: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnote: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("characters:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumberCitation: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("number format error: cannot convert '" + number + "' to float value"); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("Invalid font size value '" + size + "'"); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageRenderingError(this, pageViewport.getPageNumberString(), e); if (e instanceof RuntimeException) { throw (RuntimeException)e; } }
// in src/java/org/apache/fop/image/loader/batik/ImageConverterSVG2G2D.java
catch (Exception e) { throw new ImageException("GVT tree could not be built for SVG graphic", e); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (Exception e) { throw new FOPException(e); }
(Lib) SAXException 85
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException se) { throw new IFException("SAX error in startDocument()", se); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDataUrlImageHandler.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (SAXException saxe) { throw new IOException("Error while serializing XMP stream: " + saxe.getMessage()); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (SAXException saxex) { throw new BuildException(saxex); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (SAXException e) { throw new HyphenationException(errMsg); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException("You need a SAX parser which supports SAX version 2", e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (SAXException e) { log.error("Error while serializing Extension Attachment", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new RuntimeException("Unable to create the " + EL_LOCALE + " element.", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in clipRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawBorderRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing named destination", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing bookmark tree", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing link", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing object", e); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/cli/AreaTreeInputHandler.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (SAXException e) { if (this.sourcefile != null) { source = new StreamSource(this.sourcefile); } else { source = new StreamSource(in, uri); } }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (SAXException e) { // return StreamSource }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (SAXException e) { throw new FOPException(e); }
74
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException se) { throw new IFException("SAX error in startDocument()", se); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDataUrlImageHandler.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (SAXException saxe) { throw new IOException("Error while serializing XMP stream: " + saxe.getMessage()); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (SAXException saxex) { throw new BuildException(saxex); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (SAXException e) { throw new HyphenationException(errMsg); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException("You need a SAX parser which supports SAX version 2", e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new RuntimeException("Unable to create the " + EL_LOCALE + " element.", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in clipRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawBorderRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing named destination", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing bookmark tree", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing link", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing object", e); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/cli/AreaTreeInputHandler.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (SAXException e) { throw new FOPException(e); }
(Domain) IFException 27
            
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFExceptionWithIOException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFExceptionWithIOException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
catch (IFException ife) { throw new SAXException(ife); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting borders", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting a line", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting text", e); }
// in src/java/org/apache/fop/cli/IFInputHandler.java
catch (IFException ife) { throw new FOPException(ife); }
5
            
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
catch (IFException ife) { throw new SAXException(ife); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting borders", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting a line", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting text", e); }
// in src/java/org/apache/fop/cli/IFInputHandler.java
catch (IFException ife) { throw new FOPException(ife); }
(Lib) MalformedURLException 23
            
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mfue) { handleException(mfue, "Could not convert filename '" + href + "' to URL", throwExceptions); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mue) { try { // the above failed, we give it another go in case // the href contains only a path then file: is // assumed absoluteURL = new URL("file:" + href); } catch (MalformedURLException mfue) { handleException(mfue, "Error with URL '" + href + "'", throwExceptions); } }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mfue) { handleException(mfue, "Error with URL '" + href + "'", throwExceptions); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mfue) { handleException(mfue, "Error with base URL '" + base + "'", throwExceptions); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mfue) { handleException(mfue, "Error with URL; base '" + base + "' " + "href '" + href + "'", throwExceptions); }
// in src/java/org/apache/fop/apps/FOUserAgent.java
catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, strict); }
// in src/java/org/apache/fop/pdf/PDFFactory.java
catch (MalformedURLException e) { //TODO: Why construct a new exception here, when it is not thrown? new FileNotFoundException( "File not found. URL could not be resolved: " + e.getMessage()); }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (MalformedURLException mue) { mue.printStackTrace(); }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (MalformedURLException mue) { mue.printStackTrace(); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (MalformedURLException mfue) { logger.error("Error creating base URL from base directory", mfue); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (MalformedURLException mfue) { logger.error("Error creating base URL from XSL-FO input file", mfue); }
// in src/java/org/apache/fop/servlet/ServletContextURIResolver.java
catch (MalformedURLException mfue) { throw new TransformerException( "Error accessing resource using servlet context: " + path, mfue); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + f + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + file + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, true); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (MalformedURLException mfue) { // do nothing }
// in src/java/org/apache/fop/fonts/autodetect/FontFileFinder.java
catch (MalformedURLException e) { log.debug("MalformedURLException" + e.getMessage()); }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
catch (MalformedURLException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
catch (MalformedURLException e) { new FileNotFoundException( "File not found. URL could not be resolved: " + e.getMessage()); }
5
            
// in src/java/org/apache/fop/apps/FOUserAgent.java
catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/servlet/ServletContextURIResolver.java
catch (MalformedURLException mfue) { throw new TransformerException( "Error accessing resource using servlet context: " + path, mfue); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + f + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + file + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); }
(Lib) ConfigurationException 21
            
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, false); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, true); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, true); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, true); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (ConfigurationException ce) { LogUtil.handleException(log, ce, strict); continue; }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); continue; }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/render/XMLHandlerConfigurator.java
catch (ConfigurationException e) { // silently pass over configurations without namespace }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, false); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException ce) { eventProducer.invalidConfiguration(this, ce); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { eventProducer.invalidConfiguration(this, e); LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/AbstractConfigurator.java
catch (ConfigurationException e) { // silently pass over configurations without mime type }
2
            
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
(Lib) ClassNotFoundException 19
            
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (ClassNotFoundException e) { return false; }
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (ClassNotFoundException e) { if (checkAvailableAlgorithms()) { LOG.warn("JCE and algorithms available, but the " + "implementation class unavailable. Please do a full " + "rebuild."); } return null; }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (ClassNotFoundException are) { failed = true; }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + mappingClassName); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (ClassNotFoundException cnfe) { log.error("Error while reading hyphenation object from file", cnfe); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (ClassNotFoundException e) { // We don't really care about the exception since it's just a // cache file log.warn("Could not read font cache. Discarding font cache file. Reason: " + e.getMessage()); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
catch (ClassNotFoundException cnfe) { jaiAvailable = 0; }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassNotFoundException e) { throw new SAXException("Could not find Class for: " + className, e); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
catch (ClassNotFoundException cnfe) { // Class was not compiled so is not available. Simply ignore. }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (ClassNotFoundException e) { // No worries }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (ClassNotFoundException e) { throw new BuildException(e); }
9
            
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + mappingClassName); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassNotFoundException e) { throw new SAXException("Could not find Class for: " + className, e); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (ClassNotFoundException e) { throw new BuildException(e); }
(Domain) FOPException 19
            
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (FOPException ex) { throw new BuildException(ex); }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
catch (FOPException exc) { getFOValidationEventProducer().markerCloningFailed(this, marker.getMarkerClassName(), exc, getLocator()); }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java
catch (FOPException e) { throw new ConfigurationException("Error while setting up fonts", e); }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (FOPException fopex) { log.error("Failed to read font metrics file " + metricsFileName, fopex); if (fail) { throw new RuntimeException(fopex.getMessage()); } }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startInline:" + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startList: " + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
catch (FOPException e) { throw new NoSuchElementException(e.getMessage()); }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
// in src/java/org/apache/fop/render/awt/viewer/ImageProxyPanel.java
catch (FOPException fopEx) { // Arbitary size. Doesn't really matter what's returned here. return new Dimension(10, 10); }
// in src/java/org/apache/fop/render/awt/viewer/ImageProxyPanel.java
catch (FOPException fopEx) { fopEx.printStackTrace(); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java
catch (FOPException e) { e.printStackTrace(); // FIXME Should show exception in gui - was reportException(e); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewDialog.java
catch (FOPException fopEx) { fopEx.printStackTrace(); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewDialog.java
catch (FOPException fopEx) { fopEx.printStackTrace(); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (FOPException fe) { throw new TranscoderException(fe); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (FOPException e) { log.error(e); return NO_SUCH_PAGE; }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (FOPException e) { //TODO use error handler to handle this FOPException or propagate exception String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, e); throw new IllegalStateException("Fatal error occurred. Cannot continue. " + e.getClass().getName() + ": " + err); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (FOPException e) { printUsage(System.err); throw e; }
12
            
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (FOPException ex) { throw new BuildException(ex); }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java
catch (FOPException e) { throw new ConfigurationException("Error while setting up fonts", e); }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (FOPException fopex) { log.error("Failed to read font metrics file " + metricsFileName, fopex); if (fail) { throw new RuntimeException(fopex.getMessage()); } }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startInline:" + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startList: " + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
catch (FOPException e) { throw new NoSuchElementException(e.getMessage()); }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (FOPException fe) { throw new TranscoderException(fe); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (FOPException e) { //TODO use error handler to handle this FOPException or propagate exception String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, e); throw new IllegalStateException("Fatal error occurred. Cannot continue. " + e.getClass().getName() + ": " + err); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (FOPException e) { printUsage(System.err); throw e; }
(Lib) FileNotFoundException 17
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (FileNotFoundException fnfe) { // Note: This is on "debug" level since the caller is // supposed to handle this log.debug("File not found: " + effURL); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(fobj, uri, fnfe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, url, fnfe, getLocator()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (FileNotFoundException fnfe) { throw new HyphenationException("File not found: " + fnfe.getMessage()); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), fe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (FileNotFoundException e) { eventProducer.codePageNotFound(this, e); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (FileNotFoundException e) { eventProducer.codePageNotFound(this, e); }
// in src/java/org/apache/fop/afp/AFPStreamer.java
catch (FileNotFoundException fnfe) { LOG.error("Failed to create/open external resource group file '" + filePath + "'"); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fnfe, getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (FileNotFoundException fnfe) { getResourceEventProducer().imageNotFound(this, uri, fnfe, getExternalDocument().getLocator()); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (FileNotFoundException e) { //handled elsewhere return new StreamSource(this.sourcefile); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (java.io.FileNotFoundException e) { printUsage(System.err); throw e; }
2
            
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (FileNotFoundException fnfe) { throw new HyphenationException("File not found: " + fnfe.getMessage()); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (java.io.FileNotFoundException e) { printUsage(System.err); throw e; }
(Lib) IllegalArgumentException 17
            
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (IllegalArgumentException are) { failed = true; }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
catch (IllegalArgumentException e) { throw new SAXException(e); }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (IllegalArgumentException e) { LOG.warn("Error while adding element mapping", e); }
// in src/java/org/apache/fop/fonts/substitute/FontQualifier.java
catch (IllegalArgumentException ex) { log.error("Invalid font-weight value '" + weightString + "'"); return; }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException(e.getMessage()); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (IllegalArgumentException e) { log.error("Error while adding XMLHandler", e); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalArgumentException e) { log.error("Error while adding maker for Renderer", e); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalArgumentException e) { log.error("Error while adding maker for FOEventHandler", e); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalArgumentException e) { log.error("Error while adding maker for IFDocumentHandler", e); }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException( "Valid values for 'rendering' are 'quality', 'speed' and 'bitmap'." + " Value found: " + rendering); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IllegalArgumentException iae) { eventProducer.invalidConfiguration(this, iae); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IllegalArgumentException iae) { LogUtil.handleException(log, iae, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (IllegalArgumentException e) { log.error("Error while adding ImageHandler", e); }
// in src/java/org/apache/fop/afp/fonts/DoubleByteFont.java
catch (IllegalArgumentException e) { // We shall try and handle characters that have no mapped width metric in font resource charWidth = -1; }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (IllegalArgumentException e) { log.error("Error while adding ContentHandlerFactory", e); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
catch ( IllegalArgumentException e ) { return -1; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
catch ( IllegalArgumentException e ) { throw e; }
4
            
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
catch (IllegalArgumentException e) { throw new SAXException(e); }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException(e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException( "Valid values for 'rendering' are 'quality', 'speed' and 'bitmap'." + " Value found: " + rendering); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
catch ( IllegalArgumentException e ) { throw e; }
(Lib) UnsupportedEncodingException 17
            
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (UnsupportedEncodingException uee) { return text.getBytes(); }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
catch (java.io.UnsupportedEncodingException e) { throw new RuntimeException("Incompatible VM. It doesn't support the US-ASCII encoding"); }
// in src/java/org/apache/fop/fonts/truetype/TTFDirTabEntry.java
catch (UnsupportedEncodingException e) { return this.toString(); // Should never happen. }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
catch (java.io.UnsupportedEncodingException e) { // This should never happen! }
// in src/java/org/apache/fop/afp/fonts/CharacterSet.java
catch (UnsupportedEncodingException usee) { nameBytes = name.getBytes(); LOG.warn( "UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/afp/modca/MapPageSegment.java
catch (UnsupportedEncodingException usee) { LOG.error("UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/afp/modca/AbstractNamedAFPObject.java
catch (UnsupportedEncodingException usee) { nameBytes = name.getBytes(); LOG.warn( "Constructor:: UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (UnsupportedEncodingException e) { endPresentationTextData(); throw e; }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (UnsupportedEncodingException e) { handleUnexpectedIOError(e); //Won't happen for lines }
// in src/java/org/apache/fop/afp/modca/triplets/AttributeValueTriplet.java
catch (UnsupportedEncodingException usee) { tleByteValue = attVal.getBytes(); throw new IllegalArgumentException(attVal + " encoding failed"); }
// in src/java/org/apache/fop/afp/modca/triplets/FullyQualifiedNameTriplet.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( encoding + " encoding failed"); }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); }
// in src/java/org/apache/fop/afp/modca/MapPageOverlay.java
catch (UnsupportedEncodingException usee) { LOG.error("addOverlay():: UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/datatypes/URISpecification.java
catch (UnsupportedEncodingException e) { throw new Error("Incompatible JVM. UTF-8 not supported."); }
9
            
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
catch (java.io.UnsupportedEncodingException e) { throw new RuntimeException("Incompatible VM. It doesn't support the US-ASCII encoding"); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (UnsupportedEncodingException e) { endPresentationTextData(); throw e; }
// in src/java/org/apache/fop/afp/modca/triplets/AttributeValueTriplet.java
catch (UnsupportedEncodingException usee) { tleByteValue = attVal.getBytes(); throw new IllegalArgumentException(attVal + " encoding failed"); }
// in src/java/org/apache/fop/afp/modca/triplets/FullyQualifiedNameTriplet.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( encoding + " encoding failed"); }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); }
// in src/java/org/apache/fop/datatypes/URISpecification.java
catch (UnsupportedEncodingException e) { throw new Error("Incompatible JVM. UTF-8 not supported."); }
(Lib) ImageException 15
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageError(fobj, uri, e, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, url, e, getLocator()); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, uri, ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ie, null); }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
catch (ImageException e) { throw new IOException( "Image conversion error while converting the image to a bitmap" + " as a fallback measure: " + e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (ImageException ie) { throw new IFException( "Error while painting marks using a bitmap", ie); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.imageError(resTracker, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageError(this, uri, e, getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (ImageException ie) { getResourceEventProducer().imageError(this, uri, ie, getExternalDocument().getLocator()); }
2
            
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
catch (ImageException e) { throw new IOException( "Image conversion error while converting the image to a bitmap" + " as a fallback measure: " + e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (ImageException ie) { throw new IFException( "Error while painting marks using a bitmap", ie); }
(Domain) PropertyException 15
            
// in src/java/org/apache/fop/fo/properties/PercentLength.java
catch (PropertyException exc) { log.error(exc); return 0; }
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
catch (PropertyException propEx) { if (fo != null) { propEx.setLocator(fo.getLocator()); } propEx.setPropertyName(getName()); throw propEx; }
// in src/java/org/apache/fop/fo/PropertyList.java
catch ( PropertyException e ) { propID = -1; }
// in src/java/org/apache/fop/fo/PropertyList.java
catch (PropertyException e) { fobj.getFOValidationEventProducer().invalidPropertyValue(this, fobj.getName(), attributeName, attributeValue, e, fobj.locator); }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
catch (PropertyException exc) { log.error(exc); }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
catch (PropertyException exc) { log.error(exc); }
// in src/java/org/apache/fop/fo/expr/NCnameProperty.java
catch (PropertyException e) { //Not logging this error since for properties like "border" you would get an awful //lot of error messages for things like "solid" not being valid colors. //log.error("Can't create color value: " + e.getMessage()); return null; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
catch (PropertyException exc) { exc.setPropertyInfo(propInfo); throw exc; }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the color attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/traits/BorderProps.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
9
            
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
catch (PropertyException propEx) { if (fo != null) { propEx.setLocator(fo.getLocator()); } propEx.setPropertyName(getName()); throw propEx; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
catch (PropertyException exc) { exc.setPropertyInfo(propInfo); throw exc; }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the color attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/traits/BorderProps.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
(Lib) IllegalAccessException 14
            
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (IllegalAccessException e) { LOG.error(e); return null; }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (IllegalAccessException iae) { failed = true; }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + mappingClassName); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/complexscripts/scripts/IndicScriptProcessor.java
catch ( IllegalAccessException e ) { s = null; }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
catch (IllegalAccessException e) { // Problem instantiating the class, simply continue with the backup implementation }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (IllegalAccessException e) { log.error("Error creating the catalog resolver: " + e.getMessage()); eventProducer.catalogResolverNotCreated(this, e.getMessage()); }
9
            
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + mappingClassName); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
(Lib) CloneNotSupportedException 13
            
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
catch (CloneNotSupportedException exc) { return null; }
// in src/java/org/apache/fop/fo/FONode.java
catch (CloneNotSupportedException e) { throw new AssertionError(); // Can't happen }
// in src/java/org/apache/fop/fo/CharIterator.java
catch (CloneNotSupportedException ex) { return null; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfText.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/area/PageViewport.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/layoutmgr/SpaceSpecifier.java
catch (CloneNotSupportedException cnse) { return null; }
// in src/java/org/apache/fop/complexscripts/util/GlyphSequence.java
catch ( CloneNotSupportedException e ) { return null; }
// in src/java/org/apache/fop/complexscripts/util/GlyphSequence.java
catch ( CloneNotSupportedException e ) { return null; }
8
            
// in src/java/org/apache/fop/fo/FONode.java
catch (CloneNotSupportedException e) { throw new AssertionError(); // Can't happen }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfText.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/area/PageViewport.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
(Lib) NumberFormatException 13
            
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (NumberFormatException nfe) { LogUtil.handleException(log, nfe, strict); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (NumberFormatException ne) { throw new SAXException("Malformed width in metric file: " + ne.getMessage(), ne); }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
catch (NumberFormatException e) { err = "Invalid " + METRICS_VERSION_ATTR + " attribute value (" + str + ")"; }
// in src/java/org/apache/fop/fonts/substitute/AttributeValue.java
catch (NumberFormatException ex) { value = FontWeightRange.valueOf(token); if (value == null) { value = token; } }
// in src/java/org/apache/fop/fonts/substitute/FontWeightRange.java
catch (NumberFormatException e) { log.error("invalid font-weight value " + weightString); }
// in src/java/org/apache/fop/fonts/FontUtil.java
catch (NumberFormatException nfe) { //weight is no number, so convert symbolic name to number if (text.equals("normal")) { weight = 400; } else if (text.equals("bold")) { weight = 700; } else { throw new IllegalArgumentException( "Illegal value for font weight: '" + text + "'. Use one of: 100, 200, 300, " + "400, 500, 600, 700, 800, 900, " + "normal (=400), bold (=700)"); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch (NumberFormatException nfe) { return new Double(getDoubleValue(line, startpos)); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (NumberFormatException nfe) { //ignore and leave the default above }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (NumberFormatException nfe) { //ignore and leave the default above }
// in src/java/org/apache/fop/render/awt/viewer/GoToPageDialog.java
catch (NumberFormatException nfe) { pageNumberField.setText("???"); }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
catch (NumberFormatException e) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Invalid codepoint number in " + line); }
5
            
// in src/java/org/apache/fop/fonts/FontReader.java
catch (NumberFormatException ne) { throw new SAXException("Malformed width in metric file: " + ne.getMessage(), ne); }
// in src/java/org/apache/fop/fonts/FontUtil.java
catch (NumberFormatException nfe) { //weight is no number, so convert symbolic name to number if (text.equals("normal")) { weight = 400; } else if (text.equals("bold")) { weight = 700; } else { throw new IllegalArgumentException( "Illegal value for font weight: '" + text + "'. Use one of: 100, 200, 300, " + "400, 500, 600, 700, 800, 900, " + "normal (=400), bold (=700)"); } }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
catch (NumberFormatException e) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Invalid codepoint number in " + line); }
(Lib) URISyntaxException 11
            
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (URISyntaxException e) { //TODO not ideal: our base URLs are actually base URIs. throw new MalformedURLException(e.getMessage()); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (URISyntaxException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fo/properties/URIProperty.java
catch (URISyntaxException use) { // Let PropertyList propagate the exception throw new PropertyException("Invalid URI specified"); }
// in src/java/org/apache/fop/render/pdf/extensions/PDFEmbeddedFileElement.java
catch (URISyntaxException e) { //Filename could not be deduced from URI missingPropertyError("name"); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (URISyntaxException e) { eventProducer.invalidConfiguration(this, e); return null; }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (URISyntaxException urie) { throw new IFException("Could not handle resource url" + pageSegment.getURI(), urie); }
// in src/java/org/apache/fop/render/afp/extensions/AFPIncludeFormMapElement.java
catch (URISyntaxException e) { getFOValidationEventProducer().invalidPropertyValue(this, elementName, ATT_SRC, attr, null, getLocator()); }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
catch (URISyntaxException e) { throw new SAXException("Invalid URI: " + src, e); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (URISyntaxException e) { throw new FileNotFoundException("Invalid filename: " + filename + " (" + e.getMessage() + ")"); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
catch (URISyntaxException e) { throw new IOException("Could not create URI from resource name: " + resourceName + " (" + e.getMessage() + ")"); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (URISyntaxException e) { getResourceEventProducer().uriError(this, uri, e, getExternalDocument().getLocator()); }
7
            
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (URISyntaxException e) { //TODO not ideal: our base URLs are actually base URIs. throw new MalformedURLException(e.getMessage()); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (URISyntaxException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fo/properties/URIProperty.java
catch (URISyntaxException use) { // Let PropertyList propagate the exception throw new PropertyException("Invalid URI specified"); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (URISyntaxException urie) { throw new IFException("Could not handle resource url" + pageSegment.getURI(), urie); }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
catch (URISyntaxException e) { throw new SAXException("Invalid URI: " + src, e); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (URISyntaxException e) { throw new FileNotFoundException("Invalid filename: " + filename + " (" + e.getMessage() + ")"); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
catch (URISyntaxException e) { throw new IOException("Could not create URI from resource name: " + resourceName + " (" + e.getMessage() + ")"); }
(Lib) InstantiationException 10
            
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + mappingClassName); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/complexscripts/scripts/IndicScriptProcessor.java
catch ( InstantiationException e ) { s = null; }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
catch (InstantiationException e) { // Problem instantiating the class, simply continue with the backup implementation }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (InstantiationException e) { log.error("Error creating the catalog resolver: " + e.getMessage()); eventProducer.catalogResolverNotCreated(this, e.getMessage()); }
7
            
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + mappingClassName); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
(Lib) TransformerConfigurationException 10
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException e) { throw new IFException( "Error while setting up a TransformerHandler for SVG generation", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException("Error setting up a Transformer", tce); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (TransformerConfigurationException tce) { throw new IOException("Error setting up Transformer for XMP stream serialization: " + tce.getMessage()); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException( "Error while setting up the serializer for XML output", tce); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerConfigurationException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
10
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException e) { throw new IFException( "Error while setting up a TransformerHandler for SVG generation", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException("Error setting up a Transformer", tce); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (TransformerConfigurationException tce) { throw new IOException("Error setting up Transformer for XMP stream serialization: " + tce.getMessage()); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException( "Error while setting up the serializer for XML output", tce); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerConfigurationException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
(Lib) TransformerException 9
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException)te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
// in src/java/org/apache/fop/apps/FopFactory.java
catch (TransformerException e) { log.error("Attempt to resolve URI '" + href + "' failed: ", e); }
// in src/java/org/apache/fop/apps/FOUserAgent.java
catch (TransformerException te) { log.error("Attempt to resolve URI '" + href + "' failed: ", te); }
// in src/java/org/apache/fop/servlet/FopServlet.java
catch (TransformerException e) { src = null; }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (TransformerException te) { //Unpack original IFException if applicable if (te.getCause() instanceof SAXException) { SAXException se = (SAXException)te.getCause(); if (se.getCause() instanceof IFException) { throw (IFException)se.getCause(); } } else if (te.getCause() instanceof IFException) { throw (IFException)te.getCause(); } throw te; }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
catch (TransformerException e) { throw new MissingResourceException( "Error reading " + resourceName + ": " + e.getMessage(), DefaultEventBroadcaster.class.getName(), ""); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (TransformerException e) { throw new IOException("Error while parsing XML resource bundle: " + e.getMessage()); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
9
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException)te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (TransformerException te) { //Unpack original IFException if applicable if (te.getCause() instanceof SAXException) { SAXException se = (SAXException)te.getCause(); if (se.getCause() instanceof IFException) { throw (IFException)se.getCause(); } } else if (te.getCause() instanceof IFException) { throw (IFException)te.getCause(); } throw te; }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
catch (TransformerException e) { throw new MissingResourceException( "Error reading " + resourceName + ": " + e.getMessage(), DefaultEventBroadcaster.class.getName(), ""); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (TransformerException e) { throw new IOException("Error while parsing XML resource bundle: " + e.getMessage()); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
(Lib) ClassCastException 8
            
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(mappingClassName + " is not an ElementMapping"); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + XMLHandler.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractRendererMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractFOEventHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractIFDocumentHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ImageHandler.class.getName()); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassCastException cce) { throw new SAXException("XML format error: " + qName, cce); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ContentHandlerFactory.class.getName()); }
8
            
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(mappingClassName + " is not an ElementMapping"); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + XMLHandler.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractRendererMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractFOEventHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractIFDocumentHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ImageHandler.class.getName()); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassCastException cce) { throw new SAXException("XML format error: " + qName, cce); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ContentHandlerFactory.class.getName()); }
(Lib) RuntimeException 8
            
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (RuntimeException re) { String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, re); throw re; }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { //wrap in a PropertyException throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException("Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA"); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); //wrap in a PropertyException }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
8
            
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (RuntimeException re) { String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, re); throw re; }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { //wrap in a PropertyException throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException("Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA"); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); //wrap in a PropertyException }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
(Lib) ParserConfigurationException 6
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (ParserConfigurationException e) { throw new IFException("Error while setting up a DOM for SVG generation", e); }
// in src/java/org/apache/fop/fo/ElementMapping.java
catch (ParserConfigurationException e) { throw new RuntimeException( "Cannot return default DOM implementation: " + e.getMessage()); }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
catch (javax.xml.parsers.ParserConfigurationException e) { log.error("Can't create DOM implementation", e); return null; }
// in src/java/org/apache/fop/fonts/apps/PFMReader.java
catch (javax.xml.parsers.ParserConfigurationException e) { log.error("Can't create DOM implementation", e); return null; }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (ParserConfigurationException e) { if (this.sourcefile != null) { source = new StreamSource(this.sourcefile); } else { source = new StreamSource(in, uri); } }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (ParserConfigurationException e) { // return StreamSource }
2
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (ParserConfigurationException e) { throw new IFException("Error while setting up a DOM for SVG generation", e); }
// in src/java/org/apache/fop/fo/ElementMapping.java
catch (ParserConfigurationException e) { throw new RuntimeException( "Cannot return default DOM implementation: " + e.getMessage()); }
(Lib) InvocationTargetException 5
            
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (InvocationTargetException e) { LOG.error(e); return null; }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (InvocationTargetException are) { failed = true; }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/complexscripts/scripts/IndicScriptProcessor.java
catch ( InvocationTargetException e ) { s = null; }
2
            
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
(Domain) MaximumSizeExceededException 5
            
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException msee) { mapCodedFont = factory.createMapCodedFont(); mapCodedFonts.add(mapCodedFont); try { mapCodedFont.addFont(fontRef, font, size, orientation); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createFont():: resulted in a MaximumSizeExceededException"); } }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createFont():: resulted in a MaximumSizeExceededException"); }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException e) { //Should not happen, handled internally throw new IllegalStateException("Internal error: " + e.getMessage()); }
// in src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java
catch (MaximumSizeExceededException msee) { mpo = new MapPageOverlay(); getMapPageOverlays().add(mpo); try { mpo.addOverlay(name); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createOverlay():: resulted in a MaximumSizeExceededException"); } }
// in src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java
catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createOverlay():: resulted in a MaximumSizeExceededException"); }
1
            
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException e) { //Should not happen, handled internally throw new IllegalStateException("Internal error: " + e.getMessage()); }
(Lib) NoSuchMethodException 5
            
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (NoSuchMethodException e) { LOG.error(e); return null; }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (NoSuchMethodException are) { failed = true; }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/complexscripts/scripts/IndicScriptProcessor.java
catch ( NoSuchMethodException e ) { s = null; }
2
            
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
(Lib) SecurityException 5
            
// in src/java/org/apache/fop/fo/properties/PropertyCache.java
catch ( SecurityException e ) { useCache = true; LOG.info("Unable to access org.apache.fop.fo.properties.use-cache" + " due to security restriction; defaulting to 'true'."); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException ioe) { // We don't really care about the exception since it's just a // cache file log.warn("I/O exception while reading font cache (" + ioe.getMessage() + "). Discarding font cache file."); try { cacheFile.delete(); } catch (SecurityException ex) { log.warn("Failed to delete font cache file: " + cacheFile.getAbsolutePath()); } }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (SecurityException ex) { log.warn("Failed to delete font cache file: " + cacheFile.getAbsolutePath()); }
// in src/java/org/apache/fop/fonts/autodetect/WindowsFontDirFinder.java
catch (SecurityException e) { // should continue if this fails }
// in src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java
catch (SecurityException ex) { String msg = "unable to gain write access to external resource file: " + resourceGroupFile; LOG.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java
catch (SecurityException ex) { String msg = "unable to gain read access to external resource file: " + resourceGroupFile; LOG.error(msg); }
0
(Lib) NoClassDefFoundError 4
            
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (NoClassDefFoundError e) { batikAvailable = false; log.warn("Batik not in class path", e); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (NoClassDefFoundError ncdfe) { try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } batikAvailable = false; log.warn("Batik not in class path", ncdfe); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (NoClassDefFoundError e) { batikAvailable = false; log.warn("Batik not in class path", e); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (NoClassDefFoundError ncdfe) { if (in != null) { try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } } batikAvailable = false; log.warn("Batik not in class path", ncdfe); return null; }
0
(Lib) Throwable 4
            
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
catch (Throwable t) { printHelp(); t.printStackTrace(); System.exit(-1); }
// in src/java/org/apache/fop/fo/extensions/svg/BatikExtensionElementMapping.java
catch (Throwable t) { // if the classes are not available // the DISPLAY is not checked batikAvail = false; }
// in src/java/org/apache/fop/fo/extensions/svg/SVGElementMapping.java
catch (Throwable t) { log.error("Error while initializing the Batik SVG extensions", t); // if the classes are not available // the DISPLAY is not checked batikAvailable = false; }
// in src/java/org/apache/fop/svg/AbstractFOPBridgeContext.java
catch (Throwable t) { //simply ignore (bridges instantiated over this method are optional) }
0
(Lib) NoSuchAlgorithmException 3
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (NoSuchAlgorithmException e) { fileIDGenerator = FileIDGenerator.getRandomFileIDGenerator(); }
2
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); }
(Domain) AdvancedTypographicTableFormatException 2
            
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
catch ( AdvancedTypographicTableFormatException e ) { log.warn ( "Encountered format constraint violation in advanced (typographic) table (AT) " + "in font '" + getFullName() + "', ignoring AT data: " + e.getMessage() ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( AdvancedTypographicTableFormatException e ) { resetATStateAll(); throw e; }
1
            
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( AdvancedTypographicTableFormatException e ) { resetATStateAll(); throw e; }
(Domain) HyphenationException 2
            
// in src/java/org/apache/fop/hyphenation/SerializeHyphPattern.java
catch (HyphenationException ex) { System.err.println("Can't load patterns from xml file " + infile + " - Maybe hyphenation.dtd is missing?"); if (errorDump) { System.err.println(ex.toString()); } }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (HyphenationException ex) { log.error("Can't load user patterns from XML file " + source.getSystemId() + ": " + ex.getMessage()); return null; }
0
(Lib) IllegalStateException 2
            
// in src/java/org/apache/fop/layoutmgr/PageSequenceLayoutManager.java
catch (IllegalStateException e) { // empty title; do nothing }
// in src/java/org/apache/fop/layoutmgr/inline/ContentLayoutManager.java
catch (IllegalStateException e) { log.warn("Title has no content"); throw e; }
1
            
// in src/java/org/apache/fop/layoutmgr/inline/ContentLayoutManager.java
catch (IllegalStateException e) { log.warn("Title has no content"); throw e; }
(Lib) PrinterException 2
            
// in src/java/org/apache/fop/render/print/PrintRenderer.java
catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewDialog.java
catch (PrinterException e) { e.printStackTrace(); }
1
            
// in src/java/org/apache/fop/render/print/PrintRenderer.java
catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); }
(Lib) TranscoderException 2
            
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
2
            
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
(Lib) UnsupportedOperationException 2
            
// in src/java/org/apache/fop/fonts/SingleByteFont.java
catch (UnsupportedOperationException e) { log.error("Font '" + super.getFontName() + "': " + e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
catch (UnsupportedOperationException uoe) { log.debug( "Cannot paint graphic natively. Falling back to bitmap painting. Reason: " + uoe.getMessage()); }
0
(Domain) ValidationException 2
            
// in src/java/org/apache/fop/fo/flow/Wrapper.java
catch (ValidationException vex) { invalidChildError(loc, getName(), FO_URI, localName, "rule.wrapperInvalidChildForParent"); }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
catch (ValidationException e) { e.setLocator(locator); throw e; }
1
            
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
catch (ValidationException e) { e.setLocator(locator); throw e; }
(Lib) BadPaddingException 1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (BadPaddingException e) { throw new IllegalStateException(e.getMessage()); }
1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (BadPaddingException e) { throw new IllegalStateException(e.getMessage()); }
(Lib) DSCException 1
            
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (DSCException e) { throw new RuntimeException(e.getMessage()); }
1
            
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (DSCException e) { throw new RuntimeException(e.getMessage()); }
(Domain) EventConventionException 1
            
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (EventConventionException ece) { throw new BuildException(ece); }
1
            
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (EventConventionException ece) { throw new BuildException(ece); }
(Domain) ExternalGraphicException 1
            
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (ExternalGraphicException ie) { writeExceptionInRtf(ie); }
0
(Lib) IllegalBlockSizeException 1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (IllegalBlockSizeException e) { throw new IllegalStateException(e.getMessage()); }
1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (IllegalBlockSizeException e) { throw new IllegalStateException(e.getMessage()); }
(Lib) InvalidKeyException 1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (InvalidKeyException e) { throw new IllegalStateException(e); }
1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (InvalidKeyException e) { throw new IllegalStateException(e); }
(Lib) LinkageError 1
            
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
catch (LinkageError le) { // This can happen if fop was build with support for a // particular provider (e.g. a binary fop distribution) // but the required support files (i.e. JAI) are not // available in the current runtime environment. // Simply continue with the backup implementation. }
0
(Lib) MissingResourceException 1
            
// in src/java/org/apache/fop/events/EventFormatter.java
catch ( MissingResourceException e ) { if ( log.isTraceEnabled() ) { log.trace ( "No XMLResourceBundle for " + baseName + " available." ); } bundle = null; }
0
(Lib) NoSuchPaddingException 1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchPaddingException e) { throw new UnsupportedOperationException(e); }
1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchPaddingException e) { throw new UnsupportedOperationException(e); }
(Lib) PSDictionaryFormatException 1
            
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); }
0
(Domain) RtfException 1
            
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (RtfException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
1
            
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (RtfException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
(Lib) TransformerFactoryConfigurationError 1
            
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerFactoryConfigurationError e) { throw new IOException(e.getMessage()); }
1
            
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerFactoryConfigurationError e) { throw new IOException(e.getMessage()); }

Exception Recast Summary

There is a common practice of throwing exceptions from within a catch block (e.g. for wrapping a low-level exception). The following table summarizes the usage of this practice in the application. The last column gives the number of times it happens for a pair of exceptions. The graph below the table graphically renders the same information. For a given node, its color represents its origin (blue means library exception, orange means domain exception); the left-most number is the number of times it is thrown, the right-most is the number of times it is caught.

Catch Throw
(Lib) SAXException
(Domain) IFException
(Lib) IOException
(Lib) BuildException
(Domain) HyphenationException
(Domain) FOPException
(Lib) RuntimeException
60
                    
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException se) { throw new IFException("SAX error in startDocument()", se); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in clipRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawBorderRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing named destination", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing bookmark tree", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing link", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing object", e); }
3
                    
// in src/sandbox/org/apache/fop/render/svg/SVGDataUrlImageHandler.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (SAXException saxe) { throw new IOException("Error while serializing XMP stream: " + saxe.getMessage()); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
1
                    
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (SAXException saxex) { throw new BuildException(saxex); }
1
                    
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (SAXException e) { throw new HyphenationException(errMsg); }
4
                    
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException("You need a SAX parser which supports SAX version 2", e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/AreaTreeInputHandler.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (SAXException e) { throw new FOPException(e); }
5
                    
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new RuntimeException("Unable to create the " + EL_LOCALE + " element.", e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
(Domain) FOPException
(Lib) BuildException
(Lib) ConfigurationException
(Lib) RuntimeException
(Lib) IndexOutOfBoundsException
(Lib) NoSuchElementException
(Lib) TranscoderException
(Lib) IllegalStateException
Unknown
1
                    
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (FOPException ex) { throw new BuildException(ex); }
1
                    
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java
catch (FOPException e) { throw new ConfigurationException("Error while setting up fonts", e); }
4
                    
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (FOPException fopex) { log.error("Failed to read font metrics file " + metricsFileName, fopex); if (fail) { throw new RuntimeException(fopex.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startInline:" + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startList: " + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
2
                    
// in src/java/org/apache/fop/render/print/PageableRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
1
                    
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
catch (FOPException e) { throw new NoSuchElementException(e.getMessage()); }
1
                    
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (FOPException fe) { throw new TranscoderException(fe); }
1
                    
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (FOPException e) { //TODO use error handler to handle this FOPException or propagate exception String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, e); throw new IllegalStateException("Fatal error occurred. Cannot continue. " + e.getClass().getName() + ": " + err); }
1
                    
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (FOPException e) { printUsage(System.err); throw e; }
(Domain) PropertyException
(Domain) IFException
(Lib) IllegalArgumentException
Unknown
3
                    
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the color attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
3
                    
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/traits/BorderProps.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
3
                    
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
catch (PropertyException propEx) { if (fo != null) { propEx.setLocator(fo.getLocator()); } propEx.setPropertyName(getName()); throw propEx; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
catch (PropertyException exc) { exc.setPropertyInfo(propInfo); throw exc; }
(Domain) ValidationException
Unknown
1
                    
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
catch (ValidationException e) { e.setLocator(locator); throw e; }
(Domain) IFException
(Lib) SAXException
(Lib) RuntimeException
(Domain) FOPException
1
                    
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
catch (IFException ife) { throw new SAXException(ife); }
3
                    
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting borders", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting a line", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting text", e); }
1
                    
// in src/java/org/apache/fop/cli/IFInputHandler.java
catch (IFException ife) { throw new FOPException(ife); }
(Lib) ImageException
(Lib) IOException
(Domain) IFException
1
                    
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
catch (ImageException e) { throw new IOException( "Image conversion error while converting the image to a bitmap" + " as a fallback measure: " + e.getMessage()); }
1
                    
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (ImageException ie) { throw new IFException( "Error while painting marks using a bitmap", ie); }
(Lib) FileNotFoundException
(Domain) HyphenationException
Unknown
1
                    
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (FileNotFoundException fnfe) { throw new HyphenationException("File not found: " + fnfe.getMessage()); }
1
                    
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (java.io.FileNotFoundException e) { printUsage(System.err); throw e; }
(Lib) IOException
(Domain) IFException
(Lib) SAXException
(Lib) RuntimeException
(Lib) BuildException
(Domain) HyphenationException
(Lib) TranscoderException
(Domain) FOPException
(Lib) TransformerException
(Lib) IllegalStateException
(Domain) AdvancedTypographicTableFormatException
(Lib) MissingResourceException
(Domain) PropertyException
Unknown
61
                    
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O exception while setting up output file", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error flushing the PDF document", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error while drawing borders", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe); }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding page image", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException( "I/O error while painting marks using a bitmap", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding BufferedImage", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException( "I/O error while embedding form map resource: " + formMap.getName(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Could not handle resource" + pageSegment.getURI(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("IO error while painting rectangle", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ife) { throw new IFException("IO error while painting borders", ife); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Error while embedding font resources", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error writing the PostScript header", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageContent()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in handleExtensionObject()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in clipRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawBorderRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
7
                    
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new SAXException(ioe.getMessage()); }
// in src/java/org/apache/fop/svg/FOPSAXSVGDocumentFactory.java
catch (IOException ioe) { /**@todo Batik's SAXSVGDocumentFactory should throw IOException, * so we don't have to handle it here. */ throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException ex) { throw new SAXException(ex); }
9
                    
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (IOException e) { // won't happen. We're operating in-memory. throw new RuntimeException( "Error during base64 encodation of username/password"); }
// in src/java/org/apache/fop/pdf/PDFStream.java
catch (IOException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/pdf/PDFICCBasedColorSpace.java
catch (IOException ioe) { throw new RuntimeException( "Unexpected IOException loading the sRGB profile: " + ioe.getMessage()); }
// in src/java/org/apache/fop/svg/NativeTextPainter.java
catch (IOException ioe) { //No other possibility than to use a RuntimeException throw new RuntimeException(ioe); }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (IOException ioex) { log.error("Failed to read font metrics file " + metricsFileName, ioex); if (fail) { throw new RuntimeException(ioex.getMessage()); } }
// in src/java/org/apache/fop/render/txt/TXTStream.java
catch (IOException e) { throw new RuntimeException(e.toString()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/afp/svg/AFPTextHandler.java
catch (IOException ioe) { throw new RuntimeException("Error while embedding font resources", ioe); }
2
                    
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (IOException ioe) { throw new BuildException(ioe); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (IOException ioe) { throw new BuildException(ioe); }
1
                    
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new HyphenationException(ioe.getMessage()); }
2
                    
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
3
                    
// in src/java/org/apache/fop/fonts/FontReader.java
catch (IOException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IOException ioe) { throw new FOPException("Could not create default external resource group file" , ioe); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException e) { throw new FOPException(e); }
1
                    
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
catch (IOException ioe) { throw new TransformerException("Error writing the output file", ioe); }
1
                    
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException e) { //Won't happen with Java2D throw new IllegalStateException("Unexpected I/O error"); }
1
                    
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( IOException e ) { resetATStateAll(); throw new AdvancedTypographicTableFormatException ( e.getMessage(), e ); }
1
                    
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (IOException e) { throw new MissingResourceException(e.getMessage(), base, null); }
1
                    
// in src/java/org/apache/fop/util/ColorUtil.java
catch (IOException ioe) { //wrap in a PropertyException throw new PropertyException(ioe); }
1
                    
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
catch (IOException ioe) { if (afm == null) { // Ignore the exception if we have a valid PFM. PFM is only the fallback. throw ioe; } }
(Domain) RtfException
(Lib) RuntimeException
1
                    
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (RtfException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
(Lib) ParserConfigurationException
(Domain) IFException
(Lib) RuntimeException
1
                    
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (ParserConfigurationException e) { throw new IFException("Error while setting up a DOM for SVG generation", e); }
1
                    
// in src/java/org/apache/fop/fo/ElementMapping.java
catch (ParserConfigurationException e) { throw new RuntimeException( "Cannot return default DOM implementation: " + e.getMessage()); }
(Lib) TransformerConfigurationException
(Domain) IFException
(Lib) IOException
(Lib) SAXException
(Lib) RuntimeException
3
                    
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException e) { throw new IFException( "Error while setting up a TransformerHandler for SVG generation", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException("Error setting up a Transformer", tce); }
// in src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException( "Error while setting up the serializer for XML output", tce); }
2
                    
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (TransformerConfigurationException tce) { throw new IOException("Error setting up Transformer for XMP stream serialization: " + tce.getMessage()); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerConfigurationException e) { throw new IOException(e.getMessage()); }
3
                    
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
2
                    
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
(Lib) TransformerException
(Domain) IFException
(Lib) IOException
(Lib) MissingResourceException
Unknown
1
                    
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException)te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } }
3
                    
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (TransformerException e) { throw new IOException("Error while parsing XML resource bundle: " + e.getMessage()); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
1
                    
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
catch (TransformerException e) { throw new MissingResourceException( "Error reading " + resourceName + ": " + e.getMessage(), DefaultEventBroadcaster.class.getName(), ""); }
4
                    
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException)te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (TransformerException te) { //Unpack original IFException if applicable if (te.getCause() instanceof SAXException) { SAXException se = (SAXException)te.getCause(); if (se.getCause() instanceof IFException) { throw (IFException)se.getCause(); } } else if (te.getCause() instanceof IFException) { throw (IFException)te.getCause(); } throw te; }
(Lib) MalformedURLException
(Lib) IllegalArgumentException
(Lib) TransformerException
(Domain) HyphenationException
(Domain) ExternalGraphicException
1
                    
// in src/java/org/apache/fop/apps/FOUserAgent.java
catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); }
1
                    
// in src/java/org/apache/fop/servlet/ServletContextURIResolver.java
catch (MalformedURLException mfue) { throw new TransformerException( "Error accessing resource using servlet context: " + path, mfue); }
2
                    
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + f + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + file + "' to a URL: " + e.getMessage()); }
1
                    
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); }
(Lib) URISyntaxException
(Lib) MalformedURLException
(Domain) FOPException
(Domain) PropertyException
(Domain) IFException
(Lib) SAXException
(Lib) FileNotFoundException
(Lib) IOException
1
                    
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (URISyntaxException e) { //TODO not ideal: our base URLs are actually base URIs. throw new MalformedURLException(e.getMessage()); }
1
                    
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (URISyntaxException e) { throw new FOPException(e); }
1
                    
// in src/java/org/apache/fop/fo/properties/URIProperty.java
catch (URISyntaxException use) { // Let PropertyList propagate the exception throw new PropertyException("Invalid URI specified"); }
1
                    
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (URISyntaxException urie) { throw new IFException("Could not handle resource url" + pageSegment.getURI(), urie); }
1
                    
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
catch (URISyntaxException e) { throw new SAXException("Invalid URI: " + src, e); }
1
                    
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (URISyntaxException e) { throw new FileNotFoundException("Invalid filename: " + filename + " (" + e.getMessage() + ")"); }
1
                    
// in src/java/org/apache/fop/afp/AFPResourceManager.java
catch (URISyntaxException e) { throw new IOException("Could not create URI from resource name: " + resourceName + " (" + e.getMessage() + ")"); }
(Lib) RuntimeException
(Domain) PropertyException
Unknown
7
                    
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { //wrap in a PropertyException throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException("Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA"); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); //wrap in a PropertyException }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
1
                    
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (RuntimeException re) { String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, re); throw re; }
(Domain) AdvancedTypographicTableFormatException
Unknown
1
                    
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( AdvancedTypographicTableFormatException e ) { resetATStateAll(); throw e; }
(Lib) IllegalStateException
Unknown
1
                    
// in src/java/org/apache/fop/layoutmgr/inline/ContentLayoutManager.java
catch (IllegalStateException e) { log.warn("Title has no content"); throw e; }
(Lib) IllegalArgumentException
(Lib) SAXException
(Domain) FOPException
Unknown
1
                    
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
catch (IllegalArgumentException e) { throw new SAXException(e); }
2
                    
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException(e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException( "Valid values for 'rendering' are 'quality', 'speed' and 'bitmap'." + " Value found: " + rendering); }
1
                    
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
catch ( IllegalArgumentException e ) { throw e; }
(Lib) ConfigurationException
(Domain) FOPException
2
                    
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
(Lib) NumberFormatException
(Lib) SAXException
(Lib) IllegalArgumentException
(Lib) Exception
1
                    
// in src/java/org/apache/fop/fonts/FontReader.java
catch (NumberFormatException ne) { throw new SAXException("Malformed width in metric file: " + ne.getMessage(), ne); }
3
                    
// in src/java/org/apache/fop/fonts/FontUtil.java
catch (NumberFormatException nfe) { //weight is no number, so convert symbolic name to number if (text.equals("normal")) { weight = 400; } else if (text.equals("bold")) { weight = 700; } else { throw new IllegalArgumentException( "Illegal value for font weight: '" + text + "'. Use one of: 100, 200, 300, " + "400, 500, 600, 700, 800, 900, " + "normal (=400), bold (=700)"); } }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
1
                    
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
catch (NumberFormatException e) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Invalid codepoint number in " + line); }
(Lib) NoSuchAlgorithmException
(Lib) UnsupportedOperationException
2
                    
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); }
(Lib) IllegalBlockSizeException
(Lib) IllegalStateException
1
                    
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (IllegalBlockSizeException e) { throw new IllegalStateException(e.getMessage()); }
(Lib) BadPaddingException
(Lib) IllegalStateException
1
                    
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (BadPaddingException e) { throw new IllegalStateException(e.getMessage()); }
(Lib) InvalidKeyException
(Lib) IllegalStateException
1
                    
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (InvalidKeyException e) { throw new IllegalStateException(e); }
(Lib) NoSuchPaddingException
(Lib) UnsupportedOperationException
1
                    
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchPaddingException e) { throw new UnsupportedOperationException(e); }
(Lib) Exception
(Lib) FileNotFoundException
(Lib) BuildException
(Lib) ServletException
(Lib) RuntimeException
(Lib) TranscoderException
(Domain) FOPException
(Lib) SAXException
(Domain) ExternalGraphicException
(Lib) ImageException
Unknown
1
                    
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (Exception e) { throw new java.io.FileNotFoundException( "URI could not be resolved (" + e.getMessage() + "): " + uri); }
2
                    
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { throw new BuildException("Failed to open " + outFile, ex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { if (task.getThrowexceptions()) { throw new BuildException(ex); } throw ex; }
1
                    
// in src/java/org/apache/fop/servlet/FopServlet.java
catch (Exception ex) { throw new ServletException(ex); }
27
                    
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (Exception e) { throw new RuntimeException("Couldn't create XMLReader: " + e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startTable:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startColumn: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startLink: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnote: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("characters:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumberCitation: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
1
                    
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (Exception e) { throw new TranscoderException( "Error while setting up PDFDocumentGraphics2D", e); }
4
                    
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("number format error: cannot convert '" + number + "' to float value"); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("Invalid font size value '" + size + "'"); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (Exception e) { throw new FOPException(e); }
1
                    
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new SAXException("Error while parsing integer value: " + str, e); }
1
                    
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (Exception e) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + url + "' (" + e + ")"); }
1
                    
// in src/java/org/apache/fop/image/loader/batik/ImageConverterSVG2G2D.java
catch (Exception e) { throw new ImageException("GVT tree could not be built for SVG graphic", e); }
2
                    
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { if (task.getThrowexceptions()) { throw new BuildException(ex); } throw ex; }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageRenderingError(this, pageViewport.getPageNumberString(), e); if (e instanceof RuntimeException) { throw (RuntimeException)e; } }
(Domain) MaximumSizeExceededException
(Lib) IllegalStateException
1
                    
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException e) { //Should not happen, handled internally throw new IllegalStateException("Internal error: " + e.getMessage()); }
(Domain) EventConventionException
(Lib) BuildException
1
                    
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (EventConventionException ece) { throw new BuildException(ece); }
(Lib) UnsupportedEncodingException
(Lib) CascadingRuntimeException
(Lib) RuntimeException
(Lib) IllegalArgumentException
(Domain) FontRuntimeException
(Lib) Error
Unknown
3
                    
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
1
                    
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
catch (java.io.UnsupportedEncodingException e) { throw new RuntimeException("Incompatible VM. It doesn't support the US-ASCII encoding"); }
2
                    
// in src/java/org/apache/fop/afp/modca/triplets/AttributeValueTriplet.java
catch (UnsupportedEncodingException usee) { tleByteValue = attVal.getBytes(); throw new IllegalArgumentException(attVal + " encoding failed"); }
// in src/java/org/apache/fop/afp/modca/triplets/FullyQualifiedNameTriplet.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( encoding + " encoding failed"); }
1
                    
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); }
1
                    
// in src/java/org/apache/fop/datatypes/URISpecification.java
catch (UnsupportedEncodingException e) { throw new Error("Incompatible JVM. UTF-8 not supported."); }
1
                    
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (UnsupportedEncodingException e) { endPresentationTextData(); throw e; }
(Lib) ClassNotFoundException
(Lib) IllegalArgumentException
(Lib) SAXException
(Lib) BuildException
7
                    
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + mappingClassName); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
1
                    
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassNotFoundException e) { throw new SAXException("Could not find Class for: " + className, e); }
1
                    
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (ClassNotFoundException e) { throw new BuildException(e); }
(Lib) NoSuchMethodException
(Lib) RuntimeException
2
                    
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
(Lib) IllegalAccessException
(Lib) IllegalArgumentException
(Lib) RuntimeException
7
                    
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + mappingClassName); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
2
                    
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
(Lib) InvocationTargetException
(Lib) RuntimeException
2
                    
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
(Lib) CloneNotSupportedException
(Lib) AssertionError
(Domain) FOPException
1
                    
// in src/java/org/apache/fop/fo/FONode.java
catch (CloneNotSupportedException e) { throw new AssertionError(); // Can't happen }
7
                    
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfText.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/area/PageViewport.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
(Lib) InstantiationException
(Lib) IllegalArgumentException
7
                    
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + mappingClassName); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
(Lib) ClassCastException
(Lib) IllegalArgumentException
(Lib) SAXException
7
                    
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(mappingClassName + " is not an ElementMapping"); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + XMLHandler.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractRendererMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractFOEventHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractIFDocumentHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ImageHandler.class.getName()); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ContentHandlerFactory.class.getName()); }
1
                    
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassCastException cce) { throw new SAXException("XML format error: " + qName, cce); }
(Lib) TranscoderException
(Lib) RuntimeException
2
                    
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
(Lib) PrinterException
(Lib) IOException
1
                    
// in src/java/org/apache/fop/render/print/PrintRenderer.java
catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); }
(Lib) DSCException
(Lib) RuntimeException
1
                    
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (DSCException e) { throw new RuntimeException(e.getMessage()); }
(Lib) TransformerFactoryConfigurationError
(Lib) IOException
1
                    
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerFactoryConfigurationError e) { throw new IOException(e.getMessage()); }

Caught / Thrown Exception

Not all exceptions are thrown AND caught in the same project. The following table gives the exceptions types with respect to this. The lower left hand side sell lists all exceptions thrown but not caught (prevalent for libraries), the upper right-hand side lists all exceptions caught but not thrown (usually coming from external dependencies).

Thrown Not Thrown
Caught
Type Name
(Lib) SAXException
(Domain) FOPException
(Domain) PropertyException
(Domain) ValidationException
(Domain) IFException
(Lib) ImageException
(Lib) FileNotFoundException
(Lib) IOException
(Domain) RtfException
(Domain) ExternalGraphicException
(Lib) UnsupportedOperationException
(Lib) TransformerException
(Lib) MalformedURLException
(Lib) RuntimeException
(Domain) AdvancedTypographicTableFormatException
(Lib) IllegalStateException
(Lib) IllegalArgumentException
(Lib) ConfigurationException
(Lib) NumberFormatException
(Lib) Exception
(Domain) HyphenationException
(Domain) MaximumSizeExceededException
(Domain) EventConventionException
(Lib) TranscoderException
(Lib) DSCException
(Lib) MissingResourceException
Type Name
(Lib) ParserConfigurationException
(Lib) TransformerConfigurationException
(Lib) URISyntaxException
(Lib) NoSuchAlgorithmException
(Lib) IllegalBlockSizeException
(Lib) BadPaddingException
(Lib) InvalidKeyException
(Lib) NoSuchPaddingException
(Lib) UnsupportedEncodingException
(Lib) ClassNotFoundException
(Lib) NoSuchMethodException
(Lib) IllegalAccessException
(Lib) InvocationTargetException
(Lib) Throwable
(Lib) SecurityException
(Lib) CloneNotSupportedException
(Lib) InstantiationException
(Lib) ClassCastException
(Lib) PrinterException
(Lib) PSDictionaryFormatException
(Lib) TransformerFactoryConfigurationError
(Lib) LinkageError
(Lib) NoClassDefFoundError
Not caught
Type Name
(Lib) NullPointerException
(Domain) PDFConformanceException
(Domain) PDFFilterException
(Lib) CascadingRuntimeException
(Lib) BuildException
(Lib) ServletException
(Lib) NoSuchElementException
(Lib) IndexOutOfBoundsException
(Domain) PageProductionException
(Lib) AssertionError
(Lib) EOFException
(Domain) RtfStructureException
(Domain) FontRuntimeException
(Lib) Error
(Lib) ArithmeticException

Methods called in Catch and Finally Blocks

The following shows the methods that are called inside catch blocks (first column) and finally blocks (second column). For each method, we give the number of times it is called in a catch block (second sub-column), and the total number of calls (third sub-column). If the method name is red, it means that it is only called from catch/finally blocks. Hovering over a number triggers showing code snippets from the application code.

Catch Finally
Method Nbr Nbr total
getMessage 128
                  
// in src/sandbox/org/apache/fop/render/svg/SVGDataUrlImageHandler.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (URISyntaxException e) { //TODO not ideal: our base URLs are actually base URIs. throw new MalformedURLException(e.getMessage()); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (java.io.IOException ioe) { log.error("Error with opening URL '" + effURL + "': " + ioe.getMessage()); }
// in src/java/org/apache/fop/apps/FOUserAgent.java
catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (IllegalBlockSizeException e) { throw new IllegalStateException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (BadPaddingException e) { throw new IllegalStateException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFFactory.java
catch (MalformedURLException e) { //TODO: Why construct a new exception here, when it is not thrown? new FileNotFoundException( "File not found. URL could not be resolved: " + e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFICCBasedColorSpace.java
catch (IOException ioe) { throw new RuntimeException( "Unexpected IOException loading the sRGB profile: " + ioe.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (Exception e) { throw new java.io.FileNotFoundException( "URI could not be resolved (" + e.getMessage() + "): " + uri); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (TransformerConfigurationException tce) { throw new IOException("Error setting up Transformer for XMP stream serialization: " + tce.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (SAXException saxe) { throw new IOException("Error while serializing XMP stream: " + saxe.getMessage()); }
// in src/java/org/apache/fop/fo/ElementMapping.java
catch (ParserConfigurationException e) { throw new RuntimeException( "Cannot return default DOM implementation: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + f + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + file + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (FileNotFoundException fnfe) { throw new HyphenationException("File not found: " + fnfe.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new HyphenationException(ioe.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (Exception e) { throw new RuntimeException("Couldn't create XMLReader: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new SAXException(ioe.getMessage()); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (HyphenationException ex) { log.error("Can't load user patterns from XML file " + source.getSystemId() + ": " + ex.getMessage()); return null; }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (NumberFormatException ne) { throw new SAXException("Malformed width in metric file: " + ne.getMessage(), ne); }
// in src/java/org/apache/fop/fonts/SingleByteFont.java
catch (UnsupportedOperationException e) { log.error("Font '" + super.getFontName() + "': " + e.getMessage()); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (ClassNotFoundException e) { // We don't really care about the exception since it's just a // cache file log.warn("Could not read font cache. Discarding font cache file. Reason: " + e.getMessage()); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException ioe) { // We don't really care about the exception since it's just a // cache file log.warn("I/O exception while reading font cache (" + ioe.getMessage() + "). Discarding font cache file."); try { cacheFile.delete(); } catch (SecurityException ex) { log.warn("Failed to delete font cache file: " + cacheFile.getAbsolutePath()); } }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException e) { // Should never happen, because URL must be local log.debug("IOError: " + e.getMessage()); return 0; }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (FOPException fopex) { log.error("Failed to read font metrics file " + metricsFileName, fopex); if (fail) { throw new RuntimeException(fopex.getMessage()); } }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (IOException ioex) { log.error("Failed to read font metrics file " + metricsFileName, ioex); if (fail) { throw new RuntimeException(ioex.getMessage()); } }
// in src/java/org/apache/fop/fonts/autodetect/FontFileFinder.java
catch (MalformedURLException e) { log.debug("MalformedURLException" + e.getMessage()); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
catch ( AdvancedTypographicTableFormatException e ) { log.warn ( "Encountered format constraint violation in advanced (typographic) table (AT) " + "in font '" + getFullName() + "', ignoring AT data: " + e.getMessage() ); }
// in src/java/org/apache/fop/render/print/PrintRenderer.java
catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException(e.getMessage()); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
catch (UnsupportedOperationException uoe) { log.debug( "Cannot paint graphic natively. Falling back to bitmap painting. Reason: " + uoe.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
catch (ImageException e) { throw new IOException( "Image conversion error while converting the image to a bitmap" + " as a fallback measure: " + e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/PageAttributesConverter.java
catch (Exception e) { log.error("Exception in convertPageAttributes: " + e.getMessage() + "- page attributes ignored"); attrib = new FOPRtfAttributes(); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startTable:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startColumn: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startInline:" + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startList: " + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startLink: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnote: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("characters:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumberCitation: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (RtfException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
catch (FOPException e) { throw new NoSuchElementException(e.getMessage()); }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
catch (MalformedURLException e) { new FileNotFoundException( "File not found. URL could not be resolved: " + e.getMessage()); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (DSCException e) { throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (URISyntaxException e) { throw new FileNotFoundException("Invalid filename: " + filename + " (" + e.getMessage() + ")"); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (Exception ex) { // Lets log at least! LOG.error(ex.getMessage()); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
catch (URISyntaxException e) { throw new IOException("Could not create URI from resource name: " + resourceName + " (" + e.getMessage() + ")"); }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException e) { //Should not happen, handled internally throw new IllegalStateException("Internal error: " + e.getMessage()); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerConfigurationException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerFactoryConfigurationError e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
catch (TransformerException e) { throw new MissingResourceException( "Error reading " + resourceName + ": " + e.getMessage(), DefaultEventBroadcaster.class.getName(), ""); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/traits/BorderProps.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( IOException e ) { resetATStateAll(); throw new AdvancedTypographicTableFormatException ( e.getMessage(), e ); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (TransformerException e) { throw new IOException("Error while parsing XML resource bundle: " + e.getMessage()); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (IOException e) { throw new MissingResourceException(e.getMessage(), base, null); }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (IOException e) { // If the svg is invalid then it throws an IOException // so there is no way of knowing if it is an svg document log.debug("Error while trying to load stream as an WMF file: " + e.getMessage()); // assuming any exception means this document is not svg // or could not be loaded for some reason try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (IOException e) { // If the svg is invalid then it throws an IOException // so there is no way of knowing if it is an svg document log.debug("Error while trying to load stream as an SVG file: " + e.getMessage()); // assuming any exception means this document is not svg // or could not be loaded for some reason try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } return null; }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (InstantiationException e) { log.error("Error creating the catalog resolver: " + e.getMessage()); eventProducer.catalogResolverNotCreated(this, e.getMessage()); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (IllegalAccessException e) { log.error("Error creating the catalog resolver: " + e.getMessage()); eventProducer.catalogResolverNotCreated(this, e.getMessage()); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
145
log 99
                  
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception e) { task.log("Error setting base URL", Project.MSG_DEBUG); }
1335
error 98
                  
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (java.io.IOException ioe) { log.error("Error with opening URL '" + effURL + "': " + ioe.getMessage()); }
// in src/java/org/apache/fop/apps/FopFactory.java
catch (TransformerException e) { log.error("Attempt to resolve URI '" + href + "' failed: ", e); }
// in src/java/org/apache/fop/apps/FOUserAgent.java
catch (TransformerException te) { log.error("Attempt to resolve URI '" + href + "' failed: ", te); }
// in src/java/org/apache/fop/pdf/PDFFactory.java
catch (IOException ioe) { log.error( "Failed to write CIDSet [" + cidFont + "] " + cidFont.getEmbedFontName(), ioe); }
// in src/java/org/apache/fop/pdf/PDFFactory.java
catch (IOException ioe) { log.error( "Failed to embed font [" + desc + "] " + desc.getEmbedFontName(), ioe); return null; }
// in src/java/org/apache/fop/pdf/PDFOutputIntent.java
catch (IOException ioe) { log.error("Ignored I/O exception", ioe); }
// in src/java/org/apache/fop/pdf/PDFInfo.java
catch (IOException ioe) { log.error("Ignored I/O exception", ioe); }
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (NoSuchMethodException e) { LOG.error(e); return null; }
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (IllegalAccessException e) { LOG.error(e); return null; }
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (InvocationTargetException e) { LOG.error(e); return null; }
// in src/java/org/apache/fop/pdf/PDFOutline.java
catch (IOException ioe) { log.error("Ignored I/O exception", ioe); }
// in src/java/org/apache/fop/tools/TestConverter.java
catch (Exception e) { logger.error("Error while running tests", e); }
// in src/java/org/apache/fop/tools/TestConverter.java
catch (Exception e) { logger.error("Error setting base directory"); }
// in src/java/org/apache/fop/tools/TestConverter.java
catch (Exception e) { logger.error("Error while running tests", e); }
// in src/java/org/apache/fop/tools/TestConverter.java
catch (Exception e) { logger.error("Error while comparing files", e); return false; }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (MalformedURLException mfue) { logger.error("Error creating base URL from base directory", mfue); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (MalformedURLException mfue) { logger.error("Error creating base URL from XSL-FO input file", mfue); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (IOException ioe) { logger.error("Error closing output file", ioe); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { logger.error("Error rendering fo file: " + foFile, ex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { logger.error("Error rendering xml/xslt files: " + xmlFile + ", " + xsltFile, ex); }
// in src/java/org/apache/fop/fo/XMLObj.java
catch (Exception e) { //TODO this is ugly because there may be subsequent failures like NPEs log.error("Error while trying to instantiate a DOM Document", e); }
// in src/java/org/apache/fop/fo/properties/PercentLength.java
catch (PropertyException exc) { log.error(exc); return 0; }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
catch (PropertyException exc) { log.error(exc); }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
catch (PropertyException exc) { log.error(exc); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGElement.java
catch (Exception e) { log.error("Could not set base URL for svg", e); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGElementMapping.java
catch (Throwable t) { log.error("Error while initializing the Batik SVG extensions", t); // if the classes are not available // the DISPLAY is not checked batikAvailable = false; }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (IOException ioe) { log.error("I/O error while loading precompiled hyphenation pattern file", ioe); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (ClassNotFoundException cnfe) { log.error("Error while reading hyphenation object from file", cnfe); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (HyphenationException ex) { log.error("Can't load user patterns from XML file " + source.getSystemId() + ": " + ex.getMessage()); return null; }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
catch (Exception e) { log.error("Error while building XML font metrics file.", e); System.exit(-1); }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
catch (javax.xml.parsers.ParserConfigurationException e) { log.error("Can't create DOM implementation", e); return null; }
// in src/java/org/apache/fop/fonts/apps/PFMReader.java
catch (Exception e) { log.error("Error while building XML font metrics file", e); System.exit(-1); }
// in src/java/org/apache/fop/fonts/apps/PFMReader.java
catch (javax.xml.parsers.ParserConfigurationException e) { log.error("Can't create DOM implementation", e); return null; }
// in src/java/org/apache/fop/fonts/substitute/FontQualifier.java
catch (IllegalArgumentException ex) { log.error("Invalid font-weight value '" + weightString + "'"); return; }
// in src/java/org/apache/fop/fonts/substitute/FontWeightRange.java
catch (NumberFormatException e) { log.error("invalid font-weight value " + weightString); }
// in src/java/org/apache/fop/fonts/SingleByteFont.java
catch (UnsupportedOperationException e) { log.error("Font '" + super.getFontName() + "': " + e.getMessage()); }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (FOPException fopex) { log.error("Failed to read font metrics file " + metricsFileName, fopex); if (fail) { throw new RuntimeException(fopex.getMessage()); } }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (IOException ioex) { log.error("Failed to read font metrics file " + metricsFileName, ioex); if (fail) { throw new RuntimeException(ioex.getMessage()); } }
// in src/java/org/apache/fop/render/print/PrintRenderer.java
catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (IllegalArgumentException e) { log.error("Error while adding XMLHandler", e); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalArgumentException e) { log.error("Error while adding maker for Renderer", e); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalArgumentException e) { log.error("Error while adding maker for FOEventHandler", e); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalArgumentException e) { log.error("Error while adding maker for IFDocumentHandler", e); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (SAXException e) { log.error("Error while serializing Extension Attachment", e); }
// in src/java/org/apache/fop/render/pcl/HardcodedFonts.java
catch (Exception e) { LOG.error(e); }
// in src/java/org/apache/fop/render/rtf/PageAttributesConverter.java
catch (Exception e) { log.error("Exception in convertPageAttributes: " + e.getMessage() + "- page attributes ignored"); attrib = new FOPRtfAttributes(); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startTable:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startColumn: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startInline:" + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startList: " + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startLink: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnote: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("characters:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumberCitation: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (RtfException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java
catch (SecurityException ex) { String msg = "unable to gain write access to external resource file: " + resourceGroupFile; LOG.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java
catch (SecurityException ex) { String msg = "unable to gain read access to external resource file: " + resourceGroupFile; LOG.error(msg); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (IllegalArgumentException e) { log.error("Error while adding ImageHandler", e); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (FOPException e) { log.error(e); return NO_SUCH_PAGE; }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (Exception ex) { // Lets log at least! LOG.error(ex.getMessage()); }
// in src/java/org/apache/fop/afp/AFPStreamer.java
catch (FileNotFoundException fnfe) { LOG.error("Failed to create/open external resource group file '" + filePath + "'"); }
// in src/java/org/apache/fop/afp/modca/MapPageSegment.java
catch (UnsupportedEncodingException usee) { LOG.error("UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException msee) { mapCodedFont = factory.createMapCodedFont(); mapCodedFonts.add(mapCodedFont); try { mapCodedFont.addFont(fontRef, font, size, orientation); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createFont():: resulted in a MaximumSizeExceededException"); } }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createFont():: resulted in a MaximumSizeExceededException"); }
// in src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java
catch (MaximumSizeExceededException msee) { mpo = new MapPageOverlay(); getMapPageOverlays().add(mpo); try { mpo.addOverlay(name); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createOverlay():: resulted in a MaximumSizeExceededException"); } }
// in src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java
catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createOverlay():: resulted in a MaximumSizeExceededException"); }
// in src/java/org/apache/fop/afp/modca/MapPageOverlay.java
catch (UnsupportedEncodingException usee) { LOG.error("addOverlay():: UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (RuntimeException re) { String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, re); throw re; }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (FOPException e) { //TODO use error handler to handle this FOPException or propagate exception String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, e); throw new IllegalStateException("Fatal error occurred. Cannot continue. " + e.getClass().getName() + ": " + err); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (IllegalArgumentException e) { log.error("Error while adding ContentHandlerFactory", e); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (InstantiationException e) { log.error("Error creating the catalog resolver: " + e.getMessage()); eventProducer.catalogResolverNotCreated(this, e.getMessage()); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (IllegalAccessException e) { log.error("Error creating the catalog resolver: " + e.getMessage()); eventProducer.catalogResolverNotCreated(this, e.getMessage()); }
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { if (options != null) { options.getLogger().error("Exception", e); if (options.getOutputFile() != null) { options.getOutputFile().delete(); } } System.exit(1); }
184
get 52
                  
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageError(fobj, uri, e, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(fobj, uri, fnfe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(fobj, uri, ioe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, url, e, getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, url, fnfe, getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, url, ioe, getLocator()); }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageWritingError(this, ioe); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, uri, ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ioe, null); }
// in src/java/org/apache/fop/render/AbstractGenericSVGHandler.java
catch (Exception e) { EventBroadcaster eventBroadcaster = userAgent.getEventBroadcaster(); SVGEventProducer eventProducer = SVGEventProducer.Provider.get(eventBroadcaster); final String uri = getDocumentURI(doc); eventProducer.svgNotBuilt(this, e, uri); return null; }
// in src/java/org/apache/fop/render/AbstractRenderer.java
catch (Exception e) { // could not handle document ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( ctx.getUserAgent().getEventBroadcaster()); eventProducer.foreignXMLProcessingError(this, doc, namespace, e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, null, ioe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); }
// in src/java/org/apache/fop/render/afp/AFPSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, uri); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.imageError(resTracker, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageLoadError(this, pageViewport.getPageNumberString(), e); }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (IOException ioe) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageSaveError(this, page.getPageNumberString(), ioe); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageError(this, uri, e, getLocator()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fnfe, getLocator()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, getLocator()); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException ioe) { RendererEventProducer eventProducer = RendererEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.ioError(this, ioe); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageRenderingError(this, pageViewport.getPageNumberString(), e); if (e instanceof RuntimeException) { throw (RuntimeException)e; } }
1258
getEventBroadcaster 52
                  
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageError(fobj, uri, e, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(fobj, uri, fnfe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(fobj, uri, ioe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, url, e, getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, url, fnfe, getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, url, ioe, getLocator()); }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageWritingError(this, ioe); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, uri, ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ioe, null); }
// in src/java/org/apache/fop/render/AbstractGenericSVGHandler.java
catch (Exception e) { EventBroadcaster eventBroadcaster = userAgent.getEventBroadcaster(); SVGEventProducer eventProducer = SVGEventProducer.Provider.get(eventBroadcaster); final String uri = getDocumentURI(doc); eventProducer.svgNotBuilt(this, e, uri); return null; }
// in src/java/org/apache/fop/render/AbstractRenderer.java
catch (Exception e) { // could not handle document ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( ctx.getUserAgent().getEventBroadcaster()); eventProducer.foreignXMLProcessingError(this, doc, namespace, e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, null, ioe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); }
// in src/java/org/apache/fop/render/afp/AFPSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, uri); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.imageError(resTracker, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageLoadError(this, pageViewport.getPageNumberString(), e); }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (IOException ioe) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageSaveError(this, page.getPageNumberString(), ioe); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageError(this, uri, e, getLocator()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fnfe, getLocator()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, getLocator()); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException ioe) { RendererEventProducer eventProducer = RendererEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.ioError(this, ioe); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageRenderingError(this, pageViewport.getPageNumberString(), e); if (e instanceof RuntimeException) { throw (RuntimeException)e; } }
127
getUserAgent 48
                  
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageError(fobj, uri, e, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(fobj, uri, fnfe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(fobj, uri, ioe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, url, e, getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, url, fnfe, getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, url, ioe, getLocator()); }
// in src/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java
catch (Exception e) { ctx.getUserAgent().displayError(e); }
// in src/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java
catch (Exception e) { ctx.getUserAgent().displayError(e); }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageWritingError(this, ioe); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, uri, ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ioe, null); }
// in src/java/org/apache/fop/render/AbstractRenderer.java
catch (Exception e) { // could not handle document ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( ctx.getUserAgent().getEventBroadcaster()); eventProducer.foreignXMLProcessingError(this, doc, namespace, e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, null, ioe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageLoadError(this, pageViewport.getPageNumberString(), e); }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (IOException ioe) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageSaveError(this, page.getPageNumberString(), ioe); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException ioe) { RendererEventProducer eventProducer = RendererEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.ioError(this, ioe); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageRenderingError(this, pageViewport.getPageNumberString(), e); if (e instanceof RuntimeException) { throw (RuntimeException)e; } }
257
handleException 30
                  
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mfue) { handleException(mfue, "Could not convert filename '" + href + "' to URL", throwExceptions); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mue) { try { // the above failed, we give it another go in case // the href contains only a path then file: is // assumed absoluteURL = new URL("file:" + href); } catch (MalformedURLException mfue) { handleException(mfue, "Error with URL '" + href + "'", throwExceptions); } }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mfue) { handleException(mfue, "Error with URL '" + href + "'", throwExceptions); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mfue) { handleException(mfue, "Error with base URL '" + base + "'", throwExceptions); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mfue) { handleException(mfue, "Error with URL; base '" + base + "' " + "href '" + href + "'", throwExceptions); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, false); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (NumberFormatException nfe) { LogUtil.handleException(log, nfe, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, true); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, true); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, true); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, true); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (ConfigurationException ce) { LogUtil.handleException(log, ce, strict); continue; }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException ioe) { LogUtil.handleException(log, ioe, true); }
// in src/java/org/apache/fop/fonts/FontDetector.java
catch (IOException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/fonts/FontDetector.java
catch (IOException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); continue; }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
catch (IOException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
catch (MalformedURLException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, false); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IllegalArgumentException iae) { LogUtil.handleException(log, iae, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { eventProducer.invalidConfiguration(this, e); LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
32
handleIOTrouble
23
                  
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
23
printStackTrace 22
                  
// in src/java/org/apache/fop/pdf/PDFStream.java
catch (IOException ex) { //TODO throw the exception and catch it elsewhere ex.printStackTrace(); }
// in src/java/org/apache/fop/pdf/PDFStream.java
catch (Exception e) { //TODO throw the exception and catch it elsewhere e.printStackTrace(); return 0; }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
catch (Throwable t) { printHelp(); t.printStackTrace(); System.exit(-1); }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (MalformedURLException mue) { mue.printStackTrace(); }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (MalformedURLException mue) { mue.printStackTrace(); }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (Exception e) { e.printStackTrace(); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (Exception e) { e.printStackTrace(); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (Exception e) { e.printStackTrace(); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (Exception ioe) { System.out.println("Exception " + ioe); ioe.printStackTrace(); }
// in src/java/org/apache/fop/svg/PDFANode.java
catch (Exception e) { //TODO Move this to setDestination() and throw an IllegalArgumentException e.printStackTrace(); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
catch (IOException ioe) { System.err.println("Problem reading font: " + ioe.toString()); ioe.printStackTrace(System.err); }
// in src/java/org/apache/fop/render/awt/viewer/ImageProxyPanel.java
catch (FOPException fopEx) { fopEx.printStackTrace(); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java
catch (FOPException e) { e.printStackTrace(); // FIXME Should show exception in gui - was reportException(e); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewDialog.java
catch (FOPException fopEx) { fopEx.printStackTrace(); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewDialog.java
catch (FOPException fopEx) { fopEx.printStackTrace(); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewDialog.java
catch (PrinterException e) { e.printStackTrace(); }
// in src/java/org/apache/fop/afp/apps/FontPatternExtractor.java
catch (Exception e) { e.printStackTrace(); System.exit(-1); }
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { System.err.println("Unable to start FOP:"); e.printStackTrace(); System.exit(-1); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
catch (Exception e) { System.out.println("An unexpected error occured at line: " + lineNumber ); e.printStackTrace(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
catch (Exception e) { System.out.println("An unexpected error occured"); e.printStackTrace(); }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
catch (Exception e) { System.out.println("An unexpected error occured"); e.printStackTrace(); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (Exception e) { e.printStackTrace(); }
39
toString 21
                  
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/hyphenation/SerializeHyphPattern.java
catch (HyphenationException ex) { System.err.println("Can't load patterns from xml file " + infile + " - Maybe hyphenation.dtd is missing?"); if (errorDump) { System.err.println(ex.toString()); } }
// in src/java/org/apache/fop/fonts/truetype/TTFDirTabEntry.java
catch (UnsupportedEncodingException e) { return this.toString(); // Should never happen. }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
catch (IOException ioe) { System.err.println("Problem reading font: " + ioe.toString()); ioe.printStackTrace(System.err); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ioe, null); }
// in src/java/org/apache/fop/render/txt/TXTStream.java
catch (IOException e) { throw new RuntimeException(e.toString()); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
catch (Exception e) { final String msg = "RtfTableRow.writePaddingAttributes: " + e.toString(); // getRtfFile().getLog().logWarning(msg); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.imageError(resTracker, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
595
handleIFException 20
                  
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
21
getLocator 17
                  
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageError(fobj, uri, e, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(fobj, uri, fnfe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(fobj, uri, ioe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
catch (PropertyException propEx) { if (fo != null) { propEx.setLocator(fo.getLocator()); } propEx.setPropertyName(getName()); throw propEx; }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, url, e, getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, url, fnfe, getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, url, ioe, getLocator()); }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
catch (FOPException exc) { getFOValidationEventProducer().markerCloningFailed(this, marker.getMarkerClassName(), exc, getLocator()); }
// in src/java/org/apache/fop/render/afp/extensions/AFPIncludeFormMapElement.java
catch (URISyntaxException e) { getFOValidationEventProducer().invalidPropertyValue(this, elementName, ATT_SRC, attr, null, getLocator()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageError(this, uri, e, getLocator()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fnfe, getLocator()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (URISyntaxException e) { getResourceEventProducer().uriError(this, uri, e, getExternalDocument().getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (FileNotFoundException fnfe) { getResourceEventProducer().imageNotFound(this, uri, fnfe, getExternalDocument().getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (IOException ioe) { getResourceEventProducer().imageIOError(this, uri, ioe, getExternalDocument().getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (ImageException ie) { getResourceEventProducer().imageError(this, uri, ie, getExternalDocument().getLocator()); }
92
info 17
                  
// in src/java/org/apache/fop/fo/properties/PropertyCache.java
catch ( SecurityException e ) { useCache = true; LOG.info("Unable to access org.apache.fop.fo.properties.use-cache" + " due to security restriction; defaulting to 'true'."); }
214
getName 16
                  
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
catch (PropertyException propEx) { if (fo != null) { propEx.setLocator(fo.getLocator()); } propEx.setPropertyName(getName()); throw propEx; }
// in src/java/org/apache/fop/fo/PropertyList.java
catch (PropertyException e) { fobj.getFOValidationEventProducer().invalidPropertyValue(this, fobj.getName(), attributeName, attributeValue, e, fobj.locator); }
// in src/java/org/apache/fop/fo/flow/Wrapper.java
catch (ValidationException vex) { invalidChildError(loc, getName(), FO_URI, localName, "rule.wrapperInvalidChildForParent"); }
// in src/java/org/apache/fop/render/print/PrintRenderer.java
catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + XMLHandler.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractRendererMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractFOEventHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractIFDocumentHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException( "I/O error while embedding form map resource: " + formMap.getName(), ioe); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ImageHandler.class.getName()); }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
catch (TransformerException e) { throw new MissingResourceException( "Error reading " + resourceName + ": " + e.getMessage(), DefaultEventBroadcaster.class.getName(), ""); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (FOPException e) { //TODO use error handler to handle this FOPException or propagate exception String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, e); throw new IllegalStateException("Fatal error occurred. Cannot continue. " + e.getClass().getName() + ": " + err); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ContentHandlerFactory.class.getName()); }
426
warn 14
                  
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (ClassNotFoundException e) { if (checkAvailableAlgorithms()) { LOG.warn("JCE and algorithms available, but the " + "implementation class unavailable. Please do a full " + "rebuild."); } return null; }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (IllegalArgumentException e) { LOG.warn("Error while adding element mapping", e); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (ClassNotFoundException e) { // We don't really care about the exception since it's just a // cache file log.warn("Could not read font cache. Discarding font cache file. Reason: " + e.getMessage()); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException ioe) { // We don't really care about the exception since it's just a // cache file log.warn("I/O exception while reading font cache (" + ioe.getMessage() + "). Discarding font cache file."); try { cacheFile.delete(); } catch (SecurityException ex) { log.warn("Failed to delete font cache file: " + cacheFile.getAbsolutePath()); } }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (SecurityException ex) { log.warn("Failed to delete font cache file: " + cacheFile.getAbsolutePath()); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
catch ( AdvancedTypographicTableFormatException e ) { log.warn ( "Encountered format constraint violation in advanced (typographic) table (AT) " + "in font '" + getFullName() + "', ignoring AT data: " + e.getMessage() ); }
// in src/java/org/apache/fop/render/java2d/ConfiguredFontCollection.java
catch (Exception e) { log.warn("Unable to load custom font from file '" + fontFile + "'", e); }
// in src/java/org/apache/fop/afp/fonts/CharacterSet.java
catch (UnsupportedEncodingException usee) { nameBytes = name.getBytes(); LOG.warn( "UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/afp/modca/AbstractNamedAFPObject.java
catch (UnsupportedEncodingException usee) { nameBytes = name.getBytes(); LOG.warn( "Constructor:: UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/layoutmgr/inline/ContentLayoutManager.java
catch (IllegalStateException e) { log.warn("Title has no content"); throw e; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (NoClassDefFoundError e) { batikAvailable = false; log.warn("Batik not in class path", e); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (NoClassDefFoundError ncdfe) { try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } batikAvailable = false; log.warn("Batik not in class path", ncdfe); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (NoClassDefFoundError e) { batikAvailable = false; log.warn("Batik not in class path", e); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (NoClassDefFoundError ncdfe) { if (in != null) { try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } } batikAvailable = false; log.warn("Batik not in class path", ncdfe); return null; }
113
imageError
13
                  
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageError(fobj, uri, e, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, url, e, getLocator()); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, uri, ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.imageError(resTracker, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageError(this, uri, e, getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (ImageException ie) { getResourceEventProducer().imageError(this, uri, ie, getExternalDocument().getLocator()); }
13
println 12
                  
// in src/java/org/apache/fop/tools/anttasks/FileCompare.java
catch (IOException ioe) { System.err.println("ERROR: " + ioe); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (Exception ioe) { System.out.println("Exception " + ioe); ioe.printStackTrace(); }
// in src/java/org/apache/fop/hyphenation/SerializeHyphPattern.java
catch (IOException ioe) { System.err.println("Can't write compiled pattern file: " + outfile); System.err.println(ioe); }
// in src/java/org/apache/fop/hyphenation/SerializeHyphPattern.java
catch (HyphenationException ex) { System.err.println("Can't load patterns from xml file " + infile + " - Maybe hyphenation.dtd is missing?"); if (errorDump) { System.err.println(ex.toString()); } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
catch (IOException ioe) { System.err.println("Problem reading font: " + ioe.toString()); ioe.printStackTrace(System.err); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (Exception e) { System.err.println("Couldn't set system look & feel!"); }
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { System.err.println("Unable to start FOP:"); e.printStackTrace(); System.exit(-1); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
catch (Exception e) { System.out.println("An unexpected error occured at line: " + lineNumber ); e.printStackTrace(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
catch (Exception e) { System.out.println("An unexpected error occured"); e.printStackTrace(); }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
catch (Exception e) { System.out.println("An unexpected error occured"); e.printStackTrace(); }
454
imageIOError
11
                  
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(fobj, uri, ioe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, url, ioe, getLocator()); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ioe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, null, ioe, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (IOException ioe) { getResourceEventProducer().imageIOError(this, uri, ioe, getExternalDocument().getLocator()); }
11
imageNotFound
10
                  
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(fobj, uri, fnfe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, url, fnfe, getLocator()); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), fe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fnfe, getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (FileNotFoundException fnfe) { getResourceEventProducer().imageNotFound(this, uri, fnfe, getExternalDocument().getLocator()); }
10
debug 8
                  
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (FileNotFoundException fnfe) { // Note: This is on "debug" level since the caller is // supposed to handle this log.debug("File not found: " + effURL); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("I/O problem while trying to load " + name, ioe); } }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("I/O problem while trying to load " + name, ioe); } return null; }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException e) { // Should never happen, because URL must be local log.debug("IOError: " + e.getMessage()); return 0; }
// in src/java/org/apache/fop/fonts/autodetect/FontFileFinder.java
catch (MalformedURLException e) { log.debug("MalformedURLException" + e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
catch (UnsupportedOperationException uoe) { log.debug( "Cannot paint graphic natively. Falling back to bitmap painting. Reason: " + uoe.getMessage()); }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (IOException e) { // If the svg is invalid then it throws an IOException // so there is no way of knowing if it is an svg document log.debug("Error while trying to load stream as an WMF file: " + e.getMessage()); // assuming any exception means this document is not svg // or could not be loaded for some reason try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (IOException e) { // If the svg is invalid then it throws an IOException // so there is no way of knowing if it is an svg document log.debug("Error while trying to load stream as an SVG file: " + e.getMessage()); // assuming any exception means this document is not svg // or could not be loaded for some reason try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } return null; }
578
getCause 8
                  
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException)te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (TransformerException te) { //Unpack original IFException if applicable if (te.getCause() instanceof SAXException) { SAXException se = (SAXException)te.getCause(); if (se.getCause() instanceof IFException) { throw (IFException)se.getCause(); } } else if (te.getCause() instanceof IFException) { throw (IFException)te.getCause(); } throw te; }
14
getDocumentURI 8
                  
// in src/java/org/apache/fop/render/AbstractGenericSVGHandler.java
catch (Exception e) { EventBroadcaster eventBroadcaster = userAgent.getEventBroadcaster(); SVGEventProducer eventProducer = SVGEventProducer.Provider.get(eventBroadcaster); final String uri = getDocumentURI(doc); eventProducer.svgNotBuilt(this, e, uri); return null; }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
11
handleSAXException
8
                  
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
8
svgRenderingError
8
                  
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/afp/AFPSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, uri); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
8
exit 6
                  
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
catch (Throwable t) { printHelp(); t.printStackTrace(); System.exit(-1); }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
catch (Exception e) { log.error("Error while building XML font metrics file.", e); System.exit(-1); }
// in src/java/org/apache/fop/fonts/apps/PFMReader.java
catch (Exception e) { log.error("Error while building XML font metrics file", e); System.exit(-1); }
// in src/java/org/apache/fop/afp/apps/FontPatternExtractor.java
catch (Exception e) { e.printStackTrace(); System.exit(-1); }
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { System.err.println("Unable to start FOP:"); e.printStackTrace(); System.exit(-1); }
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { if (options != null) { options.getLogger().error("Exception", e); if (options.getOutputFile() != null) { options.getOutputFile().delete(); } } System.exit(1); }
19
handleIOException
6
                  
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/svg/AbstractFOPTextPainter.java
catch (IOException ioe) { if (g2d instanceof AFPGraphics2D) { ((AFPGraphics2D)g2d).handleIOException(ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/afp/AFPGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/afp/AFPGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
6
svgNotBuilt
6
                  
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/AbstractGenericSVGHandler.java
catch (Exception e) { EventBroadcaster eventBroadcaster = userAgent.getEventBroadcaster(); SVGEventProducer eventProducer = SVGEventProducer.Provider.get(eventBroadcaster); final String uri = getDocumentURI(doc); eventProducer.svgNotBuilt(this, e, uri); return null; }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
6
StreamSource 5
                  
// in src/java/org/apache/fop/cli/InputHandler.java
catch (FileNotFoundException e) { //handled elsewhere return new StreamSource(this.sourcefile); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (SAXException e) { if (this.sourcefile != null) { source = new StreamSource(this.sourcefile); } else { source = new StreamSource(in, uri); } }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (ParserConfigurationException e) { if (this.sourcefile != null) { source = new StreamSource(this.sourcefile); } else { source = new StreamSource(in, uri); } }
25
getInfo 5
                  
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
41
getOriginalURI 5
                  
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
25
getPageNumberString 5
                  
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageLoadError(this, pageViewport.getPageNumberString(), e); }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (IOException ioe) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageSaveError(this, page.getPageNumberString(), ioe); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (RuntimeException re) { String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, re); throw re; }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (FOPException e) { //TODO use error handler to handle this FOPException or propagate exception String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, e); throw new IllegalStateException("Fatal error occurred. Cannot continue. " + e.getClass().getName() + ": " + err); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageRenderingError(this, pageViewport.getPageNumberString(), e); if (e instanceof RuntimeException) { throw (RuntimeException)e; } }
20
invalidConfiguration
5
                  
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (URISyntaxException e) { eventProducer.invalidConfiguration(this, e); return null; }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException ce) { eventProducer.invalidConfiguration(this, ce); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IOException ioe) { eventProducer.invalidConfiguration(this, ioe); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IllegalArgumentException iae) { eventProducer.invalidConfiguration(this, iae); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { eventProducer.invalidConfiguration(this, e); LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
5
getBytes 4
                  
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (UnsupportedEncodingException uee) { return text.getBytes(); }
// in src/java/org/apache/fop/afp/fonts/CharacterSet.java
catch (UnsupportedEncodingException usee) { nameBytes = name.getBytes(); LOG.warn( "UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/afp/modca/AbstractNamedAFPObject.java
catch (UnsupportedEncodingException usee) { nameBytes = name.getBytes(); LOG.warn( "Constructor:: UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/afp/modca/triplets/AttributeValueTriplet.java
catch (UnsupportedEncodingException usee) { tleByteValue = attVal.getBytes(); throw new IllegalArgumentException(attVal + " encoding failed"); }
49
getExternalDocument 4
                  
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (URISyntaxException e) { getResourceEventProducer().uriError(this, uri, e, getExternalDocument().getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (FileNotFoundException fnfe) { getResourceEventProducer().imageNotFound(this, uri, fnfe, getExternalDocument().getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (IOException ioe) { getResourceEventProducer().imageIOError(this, uri, ioe, getExternalDocument().getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (ImageException ie) { getResourceEventProducer().imageError(this, uri, ie, getExternalDocument().getLocator()); }
8
getFactory 4
                  
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IllegalArgumentException iae) { LogUtil.handleException(log, iae, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { eventProducer.invalidConfiguration(this, e); LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
109
getResourceEventProducer
4
                  
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (URISyntaxException e) { getResourceEventProducer().uriError(this, uri, e, getExternalDocument().getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (FileNotFoundException fnfe) { getResourceEventProducer().imageNotFound(this, uri, fnfe, getExternalDocument().getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (IOException ioe) { getResourceEventProducer().imageIOError(this, uri, ioe, getExternalDocument().getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (ImageException ie) { getResourceEventProducer().imageError(this, uri, ie, getExternalDocument().getLocator()); }
4
reset 4
                  
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (NoClassDefFoundError ncdfe) { try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } batikAvailable = false; log.warn("Batik not in class path", ncdfe); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (IOException e) { // If the svg is invalid then it throws an IOException // so there is no way of knowing if it is an svg document log.debug("Error while trying to load stream as an WMF file: " + e.getMessage()); // assuming any exception means this document is not svg // or could not be loaded for some reason try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (NoClassDefFoundError ncdfe) { if (in != null) { try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } } batikAvailable = false; log.warn("Batik not in class path", ncdfe); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (IOException e) { // If the svg is invalid then it throws an IOException // so there is no way of knowing if it is an svg document log.debug("Error while trying to load stream as an SVG file: " + e.getMessage()); // assuming any exception means this document is not svg // or could not be loaded for some reason try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } return null; }
47
validateUserConfigStrictly 4
                  
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IllegalArgumentException iae) { LogUtil.handleException(log, iae, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { eventProducer.invalidConfiguration(this, e); LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
8
displayError 3
                  
// in src/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java
catch (Exception e) { ctx.getUserAgent().displayError(e); }
// in src/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java
catch (Exception e) { ctx.getUserAgent().displayError(e); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (IOException ioe) { userAgent.displayError(ioe); return null; }
4
endPresentationTextData 3
                  
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (UnsupportedEncodingException e) { endPresentationTextData(); throw e; }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (IOException ioe) { endPresentationTextData(); handleUnexpectedIOError(ioe); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (IOException ioe) { endPresentationTextData(); handleUnexpectedIOError(ioe); //Should not occur since we're writing to byte arrays }
4
fontLoadingErrorAtAutoDetection 3
                  
// in src/java/org/apache/fop/fonts/autodetect/FontInfoFinder.java
catch (Exception e) { if (this.eventListener != null) { this.eventListener.fontLoadingErrorAtAutoDetection(this, fontFileURL, e); } return null; }
// in src/java/org/apache/fop/fonts/autodetect/FontInfoFinder.java
catch (Exception e) { if (fontCache != null) { fontCache.registerFailedFont(embedURL, fileLastModified); } if (this.eventListener != null) { this.eventListener.fontLoadingErrorAtAutoDetection(this, embedURL, e); } continue; }
// in src/java/org/apache/fop/fonts/autodetect/FontInfoFinder.java
catch (Exception e) { if (fontCache != null) { fontCache.registerFailedFont(embedURL, fileLastModified); } if (this.eventListener != null) { this.eventListener.fontLoadingErrorAtAutoDetection(this, embedURL, e); } return null; }
4
getFOValidationEventProducer 3
                  
// in src/java/org/apache/fop/fo/PropertyList.java
catch (PropertyException e) { fobj.getFOValidationEventProducer().invalidPropertyValue(this, fobj.getName(), attributeName, attributeValue, e, fobj.locator); }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
catch (FOPException exc) { getFOValidationEventProducer().markerCloningFailed(this, marker.getMarkerClassName(), exc, getLocator()); }
// in src/java/org/apache/fop/render/afp/extensions/AFPIncludeFormMapElement.java
catch (URISyntaxException e) { getFOValidationEventProducer().invalidPropertyValue(this, elementName, ATT_SRC, attr, null, getLocator()); }
40
handleUnexpectedIOError
3
                  
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (IOException ioe) { endPresentationTextData(); handleUnexpectedIOError(ioe); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (UnsupportedEncodingException e) { handleUnexpectedIOError(e); //Won't happen for lines }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (IOException ioe) { endPresentationTextData(); handleUnexpectedIOError(ioe); //Should not occur since we're writing to byte arrays }
3
setLocator 3
                  
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
catch (PropertyException propEx) { if (fo != null) { propEx.setLocator(fo.getLocator()); } propEx.setPropertyName(getName()); throw propEx; }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
catch (ValidationException e) { e.setLocator(locator); throw e; }
9
add 2
                  
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException msee) { mapCodedFont = factory.createMapCodedFont(); mapCodedFonts.add(mapCodedFont); try { mapCodedFont.addFont(fontRef, font, size, orientation); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createFont():: resulted in a MaximumSizeExceededException"); } }
// in src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java
catch (MaximumSizeExceededException msee) { mpo = new MapPageOverlay(); getMapPageOverlays().add(mpo); try { mpo.addOverlay(name); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createOverlay():: resulted in a MaximumSizeExceededException"); } }
1220
catalogResolverNotCreated
2
                  
// in src/java/org/apache/fop/cli/InputHandler.java
catch (InstantiationException e) { log.error("Error creating the catalog resolver: " + e.getMessage()); eventProducer.catalogResolverNotCreated(this, e.getMessage()); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (IllegalAccessException e) { log.error("Error creating the catalog resolver: " + e.getMessage()); eventProducer.catalogResolverNotCreated(this, e.getMessage()); }
2
codePageNotFound
2
                  
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (FileNotFoundException e) { eventProducer.codePageNotFound(this, e); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (FileNotFoundException e) { eventProducer.codePageNotFound(this, e); }
2
delete 2
                  
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException ioe) { // We don't really care about the exception since it's just a // cache file log.warn("I/O exception while reading font cache (" + ioe.getMessage() + "). Discarding font cache file."); try { cacheFile.delete(); } catch (SecurityException ex) { log.warn("Failed to delete font cache file: " + cacheFile.getAbsolutePath()); } }
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { if (options != null) { options.getLogger().error("Exception", e); if (options.getOutputFile() != null) { options.getOutputFile().delete(); } } System.exit(1); }
13
equals 2
                  
// in src/java/org/apache/fop/fonts/FontUtil.java
catch (NumberFormatException nfe) { //weight is no number, so convert symbolic name to number if (text.equals("normal")) { weight = 400; } else if (text.equals("bold")) { weight = 700; } else { throw new IllegalArgumentException( "Illegal value for font weight: '" + text + "'. Use one of: 100, 200, 300, " + "400, 500, 600, 700, 800, 900, " + "normal (=400), bold (=700)"); } }
895
format 2
                  
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
213
getClass 2
                  
// in src/java/org/apache/fop/render/print/PrintRenderer.java
catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (FOPException e) { //TODO use error handler to handle this FOPException or propagate exception String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, e); throw new IllegalStateException("Fatal error occurred. Cannot continue. " + e.getClass().getName() + ": " + err); }
144
getEmbedFontName 2
                  
// in src/java/org/apache/fop/pdf/PDFFactory.java
catch (IOException ioe) { log.error( "Failed to write CIDSet [" + cidFont + "] " + cidFont.getEmbedFontName(), ioe); }
// in src/java/org/apache/fop/pdf/PDFFactory.java
catch (IOException ioe) { log.error( "Failed to embed font [" + desc + "] " + desc.getEmbedFontName(), ioe); return null; }
8
getOutputFile 2
                  
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { if (options != null) { options.getLogger().error("Exception", e); if (options.getOutputFile() != null) { options.getOutputFile().delete(); } } System.exit(1); }
11
getURI 2
                  
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (URISyntaxException urie) { throw new IFException("Could not handle resource url" + pageSegment.getURI(), urie); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Could not handle resource" + pageSegment.getURI(), ioe); }
14
handleIFExceptionWithIOException
2
                  
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFExceptionWithIOException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFExceptionWithIOException(e); }
2
invalidPropertyValue
2
                  
// in src/java/org/apache/fop/fo/PropertyList.java
catch (PropertyException e) { fobj.getFOValidationEventProducer().invalidPropertyValue(this, fobj.getName(), attributeName, attributeValue, e, fobj.locator); }
// in src/java/org/apache/fop/render/afp/extensions/AFPIncludeFormMapElement.java
catch (URISyntaxException e) { getFOValidationEventProducer().invalidPropertyValue(this, elementName, ATT_SRC, attr, null, getLocator()); }
2
isDebugEnabled 2
                  
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("I/O problem while trying to load " + name, ioe); } }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("I/O problem while trying to load " + name, ioe); } return null; }
289
printUsage 2
                  
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (FOPException e) { printUsage(System.err); throw e; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (java.io.FileNotFoundException e) { printUsage(System.err); throw e; }
4
registerFailedFont
2
                  
// in src/java/org/apache/fop/fonts/autodetect/FontInfoFinder.java
catch (Exception e) { if (fontCache != null) { fontCache.registerFailedFont(embedURL, fileLastModified); } if (this.eventListener != null) { this.eventListener.fontLoadingErrorAtAutoDetection(this, embedURL, e); } continue; }
// in src/java/org/apache/fop/fonts/autodetect/FontInfoFinder.java
catch (Exception e) { if (fontCache != null) { fontCache.registerFailedFont(embedURL, fileLastModified); } if (this.eventListener != null) { this.eventListener.fontLoadingErrorAtAutoDetection(this, embedURL, e); } return null; }
2
resetATStateAll
2
                  
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( AdvancedTypographicTableFormatException e ) { resetATStateAll(); throw e; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( IOException e ) { resetATStateAll(); throw new AdvancedTypographicTableFormatException ( e.getMessage(), e ); }
2
setPropertyName
2
                  
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
catch (PropertyException propEx) { if (fo != null) { propEx.setLocator(fo.getLocator()); } propEx.setPropertyName(getName()); throw propEx; }
2
Dimension 1
                  
// in src/java/org/apache/fop/render/awt/viewer/ImageProxyPanel.java
catch (FOPException fopEx) { // Arbitary size. Doesn't really matter what's returned here. return new Dimension(10, 10); }
40
Double 1
                  
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch (NumberFormatException nfe) { return new Double(getDoubleValue(line, startpos)); }
110
FOPRtfAttributes 1
                  
// in src/java/org/apache/fop/render/rtf/PageAttributesConverter.java
catch (Exception e) { log.error("Exception in convertPageAttributes: " + e.getMessage() + "- page attributes ignored"); attrib = new FOPRtfAttributes(); }
13
File 1
                  
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } }
97
MapPageOverlay 1
                  
// in src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java
catch (MaximumSizeExceededException msee) { mpo = new MapPageOverlay(); getMapPageOverlays().add(mpo); try { mpo.addOverlay(name); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createOverlay():: resulted in a MaximumSizeExceededException"); } }
2
URL 1
                  
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mue) { try { // the above failed, we give it another go in case // the href contains only a path then file: is // assumed absoluteURL = new URL("file:" + href); } catch (MalformedURLException mfue) { handleException(mfue, "Error with URL '" + href + "'", throwExceptions); } }
27
addFont 1
                  
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException msee) { mapCodedFont = factory.createMapCodedFont(); mapCodedFonts.add(mapCodedFont); try { mapCodedFont.addFont(fontRef, font, size, orientation); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createFont():: resulted in a MaximumSizeExceededException"); } }
9
addOverlay 1
                  
// in src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java
catch (MaximumSizeExceededException msee) { mpo = new MapPageOverlay(); getMapPageOverlays().add(mpo); try { mpo.addOverlay(name); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createOverlay():: resulted in a MaximumSizeExceededException"); } }
2
checkAvailableAlgorithms 1
                  
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (ClassNotFoundException e) { if (checkAvailableAlgorithms()) { LOG.warn("JCE and algorithms available, but the " + "implementation class unavailable. Please do a full " + "rebuild."); } return null; }
3
convertToGrayscale 1
                  
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
catch (Exception e) { //Provide a fallback if exotic formats are encountered bi = convertToGrayscale(bi, targetDimension); return converter.convertToMonochrome(bi); }
3
convertToMonochrome 1
                  
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
catch (Exception e) { //Provide a fallback if exotic formats are encountered bi = convertToGrayscale(bi, targetDimension); return converter.convertToMonochrome(bi); }
7
createMapCodedFont 1
                  
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException msee) { mapCodedFont = factory.createMapCodedFont(); mapCodedFonts.add(mapCodedFont); try { mapCodedFont.addFont(fontRef, font, size, orientation); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createFont():: resulted in a MaximumSizeExceededException"); } }
2
encode 1
                  
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
catch (IOException ioe) { //Some JPEG codecs cannot encode CMYK helper.encode(baos); }
80
foreignXMLProcessingError
1
                  
// in src/java/org/apache/fop/render/AbstractRenderer.java
catch (Exception e) { // could not handle document ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( ctx.getUserAgent().getEventBroadcaster()); eventProducer.foreignXMLProcessingError(this, doc, namespace, e); }
1
getAbsolutePath 1
                  
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException ioe) { // We don't really care about the exception since it's just a // cache file log.warn("I/O exception while reading font cache (" + ioe.getMessage() + "). Discarding font cache file."); try { cacheFile.delete(); } catch (SecurityException ex) { log.warn("Failed to delete font cache file: " + cacheFile.getAbsolutePath()); } }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (SecurityException ex) { log.warn("Failed to delete font cache file: " + cacheFile.getAbsolutePath()); }
13
getDOMImplementation 1
                  
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
catch (Exception e) { return SVGDOMImplementation.getDOMImplementation(); }
11
getDoubleValue 1
                  
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch (NumberFormatException nfe) { return new Double(getDoubleValue(line, startpos)); }
3
getFObj 1
                  
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; }
65
getFontName 1
                  
// in src/java/org/apache/fop/fonts/SingleByteFont.java
catch (UnsupportedOperationException e) { log.error("Font '" + super.getFontName() + "': " + e.getMessage()); }
56
getFullName 1
                  
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
catch ( AdvancedTypographicTableFormatException e ) { log.warn ( "Encountered format constraint violation in advanced (typographic) table (AT) " + "in font '" + getFullName() + "', ignoring AT data: " + e.getMessage() ); }
19
getLogger 1
                  
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { if (options != null) { options.getLogger().error("Exception", e); if (options.getOutputFile() != null) { options.getOutputFile().delete(); } } System.exit(1); }
10
getMapPageOverlays 1
                  
// in src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java
catch (MaximumSizeExceededException msee) { mpo = new MapPageOverlay(); getMapPageOverlays().add(mpo); try { mpo.addOverlay(name); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createOverlay():: resulted in a MaximumSizeExceededException"); } }
2
getMarkerClassName 1
                  
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
catch (FOPException exc) { getFOValidationEventProducer().markerCloningFailed(this, marker.getMarkerClassName(), exc, getLocator()); }
3
getRandomFileIDGenerator 1
                  
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (NoSuchAlgorithmException e) { fileIDGenerator = FileIDGenerator.getRandomFileIDGenerator(); }
2
getSrc 1
                  
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe); }
11
getSystemId 1
                  
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (HyphenationException ex) { log.error("Can't load user patterns from XML file " + source.getSystemId() + ": " + ex.getMessage()); return null; }
23
getThrowexceptions
1
                  
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { if (task.getThrowexceptions()) { throw new BuildException(ex); } throw ex; }
1
imageWritingError 1
                  
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageWritingError(this, ioe); }
2
invalidChildError 1
                  
// in src/java/org/apache/fop/fo/flow/Wrapper.java
catch (ValidationException vex) { invalidChildError(loc, getName(), FO_URI, localName, "rule.wrapperInvalidChildForParent"); }
75
ioError 1
                  
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException ioe) { RendererEventProducer eventProducer = RendererEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.ioError(this, ioe); }
2
isTraceEnabled 1
                  
// in src/java/org/apache/fop/events/EventFormatter.java
catch ( MissingResourceException e ) { if ( log.isTraceEnabled() ) { log.trace ( "No XMLResourceBundle for " + baseName + " available." ); } bundle = null; }
110
markerCloningFailed
1
                  
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
catch (FOPException exc) { getFOValidationEventProducer().markerCloningFailed(this, marker.getMarkerClassName(), exc, getLocator()); }
1
missingPropertyError 1
                  
// in src/java/org/apache/fop/render/pdf/extensions/PDFEmbeddedFileElement.java
catch (URISyntaxException e) { //Filename could not be deduced from URI missingPropertyError("name"); }
20
pageLoadError
1
                  
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageLoadError(this, pageViewport.getPageNumberString(), e); }
1
pageRenderingError
1
                  
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageRenderingError(this, pageViewport.getPageNumberString(), e); if (e instanceof RuntimeException) { throw (RuntimeException)e; } }
1
pageSaveError
1
                  
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (IOException ioe) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageSaveError(this, page.getPageNumberString(), ioe); }
1
postscriptDictionaryParseError
1
                  
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); }
1
printHelp 1
                  
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
catch (Throwable t) { printHelp(); t.printStackTrace(); System.exit(-1); }
2
setPropertyInfo 1
                  
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
catch (PropertyException exc) { exc.setPropertyInfo(propInfo); throw exc; }
4
setText 1
                  
// in src/java/org/apache/fop/render/awt/viewer/GoToPageDialog.java
catch (NumberFormatException nfe) { pageNumberField.setText("???"); }
10
toURI 1
                  
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } }
29
toURL 1
                  
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } }
27
trace 1
                  
// in src/java/org/apache/fop/events/EventFormatter.java
catch ( MissingResourceException e ) { if ( log.isTraceEnabled() ) { log.trace ( "No XMLResourceBundle for " + baseName + " available." ); } bundle = null; }
176
uriError
1
                  
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (URISyntaxException e) { getResourceEventProducer().uriError(this, uri, e, getExternalDocument().getLocator()); }
1
valueOf 1
                  
// in src/java/org/apache/fop/fonts/substitute/AttributeValue.java
catch (NumberFormatException ex) { value = FontWeightRange.valueOf(token); if (value == null) { value = token; } }
205
writeExceptionInRtf
1
                  
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (ExternalGraphicException ie) { writeExceptionInRtf(ie); }
1
Method Nbr Nbr total
closeQuietly 37
                  
// in src/sandbox/org/apache/fop/render/svg/SVGRenderer.java
finally { if (out != this.firstOutputStream) { IOUtils.closeQuietly(out); } else { out.flush(); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDataUrlImageHandler.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/pdf/PDFICCBasedColorSpace.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/pdf/TempFileStreamCache.java
finally { IOUtils.closeQuietly(input); }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
finally { IOUtils.closeQuietly(out); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
finally { IOUtils.closeQuietly(ois); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/fonts/FontCache.java
finally { IOUtils.closeQuietly(oin); }
// in src/java/org/apache/fop/fonts/FontCache.java
finally { IOUtils.closeQuietly(oout); }
// in src/java/org/apache/fop/fonts/FontCache.java
finally { // An InputStream is created even if it's not accessed, but we // need to close it. IOUtils.closeQuietly(conn.getInputStream()); }
// in src/java/org/apache/fop/fonts/autodetect/FontInfoFinder.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
finally { IOUtils.closeQuietly(afmIn); }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
finally { IOUtils.closeQuietly(pfmIn); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
finally { IOUtils.closeQuietly(reader); }
// in src/java/org/apache/fop/fonts/truetype/TTFFontLoader.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/render/pdf/ImageRawJPEGAdapter.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/render/bitmap/PNGRenderer.java
finally { //Only close self-created OutputStreams if (os != firstOutputStream) { IOUtils.closeQuietly(os); } }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
finally { IOUtils.closeQuietly(out); }
// in src/java/org/apache/fop/render/afp/AbstractAFPImageHandlerRawStream.java
finally { IOUtils.closeQuietly(inputStream); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRawJPEG.java
finally { IOUtils.closeQuietly(inputStream); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
finally { IOUtils.closeQuietly(in); if (!this.tempFile.delete()) { this.tempFile.deleteOnExit(); log.warn("Could not delete temporary file: " + this.tempFile); } }
// in src/java/org/apache/fop/render/ps/PSImageHandlerEPS.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/afp/apps/FontPatternExtractor.java
finally { IOUtils.closeQuietly(fout); }
// in src/java/org/apache/fop/afp/apps/FontPatternExtractor.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
finally { IOUtils.closeQuietly(inputStream); }
// in src/java/org/apache/fop/afp/modca/IncludedResourceObject.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/events/model/EventModel.java
finally { IOUtils.closeQuietly(out); }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
finally { IOUtils.closeQuietly(in); }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
finally { IOUtils.closeQuietly(tempstream); }
// in src/java/org/apache/fop/cli/Main.java
finally { IOUtils.closeQuietly(out); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
finally { IOUtils.closeQuietly(out); }
49
close 11
                  
// in src/java/org/apache/fop/pdf/PDFFactory.java
finally { in.close(); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
finally { try { out.close(); } catch (IOException ioe) { logger.error("Error closing output file", ioe); } if (!success) { outFile.delete(); } }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
finally { if (ois != null) { try { ois.close(); } catch (IOException e) { //ignore } } }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
finally { if (oos != null) { try { oos.flush(); } catch (IOException e) { //ignore } try { oos.close(); } catch (IOException e) { //ignore } } }
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
finally { out.close(); }
// in src/java/org/apache/fop/fonts/apps/PFMReader.java
finally { in.close(); }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
finally { in.close(); }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
finally { in.close(); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
finally { in.close(); }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
finally { multiWriter.close(); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
finally { stream.close(); }
67
dispose 5
                  
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
finally { g2d.dispose(); }
// in src/java/org/apache/fop/render/AbstractImageHandlerGraphics2D.java
finally { g2d.dispose(); }
// in src/java/org/apache/fop/render/AbstractGraphics2DAdapter.java
finally { g2d.dispose(); }
// in src/java/org/apache/fop/afp/AFPGraphics2D.java
finally { g2d.dispose(); //drawn so dispose immediately to free system resource }
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
finally { g2d.dispose(); }
18
closeInputStream
3
                  
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
finally { closeInputStream(inputStream); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
finally { closeInputStream(inputStream); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
finally { closeInputStream(inputStream); }
3
flush 3
                  
// in src/sandbox/org/apache/fop/render/svg/SVGRenderer.java
finally { if (out != this.firstOutputStream) { IOUtils.closeQuietly(out); } else { out.flush(); } }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
finally { if (oos != null) { try { oos.flush(); } catch (IOException e) { //ignore } try { oos.close(); } catch (IOException e) { //ignore } } }
// in src/java/org/apache/fop/afp/modca/StreamedResourceGroup.java
finally { os.flush(); }
53
delete 2
                  
// in src/java/org/apache/fop/tools/anttasks/Fop.java
finally { try { out.close(); } catch (IOException ioe) { logger.error("Error closing output file", ioe); } if (!success) { outFile.delete(); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
finally { IOUtils.closeQuietly(in); if (!this.tempFile.delete()) { this.tempFile.deleteOnExit(); log.warn("Could not delete temporary file: " + this.tempFile); } }
13
createStreamedResourceGroup 1
                  
// in src/java/org/apache/fop/afp/AFPStreamer.java
finally { if (os != null) { resourceGroup = factory.createStreamedResourceGroup(os); pathResourceGroupMap.put(filePath, resourceGroup); } }
2
deleteOnExit 1
                  
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
finally { IOUtils.closeQuietly(in); if (!this.tempFile.delete()) { this.tempFile.deleteOnExit(); log.warn("Could not delete temporary file: " + this.tempFile); } }
3
error 1
                  
// in src/java/org/apache/fop/tools/anttasks/Fop.java
finally { try { out.close(); } catch (IOException ioe) { logger.error("Error closing output file", ioe); } if (!success) { outFile.delete(); } }
184
getInputStream 1
                  
// in src/java/org/apache/fop/fonts/FontCache.java
finally { // An InputStream is created even if it's not accessed, but we // need to close it. IOUtils.closeQuietly(conn.getInputStream()); }
17
put 1
                  
// in src/java/org/apache/fop/afp/AFPStreamer.java
finally { if (os != null) { resourceGroup = factory.createStreamedResourceGroup(os); pathResourceGroupMap.put(filePath, resourceGroup); } }
867
reset 1
                  
// in src/java/org/apache/fop/render/pdf/ImageRawJPEGAdapter.java
finally { in.reset(); }
47
resetATState 1
                  
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
finally { resetATState(); }
5
setOverrideFont 1
                  
// in src/java/org/apache/fop/svg/AbstractFOPTextPainter.java
finally { nativeTextHandler.setOverrideFont(null); }
2
unlock
1
                  
// in src/java/org/apache/fop/fo/properties/PropertyCache.java
finally { cleanupLock.unlock(); }
1
warn 1
                  
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
finally { IOUtils.closeQuietly(in); if (!this.tempFile.delete()) { this.tempFile.deleteOnExit(); log.warn("Could not delete temporary file: " + this.tempFile); } }
113

Reference Table

This table concatenates the results of the previous tables.

Checked/Runtime Type Exception Thrown Thrown from Catch Declared Caught directly Caught
with Thrown
Caught
with Thrown Runtime
unknown (Lib) . 0 0 0 0 0 0
runtime (Domain) AdvancedTypographicTableFormatException
public class AdvancedTypographicTableFormatException extends RuntimeException {
    /**
     * Instantiate ATT format exception.
     */
    public AdvancedTypographicTableFormatException() {
        super();
    }
    /**
     * Instantiate ATT format exception.
     * @param message a message string
     */
    public AdvancedTypographicTableFormatException(String message) {
        super(message);
    }
    /**
     * Instantiate ATT format exception.
     * @param message a message string
     * @param cause a <code>Throwable</code> that caused this exception
     */
    public AdvancedTypographicTableFormatException(String message, Throwable cause) {
        super(message, cause);
    }
}
160
            
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( ( entries == null ) || ( entries.size() != 1 ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null and contain exactly one entry" ); } else { Value v; Object o = entries.get(0); if ( o instanceof Value ) { v = (Value) o; } else { throw new AdvancedTypographicTableFormatException ( "illegal entries entry, must be Value, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } assert this.value == null; this.value = v; this.ciMax = getCoverageSize() - 1; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof Value[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, single entry must be a Value[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { Value[] va = (Value[]) o; if ( va.length != getCoverageSize() ) { throw new AdvancedTypographicTableFormatException ( "illegal values array, " + entries.size() + " values present, but requires " + getCoverageSize() + " values" ); } else { assert this.values == null; this.values = va; } } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof PairValues[][] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first (and only) entry must be a PairValues[][], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { pvm = (PairValues[][]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 5 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 5 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphClassTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { cdt1 = (GlyphClassTable) o; } if ( ( ( o = entries.get(1) ) == null ) || ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an GlyphClassTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { cdt2 = (GlyphClassTable) o; } if ( ( ( o = entries.get(2) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { nc1 = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(3) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fourth entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { nc2 = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(4) ) == null ) || ! ( o instanceof PairValues[][] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fifth entry must be a PairValues[][], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { pvm = (PairValues[][]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof Anchor[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first (and only) entry must be a Anchor[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else if ( ( ( (Anchor[]) o ) . length % 2 ) != 0 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, Anchor[] array must have an even number of entries, but has: " + ( (Anchor[]) o ) . length ); } else { aa = (Anchor[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 4 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 4 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphCoverageTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphCoverageTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { bct = (GlyphCoverageTable) o; } if ( ( ( o = entries.get(1) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { nmc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(2) ) == null ) || ! ( o instanceof MarkAnchor[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be a MarkAnchor[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { maa = (MarkAnchor[]) o; } if ( ( ( o = entries.get(3) ) == null ) || ! ( o instanceof Anchor[][] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fourth entry must be a Anchor[][], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { bam = (Anchor[][]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 5 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 5 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphCoverageTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphCoverageTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { lct = (GlyphCoverageTable) o; } if ( ( ( o = entries.get(1) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { nmc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(2) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { mxc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(3) ) == null ) || ! ( o instanceof MarkAnchor[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fourth entry must be a MarkAnchor[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { maa = (MarkAnchor[]) o; } if ( ( ( o = entries.get(4) ) == null ) || ! ( o instanceof Anchor[][][] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fifth entry must be a Anchor[][][], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { lam = (Anchor[][][]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 4 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 4 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphCoverageTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphCoverageTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { mct2 = (GlyphCoverageTable) o; } if ( ( ( o = entries.get(1) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { nmc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(2) ) == null ) || ! ( o instanceof MarkAnchor[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be a MarkAnchor[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { maa = (MarkAnchor[]) o; } if ( ( ( o = entries.get(3) ) == null ) || ! ( o instanceof Anchor[][] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fourth entry must be a Anchor[][], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { mam = (Anchor[][]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 3 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 3 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphClassTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { cdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(1) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { ngc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(2) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; if ( rsa.length != ngc ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, RuleSet[] length is " + rsa.length + ", but expected " + ngc + " glyph classes" ); } } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 5 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 5 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphClassTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { icdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(1) ) != null ) && ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an GlyphClassTable, but is: " + o.getClass() ); } else { bcdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(2) ) != null ) && ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be an GlyphClassTable, but is: " + o.getClass() ); } else { lcdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(3) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fourth entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { ngc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(4) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fifth entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; if ( rsa.length != ngc ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, RuleSet[] length is " + rsa.length + ", but expected " + ngc + " glyph classes" ); } } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphCoverageTable.java
private void populate ( List entries ) { int i = 0; int skipped = 0; int n = entries.size(); int gidMax = -1; int[] map = new int [ n ]; for ( Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); if ( o instanceof Integer ) { int gid = ( (Integer) o ) . intValue(); if ( ( gid >= 0 ) && ( gid < 65536 ) ) { if ( gid > gidMax ) { map [ i++ ] = gidMax = gid; } else { log.info ( "ignoring out of order or duplicate glyph index: " + gid ); skipped++; } } else { throw new AdvancedTypographicTableFormatException ( "illegal glyph index: " + gid ); } } else { throw new AdvancedTypographicTableFormatException ( "illegal coverage entry, must be Integer: " + o ); } } assert ( i + skipped ) == n; assert this.map == null; this.map = map; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphTable.java
private void validateSubtable ( GlyphSubtable subtable ) { if ( subtable == null ) { throw new AdvancedTypographicTableFormatException ( "subtable must be non-null" ); } if ( subtable instanceof GlyphSubstitutionSubtable ) { if ( doesPos ) { throw new AdvancedTypographicTableFormatException ( "subtable must be positioning subtable, but is: " + subtable ); } else { doesSub = true; } } if ( subtable instanceof GlyphPositioningSubtable ) { if ( doesSub ) { throw new AdvancedTypographicTableFormatException ( "subtable must be substitution subtable, but is: " + subtable ); } else { doesPos = true; } } if ( subtables.size() > 0 ) { GlyphSubtable st = (GlyphSubtable) subtables.get(0); if ( ! st.isCompatible ( subtable ) ) { throw new AdvancedTypographicTableFormatException ( "subtable " + subtable + " is not compatible with subtable " + st ); } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphMappingTable.java
private void populate ( List entries ) { int i = 0; int n = entries.size(); int gidMax = -1; int miMax = -1; int[] sa = new int [ n ]; int[] ea = new int [ n ]; int[] ma = new int [ n ]; for ( Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); if ( o instanceof MappingRange ) { MappingRange r = (MappingRange) o; int gs = r.getStart(); int ge = r.getEnd(); int mi = r.getIndex(); if ( ( gs < 0 ) || ( gs > 65535 ) ) { throw new AdvancedTypographicTableFormatException ( "illegal glyph range: [" + gs + "," + ge + "]: bad start index" ); } else if ( ( ge < 0 ) || ( ge > 65535 ) ) { throw new AdvancedTypographicTableFormatException ( "illegal glyph range: [" + gs + "," + ge + "]: bad end index" ); } else if ( gs > ge ) { throw new AdvancedTypographicTableFormatException ( "illegal glyph range: [" + gs + "," + ge + "]: start index exceeds end index" ); } else if ( gs < gidMax ) { throw new AdvancedTypographicTableFormatException ( "out of order glyph range: [" + gs + "," + ge + "]" ); } else if ( mi < 0 ) { throw new AdvancedTypographicTableFormatException ( "illegal mapping index: " + mi ); } else { int miLast; sa [ i ] = gs; ea [ i ] = gidMax = ge; ma [ i ] = mi; if ( ( miLast = mi + ( ge - gs ) ) > miMax ) { miMax = miLast; } i++; } } else { throw new AdvancedTypographicTableFormatException ( "illegal mapping entry, must be Integer: " + o ); } } assert i == n; assert this.sa == null; assert this.ea == null; assert this.ma == null; this.sa = sa; this.ea = ea; this.ma = ma; this.miMax = miMax; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
public void readAll() throws AdvancedTypographicTableFormatException { try { readGDEF(); readGSUB(); readGPOS(); } catch ( AdvancedTypographicTableFormatException e ) { resetATStateAll(); throw e; } catch ( IOException e ) { resetATStateAll(); throw new AdvancedTypographicTableFormatException ( e.getMessage(), e ); } finally { resetATState(); } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphCoverageTable readCoverageTable(String label, long tableOffset) throws IOException { GlyphCoverageTable gct; long cp = in.getCurrentPos(); in.seekSet(tableOffset); // read coverage table format int cf = in.readTTFUShort(); if ( cf == 1 ) { gct = readCoverageTableFormat1 ( label, tableOffset, cf ); } else if ( cf == 2 ) { gct = readCoverageTableFormat2 ( label, tableOffset, cf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported coverage table format: " + cf ); } in.seekSet ( cp ); return gct; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphClassTable readClassDefTable(String label, long tableOffset) throws IOException { GlyphClassTable gct; long cp = in.getCurrentPos(); in.seekSet(tableOffset); // read class table format int cf = in.readTTFUShort(); if ( cf == 1 ) { gct = readClassDefTableFormat1 ( label, tableOffset, cf ); } else if ( cf == 2 ) { gct = readClassDefTableFormat2 ( label, tableOffset, cf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported class definition table format: " + cf ); } in.seekSet ( cp ); return gct; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readSingleSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readSingleSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readSingleSubTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported single substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMultipleSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMultipleSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported multiple substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readAlternateSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readAlternateSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported alternate substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readLigatureSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readLigatureSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported ligature substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readContextualSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readContextualSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readContextualSubTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readContextualSubTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported contextual substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readChainedContextualSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readChainedContextualSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readChainedContextualSubTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readChainedContextualSubTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported chained contextual substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readExtensionSubTable(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readExtensionSubTableFormat1 ( lookupType, lookupFlags, lookupSequence, subtableSequence, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported extension substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readReverseChainedSingleSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readReverseChainedSingleSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported reverse chained single substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readSinglePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positionining subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readSinglePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readSinglePosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported single positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readPairPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readPairPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readPairPosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported pair positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphPositioningTable.Anchor readPosAnchor(long anchorTableOffset) throws IOException { GlyphPositioningTable.Anchor a; long cp = in.getCurrentPos(); in.seekSet(anchorTableOffset); // read anchor table format int af = in.readTTFUShort(); if ( af == 1 ) { // read x coordinate int x = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read y coordinate int y = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); a = new GlyphPositioningTable.Anchor ( x, y ); } else if ( af == 2 ) { // read x coordinate int x = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read y coordinate int y = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read anchor point index int ap = in.readTTFUShort(); a = new GlyphPositioningTable.Anchor ( x, y, ap ); } else if ( af == 3 ) { // read x coordinate int x = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read y coordinate int y = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read x device table offset int xdo = in.readTTFUShort(); // read y device table offset int ydo = in.readTTFUShort(); // read x device table (if present) GlyphPositioningTable.DeviceTable xd; if ( xdo != 0 ) { xd = readPosDeviceTable ( cp, xdo ); } else { xd = null; } // read y device table (if present) GlyphPositioningTable.DeviceTable yd; if ( ydo != 0 ) { yd = readPosDeviceTable ( cp, ydo ); } else { yd = null; } a = new GlyphPositioningTable.Anchor ( x, y, xd, yd ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported positioning anchor format: " + af ); } in.seekSet(cp); return a; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readCursivePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readCursivePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported cursive positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMarkToBasePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMarkToBasePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark-to-base positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMarkToLigaturePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMarkToLigaturePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark-to-ligature positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMarkToMarkPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMarkToMarkPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark-to-mark positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readContextualPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readContextualPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readContextualPosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readContextualPosTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported contextual positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readChainedContextualPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readChainedContextualPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readChainedContextualPosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readChainedContextualPosTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported chained contextual positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readExtensionPosTable(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readExtensionPosTableFormat1 ( lookupType, lookupFlags, lookupSequence, subtableSequence, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported extension positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFMarkGlyphsTable(String tableTag, int lookupSequence, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read mark set subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readGDEFMarkGlyphsTableFormat1 ( tableTag, lookupSequence, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark glyph sets subtable format: " + sf ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphClassTable.java
private void populate ( List entries ) { // obtain entries iterator Iterator it = entries.iterator(); // extract first glyph int firstGlyph = 0; if ( it.hasNext() ) { Object o = it.next(); if ( o instanceof Integer ) { firstGlyph = ( (Integer) o ) . intValue(); } else { throw new AdvancedTypographicTableFormatException ( "illegal entry, first entry must be Integer denoting first glyph value, but is: " + o ); } } // extract glyph class array int i = 0; int n = entries.size() - 1; int gcMax = -1; int[] gca = new int [ n ]; while ( it.hasNext() ) { Object o = it.next(); if ( o instanceof Integer ) { int gc = ( (Integer) o ) . intValue(); gca [ i++ ] = gc; if ( gc > gcMax ) { gcMax = gc; } } else { throw new AdvancedTypographicTableFormatException ( "illegal mapping entry, must be Integer: " + o ); } } assert i == n; assert this.gca == null; this.firstGlyph = firstGlyph; this.gca = gca; this.gcMax = gcMax; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( ( entries == null ) || ( entries.size() != 1 ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null and contain exactly one entry" ); } else { Object o = entries.get(0); int delta = 0; if ( o instanceof Integer ) { delta = ( (Integer) o ) . intValue(); } else { throw new AdvancedTypographicTableFormatException ( "illegal entries entry, must be Integer, but is: " + o ); } this.delta = delta; this.ciMax = getCoverageSize() - 1; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { int i = 0; int n = entries.size(); int[] glyphs = new int [ n ]; for ( Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); if ( o instanceof Integer ) { int gid = ( (Integer) o ) .intValue(); if ( ( gid >= 0 ) && ( gid < 65536 ) ) { glyphs [ i++ ] = gid; } else { throw new AdvancedTypographicTableFormatException ( "illegal glyph index: " + gid ); } } else { throw new AdvancedTypographicTableFormatException ( "illegal entries entry, must be Integer: " + o ); } } assert i == n; assert this.glyphs == null; this.glyphs = glyphs; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof int[][] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an int[][], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { gsa = (int[][]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { int i = 0; int n = entries.size(); int[][] gaa = new int [ n ][]; for ( Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); if ( o instanceof int[] ) { gaa [ i++ ] = (int[]) o; } else { throw new AdvancedTypographicTableFormatException ( "illegal entries entry, must be int[]: " + o ); } } assert i == n; assert this.gaa == null; this.gaa = gaa; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { int i = 0; int n = entries.size(); LigatureSet[] ligatureSets = new LigatureSet [ n ]; for ( Iterator it = entries.iterator(); it.hasNext();) { Object o = it.next(); if ( o instanceof LigatureSet ) { ligatureSets [ i++ ] = (LigatureSet) o; } else { throw new AdvancedTypographicTableFormatException ( "illegal ligatures entry, must be LigatureSet: " + o ); } } assert i == n; assert this.ligatureSets == null; this.ligatureSets = ligatureSets; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 3 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 3 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphClassTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { cdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(1) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { ngc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(2) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; if ( rsa.length != ngc ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, RuleSet[] length is " + rsa.length + ", but expected " + ngc + " glyph classes" ); } } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 5 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 5 entries" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an GlyphClassTable, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { icdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(1) ) != null ) && ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, second entry must be an GlyphClassTable, but is: " + o.getClass() ); } else { bcdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(2) ) != null ) && ! ( o instanceof GlyphClassTable ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, third entry must be an GlyphClassTable, but is: " + o.getClass() ); } else { lcdt = (GlyphClassTable) o; } if ( ( ( o = entries.get(3) ) == null ) || ! ( o instanceof Integer ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fourth entry must be an Integer, but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { ngc = ((Integer)(o)).intValue(); } if ( ( ( o = entries.get(4) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, fifth entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; if ( rsa.length != ngc ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, RuleSet[] length is " + rsa.length + ", but expected " + ngc + " glyph classes" ); } } } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
private void populate ( List entries ) { if ( entries == null ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, must be non-null" ); } else if ( entries.size() != 1 ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, " + entries.size() + " entries present, but requires 1 entry" ); } else { Object o; if ( ( ( o = entries.get(0) ) == null ) || ! ( o instanceof RuleSet[] ) ) { throw new AdvancedTypographicTableFormatException ( "illegal entries, first entry must be an RuleSet[], but is: " + ( ( o != null ) ? o.getClass() : null ) ); } else { rsa = (RuleSet[]) o; } } }
1
            
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( IOException e ) { resetATStateAll(); throw new AdvancedTypographicTableFormatException ( e.getMessage(), e ); }
3
            
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
public void readAll() throws AdvancedTypographicTableFormatException { try { readGDEF(); readGSUB(); readGPOS(); } catch ( AdvancedTypographicTableFormatException e ) { resetATStateAll(); throw e; } catch ( IOException e ) { resetATStateAll(); throw new AdvancedTypographicTableFormatException ( e.getMessage(), e ); } finally { resetATState(); } }
2
            
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
catch ( AdvancedTypographicTableFormatException e ) { log.warn ( "Encountered format constraint violation in advanced (typographic) table (AT) " + "in font '" + getFullName() + "', ignoring AT data: " + e.getMessage() ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( AdvancedTypographicTableFormatException e ) { resetATStateAll(); throw e; }
1
            
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( AdvancedTypographicTableFormatException e ) { resetATStateAll(); throw e; }
0
unknown (Lib) ArithmeticException 1
            
// in src/java/org/apache/fop/traits/MinOptMax.java
private void checkCompatibility(int thisElasticity, int operandElasticity, String msge) { if (thisElasticity < operandElasticity) { throw new ArithmeticException( "Cannot subtract a MinOptMax from another MinOptMax that has less " + msge + " (" + thisElasticity + " < " + operandElasticity + ")"); } }
0 1
            
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax minus(MinOptMax operand) throws ArithmeticException { checkCompatibility(getShrink(), operand.getShrink(), "shrink"); checkCompatibility(getStretch(), operand.getStretch(), "stretch"); return new MinOptMax(min - operand.min, opt - operand.opt, max - operand.max); }
0 0 0
unknown (Lib) AssertionError 1
            
// in src/java/org/apache/fop/fo/FONode.java
protected Object clone() { try { return super.clone(); } catch (CloneNotSupportedException e) { throw new AssertionError(); // Can't happen } }
1
            
// in src/java/org/apache/fop/fo/FONode.java
catch (CloneNotSupportedException e) { throw new AssertionError(); // Can't happen }
0 0 0 0
unknown (Lib) BadPaddingException 0 0 0 1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (BadPaddingException e) { throw new IllegalStateException(e.getMessage()); }
1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (BadPaddingException e) { throw new IllegalStateException(e.getMessage()); }
1
unknown (Lib) BuildException 15
            
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
protected void testNewBuild() { try { ClassLoader loader = new URLClassLoader( createUrls("build/fop.jar")); Map diff = runConverter(loader, "areatree", "reference/output/"); if (diff != null && !diff.isEmpty()) { System.out.println("===================================="); System.out.println("The following files differ:"); boolean broke = false; for (Iterator keys = diff.keySet().iterator(); keys.hasNext();) { Object fname = keys.next(); Boolean pass = (Boolean)diff.get(fname); System.out.println("file: " + fname + " - reference success: " + pass); if (pass.booleanValue()) { broke = true; } } if (broke) { throw new BuildException("Working tests have been changed."); } } } catch (MalformedURLException mue) { mue.printStackTrace(); } }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
protected void runReference() throws BuildException { // check not already done File f = new File(basedir + "/reference/output/"); // if(f.exists()) { // need to check that files have actually been created. // return; // } else { try { ClassLoader loader = new URLClassLoader(createUrls(referenceJar)); boolean failed = false; try { Class cla = Class.forName("org.apache.fop.apps.Fop", true, loader); Method get = cla.getMethod("getVersion", new Class[]{}); if (!get.invoke(null, new Object[]{}).equals(refVersion)) { throw new BuildException("Reference jar is not correct version it must be: " + refVersion); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
public void setMessagelevel(String messageLevel) { if (messageLevel.equalsIgnoreCase("info")) { messageType = Project.MSG_INFO; } else if (messageLevel.equalsIgnoreCase("verbose")) { messageType = Project.MSG_VERBOSE; } else if (messageLevel.equalsIgnoreCase("debug")) { messageType = Project.MSG_DEBUG; } else if (messageLevel.equalsIgnoreCase("err") || messageLevel.equalsIgnoreCase("error")) { messageType = Project.MSG_ERR; } else if (messageLevel.equalsIgnoreCase("warn")) { messageType = Project.MSG_WARN; } else { log("messagelevel set to unknown value \"" + messageLevel + "\"", Project.MSG_ERR); throw new BuildException("unknown messagelevel"); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
public void execute() throws BuildException { int logLevel = SimpleLog.LOG_LEVEL_INFO; switch (getMessageType()) { case Project.MSG_DEBUG : logLevel = SimpleLog.LOG_LEVEL_DEBUG; break; case Project.MSG_INFO : logLevel = SimpleLog.LOG_LEVEL_INFO; break; case Project.MSG_WARN : logLevel = SimpleLog.LOG_LEVEL_WARN; break; case Project.MSG_ERR : logLevel = SimpleLog.LOG_LEVEL_ERROR; break; case Project.MSG_VERBOSE: logLevel = SimpleLog.LOG_LEVEL_DEBUG; break; default: logLevel = SimpleLog.LOG_LEVEL_INFO; } SimpleLog logger = new SimpleLog("FOP/Anttask"); logger.setLevel(logLevel); try { FOPTaskStarter starter = new FOPTaskStarter(this); starter.setLogger(logger); starter.run(); } catch (FOPException ex) { throw new BuildException(ex); } catch (IOException ioe) { throw new BuildException(ioe); } catch (SAXException saxex) { throw new BuildException(saxex); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
public void run() throws FOPException { //Set base directory if (task.getBasedir() != null) { try { this.baseURL = task.getBasedir().toURI().toURL().toExternalForm(); } catch (MalformedURLException mfue) { logger.error("Error creating base URL from base directory", mfue); } } else { try { if (task.getFofile() != null) { this.baseURL = task.getFofile().getParentFile().toURI().toURL() .toExternalForm(); } } catch (MalformedURLException mfue) { logger.error("Error creating base URL from XSL-FO input file", mfue); } } task.log("Using base URL: " + baseURL, Project.MSG_DEBUG); String outputFormat = normalizeOutputFormat(task.getFormat()); String newExtension = determineExtension(outputFormat); // actioncount = # of fofiles actually processed through FOP int actioncount = 0; // skippedcount = # of fofiles which haven't changed (force = "false") int skippedcount = 0; // deal with single source file if (task.getFofile() != null) { if (task.getFofile().exists()) { File outf = task.getOutfile(); if (outf == null) { throw new BuildException("outfile is required when fofile is used"); } if (task.getOutdir() != null) { outf = new File(task.getOutdir(), outf.getName()); } // Render if "force" flag is set OR // OR output file doesn't exist OR // output file is older than input file if (task.getForce() || !outf.exists() || (task.getFofile().lastModified() > outf.lastModified() )) { render(task.getFofile(), outf, outputFormat); actioncount++; } else if (outf.exists() && (task.getFofile().lastModified() <= outf.lastModified() )) { skippedcount++; } } } else if (task.getXmlFile() != null && task.getXsltFile() != null) { if (task.getXmlFile().exists() && task.getXsltFile().exists()) { File outf = task.getOutfile(); if (outf == null) { throw new BuildException("outfile is required when fofile is used"); } if (task.getOutdir() != null) { outf = new File(task.getOutdir(), outf.getName()); } // Render if "force" flag is set OR // OR output file doesn't exist OR // output file is older than input file if (task.getForce() || !outf.exists() || (task.getXmlFile().lastModified() > outf.lastModified() || task.getXsltFile().lastModified() > outf.lastModified())) { render(task.getXmlFile(), task.getXsltFile(), outf, outputFormat); actioncount++; } else if (outf.exists() && (task.getXmlFile().lastModified() <= outf.lastModified() || task.getXsltFile().lastModified() <= outf.lastModified())) { skippedcount++; } } } GlobPatternMapper mapper = new GlobPatternMapper(); String inputExtension = ".fo"; File xsltFile = task.getXsltFile(); if (xsltFile != null) { inputExtension = ".xml"; } mapper.setFrom("*" + inputExtension); mapper.setTo("*" + newExtension); // deal with the filesets for (int i = 0; i < task.getFilesets().size(); i++) { FileSet fs = (FileSet) task.getFilesets().get(i); DirectoryScanner ds = fs.getDirectoryScanner(task.getProject()); String[] files = ds.getIncludedFiles(); for (int j = 0; j < files.length; j++) { File f = new File(fs.getDir(task.getProject()), files[j]); File outf = null; if (task.getOutdir() != null && files[j].endsWith(inputExtension)) { String[] sa = mapper.mapFileName(files[j]); outf = new File(task.getOutdir(), sa[0]); } else { outf = replaceExtension(f, inputExtension, newExtension); if (task.getOutdir() != null) { outf = new File(task.getOutdir(), outf.getName()); } } File dir = outf.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } try { if (task.getRelativebase()) { this.baseURL = f.getParentFile().toURI().toURL() .toExternalForm(); } if (this.baseURL == null) { this.baseURL = fs.getDir(task.getProject()).toURI().toURL() .toExternalForm(); } } catch (Exception e) { task.log("Error setting base URL", Project.MSG_DEBUG); } // Render if "force" flag is set OR // OR output file doesn't exist OR // output file is older than input file if (task.getForce() || !outf.exists() || (f.lastModified() > outf.lastModified() )) { if (xsltFile != null) { render(f, xsltFile, outf, outputFormat); } else { render(f, outf, outputFormat); } actioncount++; } else if (outf.exists() && (f.lastModified() <= outf.lastModified() )) { skippedcount++; } } } if (actioncount + skippedcount == 0) { task.log("No files processed. No files were selected by the filesets " + "and no fofile was set." , Project.MSG_WARN); } else if (skippedcount > 0) { task.log(skippedcount + " xslfo file(s) skipped (no change found" + " since last generation; set force=\"true\" to override)." , Project.MSG_INFO); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
private void renderInputHandler(InputHandler inputHandler, File outFile, String outputFormat) throws Exception { OutputStream out = null; try { out = new java.io.FileOutputStream(outFile); out = new BufferedOutputStream(out); } catch (Exception ex) { throw new BuildException("Failed to open " + outFile, ex); } boolean success = false; try { FOUserAgent userAgent = fopFactory.newFOUserAgent(); userAgent.setBaseURL(this.baseURL); inputHandler.renderTo(userAgent, outputFormat, out); success = true; } catch (Exception ex) { if (task.getThrowexceptions()) { throw new BuildException(ex); } throw ex; } finally { try { out.close(); } catch (IOException ioe) { logger.error("Error closing output file", ioe); } if (!success) { outFile.delete(); } } }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
public void execute() throws BuildException { try { EventProducerCollector collector = new EventProducerCollector(); long lastModified = processFileSets(collector); for (Iterator iter = collector.getModels().iterator(); iter.hasNext();) { EventModel model = (EventModel) iter.next(); File parentDir = getParentDir(model); if (!parentDir.exists() && !parentDir.mkdirs()) { throw new BuildException( "Could not create target directory for event model file: " + parentDir); } File modelFile = new File(parentDir, "event-model.xml"); if (!modelFile.exists() || lastModified > modelFile.lastModified()) { model.saveToXML(modelFile); log("Event model written to " + modelFile); } if (getTranslationFile() != null) { // TODO Remove translation file creation facility? if (!getTranslationFile().exists() || lastModified > getTranslationFile().lastModified()) { updateTranslationFile(modelFile); } } } } catch (ClassNotFoundException e) { throw new BuildException(e); } catch (EventConventionException ece) { throw new BuildException(ece); } catch (IOException ioe) { throw new BuildException(ioe); } }
8
            
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (FOPException ex) { throw new BuildException(ex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (IOException ioe) { throw new BuildException(ioe); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (SAXException saxex) { throw new BuildException(saxex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { throw new BuildException("Failed to open " + outFile, ex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { if (task.getThrowexceptions()) { throw new BuildException(ex); } throw ex; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (ClassNotFoundException e) { throw new BuildException(e); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (EventConventionException ece) { throw new BuildException(ece); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (IOException ioe) { throw new BuildException(ioe); }
5
            
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
public void execute() throws BuildException { runReference(); testNewBuild(); }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
protected void runReference() throws BuildException { // check not already done File f = new File(basedir + "/reference/output/"); // if(f.exists()) { // need to check that files have actually been created. // return; // } else { try { ClassLoader loader = new URLClassLoader(createUrls(referenceJar)); boolean failed = false; try { Class cla = Class.forName("org.apache.fop.apps.Fop", true, loader); Method get = cla.getMethod("getVersion", new Class[]{}); if (!get.invoke(null, new Object[]{}).equals(refVersion)) { throw new BuildException("Reference jar is not correct version it must be: " + refVersion); } }
// in src/java/org/apache/fop/tools/anttasks/FileCompare.java
public void execute() throws BuildException { boolean identical = false; File oldFile; File newFile; try { PrintWriter results = new PrintWriter(new java.io.FileWriter("results.html"), true); this.writeHeader(results); for (int i = 0; i < filenameList.length; i++) { oldFile = new File(referenceDirectory + filenameList[i]); newFile = new File(testDirectory + filenameList[i]); if (filesExist(oldFile, newFile)) { identical = compareFileSize(oldFile, newFile); if (identical) { identical = compareBytes(oldFile, newFile); } if (!identical) { System.out.println("Task Compare: \nFiles " + referenceDirectory + oldFile.getName() + " - " + testDirectory + newFile.getName() + " are *not* identical."); results.println("<tr><td><a href='" + referenceDirectory + oldFile.getName() + "'>" + oldFile.getName() + "</a> </td><td> <a href='" + testDirectory + newFile.getName() + "'>" + newFile.getName() + "</a>" + " </td><td><font color='red'>No</font></td></tr>"); } else { results.println("<tr><td><a href='" + referenceDirectory + oldFile.getName() + "'>" + oldFile.getName() + "</a> </td><td> <a href='" + testDirectory + newFile.getName() + "'>" + newFile.getName() + "</a>" + " </td><td>Yes</td></tr>"); } } } results.println("</table></html>"); } catch (IOException ioe) { System.err.println("ERROR: " + ioe); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
public void execute() throws BuildException { int logLevel = SimpleLog.LOG_LEVEL_INFO; switch (getMessageType()) { case Project.MSG_DEBUG : logLevel = SimpleLog.LOG_LEVEL_DEBUG; break; case Project.MSG_INFO : logLevel = SimpleLog.LOG_LEVEL_INFO; break; case Project.MSG_WARN : logLevel = SimpleLog.LOG_LEVEL_WARN; break; case Project.MSG_ERR : logLevel = SimpleLog.LOG_LEVEL_ERROR; break; case Project.MSG_VERBOSE: logLevel = SimpleLog.LOG_LEVEL_DEBUG; break; default: logLevel = SimpleLog.LOG_LEVEL_INFO; } SimpleLog logger = new SimpleLog("FOP/Anttask"); logger.setLevel(logLevel); try { FOPTaskStarter starter = new FOPTaskStarter(this); starter.setLogger(logger); starter.run(); } catch (FOPException ex) { throw new BuildException(ex); } catch (IOException ioe) { throw new BuildException(ioe); } catch (SAXException saxex) { throw new BuildException(saxex); } }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
public void execute() throws BuildException { try { EventProducerCollector collector = new EventProducerCollector(); long lastModified = processFileSets(collector); for (Iterator iter = collector.getModels().iterator(); iter.hasNext();) { EventModel model = (EventModel) iter.next(); File parentDir = getParentDir(model); if (!parentDir.exists() && !parentDir.mkdirs()) { throw new BuildException( "Could not create target directory for event model file: " + parentDir); } File modelFile = new File(parentDir, "event-model.xml"); if (!modelFile.exists() || lastModified > modelFile.lastModified()) { model.saveToXML(modelFile); log("Event model written to " + modelFile); } if (getTranslationFile() != null) { // TODO Remove translation file creation facility? if (!getTranslationFile().exists() || lastModified > getTranslationFile().lastModified()) { updateTranslationFile(modelFile); } } } } catch (ClassNotFoundException e) { throw new BuildException(e); } catch (EventConventionException ece) { throw new BuildException(ece); } catch (IOException ioe) { throw new BuildException(ioe); } }
0 0 0
unknown (Lib) CascadingRuntimeException 3
            
// in src/java/org/apache/fop/pdf/PDFText.java
public static final String escapeText(final String text, boolean forceHexMode) { if (text != null && text.length() > 0) { boolean unicode = false; boolean hexMode = false; if (forceHexMode) { hexMode = true; } else { for (int i = 0, c = text.length(); i < c; i++) { if (text.charAt(i) >= 128) { unicode = true; hexMode = true; break; } } } if (hexMode) { final byte[] uniBytes; try { uniBytes = text.getBytes("UTF-16"); } catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); } return toHex(uniBytes); } else { final StringBuffer result = new StringBuffer(text.length() * 2); result.append("("); final int l = text.length(); if (unicode) { // byte order marker (0xfeff) result.append("\\376\\377"); for (int i = 0; i < l; i++) { final char ch = text.charAt(i); final int high = (ch & 0xff00) >>> 8; final int low = ch & 0xff; result.append("\\"); result.append(Integer.toOctalString(high)); result.append("\\"); result.append(Integer.toOctalString(low)); } } else { for (int i = 0; i < l; i++) { final char ch = text.charAt(i); if (ch < 256) { escapeStringChar(ch, result); } else { throw new IllegalStateException( "Can only treat text in 8-bit ASCII/PDFEncoding"); } } } result.append(")"); return result.toString(); } } return "()"; }
// in src/java/org/apache/fop/pdf/PDFText.java
public static final byte[] toUTF16(String text) { try { return text.getBytes("UnicodeBig"); } catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); } }
// in src/java/org/apache/fop/pdf/PDFText.java
public static final String toUnicodeHex(char c) { final StringBuffer buf = new StringBuffer(4); final byte[] uniBytes; try { final char[] a = {c}; uniBytes = new String(a).getBytes("UTF-16BE"); } catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); } for (int i = 0; i < uniBytes.length; i++) { buf.append(DIGITS[(uniBytes[i] >>> 4) & 0x0F]); buf.append(DIGITS[uniBytes[i] & 0x0F]); } return buf.toString(); }
3
            
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
0 0 0 0
unknown (Lib) ClassCastException 0 0 0 8
            
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(mappingClassName + " is not an ElementMapping"); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + XMLHandler.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractRendererMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractFOEventHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractIFDocumentHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ImageHandler.class.getName()); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassCastException cce) { throw new SAXException("XML format error: " + qName, cce); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ContentHandlerFactory.class.getName()); }
8
            
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(mappingClassName + " is not an ElementMapping"); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + XMLHandler.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractRendererMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractFOEventHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractIFDocumentHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ImageHandler.class.getName()); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassCastException cce) { throw new SAXException("XML format error: " + qName, cce); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ContentHandlerFactory.class.getName()); }
7
unknown (Lib) ClassNotFoundException 0 0 8
            
// in src/java/org/apache/fop/fonts/EmbedFontInfo.java
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); this.embedded = true; }
// in src/java/org/apache/fop/area/PageViewport.java
public void loadPage(ObjectInputStream in) throws IOException, ClassNotFoundException { page = (Page) in.readObject(); unresolvedIDRefs = page.getUnresolvedReferences(); if (unresolvedIDRefs != null && pendingResolved != null) { for (String id : pendingResolved.keySet()) { resolveIDRef(id, pendingResolved.get(id)); } pendingResolved = null; } }
// in src/java/org/apache/fop/area/inline/InlineViewport.java
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { if (in.readBoolean()) { contentPosition = new Rectangle2D.Float(in.readFloat(), in.readFloat(), in.readFloat(), in.readFloat()); } this.clip = in.readBoolean(); this.traits = (TreeMap) in.readObject(); this.content = (Area) in.readObject(); }
// in src/java/org/apache/fop/area/RegionViewport.java
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { viewArea = new Rectangle2D.Float(in.readFloat(), in.readFloat(), in.readFloat(), in.readFloat()); clip = in.readBoolean(); traits = (TreeMap)in.readObject(); setRegionReference((RegionReference) in.readObject()); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
protected long processFileSets(EventProducerCollector collector) throws IOException, EventConventionException, ClassNotFoundException { long lastModified = 0; Iterator<FileSet> iter = filesets.iterator(); while (iter.hasNext()) { FileSet fs = (FileSet)iter.next(); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); String[] srcFiles = ds.getIncludedFiles(); File directory = fs.getDir(getProject()); for (int i = 0, c = srcFiles.length; i < c; i++) { String filename = srcFiles[i]; File src = new File(directory, filename); boolean eventProducerFound = collector.scanFile(src); if (eventProducerFound) { lastModified = Math.max(lastModified, src.lastModified()); } } } return lastModified; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
public boolean scanFile(File src) throws IOException, EventConventionException, ClassNotFoundException { JavaDocBuilder builder = new JavaDocBuilder(this.tagFactory); builder.addSource(src); JavaClass[] classes = builder.getClasses(); boolean eventProducerFound = false; for (int i = 0, c = classes.length; i < c; i++) { JavaClass clazz = classes[i]; if (clazz.isInterface() && implementsInterface(clazz, CLASSNAME_EVENT_PRODUCER)) { processEventProducerInterface(clazz); eventProducerFound = true; } } return eventProducerFound; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
protected void processEventProducerInterface(JavaClass clazz) throws EventConventionException, ClassNotFoundException { EventProducerModel prodMeta = new EventProducerModel(clazz.getFullyQualifiedName()); JavaMethod[] methods = clazz.getMethods(true); for (int i = 0, c = methods.length; i < c; i++) { JavaMethod method = methods[i]; EventMethodModel methodMeta = createMethodModel(method); prodMeta.addMethod(methodMeta); } EventModel model = new EventModel(); model.addProducer(prodMeta); models.add(model); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
private EventMethodModel createMethodModel(JavaMethod method) throws EventConventionException, ClassNotFoundException { JavaClass clazz = method.getParentClass(); //Check EventProducer conventions if (!method.getReturnType().isVoid()) { throw new EventConventionException("All methods of interface " + clazz.getFullyQualifiedName() + " must have return type 'void'!"); } String methodSig = clazz.getFullyQualifiedName() + "." + method.getCallSignature(); JavaParameter[] params = method.getParameters(); if (params.length < 1) { throw new EventConventionException("The method " + methodSig + " must have at least one parameter: 'Object source'!"); } Type firstType = params[0].getType(); if (firstType.isPrimitive() || !"source".equals(params[0].getName())) { throw new EventConventionException("The first parameter of the method " + methodSig + " must be: 'Object source'!"); } //build method model DocletTag tag = method.getTagByName("event.severity"); EventSeverity severity; if (tag != null) { severity = EventSeverity.valueOf(tag.getValue()); } else { severity = EventSeverity.INFO; } EventMethodModel methodMeta = new EventMethodModel( method.getName(), severity); if (params.length > 1) { for (int j = 1, cj = params.length; j < cj; j++) { JavaParameter p = params[j]; Class<?> type; JavaClass pClass = p.getType().getJavaClass(); if (p.getType().isPrimitive()) { type = PRIMITIVE_MAP.get(pClass.getName()); if (type == null) { throw new UnsupportedOperationException( "Primitive datatype not supported: " + pClass.getName()); } } else { String className = pClass.getFullyQualifiedName(); type = Class.forName(className); } methodMeta.addParameter(type, p.getName()); } } Type[] exceptions = method.getExceptions(); if (exceptions != null && exceptions.length > 0) { //We only use the first declared exception because that is always thrown JavaClass cl = exceptions[0].getJavaClass(); methodMeta.setExceptionClass(cl.getFullyQualifiedName()); methodMeta.setSeverity(EventSeverity.FATAL); //In case it's not set in the comments } return methodMeta; }
19
            
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (ClassNotFoundException e) { return false; }
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (ClassNotFoundException e) { if (checkAvailableAlgorithms()) { LOG.warn("JCE and algorithms available, but the " + "implementation class unavailable. Please do a full " + "rebuild."); } return null; }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (ClassNotFoundException are) { failed = true; }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + mappingClassName); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (ClassNotFoundException cnfe) { log.error("Error while reading hyphenation object from file", cnfe); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (ClassNotFoundException e) { // We don't really care about the exception since it's just a // cache file log.warn("Could not read font cache. Discarding font cache file. Reason: " + e.getMessage()); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
catch (ClassNotFoundException cnfe) { jaiAvailable = 0; }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassNotFoundException e) { throw new SAXException("Could not find Class for: " + className, e); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
catch (ClassNotFoundException cnfe) { // Class was not compiled so is not available. Simply ignore. }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (ClassNotFoundException e) { // No worries }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (ClassNotFoundException e) { throw new BuildException(e); }
9
            
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + mappingClassName); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassNotFoundException e) { throw new SAXException("Could not find Class for: " + className, e); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (ClassNotFoundException e) { throw new BuildException(e); }
7
unknown (Lib) CloneNotSupportedException 0 0 10
            
// in src/java/org/apache/fop/hyphenation/CharVector.java
public Object clone() throws CloneNotSupportedException { CharVector cv = (CharVector) super.clone(); cv.array = (char[])array.clone(); return cv; }
// in src/java/org/apache/fop/hyphenation/TernaryTree.java
public Object clone() throws CloneNotSupportedException { TernaryTree t = (TernaryTree) super.clone(); t.lo = (char[])this.lo.clone(); t.hi = (char[])this.hi.clone(); t.eq = (char[])this.eq.clone(); t.sc = (char[])this.sc.clone(); t.kv = (CharVector)this.kv.clone(); return t; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAttributes.java
public Object clone() throws CloneNotSupportedException { RtfAttributes result = (RtfAttributes) super.clone(); result.values = (HashMap)values.clone(); // Added by Normand Masse // indicate the XSL attributes used to build the Rtf attributes if (xslAttributes != null) { result.xslAttributes = new org.xml.sax.helpers.AttributesImpl(xslAttributes); } return result; }
// in src/java/org/apache/fop/area/AreaTreeObject.java
public Object clone() throws CloneNotSupportedException { AreaTreeObject ato = (AreaTreeObject) super.clone(); if (foreignAttributes != null) { ato.foreignAttributes = (Map) ((HashMap) foreignAttributes).clone(); } if (extensionAttachments != null) { ato.extensionAttachments = (List) ((ArrayList) extensionAttachments).clone(); } return ato; }
// in src/java/org/apache/fop/area/PageViewport.java
public Object clone() throws CloneNotSupportedException { PageViewport pvp = (PageViewport) super.clone(); pvp.page = (Page) page.clone(); pvp.viewArea = (Rectangle) viewArea.clone(); return pvp; }
// in src/java/org/apache/fop/area/RegionReference.java
public Object clone() throws CloneNotSupportedException { RegionReference rr = (RegionReference) super.clone(); rr.blocks = (ArrayList) blocks.clone(); return rr; }
// in src/java/org/apache/fop/area/Page.java
public Object clone() throws CloneNotSupportedException { Page p = (Page) super.clone(); if (regionBefore != null) { p.regionBefore = (RegionViewport)regionBefore.clone(); } if (regionStart != null) { p.regionStart = (RegionViewport)regionStart.clone(); } if (regionBody != null) { p.regionBody = (RegionViewport)regionBody.clone(); } if (regionEnd != null) { p.regionEnd = (RegionViewport)regionEnd.clone(); } if (regionAfter != null) { p.regionAfter = (RegionViewport)regionAfter.clone(); } return p; }
// in src/java/org/apache/fop/area/Area.java
public Object clone() throws CloneNotSupportedException { Area area = (Area) super.clone(); if (traits != null) { area.traits = (TreeMap<Integer, Object>) traits.clone(); } return area; }
// in src/java/org/apache/fop/area/BodyRegion.java
public Object clone() throws CloneNotSupportedException { BodyRegion br = (BodyRegion) super.clone(); br.mainReference = new MainReference(br); return br; }
// in src/java/org/apache/fop/area/RegionViewport.java
public Object clone() throws CloneNotSupportedException { RegionViewport rv = (RegionViewport) super.clone(); rv.regionReference = (RegionReference) regionReference.clone(); rv.viewArea = (Rectangle2D) viewArea.clone(); return rv; }
13
            
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
catch (CloneNotSupportedException exc) { return null; }
// in src/java/org/apache/fop/fo/FONode.java
catch (CloneNotSupportedException e) { throw new AssertionError(); // Can't happen }
// in src/java/org/apache/fop/fo/CharIterator.java
catch (CloneNotSupportedException ex) { return null; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfText.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/area/PageViewport.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/layoutmgr/SpaceSpecifier.java
catch (CloneNotSupportedException cnse) { return null; }
// in src/java/org/apache/fop/complexscripts/util/GlyphSequence.java
catch ( CloneNotSupportedException e ) { return null; }
// in src/java/org/apache/fop/complexscripts/util/GlyphSequence.java
catch ( CloneNotSupportedException e ) { return null; }
8
            
// in src/java/org/apache/fop/fo/FONode.java
catch (CloneNotSupportedException e) { throw new AssertionError(); // Can't happen }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfText.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/area/PageViewport.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
0
unknown (Lib) ConfigurationException 2
            
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java
public void configure(PDFDocumentGraphics2D graphics, Configuration cfg, boolean useComplexScriptFeatures ) throws ConfigurationException { PDFDocument pdfDoc = graphics.getPDFDocument(); //Filter map pdfDoc.setFilterMap( PDFRendererConfigurator.buildFilterMapFromConfiguration(cfg)); //Fonts try { FontInfo fontInfo = createFontInfo(cfg, useComplexScriptFeatures); graphics.setFontInfo(fontInfo); } catch (FOPException e) { throw new ConfigurationException("Error while setting up fonts", e); } }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
public static Map buildFilterMapFromConfiguration(Configuration cfg) throws ConfigurationException { Map filterMap = new java.util.HashMap(); Configuration[] filterLists = cfg.getChildren("filterList"); for (int i = 0; i < filterLists.length; i++) { Configuration filters = filterLists[i]; String type = filters.getAttribute("type", null); Configuration[] filt = filters.getChildren("value"); List filterList = new java.util.ArrayList(); for (int j = 0; j < filt.length; j++) { String name = filt[j].getValue(); filterList.add(name); } if (type == null) { type = PDFFilterList.DEFAULT_FILTER; } if (!filterList.isEmpty() && log.isDebugEnabled()) { StringBuffer debug = new StringBuffer("Adding PDF filter"); if (filterList.size() != 1) { debug.append("s"); } debug.append(" for type ").append(type).append(": "); for (int j = 0; j < filterList.size(); j++) { if (j != 0) { debug.append(", "); } debug.append(filterList.get(j)); } log.debug(debug.toString()); } if (filterMap.get(type) != null) { throw new ConfigurationException("A filterList of type '" + type + "' has already been defined"); } filterMap.put(type, filterList); } return filterMap; }
1
            
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java
catch (FOPException e) { throw new ConfigurationException("Error while setting up fonts", e); }
6
            
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java
public void configure(PDFDocumentGraphics2D graphics, Configuration cfg, boolean useComplexScriptFeatures ) throws ConfigurationException { PDFDocument pdfDoc = graphics.getPDFDocument(); //Filter map pdfDoc.setFilterMap( PDFRendererConfigurator.buildFilterMapFromConfiguration(cfg)); //Fonts try { FontInfo fontInfo = createFontInfo(cfg, useComplexScriptFeatures); graphics.setFontInfo(fontInfo); } catch (FOPException e) { throw new ConfigurationException("Error while setting up fonts", e); } }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
public void configure(Configuration cfg) throws ConfigurationException { this.cfg = cfg; }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
public static Map buildFilterMapFromConfiguration(Configuration cfg) throws ConfigurationException { Map filterMap = new java.util.HashMap(); Configuration[] filterLists = cfg.getChildren("filterList"); for (int i = 0; i < filterLists.length; i++) { Configuration filters = filterLists[i]; String type = filters.getAttribute("type", null); Configuration[] filt = filters.getChildren("value"); List filterList = new java.util.ArrayList(); for (int j = 0; j < filt.length; j++) { String name = filt[j].getValue(); filterList.add(name); } if (type == null) { type = PDFFilterList.DEFAULT_FILTER; } if (!filterList.isEmpty() && log.isDebugEnabled()) { StringBuffer debug = new StringBuffer("Adding PDF filter"); if (filterList.size() != 1) { debug.append("s"); } debug.append(" for type ").append(type).append(": "); for (int j = 0; j < filterList.size(); j++) { if (j != 0) { debug.append(", "); } debug.append(filterList.get(j)); } log.debug(debug.toString()); } if (filterMap.get(type) != null) { throw new ConfigurationException("A filterList of type '" + type + "' has already been defined"); } filterMap.put(type, filterList); } return filterMap; }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private AFPFontInfo buildFont(Configuration fontCfg, String fontPath) throws ConfigurationException { FontManager fontManager = this.userAgent.getFactory().getFontManager(); Configuration[] triple = fontCfg.getChildren("font-triplet"); List<FontTriplet> tripletList = new ArrayList<FontTriplet>(); if (triple.length == 0) { eventProducer.fontConfigMissing(this, "<font-triplet...", fontCfg.getLocation()); return null; } for (Configuration config : triple) { int weight = FontUtil.parseCSS2FontWeight(config.getAttribute("weight")); FontTriplet triplet = new FontTriplet(config.getAttribute("name"), config.getAttribute("style"), weight); tripletList.add(triplet); } //build the fonts Configuration[] config = fontCfg.getChildren("afp-font"); if (config.length == 0) { eventProducer.fontConfigMissing(this, "<afp-font...", fontCfg.getLocation()); return null; } Configuration afpFontCfg = config[0]; URI baseURI = null; String uri = afpFontCfg.getAttribute("base-uri", fontPath); if (uri == null) { //Fallback for old attribute which only supports local filenames String path = afpFontCfg.getAttribute("path", fontPath); if (path != null) { File f = new File(path); baseURI = f.toURI(); } } else { try { baseURI = new URI(uri); } catch (URISyntaxException e) { eventProducer.invalidConfiguration(this, e); return null; } } ResourceAccessor accessor = new DefaultFOPResourceAccessor( this.userAgent, fontManager.getFontBaseURL(), baseURI); AFPFont font = null; try { String type = afpFontCfg.getAttribute("type"); if (type == null) { eventProducer.fontConfigMissing(this, "type attribute", fontCfg.getLocation()); return null; } String codepage = afpFontCfg.getAttribute("codepage"); if (codepage == null) { eventProducer.fontConfigMissing(this, "codepage attribute", fontCfg.getLocation()); return null; } String encoding = afpFontCfg.getAttribute("encoding"); if (encoding == null) { eventProducer.fontConfigMissing(this, "encoding attribute", fontCfg.getLocation()); return null; } font = fontFromType(type, codepage, encoding, accessor, afpFontCfg); } catch (ConfigurationException ce) { eventProducer.invalidConfiguration(this, ce); } catch (IOException ioe) { eventProducer.invalidConfiguration(this, ioe); } catch (IllegalArgumentException iae) { eventProducer.invalidConfiguration(this, iae); } return font != null ? new AFPFontInfo(font, tripletList) : null; }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private AFPFont fontFromType(String type, String codepage, String encoding, ResourceAccessor accessor, Configuration afpFontCfg) throws ConfigurationException, IOException { if ("raster".equalsIgnoreCase(type)) { String name = afpFontCfg.getAttribute("name", "Unknown"); // Create a new font object RasterFont font = new RasterFont(name); Configuration[] rasters = afpFontCfg.getChildren("afp-raster-font"); if (rasters.length == 0) { eventProducer.fontConfigMissing(this, "<afp-raster-font...", afpFontCfg.getLocation()); return null; } for (int j = 0; j < rasters.length; j++) { Configuration rasterCfg = rasters[j]; String characterset = rasterCfg.getAttribute("characterset"); if (characterset == null) { eventProducer.fontConfigMissing(this, "characterset attribute", afpFontCfg.getLocation()); return null; } float size = rasterCfg.getAttributeAsFloat("size"); int sizeMpt = (int) (size * 1000); String base14 = rasterCfg.getAttribute("base14-font", null); if (base14 != null) { try { Class<? extends Typeface> clazz = Class.forName( "org.apache.fop.fonts.base14." + base14).asSubclass(Typeface.class); try { Typeface tf = clazz.newInstance(); font.addCharacterSet(sizeMpt, CharacterSetBuilder.getSingleByteInstance() .build(characterset, codepage, encoding, tf, eventProducer)); } catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); } } catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); } } else { font.addCharacterSet(sizeMpt, CharacterSetBuilder.getSingleByteInstance() .buildSBCS(characterset, codepage, encoding, accessor, eventProducer)); } } return font; } else if ("outline".equalsIgnoreCase(type)) { String characterset = afpFontCfg.getAttribute("characterset"); if (characterset == null) { eventProducer.fontConfigMissing(this, "characterset attribute", afpFontCfg.getLocation()); return null; } String name = afpFontCfg.getAttribute("name", characterset); CharacterSet characterSet = null; String base14 = afpFontCfg.getAttribute("base14-font", null); if (base14 != null) { try { Class<? extends Typeface> clazz = Class.forName("org.apache.fop.fonts.base14." + base14).asSubclass(Typeface.class); try { Typeface tf = clazz.newInstance(); characterSet = CharacterSetBuilder.getSingleByteInstance() .build(characterset, codepage, encoding, tf, eventProducer); } catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); } } catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); } } else { characterSet = CharacterSetBuilder.getSingleByteInstance().buildSBCS( characterset, codepage, encoding, accessor, eventProducer); } // Return new font object return new OutlineFont(name, characterSet); } else if ("CIDKeyed".equalsIgnoreCase(type)) { String characterset = afpFontCfg.getAttribute("characterset"); if (characterset == null) { eventProducer.fontConfigMissing(this, "characterset attribute", afpFontCfg.getLocation()); return null; } String name = afpFontCfg.getAttribute("name", characterset); CharacterSet characterSet = null; CharacterSetType charsetType = afpFontCfg.getAttributeAsBoolean("ebcdic-dbcs", false) ? CharacterSetType.DOUBLE_BYTE_LINE_DATA : CharacterSetType.DOUBLE_BYTE; characterSet = CharacterSetBuilder.getDoubleByteInstance().buildDBCS(characterset, codepage, encoding, charsetType, accessor, eventProducer); // Create a new font object DoubleByteFont font = new DoubleByteFont(name, characterSet); return font; } else { log.error("No or incorrect type attribute: " + type); } return null; }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private List<AFPFontInfo> buildFontListFromConfiguration(Configuration cfg, AFPEventProducer eventProducer) throws FOPException, ConfigurationException { Configuration fonts = cfg.getChild("fonts"); FontManager fontManager = this.userAgent.getFactory().getFontManager(); // General matcher FontTriplet.Matcher referencedFontsMatcher = fontManager.getReferencedFontsMatcher(); // Renderer-specific matcher FontTriplet.Matcher localMatcher = null; // Renderer-specific referenced fonts Configuration referencedFontsCfg = fonts.getChild("referenced-fonts", false); if (referencedFontsCfg != null) { localMatcher = FontManagerConfigurator.createFontsMatcher( referencedFontsCfg, this.userAgent.getFactory().validateUserConfigStrictly()); } List<AFPFontInfo> fontList = new java.util.ArrayList<AFPFontInfo>(); Configuration[] font = fonts.getChildren("font"); final String fontPath = null; for (int i = 0; i < font.length; i++) { AFPFontInfo afi = buildFont(font[i], fontPath); if (afi != null) { if (log.isDebugEnabled()) { log.debug("Adding font " + afi.getAFPFont().getFontName()); } List<FontTriplet> fontTriplets = afi.getFontTriplets(); for (int j = 0; j < fontTriplets.size(); ++j) { FontTriplet triplet = fontTriplets.get(j); if (log.isDebugEnabled()) { log.debug(" Font triplet " + triplet.getName() + ", " + triplet.getStyle() + ", " + triplet.getWeight()); } if ((referencedFontsMatcher != null && referencedFontsMatcher.matches(triplet)) || (localMatcher != null && localMatcher.matches(triplet))) { afi.getAFPFont().setEmbeddable(false); break; } } fontList.add(afi); } } return fontList; }
21
            
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, false); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, true); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, true); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, true); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (ConfigurationException ce) { LogUtil.handleException(log, ce, strict); continue; }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); continue; }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/render/XMLHandlerConfigurator.java
catch (ConfigurationException e) { // silently pass over configurations without namespace }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, false); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException ce) { eventProducer.invalidConfiguration(this, ce); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (ConfigurationException e) { eventProducer.invalidConfiguration(this, e); LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/AbstractConfigurator.java
catch (ConfigurationException e) { // silently pass over configurations without mime type }
2
            
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
0
unknown (Lib) DSCException 3
            
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
public void process(InputStream in, OutputStream out, int pageCount, Rectangle2D documentBoundingBox) throws DSCException, IOException { DSCParser parser = new DSCParser(in); PSGenerator gen = new PSGenerator(out); parser.addListener(new DefaultNestedDocumentHandler(gen)); parser.addListener(new IncludeResourceListener(gen)); //Skip DSC header DSCHeaderComment header = DSCTools.checkAndSkipDSC30Header(parser); header.generate(gen); parser.setFilter(new DSCFilter() { private final Set filtered = new java.util.HashSet(); { //We rewrite those as part of the processing filtered.add(DSCConstants.PAGES); filtered.add(DSCConstants.BBOX); filtered.add(DSCConstants.HIRES_BBOX); filtered.add(DSCConstants.DOCUMENT_NEEDED_RESOURCES); filtered.add(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES); } public boolean accept(DSCEvent event) { if (event.isDSCComment()) { //Filter %%Pages which we add manually from a parameter return !(filtered.contains(event.asDSCComment().getName())); } else { return true; } } }); //Get PostScript language level (may be missing) while (true) { DSCEvent event = parser.nextEvent(); if (event == null) { reportInvalidDSC(); } if (DSCTools.headerCommentsEndHere(event)) { //Set number of pages DSCCommentPages pages = new DSCCommentPages(pageCount); pages.generate(gen); new DSCCommentBoundingBox(documentBoundingBox).generate(gen); new DSCCommentHiResBoundingBox(documentBoundingBox).generate(gen); PSFontUtils.determineSuppliedFonts(resTracker, fontInfo, fontInfo.getUsedFonts()); registerSuppliedForms(resTracker, globalFormResources); //Supplied Resources DSCCommentDocumentSuppliedResources supplied = new DSCCommentDocumentSuppliedResources( resTracker.getDocumentSuppliedResources()); supplied.generate(gen); //Needed Resources DSCCommentDocumentNeededResources needed = new DSCCommentDocumentNeededResources( resTracker.getDocumentNeededResources()); needed.generate(gen); //Write original comment that ends the header comments event.generate(gen); break; } if (event.isDSCComment()) { DSCComment comment = event.asDSCComment(); if (DSCConstants.LANGUAGE_LEVEL.equals(comment.getName())) { DSCCommentLanguageLevel level = (DSCCommentLanguageLevel)comment; gen.setPSLevel(level.getLanguageLevel()); } } event.generate(gen); } //Skip to the FOPFontSetup PostScriptComment fontSetupPlaceholder = parser.nextPSComment("FOPFontSetup", gen); if (fontSetupPlaceholder == null) { throw new DSCException("Didn't find %FOPFontSetup comment in stream"); } PSFontUtils.writeFontDict(gen, fontInfo, fontInfo.getUsedFonts()); generateForms(globalFormResources, gen); //Skip the prolog and to the first page DSCComment pageOrTrailer = parser.nextDSCComment(DSCConstants.PAGE, gen); if (pageOrTrailer == null) { throw new DSCException("Page expected, but none found"); } //Process individual pages (and skip as necessary) while (true) { DSCCommentPage page = (DSCCommentPage)pageOrTrailer; page.generate(gen); pageOrTrailer = DSCTools.nextPageOrTrailer(parser, gen); if (pageOrTrailer == null) { reportInvalidDSC(); } else if (!DSCConstants.PAGE.equals(pageOrTrailer.getName())) { pageOrTrailer.generate(gen); break; } } //Write the rest while (parser.hasNext()) { DSCEvent event = parser.nextEvent(); event.generate(gen); } gen.flush(); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private static void reportInvalidDSC() throws DSCException { throw new DSCException("File is not DSC-compliant: Unexpected end of file"); }
0 3
            
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
public void process(InputStream in, OutputStream out, int pageCount, Rectangle2D documentBoundingBox) throws DSCException, IOException { DSCParser parser = new DSCParser(in); PSGenerator gen = new PSGenerator(out); parser.addListener(new DefaultNestedDocumentHandler(gen)); parser.addListener(new IncludeResourceListener(gen)); //Skip DSC header DSCHeaderComment header = DSCTools.checkAndSkipDSC30Header(parser); header.generate(gen); parser.setFilter(new DSCFilter() { private final Set filtered = new java.util.HashSet(); { //We rewrite those as part of the processing filtered.add(DSCConstants.PAGES); filtered.add(DSCConstants.BBOX); filtered.add(DSCConstants.HIRES_BBOX); filtered.add(DSCConstants.DOCUMENT_NEEDED_RESOURCES); filtered.add(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES); } public boolean accept(DSCEvent event) { if (event.isDSCComment()) { //Filter %%Pages which we add manually from a parameter return !(filtered.contains(event.asDSCComment().getName())); } else { return true; } } }); //Get PostScript language level (may be missing) while (true) { DSCEvent event = parser.nextEvent(); if (event == null) { reportInvalidDSC(); } if (DSCTools.headerCommentsEndHere(event)) { //Set number of pages DSCCommentPages pages = new DSCCommentPages(pageCount); pages.generate(gen); new DSCCommentBoundingBox(documentBoundingBox).generate(gen); new DSCCommentHiResBoundingBox(documentBoundingBox).generate(gen); PSFontUtils.determineSuppliedFonts(resTracker, fontInfo, fontInfo.getUsedFonts()); registerSuppliedForms(resTracker, globalFormResources); //Supplied Resources DSCCommentDocumentSuppliedResources supplied = new DSCCommentDocumentSuppliedResources( resTracker.getDocumentSuppliedResources()); supplied.generate(gen); //Needed Resources DSCCommentDocumentNeededResources needed = new DSCCommentDocumentNeededResources( resTracker.getDocumentNeededResources()); needed.generate(gen); //Write original comment that ends the header comments event.generate(gen); break; } if (event.isDSCComment()) { DSCComment comment = event.asDSCComment(); if (DSCConstants.LANGUAGE_LEVEL.equals(comment.getName())) { DSCCommentLanguageLevel level = (DSCCommentLanguageLevel)comment; gen.setPSLevel(level.getLanguageLevel()); } } event.generate(gen); } //Skip to the FOPFontSetup PostScriptComment fontSetupPlaceholder = parser.nextPSComment("FOPFontSetup", gen); if (fontSetupPlaceholder == null) { throw new DSCException("Didn't find %FOPFontSetup comment in stream"); } PSFontUtils.writeFontDict(gen, fontInfo, fontInfo.getUsedFonts()); generateForms(globalFormResources, gen); //Skip the prolog and to the first page DSCComment pageOrTrailer = parser.nextDSCComment(DSCConstants.PAGE, gen); if (pageOrTrailer == null) { throw new DSCException("Page expected, but none found"); } //Process individual pages (and skip as necessary) while (true) { DSCCommentPage page = (DSCCommentPage)pageOrTrailer; page.generate(gen); pageOrTrailer = DSCTools.nextPageOrTrailer(parser, gen); if (pageOrTrailer == null) { reportInvalidDSC(); } else if (!DSCConstants.PAGE.equals(pageOrTrailer.getName())) { pageOrTrailer.generate(gen); break; } } //Write the rest while (parser.hasNext()) { DSCEvent event = parser.nextEvent(); event.generate(gen); } gen.flush(); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private static void reportInvalidDSC() throws DSCException { throw new DSCException("File is not DSC-compliant: Unexpected end of file"); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
public void processEvent(DSCEvent event, DSCParser parser) throws IOException, DSCException { if (event.isDSCComment() && event instanceof DSCCommentIncludeResource) { DSCCommentIncludeResource include = (DSCCommentIncludeResource)event; PSResource res = include.getResource(); if (res.getType().equals(PSResource.TYPE_FORM)) { if (inlineFormResources.containsValue(res)) { PSImageFormResource form = (PSImageFormResource) inlineFormResources.get(res); //Create an inline form //Wrap in save/restore pair to release memory gen.writeln("save"); generateFormForImage(gen, form); boolean execformFound = false; DSCEvent next = parser.nextEvent(); if (next.isLine()) { PostScriptLine line = next.asLine(); if (line.getLine().endsWith(" execform")) { line.generate(gen); execformFound = true; } } if (!execformFound) { throw new IOException( "Expected a PostScript line in the form: <form> execform"); } gen.writeln("restore"); } else { //Do nothing } parser.next(); } } }
1
            
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (DSCException e) { throw new RuntimeException(e.getMessage()); }
1
            
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (DSCException e) { throw new RuntimeException(e.getMessage()); }
1
runtime (Domain) DiscontinuousAssociationException
public class DiscontinuousAssociationException extends RuntimeException {
    /**
     * Instantiate discontinuous association exception
     */
    public DiscontinuousAssociationException() {
        super();
    }
    /**
     * Instantiate discontinuous association exception
     * @param message a message string
     */
    public DiscontinuousAssociationException(String message) {
        super(message);
    }
}
0 0 0 0 0 0
unknown (Lib) EOFException 7
            
// in src/java/org/apache/fop/fonts/type1/PFMInputStream.java
public String readString() throws IOException { InputStreamReader reader = new InputStreamReader(in, "ISO-8859-1"); StringBuffer buf = new StringBuffer(); int ch = reader.read(); while (ch > 0) { buf.append((char)ch); ch = reader.read(); } if (ch == -1) { throw new EOFException("Unexpected end of stream reached"); } return buf.toString(); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public void seekSet(long offset) throws IOException { if (offset > fsize || offset < 0) { throw new java.io.EOFException("Reached EOF, file size=" + fsize + " offset=" + offset); } current = (int)offset; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public byte read() throws IOException { if (current >= fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } final byte ret = file[current++]; return ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final void writeTTFUShort(long pos, int val) throws IOException { if ((pos + 2) > fsize) { throw new java.io.EOFException("Reached EOF"); } final byte b1 = (byte)((val >> 8) & 0xff); final byte b2 = (byte)(val & 0xff); final int fileIndex = (int) pos; file[fileIndex] = b1; file[fileIndex + 1] = b2; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final String readTTFString() throws IOException { int i = current; while (file[i++] != 0) { if (i > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } } byte[] tmp = new byte[i - current]; System.arraycopy(file, current, tmp, 0, i - current); return new String(tmp, "ISO-8859-1"); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final String readTTFString(int len) throws IOException { if ((len + current) > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } byte[] tmp = new byte[len]; System.arraycopy(file, current, tmp, 0, len); current += len; final String encoding; if ((tmp.length > 0) && (tmp[0] == 0)) { encoding = "UTF-16BE"; } else { encoding = "ISO-8859-1"; } return new String(tmp, encoding); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final String readTTFString(int len, int encodingID) throws IOException { if ((len + current) > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } byte[] tmp = new byte[len]; System.arraycopy(file, current, tmp, 0, len); current += len; final String encoding; encoding = "UTF-16BE"; //Use this for all known encoding IDs for now return new String(tmp, encoding); }
0 0 0 0 0
runtime (Lib) Error 1
            
// in src/java/org/apache/fop/datatypes/URISpecification.java
public static String escapeURI(String uri) { uri = getURL(uri); StringBuffer sb = new StringBuffer(); for (int i = 0, c = uri.length(); i < c; i++) { char ch = uri.charAt(i); if (ch == '%') { if (i < c - 3 && isHexDigit(uri.charAt(i + 1)) && isHexDigit(uri.charAt(i + 2))) { sb.append(ch); continue; } } if (isReserved(ch) || isUnreserved(ch)) { //Note: this may not be accurate for some very special cases. sb.append(ch); } else { try { byte[] utf8 = Character.toString(ch).getBytes("UTF-8"); for (int j = 0, cj = utf8.length; j < cj; j++) { appendEscape(sb, utf8[j]); } } catch (UnsupportedEncodingException e) { throw new Error("Incompatible JVM. UTF-8 not supported."); } } } return sb.toString(); }
1
            
// in src/java/org/apache/fop/datatypes/URISpecification.java
catch (UnsupportedEncodingException e) { throw new Error("Incompatible JVM. UTF-8 not supported."); }
0 0 0 0
checked (Domain) EventConventionException
public class EventConventionException extends Exception {

    private static final long serialVersionUID = 117244726033986628L;

    /**
     * Creates a new EventConventionException
     * @param message the error message
     */
    public EventConventionException(String message) {
        super(message);
    }

}
3
            
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
private EventMethodModel createMethodModel(JavaMethod method) throws EventConventionException, ClassNotFoundException { JavaClass clazz = method.getParentClass(); //Check EventProducer conventions if (!method.getReturnType().isVoid()) { throw new EventConventionException("All methods of interface " + clazz.getFullyQualifiedName() + " must have return type 'void'!"); } String methodSig = clazz.getFullyQualifiedName() + "." + method.getCallSignature(); JavaParameter[] params = method.getParameters(); if (params.length < 1) { throw new EventConventionException("The method " + methodSig + " must have at least one parameter: 'Object source'!"); } Type firstType = params[0].getType(); if (firstType.isPrimitive() || !"source".equals(params[0].getName())) { throw new EventConventionException("The first parameter of the method " + methodSig + " must be: 'Object source'!"); } //build method model DocletTag tag = method.getTagByName("event.severity"); EventSeverity severity; if (tag != null) { severity = EventSeverity.valueOf(tag.getValue()); } else { severity = EventSeverity.INFO; } EventMethodModel methodMeta = new EventMethodModel( method.getName(), severity); if (params.length > 1) { for (int j = 1, cj = params.length; j < cj; j++) { JavaParameter p = params[j]; Class<?> type; JavaClass pClass = p.getType().getJavaClass(); if (p.getType().isPrimitive()) { type = PRIMITIVE_MAP.get(pClass.getName()); if (type == null) { throw new UnsupportedOperationException( "Primitive datatype not supported: " + pClass.getName()); } } else { String className = pClass.getFullyQualifiedName(); type = Class.forName(className); } methodMeta.addParameter(type, p.getName()); } } Type[] exceptions = method.getExceptions(); if (exceptions != null && exceptions.length > 0) { //We only use the first declared exception because that is always thrown JavaClass cl = exceptions[0].getJavaClass(); methodMeta.setExceptionClass(cl.getFullyQualifiedName()); methodMeta.setSeverity(EventSeverity.FATAL); //In case it's not set in the comments } return methodMeta; }
0 4
            
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
protected long processFileSets(EventProducerCollector collector) throws IOException, EventConventionException, ClassNotFoundException { long lastModified = 0; Iterator<FileSet> iter = filesets.iterator(); while (iter.hasNext()) { FileSet fs = (FileSet)iter.next(); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); String[] srcFiles = ds.getIncludedFiles(); File directory = fs.getDir(getProject()); for (int i = 0, c = srcFiles.length; i < c; i++) { String filename = srcFiles[i]; File src = new File(directory, filename); boolean eventProducerFound = collector.scanFile(src); if (eventProducerFound) { lastModified = Math.max(lastModified, src.lastModified()); } } } return lastModified; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
public boolean scanFile(File src) throws IOException, EventConventionException, ClassNotFoundException { JavaDocBuilder builder = new JavaDocBuilder(this.tagFactory); builder.addSource(src); JavaClass[] classes = builder.getClasses(); boolean eventProducerFound = false; for (int i = 0, c = classes.length; i < c; i++) { JavaClass clazz = classes[i]; if (clazz.isInterface() && implementsInterface(clazz, CLASSNAME_EVENT_PRODUCER)) { processEventProducerInterface(clazz); eventProducerFound = true; } } return eventProducerFound; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
protected void processEventProducerInterface(JavaClass clazz) throws EventConventionException, ClassNotFoundException { EventProducerModel prodMeta = new EventProducerModel(clazz.getFullyQualifiedName()); JavaMethod[] methods = clazz.getMethods(true); for (int i = 0, c = methods.length; i < c; i++) { JavaMethod method = methods[i]; EventMethodModel methodMeta = createMethodModel(method); prodMeta.addMethod(methodMeta); } EventModel model = new EventModel(); model.addProducer(prodMeta); models.add(model); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
private EventMethodModel createMethodModel(JavaMethod method) throws EventConventionException, ClassNotFoundException { JavaClass clazz = method.getParentClass(); //Check EventProducer conventions if (!method.getReturnType().isVoid()) { throw new EventConventionException("All methods of interface " + clazz.getFullyQualifiedName() + " must have return type 'void'!"); } String methodSig = clazz.getFullyQualifiedName() + "." + method.getCallSignature(); JavaParameter[] params = method.getParameters(); if (params.length < 1) { throw new EventConventionException("The method " + methodSig + " must have at least one parameter: 'Object source'!"); } Type firstType = params[0].getType(); if (firstType.isPrimitive() || !"source".equals(params[0].getName())) { throw new EventConventionException("The first parameter of the method " + methodSig + " must be: 'Object source'!"); } //build method model DocletTag tag = method.getTagByName("event.severity"); EventSeverity severity; if (tag != null) { severity = EventSeverity.valueOf(tag.getValue()); } else { severity = EventSeverity.INFO; } EventMethodModel methodMeta = new EventMethodModel( method.getName(), severity); if (params.length > 1) { for (int j = 1, cj = params.length; j < cj; j++) { JavaParameter p = params[j]; Class<?> type; JavaClass pClass = p.getType().getJavaClass(); if (p.getType().isPrimitive()) { type = PRIMITIVE_MAP.get(pClass.getName()); if (type == null) { throw new UnsupportedOperationException( "Primitive datatype not supported: " + pClass.getName()); } } else { String className = pClass.getFullyQualifiedName(); type = Class.forName(className); } methodMeta.addParameter(type, p.getName()); } } Type[] exceptions = method.getExceptions(); if (exceptions != null && exceptions.length > 0) { //We only use the first declared exception because that is always thrown JavaClass cl = exceptions[0].getJavaClass(); methodMeta.setExceptionClass(cl.getFullyQualifiedName()); methodMeta.setSeverity(EventSeverity.FATAL); //In case it's not set in the comments } return methodMeta; }
1
            
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (EventConventionException ece) { throw new BuildException(ece); }
1
            
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (EventConventionException ece) { throw new BuildException(ece); }
0
checked (Lib) Exception 30
            
// in src/java/org/apache/fop/render/rtf/rtflib/tools/BuilderContext.java
public void replaceContainer(RtfContainer oldC, RtfContainer newC) throws Exception { // treating the Stack as a Vector allows such manipulations (yes, I hear you screaming ;-) final int index = containers.indexOf(oldC); if (index < 0) { throw new Exception("container to replace not found:" + oldC); } containers.setElementAt(newC, index); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static void readBidiClassProperties(String bidiFileName) throws Exception { // read property names BufferedReader b = new BufferedReader(new InputStreamReader(new URL(bidiFileName).openStream())); String line; int lineNumber = 0; TreeSet intervals = new TreeSet(); while ( ( line = b.readLine() ) != null ) { lineNumber++; if ( line.startsWith("#") ) { continue; } else if ( line.length() == 0 ) { continue; } else { if ( line.indexOf ( "#" ) != -1 ) { line = ( line.split ( "#" ) ) [ 0 ]; } String[] fa = line.split ( ";" ); if ( fa.length == 2 ) { int[] interval = parseInterval ( fa[0].trim() ); byte bidiClass = (byte) parseBidiClass ( fa[1].trim() ); if ( interval[1] == interval[0] ) { // singleton int c = interval[0]; if ( c <= 0x00FF ) { if ( bcL1 [ c - 0x0000 ] == 0 ) { bcL1 [ c - 0x0000 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + c ); } } else if ( ( c >= 0x0590 ) && ( c <= 0x06FF ) ) { if ( bcR1 [ c - 0x0590 ] == 0 ) { bcR1 [ c - 0x0590 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + c ); } } else { addInterval ( intervals, c, c, bidiClass ); } } else { // non-singleton int s = interval[0]; int e = interval[1]; // inclusive if ( s <= 0x00FF ) { for ( int i = s; i <= e; i++ ) { if ( i <= 0x00FF ) { if ( bcL1 [ i - 0x0000 ] == 0 ) { bcL1 [ i - 0x0000 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + i ); } } else { addInterval ( intervals, i, e, bidiClass ); break; } } } else if ( ( s >= 0x0590 ) && ( s <= 0x06FF ) ) { for ( int i = s; i <= e; i++ ) { if ( i <= 0x06FF ) { if ( bcR1 [ i - 0x0590 ] == 0 ) { bcR1 [ i - 0x0590 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + i ); } } else { addInterval ( intervals, i, e, bidiClass ); break; } } } else { addInterval ( intervals, s, e, bidiClass ); } } } else { throw new Exception ( "bad syntax, line(" + lineNumber + "): " + line ); } } } // compile interval search data int ivIndex = 0; int niv = intervals.size(); bcS1 = new int [ niv ]; bcE1 = new int [ niv ]; bcC1 = new byte [ niv ]; for ( Iterator it = intervals.iterator(); it.hasNext(); ivIndex++ ) { Interval iv = (Interval) it.next(); bcS1[ivIndex] = iv.start; bcE1[ivIndex] = iv.end; bcC1[ivIndex] = (byte) iv.bidiClass; } // test data test(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static int[] parseInterval ( String interval ) throws Exception { int s; int e; String[] fa = interval.split("\\.\\."); if ( fa.length == 1 ) { s = Integer.parseInt ( fa[0], 16 ); e = s; } else if ( fa.length == 2 ) { s = Integer.parseInt ( fa[0], 16 ); e = Integer.parseInt ( fa[1], 16 ); } else { throw new Exception ( "bad interval syntax: " + interval ); } if ( e < s ) { throw new Exception ( "bad interval, start must be less than or equal to end: " + interval ); } return new int[] {s, e}; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static void test() throws Exception { for ( int i = 0, n = testData.length / 2; i < n; i++ ) { int ch = testData [ i * 2 + 0 ]; int tc = testData [ i * 2 + 1 ]; int bc = getBidiClass ( ch ); if ( bc != tc ) { throw new Exception ( "test mapping failed for character (0x" + Integer.toHexString(ch) + "): expected " + tc + ", got " + bc ); } } }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
private static void convertLineBreakProperties( // CSOK: MethodLength String lineBreakFileName, String propertyValueFileName, String breakPairFileName, String outFileName) throws Exception { readLineBreakProperties(lineBreakFileName, propertyValueFileName); // read break pair table int lineBreakPropertyValueCount = lineBreakPropertyValues.size(); int tableSize = lineBreakPropertyValueCount - NOT_IN_PAIR_TABLE.length; Map notInPairTableMap = new HashMap(NOT_IN_PAIR_TABLE.length); for (int i = 0; i < NOT_IN_PAIR_TABLE.length; i++) { Object v = lineBreakPropertyValues.get(NOT_IN_PAIR_TABLE[i]); if (v == null) { throw new Exception("'not in pair table' property not found: " + NOT_IN_PAIR_TABLE[i]); } notInPairTableMap.put(NOT_IN_PAIR_TABLE[i], v); } byte[][] pairTable = new byte[tableSize][]; byte[] columnHeader = new byte[tableSize]; byte[] rowHeader = new byte[tableSize]; byte[] columnMap = new byte[lineBreakPropertyValueCount + 1]; Arrays.fill(columnMap, (byte)255); byte[] rowMap = new byte[lineBreakPropertyValueCount + 1]; Arrays.fill(rowMap, (byte)255); BufferedReader b = new BufferedReader(new FileReader(breakPairFileName)); String line = b.readLine(); int lineNumber = 1; String[] lineTokens; String name; // read header if (line != null) { lineTokens = line.split("\\s+"); byte columnNumber = 0; for (int i = 0; i < lineTokens.length; ++i) { name = lineTokens[i]; if (name.length() > 0) { if (columnNumber >= columnHeader.length) { throw new Exception(breakPairFileName + ':' + lineNumber + ": unexpected column header " + name); } if (notInPairTableMap.get(name) != null) { throw new Exception(breakPairFileName + ':' + lineNumber + ": invalid column header " + name); } Byte v = (Byte)lineBreakPropertyValues.get(name); if (v != null) { byte vv = v.byteValue(); columnHeader[columnNumber] = vv; columnMap[vv] = columnNumber; } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": unknown column header " + name); } columnNumber++; } } if (columnNumber < columnHeader.length) { StringBuffer missing = new StringBuffer(); for (int j = 0; j < lineBreakPropertyShortNames.size(); j++) { boolean found = false; for (int k = 0; k < columnNumber; k++) { if (columnHeader[k] == j + 1) { found = true; break; } } if (!found) { if (missing.length() > 0) { missing.append(", "); } missing.append((String)lineBreakPropertyShortNames.get(j)); } } throw new Exception( breakPairFileName + ':' + lineNumber + ": missing column for properties: " + missing.toString()); } } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": can't read table header"); } line = b.readLine().trim(); lineNumber++; byte rowNumber = 0; while (line != null && line.length() > 0) { if (rowNumber >= rowHeader.length) { throw new Exception(breakPairFileName + ':' + lineNumber + ": unexpected row " + line); } pairTable[rowNumber] = new byte[tableSize]; lineTokens = line.split("\\s+"); if (lineTokens.length > 0) { name = lineTokens[0]; if (notInPairTableMap.get(name) != null) { throw new Exception(breakPairFileName + ':' + lineNumber + ": invalid row header " + name); } Byte v = (Byte)lineBreakPropertyValues.get(name); if (v != null) { byte vv = v.byteValue(); rowHeader[rowNumber] = vv; rowMap[vv] = rowNumber; } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": unknown row header " + name); } } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": can't read row header"); } int columnNumber = 0; String token; for (int i = 1; i < lineTokens.length; ++i) { token = lineTokens[i]; if (token.length() == 1) { byte tokenBreakClass = (byte)BREAK_CLASS_TOKENS.indexOf(token.charAt(0)); if (tokenBreakClass >= 0) { pairTable[rowNumber][columnNumber] = tokenBreakClass; } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": unexpected token: " + token); } } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": token too long: " + token); } columnNumber++; } line = b.readLine().trim(); lineNumber++; rowNumber++; } if (rowNumber < rowHeader.length) { StringBuffer missing = new StringBuffer(); for (int j = 0; j < lineBreakPropertyShortNames.size(); j++) { boolean found = false; for (int k = 0; k < rowNumber; k++) { if (rowHeader[k] == j + 1) { found = true; break; } } if (!found) { if (missing.length() > 0) { missing.append(", "); } missing.append((String)lineBreakPropertyShortNames.get(j)); } } throw new Exception( breakPairFileName + ':' + lineNumber + ": missing row for properties: " + missing.toString()); } // generate class int rowsize = 512; int blocksize = lineBreakProperties.length / rowsize; byte[][] row = new byte[rowsize][]; int idx = 0; StringBuffer doStaticLinkCode = new StringBuffer(); PrintWriter out = new PrintWriter(new FileWriter(outFileName)); License.writeJavaLicenseId(out); out.println(); out.println("package org.apache.fop.text.linebreak;"); out.println(); out.println("/*"); out.println(" * !!! THIS IS A GENERATED FILE !!!"); out.println(" * If updates to the source are needed, then:"); out.println(" * - apply the necessary modifications to"); out.println(" * 'src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java'"); out.println(" * - run 'ant codegen-unicode', which will generate a new LineBreakUtils.java"); out.println(" * in 'src/java/org/apache/fop/text/linebreak'"); out.println(" * - commit BOTH changed files"); out.println(" */"); out.println(); out.println("// CSOFF: WhitespaceAfterCheck"); out.println("// CSOFF: LineLengthCheck"); out.println(); out.println("/** Line breaking utilities. */"); out.println("public final class LineBreakUtils {"); out.println(); out.println(" private LineBreakUtils() {"); out.println(" }"); out.println(); out.println(" /** Break class constant */"); out.println(" public static final byte DIRECT_BREAK = " + DIRECT_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte INDIRECT_BREAK = " + INDIRECT_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte COMBINING_INDIRECT_BREAK = " + COMBINING_INDIRECT_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte COMBINING_PROHIBITED_BREAK = " + COMBINING_PROHIBITED_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte PROHIBITED_BREAK = " + PROHIBITED_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte EXPLICIT_BREAK = " + EXPLICIT_BREAK + ';'); out.println(); out.println(" private static final byte[][] PAIR_TABLE = {"); boolean printComma = false; for (int i = 1; i <= lineBreakPropertyValueCount; i++) { if (printComma) { out.println(","); } else { printComma = true; } out.print(" {"); boolean localPrintComma = false; for (int j = 1; j <= lineBreakPropertyValueCount; j++) { if (localPrintComma) { out.print(", "); } else { localPrintComma = true; } if (columnMap[j] != -1 && rowMap[i] != -1) { out.print(pairTable[rowMap[i]][columnMap[j]]); } else { out.print('0'); } } out.print('}'); } out.println("};"); out.println(); out.println(" private static byte[][] lineBreakProperties = new byte[" + rowsize + "][];"); out.println(); out.println(" private static void init0() {"); int rowsPrinted = 0; int initSections = 0; for (int i = 0; i < rowsize; i++) { boolean found = false; for (int j = 0; j < i; j++) { if (row[j] != null) { boolean matched = true; for (int k = 0; k < blocksize; k++) { if (row[j][k] != lineBreakProperties[idx + k]) { matched = false; break; } } if (matched) { found = true; doStaticLinkCode.append(" lineBreakProperties["); doStaticLinkCode.append(i); doStaticLinkCode.append("] = lineBreakProperties["); doStaticLinkCode.append(j); doStaticLinkCode.append("];\n"); break; } } } if (!found) { if (rowsPrinted >= 64) { out.println(" }"); out.println(); initSections++; out.println(" private static void init" + initSections + "() {"); rowsPrinted = 0; } row[i] = new byte[blocksize]; boolean printLocalComma = false; out.print(" lineBreakProperties[" + i + "] = new byte[] { "); for (int k = 0; k < blocksize; k++) { row[i][k] = lineBreakProperties[idx + k]; if (printLocalComma) { out.print(", "); } else { printLocalComma = true; } out.print(row[i][k]); } out.println("};"); rowsPrinted++; } idx += blocksize; } out.println(" }"); out.println(); out.println(" static {"); for (int i = 0; i <= initSections; i++) { out.println(" init" + i + "();"); } out.print(doStaticLinkCode); out.println(" }"); out.println(); for (int i = 0; i < lineBreakPropertyShortNames.size(); i++) { String shortName = (String)lineBreakPropertyShortNames.get(i); out.println(" /** Linebreak property constant */"); out.print(" public static final byte LINE_BREAK_PROPERTY_"); out.print(shortName); out.print(" = "); out.print(i + 1); out.println(';'); } out.println(); final String shortNamePrefix = " private static String[] lineBreakPropertyShortNames = {"; out.print(shortNamePrefix); int lineLength = shortNamePrefix.length(); printComma = false; for (int i = 0; i < lineBreakPropertyShortNames.size(); i++) { name = (String)lineBreakPropertyShortNames.get(i); if (printComma) { if (lineLength <= MAX_LINE_LENGTH - 2) { out.print(", "); } else { out.print(","); } // count the space anyway to force a linebreak if the comma causes lineLength == MAX_LINE_LENGTH lineLength += 2; } else { printComma = true; } if (lineLength > MAX_LINE_LENGTH) { out.println(); out.print(" "); lineLength = 8; } out.print('"'); out.print(name); out.print('"'); lineLength += (2 + name.length()); } out.println("};"); out.println(); final String longNamePrefix = " private static String[] lineBreakPropertyLongNames = {"; out.print(longNamePrefix); lineLength = longNamePrefix.length(); printComma = false; for (int i = 0; i < lineBreakPropertyLongNames.size(); i++) { name = (String)lineBreakPropertyLongNames.get(i); if (printComma) { out.print(','); lineLength++; } else { printComma = true; } if (lineLength > MAX_LINE_LENGTH) { out.println(); out.print(" "); lineLength = 8; } out.print('"'); out.print(name); out.print('"'); lineLength += (2 + name.length()); } out.println("};"); out.println(); out.println(" /**"); out.println(" * Return the short name for the linebreak property corresponding"); out.println(" * to the given symbolic constant."); out.println(" *"); out.println(" * @param i the numeric value of the linebreak property"); out.println(" * @return the short name of the linebreak property"); out.println(" */"); out.println(" public static String getLineBreakPropertyShortName(byte i) {"); out.println(" if (i > 0 && i <= lineBreakPropertyShortNames.length) {"); out.println(" return lineBreakPropertyShortNames[i - 1];"); out.println(" } else {"); out.println(" return null;"); out.println(" }"); out.println(" }"); out.println(); out.println(" /**"); out.println(" * Return the long name for the linebreak property corresponding"); out.println(" * to the given symbolic constant."); out.println(" *"); out.println(" * @param i the numeric value of the linebreak property"); out.println(" * @return the long name of the linebreak property"); out.println(" */"); out.println(" public static String getLineBreakPropertyLongName(byte i) {"); out.println(" if (i > 0 && i <= lineBreakPropertyLongNames.length) {"); out.println(" return lineBreakPropertyLongNames[i - 1];"); out.println(" } else {"); out.println(" return null;"); out.println(" }"); out.println(" }"); out.println(); out.println(" /**"); out.println(" * Return the linebreak property constant for the given <code>char</code>"); out.println(" *"); out.println(" * @param c the <code>char</code> whose linebreak property to return"); out.println(" * @return the constant representing the linebreak property"); out.println(" */"); out.println(" public static byte getLineBreakProperty(char c) {"); out.println(" return lineBreakProperties[c / " + blocksize + "][c % " + blocksize + "];"); out.println(" }"); out.println(); out.println(" /**"); out.println(" * Return the break class constant for the given pair of linebreak"); out.println(" * property constants."); out.println(" *"); out.println(" * @param lineBreakPropertyBefore the linebreak property for the first character"); out.println(" * in a two-character sequence"); out.println(" * @param lineBreakPropertyAfter the linebreak property for the second character"); out.println(" * in a two-character sequence"); out.println(" * @return the constant representing the break class"); out.println(" */"); out.println( " public static byte getLineBreakPairProperty(int lineBreakPropertyBefore, int lineBreakPropertyAfter) {"); out.println(" return PAIR_TABLE[lineBreakPropertyBefore - 1][lineBreakPropertyAfter - 1];"); out.println(" }"); out.println(); out.println("}"); out.flush(); out.close(); }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
private static void readLineBreakProperties(String lineBreakFileName, String propertyValueFileName) throws Exception { // read property names BufferedReader b = new BufferedReader(new InputStreamReader(new URL(propertyValueFileName).openStream())); String line = b.readLine(); int lineNumber = 1; byte propertyIndex = 1; byte indexForUnknown = 0; while (line != null) { if (line.startsWith("lb")) { String shortName; String longName = null; int semi = line.indexOf(';'); if (semi < 0) { throw new Exception( propertyValueFileName + ':' + lineNumber + ": missing property short name in " + line); } line = line.substring(semi + 1); semi = line.indexOf(';'); if (semi > 0) { shortName = line.substring(0, semi).trim(); longName = line.substring(semi + 1).trim(); semi = longName.indexOf(';'); if (semi > 0) { longName = longName.substring(0, semi).trim(); } } else { shortName = line.trim(); } if (shortName.equals("XX")) { indexForUnknown = propertyIndex; } lineBreakPropertyValues.put(shortName, new Byte((byte)propertyIndex)); lineBreakPropertyShortNames.add(shortName); lineBreakPropertyLongNames.add(longName); propertyIndex++; if (propertyIndex <= 0) { throw new Exception(propertyValueFileName + ':' + lineNumber + ": property rolled over in " + line); } } line = b.readLine(); lineNumber++; } if (indexForUnknown == 0) { throw new Exception("index for XX (unknown) line break property value not found"); } // read property values Arrays.fill(lineBreakProperties, (byte)0); b = new BufferedReader(new InputStreamReader(new URL(lineBreakFileName).openStream())); line = b.readLine(); lineNumber = 1; while (line != null) { int idx = line.indexOf('#'); if (idx >= 0) { line = line.substring(0, idx); } line = line.trim(); if (line.length() > 0) { idx = line.indexOf(';'); if (idx <= 0) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": No field delimiter in " + line); } Byte v = (Byte)lineBreakPropertyValues.get(line.substring(idx + 1).trim()); if (v == null) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Unknown property value in " + line); } String codepoint = line.substring(0, idx); int low; int high; idx = codepoint.indexOf(".."); try { if (idx >= 0) { low = Integer.parseInt(codepoint.substring(0, idx), 16); high = Integer.parseInt(codepoint.substring(idx + 2), 16); } else { low = Integer.parseInt(codepoint, 16); high = low; } } catch (NumberFormatException e) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Invalid codepoint number in " + line); } if (high > 0xFFFF) { // ignore non-baseplane characters for now } else { if (low < 0 || high < 0) { throw new Exception( lineBreakFileName + ':' + lineNumber + ": Negative codepoint(s) in " + line); } byte vv = v.byteValue(); for (int i = low; i <= high; i++) { if (lineBreakProperties[i] != 0) { throw new Exception( lineBreakFileName + ':' + lineNumber + ": Property already set for " + ((char)i) + " in " + line); } lineBreakProperties[i] = vv; } } } line = b.readLine(); lineNumber++; } }
1
            
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
catch (NumberFormatException e) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Invalid codepoint number in " + line); }
21
            
// in src/sandbox/org/apache/fop/render/svg/SVGSVGHandler.java
public void handleXML(RendererContext context, org.w3c.dom.Document doc, String ns) throws Exception { if (getNamespace().equals(ns)) { if (!(doc instanceof SVGDocument)) { DOMImplementation impl = SVGDOMImplementation.getDOMImplementation(); doc = DOMUtilities.deepCloneDocument(doc, impl); } SVGSVGElement svg = ((SVGDocument) doc).getRootElement(); SVGDocument targetDoc = (SVGDocument)context.getProperty(SVG_DOCUMENT); SVGElement currentPageG = (SVGElement)context.getProperty(SVG_PAGE_G); Element view = targetDoc.createElementNS(getNamespace(), "svg"); Node newsvg = targetDoc.importNode(svg, true); //view.setAttributeNS(null, "viewBox", "0 0 "); int xpos = ((Integer)context.getProperty(XPOS)).intValue(); int ypos = ((Integer)context.getProperty(YPOS)).intValue(); view.setAttributeNS(null, "x", "" + xpos / 1000f); view.setAttributeNS(null, "y", "" + ypos / 1000f); // this fixes a problem where the xmlns is repeated sometimes Element ele = (Element) newsvg; ele.setAttributeNS(XMLSupport.XMLNS_NAMESPACE_URI, "xmlns", getNamespace()); if (ele.hasAttributeNS(null, "xmlns")) { ele.removeAttributeNS(null, "xmlns"); } view.appendChild(newsvg); currentPageG.appendChild(view); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void generate() throws Exception { prepare(); FontEventListener listener = new FontEventListener() { public void fontLoadingErrorAtAutoDetection(Object source, String fontURL, Exception e) { System.err.println("Could not load " + fontURL + " (" + e.getLocalizedMessage() + ")"); } public void fontSubstituted(Object source, FontTriplet requested, FontTriplet effective) { //ignore } public void glyphNotAvailable(Object source, char ch, String fontName) { //ignore } public void fontDirectoryNotFound(Object source, String msg) { //ignore } public void svgTextStrokedAsShapes(Object source, String fontFamily) { // ignore } }; FontListGenerator listGenerator = new FontListGenerator(); SortedMap fontFamilies = listGenerator.listFonts(fopFactory, configMime, listener); if (this.mode == GENERATE_CONSOLE) { writeToConsole(fontFamilies); } else { writeOutput(fontFamilies); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
private void renderInputHandler(InputHandler inputHandler, File outFile, String outputFormat) throws Exception { OutputStream out = null; try { out = new java.io.FileOutputStream(outFile); out = new BufferedOutputStream(out); } catch (Exception ex) { throw new BuildException("Failed to open " + outFile, ex); } boolean success = false; try { FOUserAgent userAgent = fopFactory.newFOUserAgent(); userAgent.setBaseURL(this.baseURL); inputHandler.renderTo(userAgent, outputFormat, out); success = true; } catch (Exception ex) { if (task.getThrowexceptions()) { throw new BuildException(ex); } throw ex; } finally { try { out.close(); } catch (IOException ioe) { logger.error("Error closing output file", ioe); } if (!success) { outFile.delete(); } } }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
public static void main(String[] argv) throws Exception { HyphenationTree ht = null; int minCharCount = 2; BufferedReader in = new BufferedReader(new java.io.InputStreamReader(System.in)); while (true) { System.out.print("l:\tload patterns from XML\n" + "L:\tload patterns from serialized object\n" + "s:\tset minimum character count\n" + "w:\twrite hyphenation tree to object file\n" + "h:\thyphenate\n" + "f:\tfind pattern\n" + "b:\tbenchmark\n" + "q:\tquit\n\n" + "Command:"); String token = in.readLine().trim(); if (token.equals("f")) { System.out.print("Pattern: "); token = in.readLine().trim(); System.out.println("Values: " + ht.findPattern(token)); } else if (token.equals("s")) { System.out.print("Minimun value: "); token = in.readLine().trim(); minCharCount = Integer.parseInt(token); } else if (token.equals("l")) { ht = new HyphenationTree(); System.out.print("XML file name: "); token = in.readLine().trim(); ht.loadPatterns(token); } else if (token.equals("L")) { ObjectInputStream ois = null; System.out.print("Object file name: "); token = in.readLine().trim(); try { ois = new ObjectInputStream(new FileInputStream(token)); ht = (HyphenationTree)ois.readObject(); } catch (Exception e) { e.printStackTrace(); } finally { if (ois != null) { try { ois.close(); } catch (IOException e) { //ignore } } } } else if (token.equals("w")) { System.out.print("Object file name: "); token = in.readLine().trim(); ObjectOutputStream oos = null; try { oos = new ObjectOutputStream(new FileOutputStream(token)); oos.writeObject(ht); } catch (Exception e) { e.printStackTrace(); } finally { if (oos != null) { try { oos.flush(); } catch (IOException e) { //ignore } try { oos.close(); } catch (IOException e) { //ignore } } } } else if (token.equals("h")) { System.out.print("Word: "); token = in.readLine().trim(); System.out.print("Hyphenation points: "); System.out.println(ht.hyphenate(token, minCharCount, minCharCount)); } else if (token.equals("b")) { if (ht == null) { System.out.println("No patterns have been loaded."); break; } System.out.print("Word list filename: "); token = in.readLine().trim(); long starttime = 0; int counter = 0; try { BufferedReader reader = new BufferedReader(new FileReader(token)); String line; starttime = System.currentTimeMillis(); while ((line = reader.readLine()) != null) { // System.out.print("\nline: "); Hyphenation hyp = ht.hyphenate(line, minCharCount, minCharCount); if (hyp != null) { String hword = hyp.toString(); // System.out.println(line); // System.out.println(hword); } else { // System.out.println("No hyphenation"); } counter++; } } catch (Exception ioe) { System.out.println("Exception " + ioe); ioe.printStackTrace(); } long endtime = System.currentTimeMillis(); long result = endtime - starttime; System.out.println(counter + " words in " + result + " Milliseconds hyphenated"); } else if (token.equals("q")) { break; } } }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public static void main(String[] args) throws Exception { if (args.length > 0) { PatternParser pp = new PatternParser(); PrintStream p = null; if (args.length > 1) { FileOutputStream f = new FileOutputStream(args[1]); p = new PrintStream(f, false, "utf-8"); pp.setTestOut(p); } pp.parse(args[0]); if (pp != null) { pp.closeTestOut(); } } }
// in src/java/org/apache/fop/hyphenation/TernaryTree.java
public static void main(String[] args) throws Exception { TernaryTree tt = new TernaryTree(); tt.insert("Carlos", 'C'); tt.insert("Car", 'r'); tt.insert("palos", 'l'); tt.insert("pa", 'p'); tt.trimToSize(); System.out.println((char)tt.find("Car")); System.out.println((char)tt.find("Carlos")); System.out.println((char)tt.find("alto")); tt.printStats(); }
// in src/java/org/apache/fop/render/xml/XMLXMLHandler.java
public void handleXML(RendererContext context, org.w3c.dom.Document doc, String ns) throws Exception { ContentHandler handler = (ContentHandler) context.getProperty(HANDLER); new DOM2SAX(handler).writeDocument(doc, true); }
// in src/java/org/apache/fop/render/AbstractGenericSVGHandler.java
public void handleXML(RendererContext context, Document doc, String ns) throws Exception { if (SVGDOMImplementation.SVG_NAMESPACE_URI.equals(ns)) { renderSVGDocument(context, doc); } }
// in src/java/org/apache/fop/render/rtf/rtflib/tools/BuilderContext.java
public void replaceContainer(RtfContainer oldC, RtfContainer newC) throws Exception { // treating the Stack as a Vector allows such manipulations (yes, I hear you screaming ;-) final int index = containers.indexOf(oldC); if (index < 0) { throw new Exception("container to replace not found:" + oldC); } containers.setElementAt(newC, index); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public static void main(String[] args) throws Exception { Writer w = null; if (args.length != 0) { final String outFile = args[0]; System.err.println("Outputting RTF to file '" + outFile + "'"); w = new BufferedWriter(new FileWriter(outFile)); } else { System.err.println("Outputting RTF code to standard output"); w = new BufferedWriter(new OutputStreamWriter(System.out)); } final RtfFile f = new RtfFile(w); final RtfSection sect = f.startDocumentArea().newSection(); final RtfParagraph p = sect.newParagraph(); p.newText("Hello, RTF world.\n", null); final RtfAttributes attr = new RtfAttributes(); attr.set(RtfText.ATTR_BOLD); attr.set(RtfText.ATTR_ITALIC); attr.set(RtfText.ATTR_FONT_SIZE, 36); p.newText("This is bold, italic, 36 points", attr); f.flush(); System.err.println("RtfFile test: all done."); }
// in src/java/org/apache/fop/render/afp/AFPSVGHandler.java
public void handleXML(RendererContext context, Document doc, String ns) throws Exception { if (SVGDOMImplementation.SVG_NAMESPACE_URI.equals(ns)) { renderSVGDocument(context, doc); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void convertBidiTestData(String ucdFileName, String bidiFileName, String outFileName) throws Exception { // read type data from UCD if ignoring deprecated type data if ( ignoreDeprecatedTypeData ) { readBidiTypeData(ucdFileName); } // read bidi test data readBidiTestData(bidiFileName); // generate class PrintWriter out = new PrintWriter(new FileWriter(outFileName)); License.writeJavaLicenseId(out); out.println(); out.println("package org.apache.fop.complexscripts.bidi;"); out.println(); out.println("import java.io.IOException;"); out.println("import java.io.InputStream;"); out.println("import java.io.ObjectInputStream;"); out.println(); out.println("// CSOFF: WhitespaceAfterCheck"); out.println(); out.println("/*"); out.println(" * !!! THIS IS A GENERATED FILE !!!"); out.println(" * If updates to the source are needed, then:"); out.println(" * - apply the necessary modifications to"); out.println(" * 'src/codegen/unicode/java/org/apache/fop/text/bidi/GenerateBidiTestData.java'"); out.println(" * - run 'ant codegen-unicode', which will generate a new BidiTestData.java"); out.println(" * in 'test/java/org/apache/fop/complexscripts/bidi'"); out.println(" * - commit BOTH changed files"); out.println(" */"); out.println(); out.println("/** Bidirectional test data. */"); out.println("public final class BidiTestData {"); out.println(); out.println(" private BidiTestData() {"); out.println(" }"); out.println(); dumpData ( out, outFileName ); out.println(" public static final int NUM_TEST_SEQUENCES = " + numTestSpecs + ";"); out.println(); out.println(" public static int[] readTestData ( String prefix, int index ) {"); out.println(" int[] data = null;"); out.println(" InputStream is = null;"); out.println(" Class btc = BidiTestData.class;"); out.println(" String name = btc.getSimpleName() + \"$\" + prefix + index + \".ser\";"); out.println(" try {"); out.println(" if ( ( is = btc.getResourceAsStream ( name ) ) != null ) {"); out.println(" ObjectInputStream ois = new ObjectInputStream ( is );"); out.println(" data = (int[]) ois.readObject();"); out.println(" ois.close();"); out.println(" }"); out.println(" } catch ( IOException e ) {"); out.println(" data = null;"); out.println(" } catch ( ClassNotFoundException e ) {"); out.println(" data = null;"); out.println(" } finally {"); out.println(" if ( is != null ) {"); out.println(" try { is.close(); } catch ( Exception e ) {}"); out.println(" }"); out.println(" }"); out.println(" return data;"); out.println(" }"); out.println("}"); out.flush(); out.close(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void readBidiTypeData(String ucdFileName) throws Exception { BufferedReader b = new BufferedReader(new InputStreamReader(new URL(ucdFileName).openStream())); String line; int n; // singleton map - derived from single char entry Map/*<Integer,List>*/ sm = new HashMap/*<Integer,List>*/(); // interval map - derived from pair of block endpoint entries Map/*<String,int[3]>*/ im = new HashMap/*<String,int[3]>*/(); if ( verbose ) { System.out.print("Reading bidi type data..."); } for ( lineNumber = 0; ( line = b.readLine() ) != null; ) { lineNumber++; if ( line.length() == 0 ) { continue; } else if ( line.startsWith("#") ) { continue; } else { parseTypeProperties ( line, sm, im ); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void readBidiTestData(String bidiFileName) throws Exception { BufferedReader b = new BufferedReader(new InputStreamReader(new URL(bidiFileName).openStream())); String line; int n; List tdl = new ArrayList(); List ldl = new ArrayList(); if ( verbose ) { System.out.print("Reading bidi test data..."); } for ( lineNumber = 0; ( line = b.readLine() ) != null; ) { lineNumber++; if ( line.length() == 0 ) { continue; } else if ( line.startsWith("#") ) { continue; } else if ( line.startsWith(PFX_TYPE) && ! ignoreDeprecatedTypeData ) { List lines = new ArrayList(); if ( ( n = readType ( line, b, lines ) ) < 0 ) { break; } else { lineNumber += n; tdl.add ( parseType ( lines ) ); } } else if ( line.startsWith(PFX_LEVELS) ) { List lines = new ArrayList(); if ( ( n = readLevels ( line, b, lines ) ) < 0 ) { break; } else { lineNumber += n; ldl.add ( parseLevels ( lines ) ); } } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static void convertBidiClassProperties(String bidiFileName, String outFileName) throws Exception { readBidiClassProperties(bidiFileName); // generate class PrintWriter out = new PrintWriter(new FileWriter(outFileName)); License.writeJavaLicenseId(out); out.println(); out.println("package org.apache.fop.complexscripts.bidi;"); out.println(); out.println("import java.util.Arrays;"); out.println("import org.apache.fop.complexscripts.bidi.BidiConstants;"); out.println(); out.println("// CSOFF: WhitespaceAfterCheck"); out.println("// CSOFF: LineLengthCheck"); out.println(); out.println("/*"); out.println(" * !!! THIS IS A GENERATED FILE !!!"); out.println(" * If updates to the source are needed, then:"); out.println(" * - apply the necessary modifications to"); out.println(" * 'src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java'"); out.println(" * - run 'ant codegen-unicode', which will generate a new BidiClass.java"); out.println(" * in 'src/java/org/apache/fop/complexscripts/bidi'"); out.println(" * - commit BOTH changed files"); out.println(" */"); out.println(); out.println("/** Bidirectional class utilities. */"); out.println("public final class BidiClass {"); out.println(); out.println("private BidiClass() {"); out.println("}"); out.println(); dumpData(out); out.println ("/**"); out.println (" * Lookup bidi class for character expressed as unicode scalar value."); out.println (" * @param ch a unicode scalar value"); out.println (" * @return bidi class"); out.println (" */"); out.println("public static int getBidiClass ( int ch ) {"); out.println(" if ( ch <= 0x00FF ) {"); out.println(" return bcL1 [ ch - 0x0000 ];"); out.println(" } else if ( ( ch >= 0x0590 ) && ( ch <= 0x06FF ) ) {"); out.println(" return bcR1 [ ch - 0x0590 ];"); out.println(" } else {"); out.println(" return getBidiClass ( ch, bcS1, bcE1, bcC1 );"); out.println(" }"); out.println("}"); out.println(); out.println("private static int getBidiClass ( int ch, int[] sa, int[] ea, byte[] ca ) {"); out.println(" int k = Arrays.binarySearch ( sa, ch );"); out.println(" if ( k >= 0 ) {"); out.println(" return ca [ k ];"); out.println(" } else {"); out.println(" k = - ( k + 1 );"); out.println(" if ( k == 0 ) {"); out.println(" return BidiConstants.L;"); out.println(" } else if ( ch <= ea [ k - 1 ] ) {"); out.println(" return ca [ k - 1 ];"); out.println(" } else {"); out.println(" return BidiConstants.L;"); out.println(" }"); out.println(" }"); out.println("}"); out.println(); out.println("}"); out.flush(); out.close(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static void readBidiClassProperties(String bidiFileName) throws Exception { // read property names BufferedReader b = new BufferedReader(new InputStreamReader(new URL(bidiFileName).openStream())); String line; int lineNumber = 0; TreeSet intervals = new TreeSet(); while ( ( line = b.readLine() ) != null ) { lineNumber++; if ( line.startsWith("#") ) { continue; } else if ( line.length() == 0 ) { continue; } else { if ( line.indexOf ( "#" ) != -1 ) { line = ( line.split ( "#" ) ) [ 0 ]; } String[] fa = line.split ( ";" ); if ( fa.length == 2 ) { int[] interval = parseInterval ( fa[0].trim() ); byte bidiClass = (byte) parseBidiClass ( fa[1].trim() ); if ( interval[1] == interval[0] ) { // singleton int c = interval[0]; if ( c <= 0x00FF ) { if ( bcL1 [ c - 0x0000 ] == 0 ) { bcL1 [ c - 0x0000 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + c ); } } else if ( ( c >= 0x0590 ) && ( c <= 0x06FF ) ) { if ( bcR1 [ c - 0x0590 ] == 0 ) { bcR1 [ c - 0x0590 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + c ); } } else { addInterval ( intervals, c, c, bidiClass ); } } else { // non-singleton int s = interval[0]; int e = interval[1]; // inclusive if ( s <= 0x00FF ) { for ( int i = s; i <= e; i++ ) { if ( i <= 0x00FF ) { if ( bcL1 [ i - 0x0000 ] == 0 ) { bcL1 [ i - 0x0000 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + i ); } } else { addInterval ( intervals, i, e, bidiClass ); break; } } } else if ( ( s >= 0x0590 ) && ( s <= 0x06FF ) ) { for ( int i = s; i <= e; i++ ) { if ( i <= 0x06FF ) { if ( bcR1 [ i - 0x0590 ] == 0 ) { bcR1 [ i - 0x0590 ] = bidiClass; } else { throw new Exception ( "duplicate singleton entry: " + i ); } } else { addInterval ( intervals, i, e, bidiClass ); break; } } } else { addInterval ( intervals, s, e, bidiClass ); } } } else { throw new Exception ( "bad syntax, line(" + lineNumber + "): " + line ); } } } // compile interval search data int ivIndex = 0; int niv = intervals.size(); bcS1 = new int [ niv ]; bcE1 = new int [ niv ]; bcC1 = new byte [ niv ]; for ( Iterator it = intervals.iterator(); it.hasNext(); ivIndex++ ) { Interval iv = (Interval) it.next(); bcS1[ivIndex] = iv.start; bcE1[ivIndex] = iv.end; bcC1[ivIndex] = (byte) iv.bidiClass; } // test data test(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static int[] parseInterval ( String interval ) throws Exception { int s; int e; String[] fa = interval.split("\\.\\."); if ( fa.length == 1 ) { s = Integer.parseInt ( fa[0], 16 ); e = s; } else if ( fa.length == 2 ) { s = Integer.parseInt ( fa[0], 16 ); e = Integer.parseInt ( fa[1], 16 ); } else { throw new Exception ( "bad interval syntax: " + interval ); } if ( e < s ) { throw new Exception ( "bad interval, start must be less than or equal to end: " + interval ); } return new int[] {s, e}; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static void test() throws Exception { for ( int i = 0, n = testData.length / 2; i < n; i++ ) { int ch = testData [ i * 2 + 0 ]; int tc = testData [ i * 2 + 1 ]; int bc = getBidiClass ( ch ); if ( bc != tc ) { throw new Exception ( "test mapping failed for character (0x" + Integer.toHexString(ch) + "): expected " + tc + ", got " + bc ); } } }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
private static void convertLineBreakProperties( // CSOK: MethodLength String lineBreakFileName, String propertyValueFileName, String breakPairFileName, String outFileName) throws Exception { readLineBreakProperties(lineBreakFileName, propertyValueFileName); // read break pair table int lineBreakPropertyValueCount = lineBreakPropertyValues.size(); int tableSize = lineBreakPropertyValueCount - NOT_IN_PAIR_TABLE.length; Map notInPairTableMap = new HashMap(NOT_IN_PAIR_TABLE.length); for (int i = 0; i < NOT_IN_PAIR_TABLE.length; i++) { Object v = lineBreakPropertyValues.get(NOT_IN_PAIR_TABLE[i]); if (v == null) { throw new Exception("'not in pair table' property not found: " + NOT_IN_PAIR_TABLE[i]); } notInPairTableMap.put(NOT_IN_PAIR_TABLE[i], v); } byte[][] pairTable = new byte[tableSize][]; byte[] columnHeader = new byte[tableSize]; byte[] rowHeader = new byte[tableSize]; byte[] columnMap = new byte[lineBreakPropertyValueCount + 1]; Arrays.fill(columnMap, (byte)255); byte[] rowMap = new byte[lineBreakPropertyValueCount + 1]; Arrays.fill(rowMap, (byte)255); BufferedReader b = new BufferedReader(new FileReader(breakPairFileName)); String line = b.readLine(); int lineNumber = 1; String[] lineTokens; String name; // read header if (line != null) { lineTokens = line.split("\\s+"); byte columnNumber = 0; for (int i = 0; i < lineTokens.length; ++i) { name = lineTokens[i]; if (name.length() > 0) { if (columnNumber >= columnHeader.length) { throw new Exception(breakPairFileName + ':' + lineNumber + ": unexpected column header " + name); } if (notInPairTableMap.get(name) != null) { throw new Exception(breakPairFileName + ':' + lineNumber + ": invalid column header " + name); } Byte v = (Byte)lineBreakPropertyValues.get(name); if (v != null) { byte vv = v.byteValue(); columnHeader[columnNumber] = vv; columnMap[vv] = columnNumber; } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": unknown column header " + name); } columnNumber++; } } if (columnNumber < columnHeader.length) { StringBuffer missing = new StringBuffer(); for (int j = 0; j < lineBreakPropertyShortNames.size(); j++) { boolean found = false; for (int k = 0; k < columnNumber; k++) { if (columnHeader[k] == j + 1) { found = true; break; } } if (!found) { if (missing.length() > 0) { missing.append(", "); } missing.append((String)lineBreakPropertyShortNames.get(j)); } } throw new Exception( breakPairFileName + ':' + lineNumber + ": missing column for properties: " + missing.toString()); } } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": can't read table header"); } line = b.readLine().trim(); lineNumber++; byte rowNumber = 0; while (line != null && line.length() > 0) { if (rowNumber >= rowHeader.length) { throw new Exception(breakPairFileName + ':' + lineNumber + ": unexpected row " + line); } pairTable[rowNumber] = new byte[tableSize]; lineTokens = line.split("\\s+"); if (lineTokens.length > 0) { name = lineTokens[0]; if (notInPairTableMap.get(name) != null) { throw new Exception(breakPairFileName + ':' + lineNumber + ": invalid row header " + name); } Byte v = (Byte)lineBreakPropertyValues.get(name); if (v != null) { byte vv = v.byteValue(); rowHeader[rowNumber] = vv; rowMap[vv] = rowNumber; } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": unknown row header " + name); } } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": can't read row header"); } int columnNumber = 0; String token; for (int i = 1; i < lineTokens.length; ++i) { token = lineTokens[i]; if (token.length() == 1) { byte tokenBreakClass = (byte)BREAK_CLASS_TOKENS.indexOf(token.charAt(0)); if (tokenBreakClass >= 0) { pairTable[rowNumber][columnNumber] = tokenBreakClass; } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": unexpected token: " + token); } } else { throw new Exception(breakPairFileName + ':' + lineNumber + ": token too long: " + token); } columnNumber++; } line = b.readLine().trim(); lineNumber++; rowNumber++; } if (rowNumber < rowHeader.length) { StringBuffer missing = new StringBuffer(); for (int j = 0; j < lineBreakPropertyShortNames.size(); j++) { boolean found = false; for (int k = 0; k < rowNumber; k++) { if (rowHeader[k] == j + 1) { found = true; break; } } if (!found) { if (missing.length() > 0) { missing.append(", "); } missing.append((String)lineBreakPropertyShortNames.get(j)); } } throw new Exception( breakPairFileName + ':' + lineNumber + ": missing row for properties: " + missing.toString()); } // generate class int rowsize = 512; int blocksize = lineBreakProperties.length / rowsize; byte[][] row = new byte[rowsize][]; int idx = 0; StringBuffer doStaticLinkCode = new StringBuffer(); PrintWriter out = new PrintWriter(new FileWriter(outFileName)); License.writeJavaLicenseId(out); out.println(); out.println("package org.apache.fop.text.linebreak;"); out.println(); out.println("/*"); out.println(" * !!! THIS IS A GENERATED FILE !!!"); out.println(" * If updates to the source are needed, then:"); out.println(" * - apply the necessary modifications to"); out.println(" * 'src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java'"); out.println(" * - run 'ant codegen-unicode', which will generate a new LineBreakUtils.java"); out.println(" * in 'src/java/org/apache/fop/text/linebreak'"); out.println(" * - commit BOTH changed files"); out.println(" */"); out.println(); out.println("// CSOFF: WhitespaceAfterCheck"); out.println("// CSOFF: LineLengthCheck"); out.println(); out.println("/** Line breaking utilities. */"); out.println("public final class LineBreakUtils {"); out.println(); out.println(" private LineBreakUtils() {"); out.println(" }"); out.println(); out.println(" /** Break class constant */"); out.println(" public static final byte DIRECT_BREAK = " + DIRECT_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte INDIRECT_BREAK = " + INDIRECT_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte COMBINING_INDIRECT_BREAK = " + COMBINING_INDIRECT_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte COMBINING_PROHIBITED_BREAK = " + COMBINING_PROHIBITED_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte PROHIBITED_BREAK = " + PROHIBITED_BREAK + ';'); out.println(" /** Break class constant */"); out.println(" public static final byte EXPLICIT_BREAK = " + EXPLICIT_BREAK + ';'); out.println(); out.println(" private static final byte[][] PAIR_TABLE = {"); boolean printComma = false; for (int i = 1; i <= lineBreakPropertyValueCount; i++) { if (printComma) { out.println(","); } else { printComma = true; } out.print(" {"); boolean localPrintComma = false; for (int j = 1; j <= lineBreakPropertyValueCount; j++) { if (localPrintComma) { out.print(", "); } else { localPrintComma = true; } if (columnMap[j] != -1 && rowMap[i] != -1) { out.print(pairTable[rowMap[i]][columnMap[j]]); } else { out.print('0'); } } out.print('}'); } out.println("};"); out.println(); out.println(" private static byte[][] lineBreakProperties = new byte[" + rowsize + "][];"); out.println(); out.println(" private static void init0() {"); int rowsPrinted = 0; int initSections = 0; for (int i = 0; i < rowsize; i++) { boolean found = false; for (int j = 0; j < i; j++) { if (row[j] != null) { boolean matched = true; for (int k = 0; k < blocksize; k++) { if (row[j][k] != lineBreakProperties[idx + k]) { matched = false; break; } } if (matched) { found = true; doStaticLinkCode.append(" lineBreakProperties["); doStaticLinkCode.append(i); doStaticLinkCode.append("] = lineBreakProperties["); doStaticLinkCode.append(j); doStaticLinkCode.append("];\n"); break; } } } if (!found) { if (rowsPrinted >= 64) { out.println(" }"); out.println(); initSections++; out.println(" private static void init" + initSections + "() {"); rowsPrinted = 0; } row[i] = new byte[blocksize]; boolean printLocalComma = false; out.print(" lineBreakProperties[" + i + "] = new byte[] { "); for (int k = 0; k < blocksize; k++) { row[i][k] = lineBreakProperties[idx + k]; if (printLocalComma) { out.print(", "); } else { printLocalComma = true; } out.print(row[i][k]); } out.println("};"); rowsPrinted++; } idx += blocksize; } out.println(" }"); out.println(); out.println(" static {"); for (int i = 0; i <= initSections; i++) { out.println(" init" + i + "();"); } out.print(doStaticLinkCode); out.println(" }"); out.println(); for (int i = 0; i < lineBreakPropertyShortNames.size(); i++) { String shortName = (String)lineBreakPropertyShortNames.get(i); out.println(" /** Linebreak property constant */"); out.print(" public static final byte LINE_BREAK_PROPERTY_"); out.print(shortName); out.print(" = "); out.print(i + 1); out.println(';'); } out.println(); final String shortNamePrefix = " private static String[] lineBreakPropertyShortNames = {"; out.print(shortNamePrefix); int lineLength = shortNamePrefix.length(); printComma = false; for (int i = 0; i < lineBreakPropertyShortNames.size(); i++) { name = (String)lineBreakPropertyShortNames.get(i); if (printComma) { if (lineLength <= MAX_LINE_LENGTH - 2) { out.print(", "); } else { out.print(","); } // count the space anyway to force a linebreak if the comma causes lineLength == MAX_LINE_LENGTH lineLength += 2; } else { printComma = true; } if (lineLength > MAX_LINE_LENGTH) { out.println(); out.print(" "); lineLength = 8; } out.print('"'); out.print(name); out.print('"'); lineLength += (2 + name.length()); } out.println("};"); out.println(); final String longNamePrefix = " private static String[] lineBreakPropertyLongNames = {"; out.print(longNamePrefix); lineLength = longNamePrefix.length(); printComma = false; for (int i = 0; i < lineBreakPropertyLongNames.size(); i++) { name = (String)lineBreakPropertyLongNames.get(i); if (printComma) { out.print(','); lineLength++; } else { printComma = true; } if (lineLength > MAX_LINE_LENGTH) { out.println(); out.print(" "); lineLength = 8; } out.print('"'); out.print(name); out.print('"'); lineLength += (2 + name.length()); } out.println("};"); out.println(); out.println(" /**"); out.println(" * Return the short name for the linebreak property corresponding"); out.println(" * to the given symbolic constant."); out.println(" *"); out.println(" * @param i the numeric value of the linebreak property"); out.println(" * @return the short name of the linebreak property"); out.println(" */"); out.println(" public static String getLineBreakPropertyShortName(byte i) {"); out.println(" if (i > 0 && i <= lineBreakPropertyShortNames.length) {"); out.println(" return lineBreakPropertyShortNames[i - 1];"); out.println(" } else {"); out.println(" return null;"); out.println(" }"); out.println(" }"); out.println(); out.println(" /**"); out.println(" * Return the long name for the linebreak property corresponding"); out.println(" * to the given symbolic constant."); out.println(" *"); out.println(" * @param i the numeric value of the linebreak property"); out.println(" * @return the long name of the linebreak property"); out.println(" */"); out.println(" public static String getLineBreakPropertyLongName(byte i) {"); out.println(" if (i > 0 && i <= lineBreakPropertyLongNames.length) {"); out.println(" return lineBreakPropertyLongNames[i - 1];"); out.println(" } else {"); out.println(" return null;"); out.println(" }"); out.println(" }"); out.println(); out.println(" /**"); out.println(" * Return the linebreak property constant for the given <code>char</code>"); out.println(" *"); out.println(" * @param c the <code>char</code> whose linebreak property to return"); out.println(" * @return the constant representing the linebreak property"); out.println(" */"); out.println(" public static byte getLineBreakProperty(char c) {"); out.println(" return lineBreakProperties[c / " + blocksize + "][c % " + blocksize + "];"); out.println(" }"); out.println(); out.println(" /**"); out.println(" * Return the break class constant for the given pair of linebreak"); out.println(" * property constants."); out.println(" *"); out.println(" * @param lineBreakPropertyBefore the linebreak property for the first character"); out.println(" * in a two-character sequence"); out.println(" * @param lineBreakPropertyAfter the linebreak property for the second character"); out.println(" * in a two-character sequence"); out.println(" * @return the constant representing the break class"); out.println(" */"); out.println( " public static byte getLineBreakPairProperty(int lineBreakPropertyBefore, int lineBreakPropertyAfter) {"); out.println(" return PAIR_TABLE[lineBreakPropertyBefore - 1][lineBreakPropertyAfter - 1];"); out.println(" }"); out.println(); out.println("}"); out.flush(); out.close(); }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
private static void readLineBreakProperties(String lineBreakFileName, String propertyValueFileName) throws Exception { // read property names BufferedReader b = new BufferedReader(new InputStreamReader(new URL(propertyValueFileName).openStream())); String line = b.readLine(); int lineNumber = 1; byte propertyIndex = 1; byte indexForUnknown = 0; while (line != null) { if (line.startsWith("lb")) { String shortName; String longName = null; int semi = line.indexOf(';'); if (semi < 0) { throw new Exception( propertyValueFileName + ':' + lineNumber + ": missing property short name in " + line); } line = line.substring(semi + 1); semi = line.indexOf(';'); if (semi > 0) { shortName = line.substring(0, semi).trim(); longName = line.substring(semi + 1).trim(); semi = longName.indexOf(';'); if (semi > 0) { longName = longName.substring(0, semi).trim(); } } else { shortName = line.trim(); } if (shortName.equals("XX")) { indexForUnknown = propertyIndex; } lineBreakPropertyValues.put(shortName, new Byte((byte)propertyIndex)); lineBreakPropertyShortNames.add(shortName); lineBreakPropertyLongNames.add(longName); propertyIndex++; if (propertyIndex <= 0) { throw new Exception(propertyValueFileName + ':' + lineNumber + ": property rolled over in " + line); } } line = b.readLine(); lineNumber++; } if (indexForUnknown == 0) { throw new Exception("index for XX (unknown) line break property value not found"); } // read property values Arrays.fill(lineBreakProperties, (byte)0); b = new BufferedReader(new InputStreamReader(new URL(lineBreakFileName).openStream())); line = b.readLine(); lineNumber = 1; while (line != null) { int idx = line.indexOf('#'); if (idx >= 0) { line = line.substring(0, idx); } line = line.trim(); if (line.length() > 0) { idx = line.indexOf(';'); if (idx <= 0) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": No field delimiter in " + line); } Byte v = (Byte)lineBreakPropertyValues.get(line.substring(idx + 1).trim()); if (v == null) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Unknown property value in " + line); } String codepoint = line.substring(0, idx); int low; int high; idx = codepoint.indexOf(".."); try { if (idx >= 0) { low = Integer.parseInt(codepoint.substring(0, idx), 16); high = Integer.parseInt(codepoint.substring(idx + 2), 16); } else { low = Integer.parseInt(codepoint, 16); high = low; } } catch (NumberFormatException e) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Invalid codepoint number in " + line); } if (high > 0xFFFF) { // ignore non-baseplane characters for now } else { if (low < 0 || high < 0) { throw new Exception( lineBreakFileName + ':' + lineNumber + ": Negative codepoint(s) in " + line); } byte vv = v.byteValue(); for (int i = low; i <= high; i++) { if (lineBreakProperties[i] != 0) { throw new Exception( lineBreakFileName + ':' + lineNumber + ": Property already set for " + ((char)i) + " in " + line); } lineBreakProperties[i] = vv; } } } line = b.readLine(); lineNumber++; } }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
private static void optimizeBlocks(String lineBreakFileName, String propertyValueFileName) throws Exception { readLineBreakProperties(lineBreakFileName, propertyValueFileName); for (int i = 0; i < 16; i++) { int rowsize = 1 << i; int blocksize = lineBreakProperties.length / (rowsize); byte[][] row = new byte[rowsize][]; int idx = 0; int nrOfDistinctBlocks = 0; for (int j = 0; j < rowsize; j++) { byte[] block = new byte[blocksize]; for (int k = 0; k < blocksize; k++) { block[k] = lineBreakProperties[idx]; idx++; } boolean found = false; for (int k = 0; k < j; k++) { if (row[k] != null) { boolean matched = true; for (int l = 0; l < blocksize; l++) { if (row[k][l] != block[l]) { matched = false; break; } } if (matched) { found = true; break; } } } if (!found) { row[j] = block; nrOfDistinctBlocks++; } else { row[j] = null; } } int size = rowsize * 4 + nrOfDistinctBlocks * blocksize; System.out.println( "i=" + i + " blocksize=" + blocksize + " blocks=" + nrOfDistinctBlocks + " size=" + size); } }
100
            
// in src/java/org/apache/fop/pdf/PDFStream.java
catch (Exception e) { //TODO throw the exception and catch it elsewhere e.printStackTrace(); return 0; }
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (Exception e) { throw new java.io.FileNotFoundException( "URI could not be resolved (" + e.getMessage() + "): " + uri); }
// in src/java/org/apache/fop/tools/TestConverter.java
catch (Exception e) { logger.error("Error while running tests", e); }
// in src/java/org/apache/fop/tools/TestConverter.java
catch (Exception e) { logger.error("Error setting base directory"); }
// in src/java/org/apache/fop/tools/TestConverter.java
catch (Exception e) { logger.error("Error while running tests", e); }
// in src/java/org/apache/fop/tools/TestConverter.java
catch (Exception e) { logger.error("Error while comparing files", e); return false; }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (Exception e) { e.printStackTrace(); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception e) { task.log("Error setting base URL", Project.MSG_DEBUG); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { throw new BuildException("Failed to open " + outFile, ex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { if (task.getThrowexceptions()) { throw new BuildException(ex); } throw ex; }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { logger.error("Error rendering fo file: " + foFile, ex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { logger.error("Error rendering xml/xslt files: " + xmlFile + ", " + xsltFile, ex); }
// in src/java/org/apache/fop/servlet/FopServlet.java
catch (Exception ex) { throw new ServletException(ex); }
// in src/java/org/apache/fop/fo/XMLObj.java
catch (Exception e) { //TODO this is ugly because there may be subsequent failures like NPEs log.error("Error while trying to instantiate a DOM Document", e); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGElement.java
catch (Exception e) { log.error("Could not set base URL for svg", e); }
// in src/java/org/apache/fop/fo/extensions/svg/BatikExtensionElementMapping.java
catch (Exception e) { return null; }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
catch (Exception e) { return SVGDOMImplementation.getDOMImplementation(); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGElementMapping.java
catch (Exception e) { return null; }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (Exception e) { e.printStackTrace(); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (Exception e) { e.printStackTrace(); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (Exception ioe) { System.out.println("Exception " + ioe); ioe.printStackTrace(); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (Exception e) { throw new RuntimeException("Couldn't create XMLReader: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (Exception e) { //ignore, fallback further down }
// in src/java/org/apache/fop/svg/SimpleSVGUserAgent.java
catch (Exception e) { return null; }
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (Exception e) { throw new TranscoderException( "Error while setting up PDFDocumentGraphics2D", e); }
// in src/java/org/apache/fop/svg/PDFANode.java
catch (Exception e) { //TODO Move this to setDestination() and throw an IllegalArgumentException e.printStackTrace(); }
// in src/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java
catch (Exception e) { ctx.getUserAgent().displayError(e); }
// in src/java/org/apache/fop/svg/AbstractFOPImageElementBridge.java
catch (Exception e) { ctx.getUserAgent().displayError(e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new SAXException("Error while parsing integer value: " + str, e); }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
catch (Exception e) { log.error("Error while building XML font metrics file.", e); System.exit(-1); }
// in src/java/org/apache/fop/fonts/apps/PFMReader.java
catch (Exception e) { log.error("Error while building XML font metrics file", e); System.exit(-1); }
// in src/java/org/apache/fop/fonts/autodetect/FontInfoFinder.java
catch (Exception e) { if (this.eventListener != null) { this.eventListener.fontLoadingErrorAtAutoDetection(this, fontFileURL, e); } return null; }
// in src/java/org/apache/fop/fonts/autodetect/FontInfoFinder.java
catch (Exception e) { if (fontCache != null) { fontCache.registerFailedFont(embedURL, fileLastModified); } if (this.eventListener != null) { this.eventListener.fontLoadingErrorAtAutoDetection(this, embedURL, e); } continue; }
// in src/java/org/apache/fop/fonts/autodetect/FontInfoFinder.java
catch (Exception e) { if (fontCache != null) { fontCache.registerFailedFont(embedURL, fileLastModified); } if (this.eventListener != null) { this.eventListener.fontLoadingErrorAtAutoDetection(this, embedURL, e); } return null; }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/AbstractGenericSVGHandler.java
catch (Exception e) { EventBroadcaster eventBroadcaster = userAgent.getEventBroadcaster(); SVGEventProducer eventProducer = SVGEventProducer.Provider.get(eventBroadcaster); final String uri = getDocumentURI(doc); eventProducer.svgNotBuilt(this, e, uri); return null; }
// in src/java/org/apache/fop/render/AbstractRenderer.java
catch (Exception e) { // could not handle document ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( ctx.getUserAgent().getEventBroadcaster()); eventProducer.foreignXMLProcessingError(this, doc, namespace, e); }
// in src/java/org/apache/fop/render/pcl/HardcodedFonts.java
catch (Exception e) { LOG.error(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
catch (Exception e) { final String msg = "RtfTableRow.writePaddingAttributes: " + e.toString(); // getRtfFile().getLog().logWarning(msg); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (Exception e) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + url + "' (" + e + ")"); }
// in src/java/org/apache/fop/render/rtf/PageAttributesConverter.java
catch (Exception e) { log.error("Exception in convertPageAttributes: " + e.getMessage() + "- page attributes ignored"); attrib = new FOPRtfAttributes(); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startTable:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startColumn: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startLink: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnote: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("characters:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumberCitation: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("number format error: cannot convert '" + number + "' to float value"); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("Invalid font size value '" + size + "'"); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); }
// in src/java/org/apache/fop/render/java2d/ConfiguredFontCollection.java
catch (Exception e) { log.warn("Unable to load custom font from file '" + fontFile + "'", e); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, getDocumentURI(doc)); return; }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, getDocumentURI(doc)); }
// in src/java/org/apache/fop/afp/apps/FontPatternExtractor.java
catch (Exception e) { e.printStackTrace(); System.exit(-1); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (Exception ex) { // Lets log at least! LOG.error(ex.getMessage()); }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageLoadError(this, pageViewport.getPageNumberString(), e); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageRenderingError(this, pageViewport.getPageNumberString(), e); if (e instanceof RuntimeException) { throw (RuntimeException)e; } }
// in src/java/org/apache/fop/util/ColorSpaceCache.java
catch (Exception e) { // Ignore exception - will be logged a bit further down // (colorSpace == null case) }
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
catch (Exception e) { //Provide a fallback if exotic formats are encountered bi = convertToGrayscale(bi, targetDimension); return converter.convertToMonochrome(bi); }
// in src/java/org/apache/fop/image/loader/batik/ImageConverterSVG2G2D.java
catch (Exception e) { throw new ImageException("GVT tree could not be built for SVG graphic", e); }
// in src/java/org/apache/fop/image/loader/batik/BatikUtil.java
catch (Exception e) { //ignore }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (Exception e) { return null; }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (Exception e) { baseURL = ""; }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (Exception e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (Exception e) { System.err.println("Couldn't set system look & feel!"); }
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { return false; }
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { System.err.println("Unable to start FOP:"); e.printStackTrace(); System.exit(-1); }
// in src/java/org/apache/fop/cli/Main.java
catch (Exception e) { if (options != null) { options.getLogger().error("Exception", e); if (options.getOutputFile() != null) { options.getOutputFile().delete(); } } System.exit(1); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
catch (Exception e) { System.out.println("An unexpected error occured at line: " + lineNumber ); e.printStackTrace(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
catch (Exception e) { System.out.println("An unexpected error occured"); e.printStackTrace(); }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
catch (Exception e) { System.out.println("An unexpected error occured"); e.printStackTrace(); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (Exception e) { e.printStackTrace(); }
41
            
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (Exception e) { throw new java.io.FileNotFoundException( "URI could not be resolved (" + e.getMessage() + "): " + uri); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { throw new BuildException("Failed to open " + outFile, ex); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (Exception ex) { if (task.getThrowexceptions()) { throw new BuildException(ex); } throw ex; }
// in src/java/org/apache/fop/servlet/FopServlet.java
catch (Exception ex) { throw new ServletException(ex); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (Exception e) { throw new RuntimeException("Couldn't create XMLReader: " + e.getMessage()); }
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (Exception e) { throw new TranscoderException( "Error while setting up PDFDocumentGraphics2D", e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new SAXException("Error while parsing integer value: " + str, e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (Exception e) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + url + "' (" + e + ")"); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startTable:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startColumn: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startLink: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnote: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("characters:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumberCitation: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("number format error: cannot convert '" + number + "' to float value"); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("Invalid font size value '" + size + "'"); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (Exception e) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageRenderingError(this, pageViewport.getPageNumberString(), e); if (e instanceof RuntimeException) { throw (RuntimeException)e; } }
// in src/java/org/apache/fop/image/loader/batik/ImageConverterSVG2G2D.java
catch (Exception e) { throw new ImageException("GVT tree could not be built for SVG graphic", e); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (Exception e) { throw new FOPException(e); }
27
checked (Domain) ExternalGraphicException
public static class ExternalGraphicException extends IOException {
        ExternalGraphicException(String reason) {
            super(reason);
        }
    }
4
            
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
protected void writeRtfContentWithException() throws IOException { if (writer == null) { return; } if (url == null && imagedata == null) { throw new ExternalGraphicException( "No image data is available (neither URL, nor in-memory)"); } String linkToRoot = System.getProperty("jfor_link_to_root"); if (url != null && linkToRoot != null) { writer.write("{\\field {\\* \\fldinst { INCLUDEPICTURE \""); writer.write(linkToRoot); File urlFile = new File(url.getFile()); writer.write(urlFile.getName()); writer.write("\" \\\\* MERGEFORMAT \\\\d }}}"); return; } // getRtfFile ().getLog ().logInfo ("Writing image '" + url + "'."); if (imagedata == null) { try { final InputStream in = url.openStream(); try { imagedata = IOUtils.toByteArray(url.openStream()); } finally { IOUtils.closeQuietly(in); } } catch (Exception e) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + url + "' (" + e + ")"); } } if (imagedata == null) { return; } // Determine image file format String file = (url != null ? url.getFile() : "<unknown>"); imageformat = FormatBase.determineFormat(imagedata); if (imageformat != null) { imageformat = imageformat.convert(imageformat, imagedata); } if (imageformat == null || imageformat.getType() == ImageConstants.I_NOT_SUPPORTED || "".equals(imageformat.getRtfTag())) { throw new ExternalGraphicException("The tag <fo:external-graphic> " + "does not support " + file.substring(file.lastIndexOf(".") + 1) + " - image type."); } // Writes the beginning of the rtf image writeGroupMark(true); writeStarControlWord("shppict"); writeGroupMark(true); writeControlWord("pict"); StringBuffer buf = new StringBuffer(imagedata.length * 3); writeControlWord(imageformat.getRtfTag()); computeImageSize(); writeSizeInfo(); writeAttributes(getRtfAttributes(), null); for (int i = 0; i < imagedata.length; i++) { int iData = imagedata [i]; // Make positive byte if (iData < 0) { iData += 256; } if (iData < 16) { // Set leading zero and append buf.append('0'); } buf.append(Integer.toHexString(iData)); } int len = buf.length(); char[] chars = new char[len]; buf.getChars(0, len, chars, 0); writer.write(chars); // Writes the end of RTF image writeGroupMark(false); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
public void setURL(String urlString) throws IOException { URL tmpUrl = null; try { tmpUrl = new URL (urlString); } catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } } this.url = tmpUrl; }
2
            
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (Exception e) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + url + "' (" + e + ")"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); }
0 1
            
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (ExternalGraphicException ie) { writeExceptionInRtf(ie); }
0 0
unknown (Domain) FOPException
public class FOPException extends SAXException {

    private static final String EXCEPTION_SEPARATOR = "\n---------\n";

    private String systemId;
    private int line;
    private int column;

    private String localizedMessage;

    /**
     * Constructs a new FOP exception with the specified detail message.
     * @param message the detail message.
     */
    public FOPException(String message) {
        super(message);
    }

    /**
     * Constructs a new FOP exception with the specified detail message and location.
     * @param message the detail message
     * @param systemId the system id of the FO document which is associated with the exception
     *                 may be null.
     * @param line line number in the FO document which is associated with the exception.
     * @param column clolumn number in the line which is associated with the exception.
     */
    public FOPException(String message, String systemId, int line, int column) {
        super(message);
        this.systemId = systemId;
        this.line = line;
        this.column = column;
    }

    /**
     * Constructs a new FOP exception with the specified detail message and location.
     * @param message the detail message.
     * @param locator the locator holding the location.
     */
    public FOPException(String message, Locator locator) {
        super(message);
        setLocator(locator);
    }


    /**
     * Constructs a new FOP exception with the specified cause.
     * @param cause the cause.
     */
    public FOPException(Exception cause) {
        super(cause);
    }

    /**
     * Constructs a new exception with the specified detail message and cause.
     * @param message  the detail message
     * @param cause the cause
     */
    public FOPException(String message, Exception cause) {
        super(message, cause);
    }

    /**
     * Set a location associated with the exception.
     * @param locator the locator holding the location.
     */
    public void setLocator(Locator locator) {
        if (locator != null) {
            this.systemId = locator.getSystemId();
            this.line = locator.getLineNumber();
            this.column = locator.getColumnNumber();
        }
    }

    /**
     * Set a location associated with the exception.
     * @param systemId the system id of the FO document which is associated with the exception;
     *                 may be null.
     * @param line line number in the FO document which is associated with the exception.
     * @param column column number in the line which is associated with the exception.
     */
    public void setLocation(String systemId, int line, int column) {
        this.systemId = systemId;
        this.line = line;
        this.column = column;
    }

    /**
     * Indicate whether a location was set.
     * @return whether a location was set
     */
    public boolean isLocationSet() {
        // TODO: this is actually a dangerous assumption: A line
        // number of 0 or -1 might be used to indicate an unknown line
        // number, while the system ID might still be of use.
        return line > 0;
    }

    /**
     * Returns the detail message string of this FOP exception.
     * If a location was set, the message is prepended with it in the
     * form
     * <pre>
     *  SystemId:LL:CC: &amp;the message&amp;
     * </pre>
     * (the format used by most GNU tools)
     * @return the detail message string of this FOP exception
     */
    public String getMessage() {
        if (isLocationSet()) {
            return systemId + ":" + line + ":" + column + ": " + super.getMessage();
        } else {
            return super.getMessage();
        }
    }

    /**
     * Attempts to recast the exception as other Throwable types.
     * @return the exception recast as another type if possible, otherwise null.
     */
    protected Throwable getRootException() {
        Throwable result = getException();

        if (result instanceof SAXException) {
            result = ((SAXException)result).getException();
        }
        if (result instanceof java.lang.reflect.InvocationTargetException) {
            result
                = ((java.lang.reflect.InvocationTargetException)result).getTargetException();
        }
        if (result != getException()) {
            return result;
        }
        return null;
    }

    /**
     * Prints this FOP exception and its backtrace to the standard error stream.
     */
    public void printStackTrace() {
        synchronized (System.err) {
            super.printStackTrace();
            if (getException() != null) {
                System.err.println(EXCEPTION_SEPARATOR);
                getException().printStackTrace();
            }
            if (getRootException() != null) {
                System.err.println(EXCEPTION_SEPARATOR);
                getRootException().printStackTrace();
            }
        }
    }

    /**
     * Prints this FOP exception and its backtrace to the specified print stream.
     * @param stream PrintStream to use for output
     */
    public void printStackTrace(java.io.PrintStream stream) {
        synchronized (stream) {
            super.printStackTrace(stream);
            if (getException() != null) {
                stream.println(EXCEPTION_SEPARATOR);
                getException().printStackTrace(stream);
            }
            if (getRootException() != null) {
                stream.println(EXCEPTION_SEPARATOR);
                getRootException().printStackTrace(stream);
            }
        }
    }

    /**
     * Prints this FOP exception and its backtrace to the specified print writer.
     * @param writer PrintWriter to use for output
     */
    public void printStackTrace(java.io.PrintWriter writer) {
        synchronized (writer) {
            super.printStackTrace(writer);
            if (getException() != null) {
                writer.println(EXCEPTION_SEPARATOR);
                getException().printStackTrace(writer);
            }
            if (getRootException() != null) {
                writer.println(EXCEPTION_SEPARATOR);
                getRootException().printStackTrace(writer);
            }
        }
    }

    /**
     * Sets the localized message for this exception.
     * @param msg the localized message
     */
    public void setLocalizedMessage(String msg) {
        this.localizedMessage = msg;
    }

    /** {@inheritDoc} */
    public String getLocalizedMessage() {
        if (this.localizedMessage != null) {
            return this.localizedMessage;
        } else {
            return super.getLocalizedMessage();
        }
    }



}
87
            
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(File userConfigFile) throws SAXException, IOException { try { DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); setUserConfig(cfgBuilder.buildFromFile(userConfigFile)); } catch (ConfigurationException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(String uri) throws SAXException, IOException { try { DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); setUserConfig(cfgBuilder.build(uri)); } catch (ConfigurationException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
private void setBaseURI() throws FOPException { String loc = cfg.getLocation(); try { if (loc != null && loc.startsWith("file:")) { baseURI = new URI(loc); baseURI = baseURI.resolve(".").normalize(); } if (baseURI == null) { baseURI = new File(System.getProperty("user.dir")).toURI(); } } catch (URISyntaxException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
public Maker findFOMaker(String namespaceURI, String localName, Locator locator) throws FOPException { Map<String, Maker> table = fobjTable.get(namespaceURI); Maker fobjMaker = null; if (table != null) { fobjMaker = table.get(localName); // try default if (fobjMaker == null) { fobjMaker = table.get(ElementMapping.DEFAULT); } } if (fobjMaker == null) { if (namespaces.containsKey(namespaceURI.intern())) { throw new FOPException(FONode.errorText(locator) + "No element mapping definition found for " + FONode.getNodeString(namespaceURI, localName), locator); } else { fobjMaker = new UnknownXMLObj.Maker(namespaceURI); } } return fobjMaker; }
// in src/java/org/apache/fop/fonts/FontReader.java
private void createFont(InputSource source) throws FOPException { XMLReader parser = null; try { final SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); parser = factory.newSAXParser().getXMLReader(); } catch (Exception e) { throw new FOPException(e); } if (parser == null) { throw new FOPException("Unable to create SAX parser"); } try { parser.setFeature("http://xml.org/sax/features/namespace-prefixes", false); } catch (SAXException e) { throw new FOPException("You need a SAX parser which supports SAX version 2", e); } parser.setContentHandler(this); try { parser.parse(source); } catch (SAXException e) { throw new FOPException(e); } catch (IOException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/fonts/substitute/FontSubstitutionsConfigurator.java
private static FontQualifier getQualfierFromConfiguration(Configuration cfg) throws FOPException { String fontFamily = cfg.getAttribute("font-family", null); if (fontFamily == null) { throw new FOPException("substitution qualifier must have a font-family"); } FontQualifier qualifier = new FontQualifier(); qualifier.setFontFamily(fontFamily); String fontWeight = cfg.getAttribute("font-weight", null); if (fontWeight != null) { qualifier.setFontWeight(fontWeight); } String fontStyle = cfg.getAttribute("font-style", null); if (fontStyle != null) { qualifier.setFontStyle(fontStyle); } return qualifier; }
// in src/java/org/apache/fop/fonts/substitute/FontSubstitutionsConfigurator.java
public void configure(FontSubstitutions substitutions) throws FOPException { Configuration[] substitutionCfgs = cfg.getChildren("substitution"); for (int i = 0; i < substitutionCfgs.length; i++) { Configuration fromCfg = substitutionCfgs[i].getChild("from", false); if (fromCfg == null) { throw new FOPException("'substitution' element without child 'from' element"); } Configuration toCfg = substitutionCfgs[i].getChild("to", false); if (fromCfg == null) { throw new FOPException("'substitution' element without child 'to' element"); } FontQualifier fromQualifier = getQualfierFromConfiguration(fromCfg); FontQualifier toQualifier = getQualfierFromConfiguration(toCfg); FontSubstitution substitution = new FontSubstitution(fromQualifier, toQualifier); substitutions.add(substitution); } }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
private void setPDFDocVersion(Configuration cfg, PDFRenderingUtil pdfUtil) throws FOPException { Configuration pdfVersion = cfg.getChild(PDFConfigurationConstants.PDF_VERSION, false); if (pdfVersion != null) { String version = pdfVersion.getValue(null); if (version != null && version.length() != 0) { try { pdfUtil.setPDFVersion(version); } catch (IllegalArgumentException e) { throw new FOPException(e.getMessage()); } } else { throw new FOPException("The PDF version has not been set."); } } }
// in src/java/org/apache/fop/render/RendererFactory.java
public FOEventHandler createFOEventHandler(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { if (userAgent.getFOEventHandlerOverride() != null) { return userAgent.getFOEventHandlerOverride(); } else { AbstractFOEventHandlerMaker maker = getFOEventHandlerMaker(outputFormat); if (maker != null) { return maker.makeFOEventHandler(userAgent, out); } else { AbstractRendererMaker rendMaker = getRendererMaker(outputFormat); AbstractIFDocumentHandlerMaker documentHandlerMaker = null; boolean outputStreamMissing = (userAgent.getRendererOverride() == null) && (userAgent.getDocumentHandlerOverride() == null); if (rendMaker == null) { documentHandlerMaker = getDocumentHandlerMaker(outputFormat); if (documentHandlerMaker != null) { outputStreamMissing &= (out == null) && (documentHandlerMaker.needsOutputStream()); } } else { outputStreamMissing &= (out == null) && (rendMaker.needsOutputStream()); } if (userAgent.getRendererOverride() != null || rendMaker != null || userAgent.getDocumentHandlerOverride() != null || documentHandlerMaker != null) { if (outputStreamMissing) { throw new FOPException( "OutputStream has not been set"); } //Found a Renderer so we need to construct an AreaTreeHandler. return new AreaTreeHandler(userAgent, outputFormat, out); } else { throw new UnsupportedOperationException( "Don't know how to handle \"" + outputFormat + "\" as an output format." + " Neither an FOEventHandler, nor a Renderer could be found" + " for this output format."); } } } }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
private void configure(Configuration cfg, PCLRenderingUtil pclUtil) throws FOPException { String rendering = cfg.getChild("rendering").getValue(null); if (rendering != null) { try { pclUtil.setRenderingMode(PCLRenderingMode.valueOf(rendering)); } catch (IllegalArgumentException e) { throw new FOPException( "Valid values for 'rendering' are 'quality', 'speed' and 'bitmap'." + " Value found: " + rendering); } } String textRendering = cfg.getChild("text-rendering").getValue(null); if ("bitmap".equalsIgnoreCase(textRendering)) { pclUtil.setAllTextAsBitmaps(true); } else if ("auto".equalsIgnoreCase(textRendering)) { pclUtil.setAllTextAsBitmaps(false); } else if (textRendering != null) { throw new FOPException( "Valid values for 'text-rendering' are 'auto' and 'bitmap'. Value found: " + textRendering); } pclUtil.setPJLDisabled(cfg.getChild("disable-pjl").getValueAsBoolean(false)); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public RtfTableCell newTableCellMergedHorizontally (int cellWidth, RtfAttributes attrs) throws IOException, FOPException { highestCell++; // Added by Normand Masse // Inherit attributes from base cell for merge RtfAttributes wAttributes = null; if (attrs != null) { try { wAttributes = (RtfAttributes)attrs.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } } cell = new RtfTableCell(this, writer, cellWidth, wAttributes, highestCell); cell.setHMerge(RtfTableCell.MERGE_WITH_PREVIOUS); return cell; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfText.java
public RtfAttributes getTextContainerAttributes() throws FOPException { if (attrib == null) { return null; } try { return (RtfAttributes)this.attrib.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfAttributes getTextContainerAttributes() throws FOPException { if (attrib == null) { return null; } try { return (RtfAttributes)this.attrib.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public RtfAttributes getTextContainerAttributes() throws FOPException { if (attrib == null) { return null; } try { return (RtfAttributes) this.attrib.clone (); } catch (CloneNotSupportedException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
public RtfTableRow newTableRow(RtfAttributes attrs) throws IOException, FOPException { RtfAttributes attr = null; if (attrib != null) { try { attr = (RtfAttributes) attrib.clone (); } catch (CloneNotSupportedException e) { throw new FOPException(e); } attr.set (attrs); } else { attr = attrs; } if (row != null) { row.close(); } highestRow++; row = new RtfTableRow(this, writer, attr, highestRow); return row; }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
private float numberToTwips(String number, String units) throws FOPException { float result = 0; // convert number to integer try { if (number != null && number.trim().length() > 0) { result = Float.valueOf(number).floatValue(); } } catch (Exception e) { throw new FOPException("number format error: cannot convert '" + number + "' to float value"); } // find conversion factor if (units != null && units.trim().length() > 0) { final Float factor = (Float)TWIP_FACTORS.get(units.toLowerCase()); if (factor == null) { throw new FOPException("conversion factor not found for '" + units + "' units"); } result *= factor.floatValue(); } return result; }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
int convertFontSize(String size) throws FOPException { size = size.trim(); final String sFONTSUFFIX = FixedLength.POINT; if (!size.endsWith(sFONTSUFFIX)) { throw new FOPException("Invalid font size '" + size + "', must end with '" + sFONTSUFFIX + "'"); } float result = 0; size = size.substring(0, size.length() - sFONTSUFFIX.length()); try { result = (Float.valueOf(size).floatValue()); } catch (Exception e) { throw new FOPException("Invalid font size value '" + size + "'"); } // RTF font size units are in half-points return (int)(result * 2.0); }
// in src/java/org/apache/fop/render/bitmap/BitmapRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { super.configure(documentHandler); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { AbstractBitmapDocumentHandler bitmapHandler = (AbstractBitmapDocumentHandler)documentHandler; BitmapRenderingSettings settings = bitmapHandler.getSettings(); boolean transparent = cfg.getChild( Java2DRenderer.JAVA2D_TRANSPARENT_PAGE_BACKGROUND).getValueAsBoolean( settings.hasTransparentPageBackground()); if (transparent) { settings.setPageBackgroundColor(null); } else { String background = cfg.getChild("background-color").getValue(null); if (background != null) { settings.setPageBackgroundColor( ColorUtil.parseColorString(this.userAgent, background)); } } boolean antiAliasing = cfg.getChild("anti-aliasing").getValueAsBoolean( settings.isAntiAliasingEnabled()); settings.setAntiAliasing(antiAliasing); String optimization = cfg.getChild("rendering").getValue(null); if ("quality".equalsIgnoreCase(optimization)) { settings.setQualityRendering(true); } else if ("speed".equalsIgnoreCase(optimization)) { settings.setQualityRendering(false); } String color = cfg.getChild("color-mode").getValue(null); if (color != null) { if ("rgba".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_INT_ARGB); } else if ("rgb".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_INT_RGB); } else if ("gray".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_BYTE_GRAY); } else if ("binary".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_BYTE_BINARY); } else if ("bi-level".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_BYTE_BINARY); } else { throw new FOPException("Invalid value for color-mode: " + color); } } } }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private void configure(AFPCustomizable customizable, Configuration cfg) throws FOPException { // image information Configuration imagesCfg = cfg.getChild("images"); // default to grayscale images String imagesMode = imagesCfg.getAttribute("mode", IMAGES_MODE_GRAYSCALE); if (IMAGES_MODE_COLOR.equals(imagesMode)) { customizable.setColorImages(true); boolean cmyk = imagesCfg.getAttributeAsBoolean("cmyk", false); customizable.setCMYKImagesSupported(cmyk); } else { customizable.setColorImages(false); // default to 8 bits per pixel int bitsPerPixel = imagesCfg.getAttributeAsInteger("bits-per-pixel", 8); customizable.setBitsPerPixel(bitsPerPixel); } String dithering = imagesCfg.getAttribute("dithering-quality", "medium"); float dq = 0.5f; if (dithering.startsWith("min")) { dq = 0.0f; } else if (dithering.startsWith("max")) { dq = 1.0f; } else { try { dq = Float.parseFloat(dithering); } catch (NumberFormatException nfe) { //ignore and leave the default above } } customizable.setDitheringQuality(dq); // native image support boolean nativeImageSupport = imagesCfg.getAttributeAsBoolean("native", false); customizable.setNativeImagesSupported(nativeImageSupport); Configuration jpegConfig = imagesCfg.getChild("jpeg"); boolean allowEmbedding = false; float ieq = 1.0f; if (jpegConfig != null) { allowEmbedding = jpegConfig.getAttributeAsBoolean("allow-embedding", false); String bitmapEncodingQuality = jpegConfig.getAttribute("bitmap-encoding-quality", null); if (bitmapEncodingQuality != null) { try { ieq = Float.parseFloat(bitmapEncodingQuality); } catch (NumberFormatException nfe) { //ignore and leave the default above } } } customizable.canEmbedJpeg(allowEmbedding); customizable.setBitmapEncodingQuality(ieq); //FS11 and FS45 page segment wrapping boolean pSeg = imagesCfg.getAttributeAsBoolean("pseg", false); customizable.setWrapPSeg(pSeg); //FS45 image forcing boolean fs45 = imagesCfg.getAttributeAsBoolean("fs45", false); customizable.setFS45(fs45); // shading (filled rectangles) Configuration shadingCfg = cfg.getChild("shading"); AFPShadingMode shadingMode = AFPShadingMode.valueOf( shadingCfg.getValue(AFPShadingMode.COLOR.getName())); customizable.setShadingMode(shadingMode); // GOCA Support Configuration gocaCfg = cfg.getChild("goca"); boolean gocaEnabled = gocaCfg.getAttributeAsBoolean( "enabled", customizable.isGOCAEnabled()); customizable.setGOCAEnabled(gocaEnabled); String gocaText = gocaCfg.getAttribute( "text", customizable.isStrokeGOCAText() ? "stroke" : "default"); customizable.setStrokeGOCAText("stroke".equalsIgnoreCase(gocaText) || "shapes".equalsIgnoreCase(gocaText)); // renderer resolution Configuration rendererResolutionCfg = cfg.getChild("renderer-resolution", false); if (rendererResolutionCfg != null) { customizable.setResolution(rendererResolutionCfg.getValueAsInteger(240)); } // renderer resolution Configuration lineWidthCorrectionCfg = cfg.getChild("line-width-correction", false); if (lineWidthCorrectionCfg != null) { customizable.setLineWidthCorrection(lineWidthCorrectionCfg .getValueAsFloat(AFPConstants.LINE_WIDTH_CORRECTION)); } // a default external resource group file setting Configuration resourceGroupFileCfg = cfg.getChild("resource-group-file", false); if (resourceGroupFileCfg != null) { String resourceGroupDest = null; try { resourceGroupDest = resourceGroupFileCfg.getValue(); if (resourceGroupDest != null) { File resourceGroupFile = new File(resourceGroupDest); boolean created = resourceGroupFile.createNewFile(); if (created && resourceGroupFile.canWrite()) { customizable.setDefaultResourceGroupFilePath(resourceGroupDest); } else { log.warn("Unable to write to default external resource group file '" + resourceGroupDest + "'"); } } } catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); } catch (IOException ioe) { throw new FOPException("Could not create default external resource group file" , ioe); } } Configuration defaultResourceLevelCfg = cfg.getChild("default-resource-levels", false); if (defaultResourceLevelCfg != null) { AFPResourceLevelDefaults defaults = new AFPResourceLevelDefaults(); String[] types = defaultResourceLevelCfg.getAttributeNames(); for (int i = 0, c = types.length; i < c; i++) { String type = types[i]; try { String level = defaultResourceLevelCfg.getAttribute(type); defaults.setDefaultResourceLevel(type, AFPResourceLevel.valueOf(level)); } catch (IllegalArgumentException iae) { LogUtil.handleException(log, iae, userAgent.getFactory().validateUserConfigStrictly()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); } } customizable.setResourceLevelDefaults(defaults); } }
// in src/java/org/apache/fop/render/afp/extensions/AbstractAFPExtensionObject.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { getExtensionAttachment(); String attr = attlist.getValue("name"); if (attr != null && attr.length() > 0) { extensionAttachment.setName(attr); } else { throw new FOPException(elementName + " must have a name attribute."); } }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public void renderPage(PageViewport pageViewport) throws IOException, FOPException { try { rememberPage((PageViewport)pageViewport.clone()); } catch (CloneNotSupportedException e) { throw new FOPException(e); } //The clone() call is necessary as we store the page for later. Otherwise, the //RenderPagesModel calls PageViewport.clear() to release memory as early as possible. currentPageNumber++; }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public PageViewport getPageViewport(int pageIndex) throws FOPException { if (pageIndex < 0 || pageIndex >= pageViewportList.size()) { throw new FOPException("Requested page number is out of range: " + pageIndex + "; only " + pageViewportList.size() + " page(s) available."); } return (PageViewport) pageViewportList.get(pageIndex); }
// in src/java/org/apache/fop/util/LogUtil.java
public static void handleException(Log log, Exception e, boolean strict) throws FOPException { if (strict) { if (e instanceof FOPException) { throw (FOPException)e; } throw new FOPException(e); } log.error(e.getMessage()); }
// in src/java/org/apache/fop/cli/AreaTreeInputHandler.java
public void renderTo(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { FontInfo fontInfo = new FontInfo(); AreaTreeModel treeModel = new RenderPagesModel(userAgent, outputFormat, fontInfo, out); //Iterate over all intermediate files AreaTreeParser parser = new AreaTreeParser(); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(parser.getContentHandler(treeModel, userAgent)); transformTo(res); try { treeModel.endDocument(); } catch (SAXException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/cli/InputHandler.java
protected void transformTo(Result result) throws FOPException { try { // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer; Source xsltSource = createXSLTSource(); if (xsltSource == null) { // FO Input transformer = factory.newTransformer(); } else { // XML/XSLT input transformer = factory.newTransformer(xsltSource); // Set the value of parameters, if any, defined for stylesheet if (xsltParams != null) { for (int i = 0; i < xsltParams.size(); i += 2) { transformer.setParameter((String) xsltParams.elementAt(i), (String) xsltParams.elementAt(i + 1)); } } if (uriResolver != null) { transformer.setURIResolver(uriResolver); } } transformer.setErrorListener(this); // Create a SAXSource from the input Source file Source src = createMainSource(); // Start XSLT transformation and FOP processing transformer.transform(src, result); } catch (Exception e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private boolean parseOptions(String[] args) throws FOPException { // do not throw an exception for no args if (args.length == 0) { printVersion(); printUsage(System.out); return false; } for (int i = 0; i < args.length; i++) { if (args[i].equals("-x") || args[i].equals("--dump-config")) { showConfiguration = Boolean.TRUE; } else if (args[i].equals("-c")) { i = i + parseConfigurationOption(args, i); } else if (args[i].equals("-l")) { i = i + parseLanguageOption(args, i); } else if (args[i].equals("-s")) { suppressLowLevelAreas = Boolean.TRUE; } else if (args[i].equals("-d")) { setLogOption("debug", "debug"); } else if (args[i].equals("-r")) { factory.setStrictValidation(false); } else if (args[i].equals("-conserve")) { conserveMemoryPolicy = true; } else if (args[i].equals("-flush")) { flushCache = true; } else if (args[i].equals("-cache")) { parseCacheOption(args, i); } else if (args[i].equals("-dpi")) { i = i + parseResolution(args, i); } else if (args[i].equals("-q") || args[i].equals("--quiet")) { setLogOption("quiet", "error"); } else if (args[i].equals("-fo")) { i = i + parseFOInputOption(args, i); } else if (args[i].equals("-xsl")) { i = i + parseXSLInputOption(args, i); } else if (args[i].equals("-xml")) { i = i + parseXMLInputOption(args, i); } else if (args[i].equals("-atin")) { i = i + parseAreaTreeInputOption(args, i); } else if (args[i].equals("-ifin")) { i = i + parseIFInputOption(args, i); } else if (args[i].equals("-imagein")) { i = i + parseImageInputOption(args, i); } else if (args[i].equals("-awt")) { i = i + parseAWTOutputOption(args, i); } else if (args[i].equals("-pdf")) { i = i + parsePDFOutputOption(args, i, null); } else if (args[i].equals("-pdfa1b")) { i = i + parsePDFOutputOption(args, i, "PDF/A-1b"); } else if (args[i].equals("-mif")) { i = i + parseMIFOutputOption(args, i); } else if (args[i].equals("-rtf")) { i = i + parseRTFOutputOption(args, i); } else if (args[i].equals("-tiff")) { i = i + parseTIFFOutputOption(args, i); } else if (args[i].equals("-png")) { i = i + parsePNGOutputOption(args, i); } else if (args[i].equals("-print")) { // show print help if (i + 1 < args.length) { if (args[i + 1].equals("help")) { printUsagePrintOutput(); return false; } } i = i + parsePrintOutputOption(args, i); } else if (args[i].equals("-copies")) { i = i + parseCopiesOption(args, i); } else if (args[i].equals("-pcl")) { i = i + parsePCLOutputOption(args, i); } else if (args[i].equals("-ps")) { i = i + parsePostscriptOutputOption(args, i); } else if (args[i].equals("-txt")) { i = i + parseTextOutputOption(args, i); } else if (args[i].equals("-svg")) { i = i + parseSVGOutputOption(args, i); } else if (args[i].equals("-afp")) { i = i + parseAFPOutputOption(args, i); } else if (args[i].equals("-foout")) { i = i + parseFOOutputOption(args, i); } else if (args[i].equals("-out")) { i = i + parseCustomOutputOption(args, i); } else if (args[i].equals("-at")) { i = i + parseAreaTreeOption(args, i); } else if (args[i].equals("-if")) { i = i + parseIntermediateFormatOption(args, i); } else if (args[i].equals("-a")) { this.renderingOptions.put(Accessibility.ACCESSIBILITY, Boolean.TRUE); } else if (args[i].equals("-v")) { /* verbose mode although users may expect version; currently just print the version */ printVersion(); if (args.length == 1) { return false; } } else if (args[i].equals("-param")) { if (i + 2 < args.length) { String name = args[++i]; String expression = args[++i]; addXSLTParameter(name, expression); } else { throw new FOPException("invalid param usage: use -param <name> <value>"); } } else if (args[i].equals("-catalog")) { useCatalogResolver = true; } else if (args[i].equals("-o")) { i = i + parsePDFOwnerPassword(args, i); } else if (args[i].equals("-u")) { i = i + parsePDFUserPassword(args, i); } else if (args[i].equals("-pdfprofile")) { i = i + parsePDFProfile(args, i); } else if (args[i].equals("-noprint")) { getPDFEncryptionParams().setAllowPrint(false); } else if (args[i].equals("-nocopy")) { getPDFEncryptionParams().setAllowCopyContent(false); } else if (args[i].equals("-noedit")) { getPDFEncryptionParams().setAllowEditContent(false); } else if (args[i].equals("-noannotations")) { getPDFEncryptionParams().setAllowEditAnnotations(false); } else if (args[i].equals("-nocs")) { useComplexScriptFeatures = false; } else if (args[i].equals("-nofillinforms")) { getPDFEncryptionParams().setAllowFillInForms(false); } else if (args[i].equals("-noaccesscontent")) { getPDFEncryptionParams().setAllowAccessContent(false); } else if (args[i].equals("-noassembledoc")) { getPDFEncryptionParams().setAllowAssembleDocument(false); } else if (args[i].equals("-noprinthq")) { getPDFEncryptionParams().setAllowPrintHq(false); } else if (args[i].equals("-version")) { printVersion(); return false; } else if (!isOption(args[i])) { i = i + parseUnknownOption(args, i); } else { printUsage(System.err); System.exit(1); } } return true; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseCacheOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("if you use '-cache', you must specify " + "the name of the font cache file"); } else { factory.getFontManager().setCacheFile(new File(args[i + 1])); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseConfigurationOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("if you use '-c', you must specify " + "the name of the configuration file"); } else { userConfigFile = new File(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseLanguageOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("if you use '-l', you must specify a language"); } else { Locale.setDefault(new Locale(args[i + 1], "")); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseResolution(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException( "if you use '-dpi', you must specify a resolution (dots per inch)"); } else { this.targetResolution = Integer.parseInt(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseFOInputOption(String[] args, int i) throws FOPException { setInputFormat(FO_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the fo file for the '-fo' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { fofile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseXSLInputOption(String[] args, int i) throws FOPException { setInputFormat(XSLT_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the stylesheet " + "file for the '-xsl' option"); } else { xsltfile = new File(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseXMLInputOption(String[] args, int i) throws FOPException { setInputFormat(XSLT_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the input file " + "for the '-xml' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { xmlfile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePDFOutputOption(String[] args, int i, String pdfAMode) throws FOPException { setOutputMode(MimeConstants.MIME_PDF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PDF output file"); } else { setOutputFile(args[i + 1]); if (pdfAMode != null) { if (renderingOptions.get("pdf-a-mode") != null) { throw new FOPException("PDF/A mode already set"); } renderingOptions.put("pdf-a-mode", pdfAMode); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseMIFOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_MIF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the MIF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseRTFOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_RTF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the RTF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseTIFFOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_TIFF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the TIFF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePNGOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_PNG); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PNG output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseCopiesOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the number of copies"); } else { renderingOptions.put(PrintRenderer.COPIES, new Integer(args[i + 1])); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePCLOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_PCL); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PDF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePostscriptOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_POSTSCRIPT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PostScript output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseTextOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_PLAIN_TEXT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the text output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseSVGOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_SVG); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the SVG output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAFPOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_AFP); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the AFP output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseFOOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_XSL_FO); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the FO output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseCustomOutputOption(String[] args, int i) throws FOPException { String mime = null; if ((i + 1 < args.length) || (args[i + 1].charAt(0) != '-')) { mime = args[i + 1]; if ("list".equals(mime)) { String[] mimes = factory.getRendererFactory().listSupportedMimeTypes(); System.out.println("Supported MIME types:"); for (int j = 0; j < mimes.length; j++) { System.out.println(" " + mimes[j]); } System.exit(0); } } if ((i + 2 >= args.length) || (isOption(args[i + 1])) || (isOption(args[i + 2]))) { throw new FOPException("you must specify the output format and the output file"); } else { setOutputMode(mime); setOutputFile(args[i + 2]); return 2; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseUnknownOption(String[] args, int i) throws FOPException { if (inputmode == NOT_SET) { inputmode = FO_INPUT; String filename = args[i]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { fofile = new File(filename); } } else if (outputmode == null) { outputmode = MimeConstants.MIME_PDF; setOutputFile(args[i]); } else { throw new FOPException("Don't know what to do with " + args[i]); } return 0; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAreaTreeOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_FOP_AREA_TREE); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the area-tree output file"); } else if ((i + 2 == args.length) || (isOption(args[i + 2]))) { // only output file is specified setOutputFile(args[i + 1]); return 1; } else { // mimic format and output file have been specified mimicRenderer = args[i + 1]; setOutputFile(args[i + 2]); return 2; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseIntermediateFormatOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_FOP_IF); if ((i + 1 == args.length) || (args[i + 1].charAt(0) == '-')) { throw new FOPException("you must specify the intermediate format output file"); } else if ((i + 2 == args.length) || (args[i + 2].charAt(0) == '-')) { // only output file is specified setOutputFile(args[i + 1]); return 1; } else { // mimic format and output file have been specified mimicRenderer = args[i + 1]; setOutputFile(args[i + 2]); return 2; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAreaTreeInputOption(String[] args, int i) throws FOPException { setInputFormat(AREATREE_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the Area Tree file for the '-atin' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { areatreefile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseIFInputOption(String[] args, int i) throws FOPException { setInputFormat(IF_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the intermediate file for the '-ifin' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { iffile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseImageInputOption(String[] args, int i) throws FOPException { setInputFormat(IMAGE_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the image file for the '-imagein' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { imagefile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private PDFEncryptionParams getPDFEncryptionParams() throws FOPException { PDFEncryptionParams params = (PDFEncryptionParams)renderingOptions.get( PDFConfigurationConstants.ENCRYPTION_PARAMS); if (params == null) { if (!PDFEncryptionManager.checkAvailableAlgorithms()) { throw new FOPException("PDF encryption requested but it is not available." + " Please make sure MD5 and RC4 algorithms are available."); } params = new PDFEncryptionParams(); renderingOptions.put(PDFConfigurationConstants.ENCRYPTION_PARAMS, params); } return params; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePDFProfile(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("You must specify a PDF profile"); } else { String profile = args[i + 1]; PDFAMode pdfAMode = PDFAMode.valueOf(profile); if (pdfAMode != null && pdfAMode != PDFAMode.DISABLED) { if (renderingOptions.get("pdf-a-mode") != null) { throw new FOPException("PDF/A mode already set"); } renderingOptions.put("pdf-a-mode", pdfAMode.getName()); return 1; } else { PDFXMode pdfXMode = PDFXMode.valueOf(profile); if (pdfXMode != null && pdfXMode != PDFXMode.DISABLED) { if (renderingOptions.get("pdf-x-mode") != null) { throw new FOPException("PDF/X mode already set"); } renderingOptions.put("pdf-x-mode", pdfXMode.getName()); return 1; } } throw new FOPException("Unsupported PDF profile: " + profile); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setOutputMode(String mime) throws FOPException { if (outputmode == null) { outputmode = mime; } else { throw new FOPException("you can only set one output method"); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setInputFormat(int format) throws FOPException { if (inputmode == NOT_SET || inputmode == format) { inputmode = format; } else { throw new FOPException("Only one input mode can be specified!"); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void checkSettings() throws FOPException, FileNotFoundException { if (inputmode == NOT_SET) { throw new FOPException("No input file specified"); } if (outputmode == null) { throw new FOPException("No output file specified"); } if ((outputmode.equals(MimeConstants.MIME_FOP_AWT_PREVIEW) || outputmode.equals(MimeConstants.MIME_FOP_PRINT)) && outfile != null) { throw new FOPException("Output file may not be specified " + "for AWT or PRINT output"); } if (inputmode == XSLT_INPUT) { // check whether xml *and* xslt file have been set if (xmlfile == null && !this.useStdIn) { throw new FOPException("XML file must be specified for the transform mode"); } if (xsltfile == null) { throw new FOPException("XSLT file must be specified for the transform mode"); } // warning if fofile has been set in xslt mode if (fofile != null) { log.warn("Can't use fo file with transform mode! Ignoring.\n" + "Your input is " + "\n xmlfile: " + xmlfile.getAbsolutePath() + "\nxsltfile: " + xsltfile.getAbsolutePath() + "\n fofile: " + fofile.getAbsolutePath()); } if (xmlfile != null && !xmlfile.exists()) { throw new FileNotFoundException("Error: xml file " + xmlfile.getAbsolutePath() + " not found "); } if (!xsltfile.exists()) { throw new FileNotFoundException("Error: xsl file " + xsltfile.getAbsolutePath() + " not found "); } } else if (inputmode == FO_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (fofile != null && !fofile.exists()) { throw new FileNotFoundException("Error: fo file " + fofile.getAbsolutePath() + " not found "); } } else if (inputmode == AREATREE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Area Tree is used as input!"); } if (areatreefile != null && !areatreefile.exists()) { throw new FileNotFoundException("Error: area tree file " + areatreefile.getAbsolutePath() + " not found "); } } else if (inputmode == IF_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Intermediate Format" + " is used as input!"); } else if (outputmode.equals(MimeConstants.MIME_FOP_IF)) { throw new FOPException( "Intermediate Output is not available if Intermediate Format" + " is used as input!"); } if (iffile != null && !iffile.exists()) { throw new FileNotFoundException("Error: intermediate format file " + iffile.getAbsolutePath() + " not found "); } } else if (inputmode == IMAGE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (imagefile != null && !imagefile.exists()) { throw new FileNotFoundException("Error: image file " + imagefile.getAbsolutePath() + " not found "); } } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setUserConfig() throws FOPException, IOException { if (userConfigFile == null) { return; } try { factory.setUserConfig(userConfigFile); } catch (SAXException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
protected String getOutputFormat() throws FOPException { if (outputmode == null) { throw new FOPException("Renderer has not been set!"); } if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { renderingOptions.put("fineDetail", isCoarseAreaXml()); } return outputmode; }
// in src/java/org/apache/fop/cli/IFInputHandler.java
public void renderTo(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { IFDocumentHandler documentHandler = userAgent.getFactory().getRendererFactory().createDocumentHandler( userAgent, outputFormat); try { documentHandler.setResult(new StreamResult(out)); IFUtil.setupFonts(documentHandler); //Create IF parser IFParser parser = new IFParser(); // Resulting SAX events are sent to the parser Result res = new SAXResult(parser.getContentHandler(documentHandler, userAgent)); transformTo(res); } catch (IFException ife) { throw new FOPException(ife); } }
24
            
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (ConfigurationException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (URISyntaxException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException("You need a SAX parser which supports SAX version 2", e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (IOException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException(e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException( "Valid values for 'rendering' are 'quality', 'speed' and 'bitmap'." + " Value found: " + rendering); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfText.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("number format error: cannot convert '" + number + "' to float value"); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
catch (Exception e) { throw new FOPException("Invalid font size value '" + size + "'"); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IOException ioe) { throw new FOPException("Could not create default external resource group file" , ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/area/PageViewport.java
catch (CloneNotSupportedException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/AreaTreeInputHandler.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (Exception e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/IFInputHandler.java
catch (IFException ife) { throw new FOPException(ife); }
380
            
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(String outputFormat) throws FOPException { return newFop(outputFormat, newFOUserAgent()); }
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(String outputFormat, FOUserAgent userAgent) throws FOPException { return newFop(outputFormat, userAgent, null); }
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(String outputFormat, OutputStream stream) throws FOPException { return newFop(outputFormat, newFOUserAgent(), stream); }
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(String outputFormat, FOUserAgent userAgent, OutputStream stream) throws FOPException { if (userAgent == null) { throw new NullPointerException("The userAgent parameter must not be null!"); } return new Fop(outputFormat, userAgent, stream); }
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(FOUserAgent userAgent) throws FOPException { if (userAgent.getRendererOverride() == null && userAgent.getFOEventHandlerOverride() == null && userAgent.getDocumentHandlerOverride() == null) { throw new IllegalStateException("An overriding renderer," + " FOEventHandler or IFDocumentHandler must be set on the user agent" + " when this factory method is used!"); } return newFop(null, userAgent); }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setUserConfig(Configuration userConfig) throws FOPException { config.setUserConfig(userConfig); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void configure(FopFactory factory) throws FOPException { // CSOK: MethodLength // strict configuration if (cfg.getChild("strict-configuration", false) != null) { try { factory.setStrictUserConfigValidation( cfg.getChild("strict-configuration").getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, false); } } boolean strict = factory.validateUserConfigStrictly(); if (log.isDebugEnabled()) { log.debug("Initializing FopFactory Configuration" + "with " + (strict ? "strict" : "permissive") + " validation"); } if (cfg.getChild("accessibility", false) != null) { try { this.factory.setAccessibility( cfg.getChild("accessibility").getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); } } // strict fo validation if (cfg.getChild("strict-validation", false) != null) { try { factory.setStrictValidation( cfg.getChild("strict-validation").getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); } } // base definitions for relative path resolution if (cfg.getChild("base", false) != null) { String path = cfg.getChild("base").getValue(null); if (baseURI != null) { path = baseURI.resolve(path).normalize().toString(); } try { factory.setBaseURL(path); } catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, strict); } } if (cfg.getChild("hyphenation-base", false) != null) { String path = cfg.getChild("hyphenation-base").getValue(null); if (baseURI != null) { path = baseURI.resolve(path).normalize().toString(); } try { factory.setHyphenBaseURL(path); } catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, strict); } } /** * Read configuration elements hyphenation-pattern, * construct a map ll_CC => filename, and set it on the factory */ Configuration[] hyphPatConfig = cfg.getChildren("hyphenation-pattern"); if (hyphPatConfig.length != 0) { Map/*<String,String>*/ hyphPatNames = new HashMap/*<String,String>*/(); for (int i = 0; i < hyphPatConfig.length; ++i) { String lang; String country; String filename; StringBuffer error = new StringBuffer(); String location = hyphPatConfig[i].getLocation(); lang = hyphPatConfig[i].getAttribute("lang", null); if (lang == null) { addError("The lang attribute of a hyphenation-pattern configuration" + " element must exist (" + location + ")", error); } else if (!lang.matches("[a-zA-Z]{2}")) { addError("The lang attribute of a hyphenation-pattern configuration" + " element must consist of exactly two letters (" + location + ")", error); } lang = lang.toLowerCase(); country = hyphPatConfig[i].getAttribute("country", null); if ("".equals(country)) { country = null; } if (country != null) { if (!country.matches("[a-zA-Z]{2}")) { addError("The country attribute of a hyphenation-pattern configuration" + " element must consist of exactly two letters (" + location + ")", error); } country = country.toUpperCase(); } filename = hyphPatConfig[i].getValue(null); if (filename == null) { addError("The value of a hyphenation-pattern configuration" + " element may not be empty (" + location + ")", error); } if (error.length() != 0) { LogUtil.handleError(log, error.toString(), strict); continue; } String llccKey = HyphenationTreeCache.constructLlccKey(lang, country); hyphPatNames.put(llccKey, filename); if (log.isDebugEnabled()) { log.debug("Using hyphenation pattern filename " + filename + " for lang=\"" + lang + "\"" + (country != null ? ", country=\"" + country + "\"" : "")); } } factory.setHyphPatNames(hyphPatNames); } // renderer options if (cfg.getChild("source-resolution", false) != null) { factory.setSourceResolution( cfg.getChild("source-resolution").getValueAsFloat( FopFactoryConfigurator.DEFAULT_SOURCE_RESOLUTION)); if (log.isDebugEnabled()) { log.debug("source-resolution set to: " + factory.getSourceResolution() + "dpi (px2mm=" + factory.getSourcePixelUnitToMillimeter() + ")"); } } if (cfg.getChild("target-resolution", false) != null) { factory.setTargetResolution( cfg.getChild("target-resolution").getValueAsFloat( FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION)); if (log.isDebugEnabled()) { log.debug("target-resolution set to: " + factory.getTargetResolution() + "dpi (px2mm=" + factory.getTargetPixelUnitToMillimeter() + ")"); } } if (cfg.getChild("break-indent-inheritance", false) != null) { try { factory.setBreakIndentInheritanceOnReferenceAreaBoundary( cfg.getChild("break-indent-inheritance").getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); } } Configuration pageConfig = cfg.getChild("default-page-settings"); if (pageConfig.getAttribute("height", null) != null) { factory.setPageHeight( pageConfig.getAttribute("height", FopFactoryConfigurator.DEFAULT_PAGE_HEIGHT)); if (log.isInfoEnabled()) { log.info("Default page-height set to: " + factory.getPageHeight()); } } if (pageConfig.getAttribute("width", null) != null) { factory.setPageWidth( pageConfig.getAttribute("width", FopFactoryConfigurator.DEFAULT_PAGE_WIDTH)); if (log.isInfoEnabled()) { log.info("Default page-width set to: " + factory.getPageWidth()); } } // prefer Renderer over IFDocumentHandler if (cfg.getChild(PREFER_RENDERER, false) != null) { try { factory.getRendererFactory().setRendererPreferred( cfg.getChild(PREFER_RENDERER).getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); } } // configure complex script support Configuration csConfig = cfg.getChild("complex-scripts"); if (csConfig != null) { this.factory.setComplexScriptFeaturesEnabled (!csConfig.getAttributeAsBoolean ( "disabled", false )); } // configure font manager new FontManagerConfigurator(cfg, baseURI).configure(factory.getFontManager(), strict); // configure image loader framework configureImageLoading(cfg.getChild("image-loading", false), strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
private void configureImageLoading(Configuration parent, boolean strict) throws FOPException { if (parent == null) { return; } ImageImplRegistry registry = factory.getImageManager().getRegistry(); Configuration[] penalties = parent.getChildren("penalty"); try { for (int i = 0, c = penalties.length; i < c; i++) { Configuration penaltyCfg = penalties[i]; String className = penaltyCfg.getAttribute("class"); String value = penaltyCfg.getAttribute("value"); Penalty p = null; if (value.toUpperCase().startsWith("INF")) { p = Penalty.INFINITE_PENALTY; } else { try { p = Penalty.toPenalty(Integer.parseInt(value)); } catch (NumberFormatException nfe) { LogUtil.handleException(log, nfe, strict); } } if (p != null) { registry.setAdditionalPenalty(className, p); } } } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); } }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(Configuration cfg) throws FOPException { this.cfg = cfg; setBaseURI(); configure(this.factory); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
private void setBaseURI() throws FOPException { String loc = cfg.getLocation(); try { if (loc != null && loc.startsWith("file:")) { baseURI = new URI(loc); baseURI = baseURI.resolve(".").normalize(); } if (baseURI == null) { baseURI = new File(System.getProperty("user.dir")).toURI(); } } catch (URISyntaxException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/apps/Fop.java
private void createDefaultHandler() throws FOPException { this.foTreeBuilder = new FOTreeBuilder(outputFormat, foUserAgent, stream); }
// in src/java/org/apache/fop/apps/Fop.java
public DefaultHandler getDefaultHandler() throws FOPException { if (foTreeBuilder == null) { createDefaultHandler(); } return this.foTreeBuilder; }
// in src/java/org/apache/fop/tools/fontlist/FontListGenerator.java
public SortedMap listFonts(FopFactory fopFactory, String mime, FontEventListener listener) throws FOPException { FontInfo fontInfo = setupFonts(fopFactory, mime, listener); SortedMap fontFamilies = buildFamilyMap(fontInfo); return fontFamilies; }
// in src/java/org/apache/fop/tools/fontlist/FontListGenerator.java
private FontInfo setupFonts(FopFactory fopFactory, String mime, FontEventListener listener) throws FOPException { FOUserAgent userAgent = fopFactory.newFOUserAgent(); //The document handler is only instantiated to get access to its configurator! IFDocumentHandler documentHandler = fopFactory.getRendererFactory().createDocumentHandler(userAgent, mime); IFDocumentHandlerConfigurator configurator = documentHandler.getConfigurator(); FontInfo fontInfo = new FontInfo(); configurator.setupFontInfo(documentHandler, fontInfo); return fontInfo; }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private ContentHandler getFOPContentHandler(OutputStream out) throws FOPException { Fop fop = fopFactory.newFop(this.outputMime, out); return fop.getDefaultHandler(); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
public void run() throws FOPException { //Set base directory if (task.getBasedir() != null) { try { this.baseURL = task.getBasedir().toURI().toURL().toExternalForm(); } catch (MalformedURLException mfue) { logger.error("Error creating base URL from base directory", mfue); } } else { try { if (task.getFofile() != null) { this.baseURL = task.getFofile().getParentFile().toURI().toURL() .toExternalForm(); } } catch (MalformedURLException mfue) { logger.error("Error creating base URL from XSL-FO input file", mfue); } } task.log("Using base URL: " + baseURL, Project.MSG_DEBUG); String outputFormat = normalizeOutputFormat(task.getFormat()); String newExtension = determineExtension(outputFormat); // actioncount = # of fofiles actually processed through FOP int actioncount = 0; // skippedcount = # of fofiles which haven't changed (force = "false") int skippedcount = 0; // deal with single source file if (task.getFofile() != null) { if (task.getFofile().exists()) { File outf = task.getOutfile(); if (outf == null) { throw new BuildException("outfile is required when fofile is used"); } if (task.getOutdir() != null) { outf = new File(task.getOutdir(), outf.getName()); } // Render if "force" flag is set OR // OR output file doesn't exist OR // output file is older than input file if (task.getForce() || !outf.exists() || (task.getFofile().lastModified() > outf.lastModified() )) { render(task.getFofile(), outf, outputFormat); actioncount++; } else if (outf.exists() && (task.getFofile().lastModified() <= outf.lastModified() )) { skippedcount++; } } } else if (task.getXmlFile() != null && task.getXsltFile() != null) { if (task.getXmlFile().exists() && task.getXsltFile().exists()) { File outf = task.getOutfile(); if (outf == null) { throw new BuildException("outfile is required when fofile is used"); } if (task.getOutdir() != null) { outf = new File(task.getOutdir(), outf.getName()); } // Render if "force" flag is set OR // OR output file doesn't exist OR // output file is older than input file if (task.getForce() || !outf.exists() || (task.getXmlFile().lastModified() > outf.lastModified() || task.getXsltFile().lastModified() > outf.lastModified())) { render(task.getXmlFile(), task.getXsltFile(), outf, outputFormat); actioncount++; } else if (outf.exists() && (task.getXmlFile().lastModified() <= outf.lastModified() || task.getXsltFile().lastModified() <= outf.lastModified())) { skippedcount++; } } } GlobPatternMapper mapper = new GlobPatternMapper(); String inputExtension = ".fo"; File xsltFile = task.getXsltFile(); if (xsltFile != null) { inputExtension = ".xml"; } mapper.setFrom("*" + inputExtension); mapper.setTo("*" + newExtension); // deal with the filesets for (int i = 0; i < task.getFilesets().size(); i++) { FileSet fs = (FileSet) task.getFilesets().get(i); DirectoryScanner ds = fs.getDirectoryScanner(task.getProject()); String[] files = ds.getIncludedFiles(); for (int j = 0; j < files.length; j++) { File f = new File(fs.getDir(task.getProject()), files[j]); File outf = null; if (task.getOutdir() != null && files[j].endsWith(inputExtension)) { String[] sa = mapper.mapFileName(files[j]); outf = new File(task.getOutdir(), sa[0]); } else { outf = replaceExtension(f, inputExtension, newExtension); if (task.getOutdir() != null) { outf = new File(task.getOutdir(), outf.getName()); } } File dir = outf.getParentFile(); if (!dir.exists()) { dir.mkdirs(); } try { if (task.getRelativebase()) { this.baseURL = f.getParentFile().toURI().toURL() .toExternalForm(); } if (this.baseURL == null) { this.baseURL = fs.getDir(task.getProject()).toURI().toURL() .toExternalForm(); } } catch (Exception e) { task.log("Error setting base URL", Project.MSG_DEBUG); } // Render if "force" flag is set OR // OR output file doesn't exist OR // output file is older than input file if (task.getForce() || !outf.exists() || (f.lastModified() > outf.lastModified() )) { if (xsltFile != null) { render(f, xsltFile, outf, outputFormat); } else { render(f, outf, outputFormat); } actioncount++; } else if (outf.exists() && (f.lastModified() <= outf.lastModified() )) { skippedcount++; } } } if (actioncount + skippedcount == 0) { task.log("No files processed. No files were selected by the filesets " + "and no fofile was set." , Project.MSG_WARN); } else if (skippedcount > 0) { task.log(skippedcount + " xslfo file(s) skipped (no change found" + " since last generation; set force=\"true\" to override)." , Project.MSG_INFO); } }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
private void render(File foFile, File outFile, String outputFormat) throws FOPException { InputHandler inputHandler = new InputHandler(foFile); try { renderInputHandler(inputHandler, outFile, outputFormat); } catch (Exception ex) { logger.error("Error rendering fo file: " + foFile, ex); } if (task.getLogFiles()) { task.log(foFile + " -> " + outFile, Project.MSG_INFO); } }
// in src/java/org/apache/fop/servlet/FopPrintServlet.java
protected void render(Source src, Transformer transformer, HttpServletResponse response) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_FOP_PRINT, foUserAgent); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer.transform(src, res); //Return the result reportOK(response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void renderFO(String fo, HttpServletResponse response) throws FOPException, TransformerException, IOException { //Setup source Source foSrc = convertString2Source(fo); //Setup the identity transformation Transformer transformer = this.transFactory.newTransformer(); transformer.setURIResolver(this.uriResolver); //Start transformation and rendering process render(foSrc, transformer, response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void renderXML(String xml, String xslt, HttpServletResponse response) throws FOPException, TransformerException, IOException { //Setup sources Source xmlSrc = convertString2Source(xml); Source xsltSrc = convertString2Source(xslt); //Setup the XSL transformation Transformer transformer = this.transFactory.newTransformer(xsltSrc); transformer.setURIResolver(this.uriResolver); //Start transformation and rendering process render(xmlSrc, transformer, response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void render(Source src, Transformer transformer, HttpServletResponse response) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(); //Setup output ByteArrayOutputStream out = new ByteArrayOutputStream(); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer.transform(src, res); //Return the result sendPDF(out.toByteArray(), response); }
// in src/java/org/apache/fop/fo/UnknownXMLObj.java
protected void characters(char[] data, int start, int length, PropertyList pList, Locator locator) throws FOPException { if (doc == null) { createBasicDocument(); } super.characters(data, start, length, pList, locator); }
// in src/java/org/apache/fop/fo/XMLObj.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { setLocator(locator); name = elementName; attr = attlist; }
// in src/java/org/apache/fop/fo/XMLObj.java
protected void characters(char[] data, int start, int length, PropertyList pList, Locator locator) throws FOPException { super.characters(data, start, length, pList, locator); String str = new String(data, start, length); org.w3c.dom.Text text = doc.createTextNode(str); element.appendChild(text); }
// in src/java/org/apache/fop/fo/FObjMixed.java
Override protected void characters(char[] data, int start, int length, PropertyList pList, Locator locator) throws FOPException { if (ft == null) { ft = new FOText(this); ft.setLocator(locator); if (!inMarker()) { ft.bind(pList); } } ft.characters(data, start, length, null, null); }
// in src/java/org/apache/fop/fo/FObjMixed.java
Override protected void endOfNode() throws FOPException { super.endOfNode(); if (!inMarker() || getNameId() == FO_MARKER) { // send character[s]() events to the FOEventHandler sendCharacters(); } }
// in src/java/org/apache/fop/fo/FObjMixed.java
private void flushText() throws FOPException { if (ft != null) { FOText lft = ft; /* make sure nested calls to itself have no effect */ ft = null; if (getNameId() == FO_BLOCK) { lft.createBlockPointers((org.apache.fop.fo.flow.Block) this); this.lastFOTextProcessed = lft; } else if (getNameId() != FO_MARKER && getNameId() != FO_TITLE && getNameId() != FO_BOOKMARK_TITLE) { FONode fo = parent; int foNameId = fo.getNameId(); while (foNameId != FO_BLOCK && foNameId != FO_MARKER && foNameId != FO_TITLE && foNameId != FO_BOOKMARK_TITLE && foNameId != FO_PAGE_SEQUENCE) { fo = fo.getParent(); foNameId = fo.getNameId(); } if (foNameId == FO_BLOCK) { lft.createBlockPointers((org.apache.fop.fo.flow.Block) fo); ((FObjMixed) fo).lastFOTextProcessed = lft; } else if (foNameId == FO_PAGE_SEQUENCE && lft.willCreateArea()) { log.error("Could not create block pointers." + " FOText w/o Block ancestor."); } } this.addChildNode(lft); } }
// in src/java/org/apache/fop/fo/FObjMixed.java
private void sendCharacters() throws FOPException { if (this.currentTextNode != null) { FONodeIterator nodeIter = this.getChildNodes(this.currentTextNode); FONode node; while (nodeIter.hasNext()) { node = nodeIter.nextNode(); assert (node instanceof FOText || node.getNameId() == FO_CHARACTER); if (node.getNameId() == FO_CHARACTER) { node.startOfNode(); } node.endOfNode(); } } this.currentTextNode = null; }
// in src/java/org/apache/fop/fo/FObjMixed.java
Override protected void addChildNode(FONode child) throws FOPException { flushText(); if (!inMarker()) { if (child instanceof FOText || child.getNameId() == FO_CHARACTER) { if (this.currentTextNode == null) { this.currentTextNode = child; } } else { // handle white-space for all text up to here handleWhiteSpaceFor(this, child); // send character[s]() events to the FOEventHandler sendCharacters(); } } super.addChildNode(child); }
// in src/java/org/apache/fop/fo/FObjMixed.java
Override public void finalizeNode() throws FOPException { flushText(); if (!inMarker() || getNameId() == FO_MARKER) { handleWhiteSpaceFor(this, null); } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void characters(char[] data, int start, int length) throws FOPException { if (currentFObj != null) { currentFObj.characters(data, start, length, currentPropertyList, getEffectiveLocator()); } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
private Maker findFOMaker(String namespaceURI, String localName) throws FOPException { Maker maker = elementMappingRegistry.findFOMaker(namespaceURI, localName, locator); if (maker instanceof UnknownXMLObj.Maker) { FOValidationEventProducer eventProducer = FOValidationEventProducer.Provider.get( userAgent.getEventBroadcaster()); String name = (currentFObj != null ? currentFObj.getName() : "{" + namespaceURI + "}" + localName); eventProducer.unknownFormattingObject(this, name, new QName(namespaceURI, localName), getEffectiveLocator()); } return maker; }
// in src/java/org/apache/fop/fo/flow/AbstractListItemPart.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); }
// in src/java/org/apache/fop/fo/flow/AbstractListItemPart.java
protected void endOfNode() throws FOPException { if (!this.blockItemFound) { String contentModel = "marker* (%block;)+"; getFOValidationEventProducer().missingChildElement(this, getName(), contentModel, true, getLocator()); } }
// in src/java/org/apache/fop/fo/flow/ListItemBody.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startListBody(this); }
// in src/java/org/apache/fop/fo/flow/ListItemBody.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endListBody(this); }
// in src/java/org/apache/fop/fo/flow/ListItemLabel.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startListLabel(this); }
// in src/java/org/apache/fop/fo/flow/ListItemLabel.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endListLabel(this); }
// in src/java/org/apache/fop/fo/flow/ListItem.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonMarginBlock = pList.getMarginBlockProps(); breakAfter = pList.get(PR_BREAK_AFTER).getEnum(); breakBefore = pList.get(PR_BREAK_BEFORE).getEnum(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); }
// in src/java/org/apache/fop/fo/flow/ListItem.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startListItem(this); }
// in src/java/org/apache/fop/fo/flow/ListItem.java
protected void endOfNode() throws FOPException { if (label == null || body == null) { missingChildElementError("marker* (list-item-label,list-item-body)"); } getFOEventHandler().endListItem(this); }
// in src/java/org/apache/fop/fo/flow/RetrieveTableMarker.java
public void processNode (String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { if (findAncestor(FO_TABLE_HEADER) < 0 && findAncestor(FO_TABLE_FOOTER) < 0) { invalidChildError(locator, getParent().getName(), FO_URI, getName(), "rule.retrieveTableMarkerDescendantOfHeaderOrFooter"); } else { super.processNode(elementName, locator, attlist, pList); } }
// in src/java/org/apache/fop/fo/flow/RetrieveTableMarker.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); this.retrievePositionWithinTable = pList.get(PR_RETRIEVE_POSITION_WITHIN_TABLE).getEnum(); this.retrieveBoundaryWithinTable = pList.get(PR_RETRIEVE_BOUNDARY_WITHIN_TABLE).getEnum(); }
// in src/java/org/apache/fop/fo/flow/Float.java
public void bind(PropertyList pList) throws FOPException { // No active properties -> Nothing to do. }
// in src/java/org/apache/fop/fo/flow/Float.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("(%block;)+"); } }
// in src/java/org/apache/fop/fo/flow/PageNumber.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonFont = pList.getFontProps(); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); // letterSpacing = pList.get(PR_LETTER_SPACING); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); textDecoration = pList.getTextDecorationProps(); // textShadow = pList.get(PR_TEXT_SHADOW); // implicit properties color = pList.get(Constants.PR_COLOR).getColor(getUserAgent()); }
// in src/java/org/apache/fop/fo/flow/PageNumber.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startPageNumber(this); }
// in src/java/org/apache/fop/fo/flow/PageNumber.java
protected void endOfNode() throws FOPException { getFOEventHandler().endPageNumber(this); }
// in src/java/org/apache/fop/fo/flow/Wrapper.java
Override public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/flow/Wrapper.java
Override protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startWrapper(this); }
// in src/java/org/apache/fop/fo/flow/Wrapper.java
Override protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endWrapper(this); }
// in src/java/org/apache/fop/fo/flow/Wrapper.java
protected void addChildNode(FONode child) throws FOPException { super.addChildNode(child); /* If the child is a text node, and it generates areas * (i.e. contains either non-white-space or preserved * white-space), then check whether the nearest non-wrapper * ancestor allows this. */ if (child instanceof FOText && ((FOText)child).willCreateArea()) { FONode ancestor = parent; while (ancestor.getNameId() == Constants.FO_WRAPPER) { ancestor = ancestor.getParent(); } if (!(ancestor instanceof FObjMixed)) { invalidChildError( getLocator(), getLocalName(), FONode.FO_URI, "#PCDATA", "rule.wrapperInvalidChildForParent"); } } }
// in src/java/org/apache/fop/fo/flow/PageNumberCitationLast.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startPageNumberCitationLast(this); }
// in src/java/org/apache/fop/fo/flow/PageNumberCitationLast.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endPageNumberCitationLast(this); }
// in src/java/org/apache/fop/fo/flow/InlineContainer.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonMarginInline = pList.getMarginInlineProps(); clip = pList.get(PR_CLIP).getEnum(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); inlineProgressionDimension = pList.get(PR_INLINE_PROGRESSION_DIMENSION).getLengthRange(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); overflow = pList.get(PR_OVERFLOW).getEnum(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); writingModeTraits = new WritingModeTraits ( WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()) ); }
// in src/java/org/apache/fop/fo/flow/InlineContainer.java
protected void endOfNode() throws FOPException { if (!blockItemFound) { missingChildElementError("marker* (%block;)+"); } }
// in src/java/org/apache/fop/fo/flow/InlineLevel.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonMarginInline = pList.getMarginInlineProps(); commonFont = pList.getFontProps(); color = pList.get(PR_COLOR).getColor(getUserAgent()); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); }
// in src/java/org/apache/fop/fo/flow/MultiCase.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); startingState = pList.get(PR_STARTING_STATE).getEnum(); // caseName = pList.get(PR_CASE_NAME); // caseTitle = pList.get(PR_CASE_TITLE); }
// in src/java/org/apache/fop/fo/flow/BasicLink.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); // destinationPlacementOffset = pList.get(PR_DESTINATION_PLACEMENT_OFFSET); externalDestination = pList.get(PR_EXTERNAL_DESTINATION).getString(); // indicateDestination = pList.get(PR_INDICATE_DESTINATION); internalDestination = pList.get(PR_INTERNAL_DESTINATION).getString(); showDestination = pList.get(PR_SHOW_DESTINATION).getEnum(); // targetProcessingContext = pList.get(PR_TARGET_PROCESSING_CONTEXT); // targetPresentationContext = pList.get(PR_TARGET_PRESENTATION_CONTEXT); // targetStylesheet = pList.get(PR_TARGET_STYLESHEET); // per spec, internal takes precedence if both specified if (internalDestination.length() > 0) { externalDestination = null; } else if (externalDestination.length() == 0) { // slightly stronger than spec "should be specified" getFOValidationEventProducer().missingLinkDestination(this, getName(), locator); } }
// in src/java/org/apache/fop/fo/flow/BasicLink.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startLink(this); }
// in src/java/org/apache/fop/fo/flow/BasicLink.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endLink(this); }
// in src/java/org/apache/fop/fo/flow/FootnoteBody.java
public void bind(PropertyList pList) throws FOPException { commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/flow/FootnoteBody.java
protected void startOfNode() throws FOPException { getFOEventHandler().startFootnoteBody(this); }
// in src/java/org/apache/fop/fo/flow/FootnoteBody.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("(%block;)+"); } getFOEventHandler().endFootnoteBody(this); }
// in src/java/org/apache/fop/fo/flow/Leader.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); }
// in src/java/org/apache/fop/fo/flow/Leader.java
Override protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startLeader(this); }
// in src/java/org/apache/fop/fo/flow/Leader.java
Override protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endLeader(this); }
// in src/java/org/apache/fop/fo/flow/InitialPropertySet.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); // letterSpacing = pList.get(PR_LETTER_SPACING); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); // textShadow = pList.get(PR_TEXT_SHADOW); }
// in src/java/org/apache/fop/fo/flow/AbstractPageNumberCitation.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonFont = pList.getFontProps(); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); // letterSpacing = pList.get(PR_LETTER_SPACING); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); refId = pList.get(PR_REF_ID).getString(); textDecoration = pList.getTextDecorationProps(); // textShadow = pList.get(PR_TEXT_SHADOW); // implicit properties color = pList.get(Constants.PR_COLOR).getColor(getUserAgent()); }
// in src/java/org/apache/fop/fo/flow/AbstractPageNumberCitation.java
public void processNode (String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { super.processNode(elementName, locator, attlist, pList); if (!inMarker() && (refId == null || "".equals(refId))) { missingPropertyError("ref-id"); } }
// in src/java/org/apache/fop/fo/flow/ListBlock.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonMarginBlock = pList.getMarginBlockProps(); breakAfter = pList.get(PR_BREAK_AFTER).getEnum(); breakBefore = pList.get(PR_BREAK_BEFORE).getEnum(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); //Bind extension properties widowContentLimit = pList.get(PR_X_WIDOW_CONTENT_LIMIT).getLength(); orphanContentLimit = pList.get(PR_X_ORPHAN_CONTENT_LIMIT).getLength(); }
// in src/java/org/apache/fop/fo/flow/ListBlock.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startList(this); }
// in src/java/org/apache/fop/fo/flow/ListBlock.java
protected void endOfNode() throws FOPException { if (!hasListItem) { missingChildElementError("marker* (list-item)+"); } getFOEventHandler().endList(this); }
// in src/java/org/apache/fop/fo/flow/Inline.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); }
// in src/java/org/apache/fop/fo/flow/Inline.java
protected void startOfNode() throws FOPException { super.startOfNode(); /* Check to see if this node can have block-level children. * See validateChildNode() below. */ int lvlLeader = findAncestor(FO_LEADER); int lvlFootnote = findAncestor(FO_FOOTNOTE); int lvlInCntr = findAncestor(FO_INLINE_CONTAINER); if (lvlLeader > 0) { if (lvlInCntr < 0 || (lvlInCntr > 0 && lvlInCntr > lvlLeader)) { canHaveBlockLevelChildren = false; } } else if (lvlFootnote > 0) { if (lvlInCntr < 0 || lvlInCntr > lvlFootnote) { canHaveBlockLevelChildren = false; } } getFOEventHandler().startInline(this); }
// in src/java/org/apache/fop/fo/flow/Inline.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endInline(this); }
// in src/java/org/apache/fop/fo/flow/MultiToggle.java
public void bind(PropertyList pList) throws FOPException { // prSwitchTo = pList.get(PR_SWITCH_TO); }
// in src/java/org/apache/fop/fo/flow/InstreamForeignObject.java
Override protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startInstreamForeignObject(this); }
// in src/java/org/apache/fop/fo/flow/InstreamForeignObject.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("one (1) non-XSL namespace child"); } getFOEventHandler().endInstreamForeignObject(this); }
// in src/java/org/apache/fop/fo/flow/InstreamForeignObject.java
protected void addChildNode(FONode child) throws FOPException { super.addChildNode(child); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); src = pList.get(PR_SRC).getString(); //Additional processing: obtain the image's intrinsic size and baseline information url = URISpecification.getURL(src); FOUserAgent userAgent = getUserAgent(); ImageManager manager = userAgent.getFactory().getImageManager(); ImageInfo info = null; try { info = manager.getImageInfo(url, userAgent.getImageSessionContext()); } catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, url, e, getLocator()); } catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, url, fnfe, getLocator()); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, url, ioe, getLocator()); } if (info != null) { this.intrinsicWidth = info.getSize().getWidthMpt(); this.intrinsicHeight = info.getSize().getHeightMpt(); int baseline = info.getSize().getBaselinePositionFromBottom(); if (baseline != 0) { this.intrinsicAlignmentAdjust = FixedLength.getInstance(-baseline); } } }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().image(this); }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); this.retrieveClassName = pList.get(PR_RETRIEVE_CLASS_NAME).getString(); if (retrieveClassName == null || retrieveClassName.equals("")) { missingPropertyError("retrieve-class-name"); } this.propertyList = pList.getParentPropertyList(); }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
private void cloneSingleNode(FONode child, FONode newParent, Marker marker, PropertyList parentPropertyList) throws FOPException { if (child != null) { FONode newChild = child.clone(newParent, true); if (child instanceof FObj) { Marker.MarkerPropertyList pList; PropertyList newPropertyList = createPropertyListFor( (FObj) newChild, parentPropertyList); pList = marker.getPropertyListFor(child); newChild.processNode( child.getLocalName(), getLocator(), pList, newPropertyList); addChildTo(newChild, newParent); switch ( newChild.getNameId() ) { case FO_TABLE: Table t = (Table) child; cloneSubtree(t.getColumns().iterator(), newChild, marker, newPropertyList); cloneSingleNode(t.getTableHeader(), newChild, marker, newPropertyList); cloneSingleNode(t.getTableFooter(), newChild, marker, newPropertyList); cloneSubtree(child.getChildNodes(), newChild, marker, newPropertyList); break; case FO_LIST_ITEM: ListItem li = (ListItem) child; cloneSingleNode(li.getLabel(), newChild, marker, newPropertyList); cloneSingleNode(li.getBody(), newChild, marker, newPropertyList); break; default: cloneSubtree(child.getChildNodes(), newChild, marker, newPropertyList); break; } } else if (child instanceof FOText) { FOText ft = (FOText) newChild; ft.bind(parentPropertyList); addChildTo(newChild, newParent); } else if (child instanceof XMLObj) { addChildTo(newChild, newParent); } // trigger end-of-node white-space handling // and finalization for table-FOs newChild.finalizeNode(); } }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
private void cloneSubtree(Iterator parentIter, FONode newParent, Marker marker, PropertyList parentPropertyList) throws FOPException { if (parentIter != null) { FONode child; while (parentIter.hasNext()) { child = (FONode) parentIter.next(); cloneSingleNode(child, newParent, marker, parentPropertyList); } } }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
private void cloneFromMarker(Marker marker) throws FOPException { cloneSubtree(marker.getChildNodes(), this, marker, propertyList); handleWhiteSpaceFor(this, null); }
// in src/java/org/apache/fop/fo/flow/MultiProperties.java
protected void endOfNode() throws FOPException { if (!hasMultiPropertySet || !hasWrapper) { missingChildElementError("(multi-property-set+, wrapper)"); } }
// in src/java/org/apache/fop/fo/flow/PageNumberCitation.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startPageNumberCitation(this); }
// in src/java/org/apache/fop/fo/flow/PageNumberCitation.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endPageNumberCitation(this); }
// in src/java/org/apache/fop/fo/flow/BlockContainer.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAbsolutePosition = pList.getAbsolutePositionProps(); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonMarginBlock = pList.getMarginBlockProps(); blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); breakAfter = pList.get(PR_BREAK_AFTER).getEnum(); breakBefore = pList.get(PR_BREAK_BEFORE).getEnum(); // clip = pList.get(PR_CLIP); displayAlign = pList.get(PR_DISPLAY_ALIGN).getEnum(); inlineProgressionDimension = pList.get(PR_INLINE_PROGRESSION_DIMENSION).getLengthRange(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); overflow = pList.get(PR_OVERFLOW).getEnum(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); span = pList.get(PR_SPAN).getEnum(); writingModeTraits = new WritingModeTraits ( WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()) ); disableColumnBalancing = pList.get(PR_X_DISABLE_COLUMN_BALANCING).getEnum(); }
// in src/java/org/apache/fop/fo/flow/BlockContainer.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startBlockContainer(this); }
// in src/java/org/apache/fop/fo/flow/BlockContainer.java
protected void endOfNode() throws FOPException { if (!blockItemFound) { missingChildElementError("marker* (%block;)+"); } getFOEventHandler().endBlockContainer(this); }
// in src/java/org/apache/fop/fo/flow/BidiOverride.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); letterSpacing = pList.get(PR_LETTER_SPACING); wordSpacing = pList.get(PR_WORD_SPACING); direction = pList.get(PR_DIRECTION).getEnum(); unicodeBidi = pList.get(PR_UNICODE_BIDI).getEnum(); }
// in src/java/org/apache/fop/fo/flow/AbstractGraphics.java
public void bind(PropertyList pList) throws FOPException { commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); // clip = pList.get(PR_CLIP); contentHeight = pList.get(PR_CONTENT_HEIGHT).getLength(); contentWidth = pList.get(PR_CONTENT_WIDTH).getLength(); displayAlign = pList.get(PR_DISPLAY_ALIGN).getEnum(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); height = pList.get(PR_HEIGHT).getLength(); id = pList.get(PR_ID).getString(); inlineProgressionDimension = pList.get(PR_INLINE_PROGRESSION_DIMENSION).getLengthRange(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); overflow = pList.get(PR_OVERFLOW).getEnum(); scaling = pList.get(PR_SCALING).getEnum(); textAlign = pList.get(PR_TEXT_ALIGN).getEnum(); width = pList.get(PR_WIDTH).getLength(); if (getUserAgent().isAccessibilityEnabled()) { altText = pList.get(PR_X_ALT_TEXT).getString(); if (altText.equals("")) { getFOValidationEventProducer().altTextMissing(this, getLocalName(), getLocator()); } } }
// in src/java/org/apache/fop/fo/flow/MultiPropertySet.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); // activeState = pList.get(PR_ACTIVE_STATE); }
// in src/java/org/apache/fop/fo/flow/RetrieveMarker.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { if (findAncestor(FO_STATIC_CONTENT) < 0) { invalidChildError(locator, getParent().getName(), FO_URI, getLocalName(), "rule.retrieveMarkerDescendantOfStaticContent"); } else { super.processNode(elementName, locator, attlist, pList); } }
// in src/java/org/apache/fop/fo/flow/RetrieveMarker.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); this.retrievePosition = pList.get(PR_RETRIEVE_POSITION).getEnum(); this.retrieveBoundary = pList.get(PR_RETRIEVE_BOUNDARY).getEnum(); }
// in src/java/org/apache/fop/fo/flow/Character.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonFont = pList.getFontProps(); commonHyphenation = pList.getHyphenationProps(); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); character = pList.get(PR_CHARACTER).getCharacter(); color = pList.get(PR_COLOR).getColor(getUserAgent()); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); letterSpacing = pList.get(PR_LETTER_SPACING); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); textDecoration = pList.getTextDecorationProps(); wordSpacing = pList.get(PR_WORD_SPACING); }
// in src/java/org/apache/fop/fo/flow/Character.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().character(this); }
// in src/java/org/apache/fop/fo/flow/Footnote.java
public void bind(PropertyList pList) throws FOPException { commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/flow/Footnote.java
protected void startOfNode() throws FOPException { getFOEventHandler().startFootnote(this); }
// in src/java/org/apache/fop/fo/flow/Footnote.java
protected void endOfNode() throws FOPException { super.endOfNode(); if (footnoteCitation == null || footnoteBody == null) { missingChildElementError("(inline,footnote-body)"); } getFOEventHandler().endFootnote(this); }
// in src/java/org/apache/fop/fo/flow/Marker.java
public void bind(PropertyList pList) throws FOPException { if (findAncestor(FO_FLOW) < 0) { invalidChildError(locator, getParent().getName(), FO_URI, getLocalName(), "rule.markerDescendantOfFlow"); } markerClassName = pList.get(PR_MARKER_CLASS_NAME).getString(); if (markerClassName == null || markerClassName.equals("")) { missingPropertyError("marker-class-name"); } }
// in src/java/org/apache/fop/fo/flow/Marker.java
protected void endOfNode() throws FOPException { super.endOfNode(); // Pop the MarkerPropertyList maker. getBuilderContext().setPropertyListMaker(savePropertyListMaker); savePropertyListMaker = null; }
// in src/java/org/apache/fop/fo/flow/Block.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonFont = pList.getFontProps(); commonHyphenation = pList.getHyphenationProps(); commonMarginBlock = pList.getMarginBlockProps(); commonRelativePosition = pList.getRelativePositionProps(); breakAfter = pList.get(PR_BREAK_AFTER).getEnum(); breakBefore = pList.get(PR_BREAK_BEFORE).getEnum(); color = pList.get(PR_COLOR).getColor(getUserAgent()); hyphenationKeep = pList.get(PR_HYPHENATION_KEEP).getEnum(); hyphenationLadderCount = pList.get(PR_HYPHENATION_LADDER_COUNT).getNumeric(); intrusionDisplace = pList.get(PR_INTRUSION_DISPLACE).getEnum(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); lastLineEndIndent = pList.get(PR_LAST_LINE_END_INDENT).getLength(); linefeedTreatment = pList.get(PR_LINEFEED_TREATMENT).getEnum(); lineHeight = pList.get(PR_LINE_HEIGHT).getSpace(); lineHeightShiftAdjustment = pList.get(PR_LINE_HEIGHT_SHIFT_ADJUSTMENT).getEnum(); lineStackingStrategy = pList.get(PR_LINE_STACKING_STRATEGY).getEnum(); orphans = pList.get(PR_ORPHANS).getNumeric(); whiteSpaceTreatment = pList.get(PR_WHITE_SPACE_TREATMENT).getEnum(); span = pList.get(PR_SPAN).getEnum(); textAlign = pList.get(PR_TEXT_ALIGN).getEnum(); textAlignLast = pList.get(PR_TEXT_ALIGN_LAST).getEnum(); textIndent = pList.get(PR_TEXT_INDENT).getLength(); whiteSpaceCollapse = pList.get(PR_WHITE_SPACE_COLLAPSE).getEnum(); widows = pList.get(PR_WIDOWS).getNumeric(); wrapOption = pList.get(PR_WRAP_OPTION).getEnum(); disableColumnBalancing = pList.get(PR_X_DISABLE_COLUMN_BALANCING).getEnum(); }
// in src/java/org/apache/fop/fo/flow/Block.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startBlock(this); }
// in src/java/org/apache/fop/fo/flow/Block.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endBlock(this); }
// in src/java/org/apache/fop/fo/flow/table/TableCellContainer.java
Override public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/flow/table/TableCellContainer.java
protected void addTableCellChild(TableCell cell, boolean firstRow) throws FOPException { int colNumber = cell.getColumnNumber(); int colSpan = cell.getNumberColumnsSpanned(); int rowSpan = cell.getNumberRowsSpanned(); Table t = getTable(); if (t.hasExplicitColumns()) { if (colNumber + colSpan - 1 > t.getNumberOfColumns()) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.tooManyCells(this, getLocator()); } } else { t.ensureColumnNumber(colNumber + colSpan - 1); // re-cap the size of pendingSpans while (pendingSpans.size() < colNumber + colSpan - 1) { pendingSpans.add(null); } } if (firstRow) { handleCellWidth(cell, colNumber, colSpan); } /* if the current cell spans more than one row, * update pending span list for the next row */ if (rowSpan > 1) { for (int i = 0; i < colSpan; i++) { pendingSpans.set(colNumber - 1 + i, new PendingSpan(rowSpan)); } } columnNumberManager.signalUsedColumnNumbers(colNumber, colNumber + colSpan - 1); t.getRowGroupBuilder().addTableCell(cell); }
// in src/java/org/apache/fop/fo/flow/table/TableCellContainer.java
private void handleCellWidth(TableCell cell, int colNumber, int colSpan) throws FOPException { Table t = getTable(); Length colWidth = null; if (cell.getWidth().getEnum() != EN_AUTO && colSpan == 1) { colWidth = cell.getWidth(); } for (int i = colNumber; i < colNumber + colSpan; ++i) { TableColumn col = t.getColumn(i - 1); if (colWidth != null) { col.setColumnWidth(colWidth); } } }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
public void bind(PropertyList pList) throws FOPException { blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); breakAfter = pList.get(PR_BREAK_AFTER).getEnum(); breakBefore = pList.get(PR_BREAK_BEFORE).getEnum(); height = pList.get(PR_HEIGHT).getLength(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); super.bind(pList); }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { super.processNode(elementName, locator, attlist, pList); if (!inMarker()) { TablePart part = (TablePart) parent; pendingSpans = part.pendingSpans; columnNumberManager = part.columnNumberManager; } }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
protected void addChildNode(FONode child) throws FOPException { if (!inMarker()) { TableCell cell = (TableCell) child; TablePart part = (TablePart) getParent(); addTableCellChild(cell, part.isFirst(this)); } super.addChildNode(child); }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startRow(this); }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endRow(this); }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
public void finalizeNode() throws FOPException { if (firstChild == null) { missingChildElementError("(table-cell+)"); } if (!inMarker()) { pendingSpans = null; columnNumberManager = null; } }
// in src/java/org/apache/fop/fo/flow/table/TableFooter.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startFooter(this); }
// in src/java/org/apache/fop/fo/flow/table/TableFooter.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endFooter(this); }
// in src/java/org/apache/fop/fo/flow/table/TableCell.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); displayAlign = pList.get(PR_DISPLAY_ALIGN).getEnum(); emptyCells = pList.get(PR_EMPTY_CELLS).getEnum(); startsRow = pList.get(PR_STARTS_ROW).getEnum(); // For properly computing columnNumber if (startsRow() && getParent().getNameId() != FO_TABLE_ROW) { ((TablePart) getParent()).signalNewRow(); } endsRow = pList.get(PR_ENDS_ROW).getEnum(); columnNumber = pList.get(PR_COLUMN_NUMBER).getNumeric().getValue(); numberColumnsSpanned = pList.get(PR_NUMBER_COLUMNS_SPANNED).getNumeric().getValue(); numberRowsSpanned = pList.get(PR_NUMBER_ROWS_SPANNED).getNumeric().getValue(); width = pList.get(PR_WIDTH).getLength(); }
// in src/java/org/apache/fop/fo/flow/table/TableCell.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startCell(this); }
// in src/java/org/apache/fop/fo/flow/table/TableCell.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endCell(this); }
// in src/java/org/apache/fop/fo/flow/table/TableCell.java
public void finalizeNode() throws FOPException { if (!blockItemFound) { missingChildElementError("marker* (%block;)+", true); } if ((startsRow() || endsRow()) && getParent().getNameId() == FO_TABLE_ROW ) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.startEndRowUnderTableRowWarning(this, getLocator()); } }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
public void bind(PropertyList pList) throws FOPException { commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); super.bind(pList); }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { super.processNode(elementName, locator, attlist, pList); if (!inMarker()) { Table t = getTable(); if (t.hasExplicitColumns()) { int size = t.getNumberOfColumns(); pendingSpans = new ArrayList(size); for (int i = 0; i < size; i++) { pendingSpans.add(null); } } else { pendingSpans = new ArrayList(); } columnNumberManager = new ColumnNumberManager(); } }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
public void finalizeNode() throws FOPException { if (!inMarker()) { pendingSpans = null; columnNumberManager = null; } if (!(tableRowsFound || tableCellsFound)) { missingChildElementError("marker* (table-row+|table-cell+)", true); getParent().removeChild(this); } else { finishLastRowGroup(); } }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
protected void addChildNode(FONode child) throws FOPException { if (!inMarker()) { switch (child.getNameId()) { case FO_TABLE_ROW: if (!rowsStarted) { getTable().getRowGroupBuilder().startTablePart(this); } else { columnNumberManager.prepareForNextRow(pendingSpans); getTable().getRowGroupBuilder().endTableRow(); } rowsStarted = true; getTable().getRowGroupBuilder().startTableRow((TableRow)child); break; case FO_TABLE_CELL: if (!rowsStarted) { getTable().getRowGroupBuilder().startTablePart(this); } rowsStarted = true; TableCell cell = (TableCell) child; addTableCellChild(cell, firstRow); lastCellEndsRow = cell.endsRow(); if (lastCellEndsRow) { firstRow = false; columnNumberManager.prepareForNextRow(pendingSpans); getTable().getRowGroupBuilder().endRow(this); } break; default: //nop } } //TODO: possible performance problems in case of large tables... //If the number of children grows significantly large, the default //implementation in FObj will get slower and slower... super.addChildNode(child); }
// in src/java/org/apache/fop/fo/flow/table/TableColumn.java
public void bind(PropertyList pList) throws FOPException { commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); columnNumber = pList.get(PR_COLUMN_NUMBER).getNumeric().getValue(); columnWidth = pList.get(PR_COLUMN_WIDTH).getLength(); numberColumnsRepeated = pList.get(PR_NUMBER_COLUMNS_REPEATED) .getNumeric().getValue(); numberColumnsSpanned = pList.get(PR_NUMBER_COLUMNS_SPANNED) .getNumeric().getValue(); super.bind(pList); if (numberColumnsRepeated <= 0) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.valueMustBeBiggerGtEqOne(this, "number-columns-repeated", numberColumnsRepeated, getLocator()); } if (numberColumnsSpanned <= 0) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.valueMustBeBiggerGtEqOne(this, "number-columns-spanned", numberColumnsSpanned, getLocator()); } /* check for unspecified width and replace with default of * proportional-column-width(1), in case of fixed table-layout * warn only for explicit columns */ if (columnWidth.getEnum() == EN_AUTO) { if (!this.implicitColumn && !getTable().isAutoLayout()) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.warnImplicitColumns(this, getLocator()); } columnWidth = new TableColLength(1.0, this); } /* in case of explicit columns, from-table-column() * can be used on descendants of the table-cells, so * we need a reference to the column's property list * (cleared in Table.endOfNode()) */ if (!this.implicitColumn) { this.pList = pList; } }
// in src/java/org/apache/fop/fo/flow/table/TableColumn.java
public void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startColumn(this); }
// in src/java/org/apache/fop/fo/flow/table/TableColumn.java
public void endOfNode() throws FOPException { getFOEventHandler().endColumn(this); }
// in src/java/org/apache/fop/fo/flow/table/TableCaption.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/flow/table/TableCaption.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("marker* (%block;)"); } }
// in src/java/org/apache/fop/fo/flow/table/TableFObj.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); borderAfterPrecedence = pList.get(PR_BORDER_AFTER_PRECEDENCE).getNumeric(); borderBeforePrecedence = pList.get(PR_BORDER_BEFORE_PRECEDENCE).getNumeric(); borderEndPrecedence = pList.get(PR_BORDER_END_PRECEDENCE).getNumeric(); borderStartPrecedence = pList.get(PR_BORDER_START_PRECEDENCE).getNumeric(); if (getNameId() != FO_TABLE //Separate check for fo:table in Table.java && getNameId() != FO_TABLE_CELL && getCommonBorderPaddingBackground().hasPadding( ValidationPercentBaseContext.getPseudoContext())) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.paddingNotApplicable(this, getName(), getLocator()); } }
// in src/java/org/apache/fop/fo/flow/table/TableFObj.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { super.processNode(elementName, locator, attlist, pList); Table table = getTable(); if (!inMarker() && !table.isSeparateBorderModel()) { collapsingBorderModel = CollapsingBorderModel.getBorderModelFor(table .getBorderCollapse()); setCollapsedBorders(); } }
// in src/java/org/apache/fop/fo/flow/table/TableBody.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startBody(this); }
// in src/java/org/apache/fop/fo/flow/table/TableBody.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endBody(this); }
// in src/java/org/apache/fop/fo/flow/table/Table.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); commonMarginBlock = pList.getMarginBlockProps(); blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); borderCollapse = pList.get(PR_BORDER_COLLAPSE).getEnum(); borderSeparation = pList.get(PR_BORDER_SEPARATION).getLengthPair(); breakAfter = pList.get(PR_BREAK_AFTER).getEnum(); breakBefore = pList.get(PR_BREAK_BEFORE).getEnum(); inlineProgressionDimension = pList.get(PR_INLINE_PROGRESSION_DIMENSION).getLengthRange(); keepTogether = pList.get(PR_KEEP_TOGETHER).getKeep(); keepWithNext = pList.get(PR_KEEP_WITH_NEXT).getKeep(); keepWithPrevious = pList.get(PR_KEEP_WITH_PREVIOUS).getKeep(); tableLayout = pList.get(PR_TABLE_LAYOUT).getEnum(); tableOmitFooterAtBreak = pList.get(PR_TABLE_OMIT_FOOTER_AT_BREAK).getEnum(); tableOmitHeaderAtBreak = pList.get(PR_TABLE_OMIT_HEADER_AT_BREAK).getEnum(); writingModeTraits = new WritingModeTraits ( WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()) ); //Bind extension properties widowContentLimit = pList.get(PR_X_WIDOW_CONTENT_LIMIT).getLength(); orphanContentLimit = pList.get(PR_X_ORPHAN_CONTENT_LIMIT).getLength(); if (!blockProgressionDimension.getOptimum(null).isAuto()) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.nonAutoBPDOnTable(this, getLocator()); // Anyway, the bpd of a table is not used by the layout code } if (tableLayout == EN_AUTO) { getFOValidationEventProducer().unimplementedFeature(this, getName(), "table-layout=\"auto\"", getLocator()); } if (!isSeparateBorderModel()) { if (borderCollapse == EN_COLLAPSE_WITH_PRECEDENCE) { getFOValidationEventProducer().unimplementedFeature(this, getName(), "border-collapse=\"collapse-with-precedence\"; defaulting to \"collapse\"", getLocator()); borderCollapse = EN_COLLAPSE; } if (getCommonBorderPaddingBackground().hasPadding( ValidationPercentBaseContext.getPseudoContext())) { //See "17.6.2 The collapsing border model" in CSS2 TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noTablePaddingWithCollapsingBorderModel(this, getLocator()); } } /* Store reference to the property list, so * new lists can be created in case the table has no * explicit columns * (see addDefaultColumn()) */ this.propList = pList; }
// in src/java/org/apache/fop/fo/flow/table/Table.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startTable(this); }
// in src/java/org/apache/fop/fo/flow/table/Table.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endTable(this); }
// in src/java/org/apache/fop/fo/flow/table/Table.java
public void finalizeNode() throws FOPException { if (!tableBodyFound) { missingChildElementError( "(marker*,table-column*,table-header?,table-footer?" + ",table-body+)"); } if (!hasChildren()) { getParent().removeChild(this); return; } if (!inMarker()) { rowGroupBuilder.endTable(); /* clean up */ for (int i = columns.size(); --i >= 0;) { TableColumn col = (TableColumn) columns.get(i); if (col != null) { col.releasePropertyList(); } } this.propList = null; rowGroupBuilder = null; } }
// in src/java/org/apache/fop/fo/flow/table/Table.java
protected void addChildNode(FONode child) throws FOPException { int childId = child.getNameId(); switch (childId) { case FO_TABLE_COLUMN: hasExplicitColumns = true; if (!inMarker()) { addColumnNode((TableColumn) child); } else { columns.add(child); } break; case FO_TABLE_HEADER: case FO_TABLE_FOOTER: case FO_TABLE_BODY: if (!inMarker() && !columnsFinalized) { columnsFinalized = true; if (hasExplicitColumns) { finalizeColumns(); rowGroupBuilder = new FixedColRowGroupBuilder(this); } else { rowGroupBuilder = new VariableColRowGroupBuilder(this); } } switch (childId) { case FO_TABLE_FOOTER: tableFooter = (TableFooter) child; break; case FO_TABLE_HEADER: tableHeader = (TableHeader) child; break; default: super.addChildNode(child); } break; default: super.addChildNode(child); } }
// in src/java/org/apache/fop/fo/flow/table/Table.java
private void finalizeColumns() throws FOPException { for (int i = 0; i < columns.size(); i++) { if (columns.get(i) == null) { columns.set(i, createImplicitColumn(i + 1)); } } }
// in src/java/org/apache/fop/fo/flow/table/Table.java
void ensureColumnNumber(int columnNumber) throws FOPException { assert !hasExplicitColumns; for (int i = columns.size() + 1; i <= columnNumber; i++) { columns.add(createImplicitColumn(i)); } }
// in src/java/org/apache/fop/fo/flow/table/Table.java
private TableColumn createImplicitColumn(int colNumber) throws FOPException { TableColumn implicitColumn = new TableColumn(this, true); PropertyList pList = new StaticPropertyList( implicitColumn, this.propList); implicitColumn.bind(pList); implicitColumn.setColumnWidth(new TableColLength(1.0, implicitColumn)); implicitColumn.setColumnNumber(colNumber); if (!isSeparateBorderModel()) { implicitColumn.setCollapsedBorders(collapsingBorderModel); // TODO } return implicitColumn; }
// in src/java/org/apache/fop/fo/flow/table/Table.java
public FONode clone(FONode parent, boolean removeChildren) throws FOPException { Table clone = (Table) super.clone(parent, removeChildren); if (removeChildren) { clone.columns = new ArrayList(); clone.columnsFinalized = false; clone.columnNumberManager = new ColumnNumberManager(); clone.tableHeader = null; clone.tableFooter = null; clone.rowGroupBuilder = null; } return clone; }
// in src/java/org/apache/fop/fo/flow/table/TableAndCaption.java
Override public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/flow/table/TableAndCaption.java
protected void endOfNode() throws FOPException { if (!tableFound) { missingChildElementError("marker* table-caption? table"); } }
// in src/java/org/apache/fop/fo/flow/table/TableHeader.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startHeader(this); }
// in src/java/org/apache/fop/fo/flow/table/TableHeader.java
protected void endOfNode() throws FOPException { super.endOfNode(); getFOEventHandler().endHeader(this); }
// in src/java/org/apache/fop/fo/flow/MultiSwitch.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); // autoRestore = pList.get(PR_AUTO_RESTORE); }
// in src/java/org/apache/fop/fo/flow/MultiSwitch.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("(multi-case+)"); } }
// in src/java/org/apache/fop/fo/FOText.java
protected void characters(char[] data, int start, int length, PropertyList list, Locator locator) throws FOPException { if (charBuffer == null) { // buffer not yet initialized, do so now int newLength = ( length < 16 ) ? 16 : length; charBuffer = CharBuffer.allocate(newLength); } else { // allocate a larger buffer, and transfer contents int requires = charBuffer.position() + length; int capacity = charBuffer.capacity(); if ( requires > capacity ) { int newCapacity = capacity * 2; if ( requires > newCapacity ) { newCapacity = requires; } CharBuffer newBuffer = CharBuffer.allocate(newCapacity); charBuffer.rewind(); newBuffer.put(charBuffer); charBuffer = newBuffer; } } // extend limit to capacity charBuffer.limit(charBuffer.capacity()); // append characters charBuffer.put(data, start, length); // shrink limit to position charBuffer.limit(charBuffer.position()); }
// in src/java/org/apache/fop/fo/FOText.java
public FONode clone(FONode parent, boolean removeChildren) throws FOPException { FOText ft = (FOText) super.clone(parent, removeChildren); if (removeChildren) { // not really removing, just make sure the char buffer // pointed to is really a different one if (charBuffer != null) { ft.charBuffer = CharBuffer.allocate(charBuffer.limit()); charBuffer.rewind(); ft.charBuffer.put(charBuffer); ft.charBuffer.rewind(); } } ft.prevFOTextThisBlock = null; ft.nextFOTextThisBlock = null; ft.ancestorBlock = null; return ft; }
// in src/java/org/apache/fop/fo/FOText.java
public void bind(PropertyList pList) throws FOPException { this.commonFont = pList.getFontProps(); this.commonHyphenation = pList.getHyphenationProps(); this.color = pList.get(Constants.PR_COLOR).getColor(getUserAgent()); this.keepTogether = pList.get(Constants.PR_KEEP_TOGETHER).getKeep(); this.lineHeight = pList.get(Constants.PR_LINE_HEIGHT).getSpace(); this.letterSpacing = pList.get(Constants.PR_LETTER_SPACING); this.whiteSpaceCollapse = pList.get(Constants.PR_WHITE_SPACE_COLLAPSE).getEnum(); this.whiteSpaceTreatment = pList.get(Constants.PR_WHITE_SPACE_TREATMENT).getEnum(); this.textTransform = pList.get(Constants.PR_TEXT_TRANSFORM).getEnum(); this.wordSpacing = pList.get(Constants.PR_WORD_SPACING); this.wrapOption = pList.get(Constants.PR_WRAP_OPTION).getEnum(); this.textDecoration = pList.getTextDecorationProps(); this.baselineShift = pList.get(Constants.PR_BASELINE_SHIFT).getLength(); this.country = pList.get(Constants.PR_COUNTRY).getString(); this.language = pList.get(Constants.PR_LANGUAGE).getString(); this.script = pList.get(Constants.PR_SCRIPT).getString(); }
// in src/java/org/apache/fop/fo/FOText.java
protected void endOfNode() throws FOPException { if ( charBuffer != null ) { charBuffer.rewind(); } super.endOfNode(); getFOEventHandler().characters(this); }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
public void bind(PropertyList pList) throws FOPException { // No properties in layout-master-set. }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
protected void startOfNode() throws FOPException { getRoot().setLayoutMasterSet(this); simplePageMasters = new java.util.HashMap<String, SimplePageMaster>(); pageSequenceMasters = new java.util.HashMap<String, PageSequenceMaster>(); }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("(simple-page-master|page-sequence-master)+"); } checkRegionNames(); resolveSubSequenceReferences(); }
// in src/java/org/apache/fop/fo/pagination/Declarations.java
public void bind(PropertyList pList) throws FOPException { // No properties defined for fo:declarations }
// in src/java/org/apache/fop/fo/pagination/Declarations.java
protected void endOfNode() throws FOPException { if (firstChild != null) { for (FONodeIterator iter = getChildNodes(); iter.hasNext();) { FONode node = iter.nextNode(); if (node.getName().equals("fo:color-profile")) { ColorProfile cp = (ColorProfile)node; if (!"".equals(cp.getColorProfileName())) { addColorProfile(cp); } else { getFOValidationEventProducer().missingProperty(this, cp.getName(), "color-profile-name", locator); } } else { log.debug("Ignoring element " + node.getName() + " inside fo:declarations."); } } } firstChild = null; }
// in src/java/org/apache/fop/fo/pagination/Root.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); mediaUsage = pList.get(PR_MEDIA_USAGE).getEnum(); String language = pList.get(PR_LANGUAGE).getString(); String country = pList.get(PR_COUNTRY).getString(); if (isLocalePropertySet(language)) { if (isLocalePropertySet(country)) { locale = new Locale(language, country); } else { locale = new Locale(language); } } }
// in src/java/org/apache/fop/fo/pagination/Root.java
protected void startOfNode() throws FOPException { foEventHandler.startRoot(this); }
// in src/java/org/apache/fop/fo/pagination/Root.java
protected void endOfNode() throws FOPException { if (!pageSequenceFound || layoutMasterSet == null) { missingChildElementError("(layout-master-set, declarations?, " + "bookmark-tree?, (page-sequence|fox:external-document)+)"); } foEventHandler.endRoot(this); }
// in src/java/org/apache/fop/fo/pagination/SimplePageMaster.java
public void bind(PropertyList pList) throws FOPException { commonMarginBlock = pList.getMarginBlockProps(); masterName = pList.get(PR_MASTER_NAME).getString(); pageHeight = pList.get(PR_PAGE_HEIGHT).getLength(); pageWidth = pList.get(PR_PAGE_WIDTH).getLength(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); writingMode = WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()); if (masterName == null || masterName.equals("")) { missingPropertyError("master-name"); } }
// in src/java/org/apache/fop/fo/pagination/SimplePageMaster.java
protected void startOfNode() throws FOPException { LayoutMasterSet layoutMasterSet = (LayoutMasterSet) parent; if (masterName == null) { missingPropertyError("master-name"); } else { layoutMasterSet.addSimplePageMaster(this); } //Well, there are only 5 regions so we can save a bit of memory here regions = new HashMap<String, Region>(5); }
// in src/java/org/apache/fop/fo/pagination/SimplePageMaster.java
protected void endOfNode() throws FOPException { if (!hasRegionBody) { missingChildElementError( "(region-body, region-before?, region-after?, region-start?, region-end?)"); } }
// in src/java/org/apache/fop/fo/pagination/SimplePageMaster.java
protected void addChildNode(FONode child) throws FOPException { if (child instanceof Region) { addRegion((Region)child); } else { super.addChildNode(child); } }
// in src/java/org/apache/fop/fo/pagination/Flow.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); flowName = pList.get(PR_FLOW_NAME).getString(); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/pagination/Flow.java
protected void startOfNode() throws FOPException { if (flowName == null || flowName.equals("")) { missingPropertyError("flow-name"); } // according to communication from Paul Grosso (XSL-List, // 001228, Number 406), confusion in spec section 6.4.5 about // multiplicity of fo:flow in XSL 1.0 is cleared up - one (1) // fo:flow per fo:page-sequence only. /* if (pageSequence.isFlowSet()) { if (this.name.equals("fo:flow")) { throw new FOPException("Only a single fo:flow permitted" + " per fo:page-sequence"); } else { throw new FOPException(this.name + " not allowed after fo:flow"); } } */ // Now done in addChild of page-sequence //pageSequence.addFlow(this); getFOEventHandler().startFlow(this); }
// in src/java/org/apache/fop/fo/pagination/Flow.java
protected void endOfNode() throws FOPException { if (!blockItemFound) { missingChildElementError("marker* (%block;)+"); } getFOEventHandler().endFlow(this); }
// in src/java/org/apache/fop/fo/pagination/SideRegion.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); extent = pList.get(PR_EXTENT).getLength(); }
// in src/java/org/apache/fop/fo/pagination/StaticContent.java
protected void startOfNode() throws FOPException { if (getFlowName() == null || getFlowName().equals("")) { missingPropertyError("flow-name"); } getFOEventHandler().startStatic(this); }
// in src/java/org/apache/fop/fo/pagination/StaticContent.java
protected void endOfNode() throws FOPException { if (firstChild == null && getUserAgent().validateStrictly()) { missingChildElementError("(%block;)+"); } getFOEventHandler().endStatic(this); }
// in src/java/org/apache/fop/fo/pagination/RegionBA.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); precedence = pList.get(PR_PRECEDENCE).getEnum(); }
// in src/java/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java
public void bind(PropertyList pList) throws FOPException { masterReference = pList.get(PR_MASTER_REFERENCE).getString(); pagePosition = pList.get(PR_PAGE_POSITION).getEnum(); oddOrEven = pList.get(PR_ODD_OR_EVEN).getEnum(); blankOrNotBlank = pList.get(PR_BLANK_OR_NOT_BLANK).getEnum(); if (masterReference == null || masterReference.equals("")) { missingPropertyError("master-reference"); } }
// in src/java/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java
protected void startOfNode() throws FOPException { getConcreteParent().addConditionalPageMasterReference(this); }
// in src/java/org/apache/fop/fo/pagination/RegionSE.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
public void bind(PropertyList pList) throws FOPException { maximumRepeats = pList.get(PR_MAXIMUM_REPEATS); }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
protected void startOfNode() throws FOPException { conditionalPageMasterRefs = new java.util.ArrayList<ConditionalPageMasterReference>(); assert parent.getName().equals("fo:page-sequence-master"); //Validation by the parent PageSequenceMaster pageSequenceMaster = (PageSequenceMaster)parent; pageSequenceMaster.addSubsequenceSpecifier(this); }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("(conditional-page-master-reference+)"); } }
// in src/java/org/apache/fop/fo/pagination/bookmarks/BookmarkTitle.java
Override public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/pagination/bookmarks/Bookmark.java
public void bind(PropertyList pList) throws FOPException { commonAccessibility = CommonAccessibility.getInstance(pList); externalDestination = pList.get(PR_EXTERNAL_DESTINATION).getString(); internalDestination = pList.get(PR_INTERNAL_DESTINATION).getString(); bShow = (pList.get(PR_STARTING_STATE).getEnum() == EN_SHOW); // per spec, internal takes precedence if both specified if (internalDestination.length() > 0) { externalDestination = null; } else if (externalDestination.length() == 0) { // slightly stronger than spec "should be specified" getFOValidationEventProducer().missingLinkDestination(this, getName(), locator); } else { getFOValidationEventProducer().unimplementedFeature(this, getName(), "external-destination", getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/bookmarks/Bookmark.java
protected void endOfNode() throws FOPException { if (bookmarkTitle == null) { missingChildElementError("(bookmark-title, bookmark*)"); } }
// in src/java/org/apache/fop/fo/pagination/bookmarks/BookmarkTree.java
protected void endOfNode() throws FOPException { if (bookmarks == null) { missingChildElementError("(fo:bookmark+)"); } ((Root) parent).setBookmarkTree(this); }
// in src/java/org/apache/fop/fo/pagination/SinglePageMasterReference.java
public void bind(PropertyList pList) throws FOPException { masterReference = pList.get(PR_MASTER_REFERENCE).getString(); if (masterReference == null || masterReference.equals("")) { missingPropertyError("master-reference"); } }
// in src/java/org/apache/fop/fo/pagination/SinglePageMasterReference.java
protected void startOfNode() throws FOPException { PageSequenceMaster pageSequenceMaster = (PageSequenceMaster) parent; pageSequenceMaster.addSubsequenceSpecifier(this); }
// in src/java/org/apache/fop/fo/pagination/RegionBody.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); commonMarginBlock = pList.getMarginBlockProps(); columnCount = pList.get(PR_COLUMN_COUNT).getNumeric(); columnGap = pList.get(PR_COLUMN_GAP).getLength(); if ((getColumnCount() > 1) && (getOverflow() == EN_SCROLL)) { /* This is an error (See XSL Rec, fo:region-body description). * The Rec allows for acting as if "1" is chosen in * these cases, but we will need to be able to change Numeric * values in order to do this. */ getFOValidationEventProducer().columnCountErrorOnRegionBodyOverflowScroll(this, getName(), getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/AbstractPageSequence.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); initialPageNumber = pList.get(PR_INITIAL_PAGE_NUMBER).getNumeric(); forcePageCount = pList.get(PR_FORCE_PAGE_COUNT).getEnum(); format = pList.get(PR_FORMAT).getString(); letterValue = pList.get(PR_LETTER_VALUE).getEnum(); groupingSeparator = pList.get(PR_GROUPING_SEPARATOR).getCharacter(); groupingSize = pList.get(PR_GROUPING_SIZE).getNumber().intValue(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); language = pList.get(PR_LANGUAGE).getString(); country = pList.get(PR_COUNTRY).getString(); numberConversionFeatures = pList.get(PR_X_NUMBER_CONVERSION_FEATURES).getString(); commonAccessibility = CommonAccessibility.getInstance(pList); }
// in src/java/org/apache/fop/fo/pagination/AbstractPageSequence.java
protected void startOfNode() throws FOPException { this.pageNumberGenerator = new PageNumberGenerator( format, groupingSeparator, groupingSize, letterValue, numberConversionFeatures, language, country); }
// in src/java/org/apache/fop/fo/pagination/PageSequenceWrapper.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); indexClass = pList.get(PR_INDEX_CLASS).getString(); indexKey = pList.get(PR_INDEX_KEY).getString(); }
// in src/java/org/apache/fop/fo/pagination/ColorProfile.java
public void bind(PropertyList pList) throws FOPException { src = pList.get(PR_SRC).getString(); colorProfileName = pList.get(PR_COLOR_PROFILE_NAME).getString(); renderingIntent = pList.get(PR_RENDERING_INTENT).getEnum(); }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java
public void bind(PropertyList pList) throws FOPException { masterReference = pList.get(PR_MASTER_REFERENCE).getString(); maximumRepeats = pList.get(PR_MAXIMUM_REPEATS); if (masterReference == null || masterReference.equals("")) { missingPropertyError("master-reference"); } }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java
protected void startOfNode() throws FOPException { PageSequenceMaster pageSequenceMaster = (PageSequenceMaster) parent; if (masterReference == null) { missingPropertyError("master-reference"); } else { pageSequenceMaster.addSubsequenceSpecifier(this); } }
// in src/java/org/apache/fop/fo/pagination/Region.java
public void bind(PropertyList pList) throws FOPException { commonBorderPaddingBackground = pList.getBorderPaddingBackgroundProps(); // clip = pList.get(PR_CLIP); displayAlign = pList.get(PR_DISPLAY_ALIGN).getEnum(); overflow = pList.get(PR_OVERFLOW).getEnum(); regionName = pList.get(PR_REGION_NAME).getString(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); writingMode = WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()); // regions may have name, or default if (regionName.equals("")) { regionName = getDefaultRegionName(); } else { // check that name is OK. Not very pretty. if (isReserved(getRegionName()) && !getRegionName().equals(getDefaultRegionName())) { getFOValidationEventProducer().illegalRegionName(this, getName(), regionName, getLocator()); } } //TODO do we need context for getBPPaddingAndBorder() and getIPPaddingAndBorder()? if ((getCommonBorderPaddingBackground().getBPPaddingAndBorder(false, null) != 0 || getCommonBorderPaddingBackground().getIPPaddingAndBorder(false, null) != 0)) { getFOValidationEventProducer().nonZeroBorderPaddingOnRegion(this, getName(), regionName, true, getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); country = pList.get(PR_COUNTRY).getString(); language = pList.get(PR_LANGUAGE).getString(); masterReference = pList.get(PR_MASTER_REFERENCE).getString(); referenceOrientation = pList.get(PR_REFERENCE_ORIENTATION).getNumeric(); writingModeTraits = new WritingModeTraits ( WritingMode.valueOf(pList.get(PR_WRITING_MODE).getEnum()) ); if (masterReference == null || masterReference.equals("")) { missingPropertyError("master-reference"); } }
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
protected void startOfNode() throws FOPException { super.startOfNode(); flowMap = new java.util.HashMap<String, FONode>(); this.simplePageMaster = getRoot().getLayoutMasterSet().getSimplePageMaster(masterReference); if (simplePageMaster == null) { this.pageSequenceMaster = getRoot().getLayoutMasterSet().getPageSequenceMaster(masterReference); if (pageSequenceMaster == null) { getFOValidationEventProducer().masterNotFound(this, getName(), masterReference, getLocator()); } } getFOEventHandler().startPageSequence(this); }
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
protected void endOfNode() throws FOPException { if (mainFlow == null) { missingChildElementError("(title?,static-content*,flow)"); } getFOEventHandler().endPageSequence(this); }
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
public void addChildNode(FONode child) throws FOPException { int childId = child.getNameId(); switch (childId) { case FO_TITLE: this.titleFO = (Title)child; break; case FO_FLOW: this.mainFlow = (Flow)child; addFlow(mainFlow); break; case FO_STATIC_CONTENT: addFlow((StaticContent)child); flowMap.put(((Flow)child).getFlowName(), (Flow)child); break; default: super.addChildNode(child); } }
// in src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java
public void bind(PropertyList pList) throws FOPException { masterName = pList.get(PR_MASTER_NAME).getString(); if (masterName == null || masterName.equals("")) { missingPropertyError("master-name"); } }
// in src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java
protected void startOfNode() throws FOPException { subSequenceSpecifiers = new java.util.ArrayList<SubSequenceSpecifier>(); layoutMasterSet = parent.getRoot().getLayoutMasterSet(); layoutMasterSet.addPageSequenceMaster(masterName, this); }
// in src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java
protected void endOfNode() throws FOPException { if (firstChild == null) { missingChildElementError("(single-page-master-reference|" + "repeatable-page-master-reference|repeatable-page-master-alternatives)+"); } }
// in src/java/org/apache/fop/fo/FObj.java
public FONode clone(FONode parent, boolean removeChildren) throws FOPException { FObj fobj = (FObj) super.clone(parent, removeChildren); if (removeChildren) { fobj.firstChild = null; } return fobj; }
// in src/java/org/apache/fop/fo/FObj.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { setLocator(locator); pList.addAttributesToList(attlist); if (!inMarker() || "marker".equals(elementName)) { bind(pList); } }
// in src/java/org/apache/fop/fo/FObj.java
protected PropertyList createPropertyList(PropertyList parent, FOEventHandler foEventHandler) throws FOPException { return getBuilderContext().getPropertyListMaker().make(this, parent); }
// in src/java/org/apache/fop/fo/FObj.java
public void bind(PropertyList pList) throws FOPException { id = pList.get(PR_ID).getString(); }
// in src/java/org/apache/fop/fo/FObj.java
protected void startOfNode() throws FOPException { if (id != null) { checkId(id); } }
// in src/java/org/apache/fop/fo/FObj.java
protected void addChildNode(FONode child) throws FOPException { if (child.getNameId() == FO_MARKER) { addMarker((Marker) child); } else { ExtensionAttachment attachment = child.getExtensionAttachment(); if (attachment != null) { /* This removes the element from the normal children, * so no layout manager is being created for them * as they are only additional information. */ addExtensionAttachment(attachment); } else { if (firstChild == null) { firstChild = child; lastChild = child; } else { if (lastChild == null) { FONode prevChild = firstChild; while (prevChild.siblings != null && prevChild.siblings[1] != null) { prevChild = prevChild.siblings[1]; } FONode.attachSiblings(prevChild, child); } else { FONode.attachSiblings(lastChild, child); lastChild = child; } } } } }
// in src/java/org/apache/fop/fo/FObj.java
protected static void addChildTo(FONode child, FONode parent) throws FOPException { parent.addChildNode(child); }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
public Maker findFOMaker(String namespaceURI, String localName, Locator locator) throws FOPException { Map<String, Maker> table = fobjTable.get(namespaceURI); Maker fobjMaker = null; if (table != null) { fobjMaker = table.get(localName); // try default if (fobjMaker == null) { fobjMaker = table.get(ElementMapping.DEFAULT); } } if (fobjMaker == null) { if (namespaces.containsKey(namespaceURI.intern())) { throw new FOPException(FONode.errorText(locator) + "No element mapping definition found for " + FONode.getNodeString(namespaceURI, localName), locator); } else { fobjMaker = new UnknownXMLObj.Maker(namespaceURI); } } return fobjMaker; }
// in src/java/org/apache/fop/fo/FONode.java
public FONode clone(FONode cloneparent, boolean removeChildren) throws FOPException { FONode foNode = (FONode) clone(); foNode.parent = cloneparent; foNode.siblings = null; return foNode; }
// in src/java/org/apache/fop/fo/FONode.java
public void bind(PropertyList propertyList) throws FOPException { //nop }
// in src/java/org/apache/fop/fo/FONode.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { if (log.isDebugEnabled()) { log.debug("Unhandled element: " + elementName + (locator != null ? " at " + getLocatorString(locator) : "")); } }
// in src/java/org/apache/fop/fo/FONode.java
protected PropertyList createPropertyList( PropertyList pList, FOEventHandler foEventHandler) throws FOPException { return null; }
// in src/java/org/apache/fop/fo/FONode.java
protected void addCharacters(char[] data, int start, int end, PropertyList pList, Locator locator) throws FOPException { // ignore }
// in src/java/org/apache/fop/fo/FONode.java
protected void characters(char[] data, int start, int length, PropertyList pList, Locator locator) throws FOPException { addCharacters(data, start, start + length, pList, locator); }
// in src/java/org/apache/fop/fo/FONode.java
protected void startOfNode() throws FOPException { // do nothing by default }
// in src/java/org/apache/fop/fo/FONode.java
protected void endOfNode() throws FOPException { this.finalizeNode(); }
// in src/java/org/apache/fop/fo/FONode.java
protected void addChildNode(FONode child) throws FOPException { // do nothing by default }
// in src/java/org/apache/fop/fo/FONode.java
public void finalizeNode() throws FOPException { // do nothing by default }
// in src/java/org/apache/fop/fo/extensions/ExternalDocument.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); blockProgressionDimension = pList.get(PR_BLOCK_PROGRESSION_DIMENSION).getLengthRange(); contentHeight = pList.get(PR_CONTENT_HEIGHT).getLength(); contentWidth = pList.get(PR_CONTENT_WIDTH).getLength(); displayAlign = pList.get(PR_DISPLAY_ALIGN).getEnum(); height = pList.get(PR_HEIGHT).getLength(); inlineProgressionDimension = pList.get(PR_INLINE_PROGRESSION_DIMENSION).getLengthRange(); overflow = pList.get(PR_OVERFLOW).getEnum(); scaling = pList.get(PR_SCALING).getEnum(); textAlign = pList.get(PR_TEXT_ALIGN).getEnum(); width = pList.get(PR_WIDTH).getLength(); src = pList.get(PR_SRC).getString(); if (this.src == null || this.src.length() == 0) { missingPropertyError("src"); } }
// in src/java/org/apache/fop/fo/extensions/ExternalDocument.java
protected void startOfNode() throws FOPException { super.startOfNode(); getFOEventHandler().startExternalDocument(this); }
// in src/java/org/apache/fop/fo/extensions/ExternalDocument.java
protected void endOfNode() throws FOPException { getFOEventHandler().endExternalDocument(this); super.endOfNode(); }
// in src/java/org/apache/fop/fo/extensions/destination/Destination.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { internalDestination = attlist.getValue("internal-destination"); if (internalDestination == null || internalDestination.length() == 0) { missingPropertyError("internal-destination"); } }
// in src/java/org/apache/fop/fo/extensions/destination/Destination.java
protected void endOfNode() throws FOPException { root.addDestination(this); }
// in src/java/org/apache/fop/fo/extensions/ExtensionObj.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList pList) throws FOPException { }
// in src/java/org/apache/fop/fo/extensions/ExtensionObj.java
protected PropertyList createPropertyList(PropertyList parent, FOEventHandler foEventHandler) throws FOPException { return null; }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java
public static FontInfo createFontInfo(Configuration cfg, boolean useComplexScriptFeatures) throws FOPException { FontInfo fontInfo = new FontInfo(); final boolean strict = false; FontResolver fontResolver = FontManager.createMinimalFontResolver(useComplexScriptFeatures); //TODO The following could be optimized by retaining the FontManager somewhere FontManager fontManager = new FontManager(); if (cfg != null) { FontManagerConfigurator fmConfigurator = new FontManagerConfigurator(cfg); fmConfigurator.configure(fontManager, strict); } List fontCollections = new java.util.ArrayList(); fontCollections.add(new Base14FontCollection(fontManager.isBase14KerningEnabled())); if (cfg != null) { //TODO Wire in the FontEventListener FontEventListener listener = null; //new FontEventAdapter(eventBroadcaster); FontInfoConfigurator fontInfoConfigurator = new FontInfoConfigurator(cfg, fontManager, fontResolver, listener, strict); List/*<EmbedFontInfo>*/ fontInfoList = new java.util.ArrayList/*<EmbedFontInfo>*/(); fontInfoConfigurator.configure(fontInfoList); fontCollections.add(new CustomFontCollection(fontResolver, fontInfoList, fontResolver.isComplexScriptFeaturesEnabled())); } fontManager.setup(fontInfo, (FontCollection[])fontCollections.toArray( new FontCollection[fontCollections.size()])); return fontInfo; }
// in src/java/org/apache/fop/fonts/FontReader.java
private void createFont(InputSource source) throws FOPException { XMLReader parser = null; try { final SAXParserFactory factory = javax.xml.parsers.SAXParserFactory.newInstance(); factory.setNamespaceAware(true); parser = factory.newSAXParser().getXMLReader(); } catch (Exception e) { throw new FOPException(e); } if (parser == null) { throw new FOPException("Unable to create SAX parser"); } try { parser.setFeature("http://xml.org/sax/features/namespace-prefixes", false); } catch (SAXException e) { throw new FOPException("You need a SAX parser which supports SAX version 2", e); } parser.setContentHandler(this); try { parser.parse(source); } catch (SAXException e) { throw new FOPException(e); } catch (IOException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/fonts/FontManager.java
public void saveCache() throws FOPException { if (useCache) { if (fontCache != null && fontCache.hasChanged()) { if (cacheFile != null) { fontCache.saveTo(cacheFile); } else { fontCache.save(); } } } }
// in src/java/org/apache/fop/fonts/substitute/FontSubstitutionsConfigurator.java
private static FontQualifier getQualfierFromConfiguration(Configuration cfg) throws FOPException { String fontFamily = cfg.getAttribute("font-family", null); if (fontFamily == null) { throw new FOPException("substitution qualifier must have a font-family"); } FontQualifier qualifier = new FontQualifier(); qualifier.setFontFamily(fontFamily); String fontWeight = cfg.getAttribute("font-weight", null); if (fontWeight != null) { qualifier.setFontWeight(fontWeight); } String fontStyle = cfg.getAttribute("font-style", null); if (fontStyle != null) { qualifier.setFontStyle(fontStyle); } return qualifier; }
// in src/java/org/apache/fop/fonts/substitute/FontSubstitutionsConfigurator.java
public void configure(FontSubstitutions substitutions) throws FOPException { Configuration[] substitutionCfgs = cfg.getChildren("substitution"); for (int i = 0; i < substitutionCfgs.length; i++) { Configuration fromCfg = substitutionCfgs[i].getChild("from", false); if (fromCfg == null) { throw new FOPException("'substitution' element without child 'from' element"); } Configuration toCfg = substitutionCfgs[i].getChild("to", false); if (fromCfg == null) { throw new FOPException("'substitution' element without child 'to' element"); } FontQualifier fromQualifier = getQualfierFromConfiguration(fromCfg); FontQualifier toQualifier = getQualfierFromConfiguration(toCfg); FontSubstitution substitution = new FontSubstitution(fromQualifier, toQualifier); substitutions.add(substitution); } }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
public void configure(FontManager fontManager, boolean strict) throws FOPException { // caching (fonts) if (cfg.getChild("use-cache", false) != null) { try { fontManager.setUseCache(cfg.getChild("use-cache").getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, true); } } if (cfg.getChild("cache-file", false) != null) { try { fontManager.setCacheFile(new File(cfg.getChild("cache-file").getValue())); } catch (ConfigurationException e) { LogUtil.handleException(log, e, true); } } if (cfg.getChild("font-base", false) != null) { String path = cfg.getChild("font-base").getValue(null); if (baseURI != null) { path = baseURI.resolve(path).normalize().toString(); } try { fontManager.setFontBaseURL(path); } catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, true); } } // [GA] permit configuration control over base14 kerning; without this, // there is no way for a user to enable base14 kerning other than by // programmatic API; if (cfg.getChild("base14-kerning", false) != null) { try { fontManager .setBase14KerningEnabled(cfg.getChild("base14-kerning").getValueAsBoolean()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, true); } } // global font configuration Configuration fontsCfg = cfg.getChild("fonts", false); if (fontsCfg != null) { // font substitution Configuration substitutionsCfg = fontsCfg.getChild("substitutions", false); if (substitutionsCfg != null) { FontSubstitutions substitutions = new FontSubstitutions(); new FontSubstitutionsConfigurator(substitutionsCfg).configure(substitutions); fontManager.setFontSubstitutions(substitutions); } // referenced fonts (fonts which are not to be embedded) Configuration referencedFontsCfg = fontsCfg.getChild("referenced-fonts", false); if (referencedFontsCfg != null) { FontTriplet.Matcher matcher = createFontsMatcher( referencedFontsCfg, strict); fontManager.setReferencedFontsMatcher(matcher); } } }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
public static FontTriplet.Matcher createFontsMatcher( Configuration cfg, boolean strict) throws FOPException { List<FontTriplet.Matcher> matcherList = new java.util.ArrayList<FontTriplet.Matcher>(); Configuration[] matches = cfg.getChildren("match"); for (int i = 0; i < matches.length; i++) { try { matcherList.add(new FontFamilyRegExFontTripletMatcher( matches[i].getAttribute("font-family"))); } catch (ConfigurationException ce) { LogUtil.handleException(log, ce, strict); continue; } } FontTriplet.Matcher orMatcher = new OrFontTripletMatcher( matcherList.toArray(new FontTriplet.Matcher[matcherList.size()])); return orMatcher; }
// in src/java/org/apache/fop/fonts/FontCache.java
public void save() throws FOPException { saveTo(getDefaultCacheFile(true)); }
// in src/java/org/apache/fop/fonts/FontCache.java
public void saveTo(File cacheFile) throws FOPException { synchronized (changeLock) { if (changed) { try { log.trace("Writing font cache to " + cacheFile.getCanonicalPath()); OutputStream out = new java.io.FileOutputStream(cacheFile); out = new java.io.BufferedOutputStream(out); ObjectOutputStream oout = new ObjectOutputStream(out); try { oout.writeObject(this); } finally { IOUtils.closeQuietly(oout); } } catch (IOException ioe) { LogUtil.handleException(log, ioe, true); } changed = false; log.trace("Cache file written."); } } }
// in src/java/org/apache/fop/fonts/FontDetector.java
public void detect(List<EmbedFontInfo> fontInfoList) throws FOPException { // search in font base if it is defined and // is a directory but don't recurse FontFileFinder fontFileFinder = new FontFileFinder(eventListener); String fontBaseURL = fontManager.getFontBaseURL(); if (fontBaseURL != null) { try { File fontBase = FileUtils.toFile(new URL(fontBaseURL)); if (fontBase != null) { List<URL> fontURLList = fontFileFinder.find(fontBase.getAbsolutePath()); fontAdder.add(fontURLList, fontInfoList); //Can only use the font base URL if it's a file URL } } catch (IOException e) { LogUtil.handleException(log, e, strict); } } // native o/s font directory finding List<URL> systemFontList; try { systemFontList = fontFileFinder.find(); fontAdder.add(systemFontList, fontInfoList); } catch (IOException e) { LogUtil.handleException(log, e, strict); } // classpath font finding ClasspathResource resource = ClasspathResource.getInstance(); for (int i = 0; i < FONT_MIMETYPES.length; i++) { fontAdder.add(resource.listResourcesOfMimeType(FONT_MIMETYPES[i]), fontInfoList); } }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
public void configure(List<EmbedFontInfo> fontInfoList) throws FOPException { Configuration fontsCfg = cfg.getChild("fonts", false); if (fontsCfg != null) { long start = 0; if (log.isDebugEnabled()) { log.debug("Starting font configuration..."); start = System.currentTimeMillis(); } FontAdder fontAdder = new FontAdder(fontManager, fontResolver, listener); // native o/s search (autodetect) configuration boolean autodetectFonts = (fontsCfg.getChild("auto-detect", false) != null); if (autodetectFonts) { FontDetector fontDetector = new FontDetector(fontManager, fontAdder, strict, listener); fontDetector.detect(fontInfoList); } // Add configured directories to FontInfo list addDirectories(fontsCfg, fontAdder, fontInfoList); // Add fonts from configuration to FontInfo list addFonts(fontsCfg, fontManager.getFontCache(), fontInfoList); // Update referenced fonts (fonts which are not to be embedded) fontManager.updateReferencedFonts(fontInfoList); // Renderer-specific referenced fonts Configuration referencedFontsCfg = fontsCfg.getChild("referenced-fonts", false); if (referencedFontsCfg != null) { FontTriplet.Matcher matcher = FontManagerConfigurator.createFontsMatcher( referencedFontsCfg, strict); fontManager.updateReferencedFonts(fontInfoList, matcher); } // Update font cache if it has changed fontManager.saveCache(); if (log.isDebugEnabled()) { log.debug("Finished font configuration in " + (System.currentTimeMillis() - start) + "ms"); } } }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
private void addDirectories(Configuration fontsCfg, FontAdder fontAdder, List<EmbedFontInfo> fontInfoList) throws FOPException { // directory (multiple font) configuration Configuration[] directories = fontsCfg.getChildren("directory"); for (int i = 0; i < directories.length; i++) { boolean recursive = directories[i].getAttributeAsBoolean("recursive", false); String directory = null; try { directory = directories[i].getValue(); } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); continue; } if (directory == null) { LogUtil.handleException(log, new FOPException("directory defined without value"), strict); continue; } // add fonts found in directory FontFileFinder fontFileFinder = new FontFileFinder(recursive ? -1 : 1, listener); List<URL> fontURLList; try { fontURLList = fontFileFinder.find(directory); fontAdder.add(fontURLList, fontInfoList); } catch (IOException e) { LogUtil.handleException(log, e, strict); } } }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
protected void addFonts(Configuration fontsCfg, FontCache fontCache, List<EmbedFontInfo> fontInfoList) throws FOPException { // font file (singular) configuration Configuration[] font = fontsCfg.getChildren("font"); for (int i = 0; i < font.length; i++) { EmbedFontInfo embedFontInfo = getFontInfo( font[i], fontCache); if (embedFontInfo != null) { fontInfoList.add(embedFontInfo); } } }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
protected EmbedFontInfo getFontInfo(Configuration fontCfg, FontCache fontCache) throws FOPException { String metricsUrl = fontCfg.getAttribute("metrics-url", null); String embedUrl = fontCfg.getAttribute("embed-url", null); String subFont = fontCfg.getAttribute("sub-font", null); if (metricsUrl == null && embedUrl == null) { LogUtil.handleError(log, "Font configuration without metric-url or embed-url attribute", strict); return null; } if (strict) { //This section just checks early whether the URIs can be resolved //Stream are immediately closed again since they will never be used anyway if (embedUrl != null) { Source source = fontResolver.resolve(embedUrl); closeSource(source); if (source == null) { LogUtil.handleError(log, "Failed to resolve font with embed-url '" + embedUrl + "'", strict); return null; } } if (metricsUrl != null) { Source source = fontResolver.resolve(metricsUrl); closeSource(source); if (source == null) { LogUtil.handleError(log, "Failed to resolve font with metric-url '" + metricsUrl + "'", strict); return null; } } } Configuration[] tripletCfg = fontCfg.getChildren("font-triplet"); // no font triplet info if (tripletCfg.length == 0) { LogUtil.handleError(log, "font without font-triplet", strict); File fontFile = FontCache.getFileFromUrls(new String[] {embedUrl, metricsUrl}); URL fontURL = null; try { fontURL = fontFile.toURI().toURL(); } catch (MalformedURLException e) { LogUtil.handleException(log, e, strict); } if (fontFile != null) { FontInfoFinder finder = new FontInfoFinder(); finder.setEventListener(listener); EmbedFontInfo[] infos = finder.find(fontURL, fontResolver, fontCache); return infos[0]; //When subFont is set, only one font is returned } else { return null; } } List<FontTriplet> tripletList = new java.util.ArrayList<FontTriplet>(); for (int j = 0; j < tripletCfg.length; j++) { FontTriplet fontTriplet = getFontTriplet(tripletCfg[j]); tripletList.add(fontTriplet); } boolean useKerning = fontCfg.getAttributeAsBoolean("kerning", true); boolean useAdvanced = fontCfg.getAttributeAsBoolean("advanced", true); EncodingMode encodingMode = EncodingMode.getEncodingMode( fontCfg.getAttribute("encoding-mode", EncodingMode.AUTO.getName())); EmbedFontInfo embedFontInfo = new EmbedFontInfo(metricsUrl, useKerning, useAdvanced, tripletList, embedUrl, subFont); embedFontInfo.setEncodingMode(encodingMode); boolean skipCachedFont = false; if (fontCache != null) { if (!fontCache.containsFont(embedFontInfo)) { fontCache.addFont(embedFontInfo); } else { skipCachedFont = true; } } if (log.isDebugEnabled()) { String embedFile = embedFontInfo.getEmbedFile(); log.debug( ( skipCachedFont ? "Skipping (cached) font " : "Adding font " ) + (embedFile != null ? embedFile + ", " : "") + "metric file " + embedFontInfo.getMetricsFile()); for (int j = 0; j < tripletList.size(); ++j) { FontTriplet triplet = tripletList.get(j); log.debug(" Font triplet " + triplet.getName() + ", " + triplet.getStyle() + ", " + triplet.getWeight()); } } return embedFontInfo; }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
private FontTriplet getFontTriplet(Configuration tripletCfg) throws FOPException { try { String name = tripletCfg.getAttribute("name"); if (name == null) { LogUtil.handleError(log, "font-triplet without name", strict); return null; } String weightStr = tripletCfg.getAttribute("weight"); if (weightStr == null) { LogUtil.handleError(log, "font-triplet without weight", strict); return null; } int weight = FontUtil.parseCSS2FontWeight(FontUtil.stripWhiteSpace(weightStr)); String style = tripletCfg.getAttribute("style"); if (style == null) { LogUtil.handleError(log, "font-triplet without style", strict); return null; } else { style = FontUtil.stripWhiteSpace(style); } return FontInfo.createFontKey(name, style, weight); } catch (ConfigurationException e) { LogUtil.handleException(log, e, strict); } return null; }
// in src/java/org/apache/fop/render/XMLHandlerConfigurator.java
public void configure(RendererContext context, String ns) throws FOPException { //Optional XML handler configuration Configuration cfg = getRendererConfig(context.getRenderer()); if (cfg != null) { cfg = getHandlerConfig(cfg, ns); if (cfg != null) { context.setProperty(RendererContextConstants.HANDLER_CONFIGURATION, cfg); } } }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
private void configure(Configuration cfg, PDFRenderingUtil pdfUtil) throws FOPException { //PDF filters try { Map filterMap = buildFilterMapFromConfiguration(cfg); if (filterMap != null) { pdfUtil.setFilterMap(filterMap); } } catch (ConfigurationException e) { LogUtil.handleException(log, e, false); } String s = cfg.getChild(PDFConfigurationConstants.PDF_A_MODE, true).getValue(null); if (s != null) { pdfUtil.setAMode(PDFAMode.valueOf(s)); } s = cfg.getChild(PDFConfigurationConstants.PDF_X_MODE, true).getValue(null); if (s != null) { pdfUtil.setXMode(PDFXMode.valueOf(s)); } Configuration encryptionParamsConfig = cfg.getChild(PDFConfigurationConstants.ENCRYPTION_PARAMS, false); if (encryptionParamsConfig != null) { PDFEncryptionParams encryptionParams = pdfUtil.getEncryptionParams(); Configuration ownerPasswordConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.OWNER_PASSWORD, false); if (ownerPasswordConfig != null) { String ownerPassword = ownerPasswordConfig.getValue(null); if (ownerPassword != null) { encryptionParams.setOwnerPassword(ownerPassword); } } Configuration userPasswordConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.USER_PASSWORD, false); if (userPasswordConfig != null) { String userPassword = userPasswordConfig.getValue(null); if (userPassword != null) { encryptionParams.setUserPassword(userPassword); } } Configuration noPrintConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_PRINT, false); if (noPrintConfig != null) { encryptionParams.setAllowPrint(false); } Configuration noCopyContentConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_COPY_CONTENT, false); if (noCopyContentConfig != null) { encryptionParams.setAllowCopyContent(false); } Configuration noEditContentConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_EDIT_CONTENT, false); if (noEditContentConfig != null) { encryptionParams.setAllowEditContent(false); } Configuration noAnnotationsConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_ANNOTATIONS, false); if (noAnnotationsConfig != null) { encryptionParams.setAllowEditAnnotations(false); } Configuration noFillInForms = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_FILLINFORMS, false); if (noFillInForms != null) { encryptionParams.setAllowFillInForms(false); } Configuration noAccessContentConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_ACCESSCONTENT, false); if (noAccessContentConfig != null) { encryptionParams.setAllowAccessContent(false); } Configuration noAssembleDocConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_ASSEMBLEDOC, false); if (noAssembleDocConfig != null) { encryptionParams.setAllowAssembleDocument(false); } Configuration noPrintHqConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.NO_PRINTHQ, false); if (noPrintHqConfig != null) { encryptionParams.setAllowPrintHq(false); } Configuration encryptionLengthConfig = encryptionParamsConfig.getChild( PDFConfigurationConstants.ENCRYPTION_LENGTH, false); if (encryptionLengthConfig != null) { int encryptionLength = checkEncryptionLength( Integer.parseInt(encryptionLengthConfig.getValue(null))); encryptionParams.setEncryptionLengthInBits(encryptionLength); } } s = cfg.getChild(PDFConfigurationConstants.KEY_OUTPUT_PROFILE, true).getValue(null); if (s != null) { pdfUtil.setOutputProfileURI(s); } Configuration disableColorSpaceConfig = cfg.getChild( PDFConfigurationConstants.KEY_DISABLE_SRGB_COLORSPACE, false); if (disableColorSpaceConfig != null) { pdfUtil.setDisableSRGBColorSpace( disableColorSpaceConfig.getValueAsBoolean(false)); } setPDFDocVersion(cfg, pdfUtil); }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
private void setPDFDocVersion(Configuration cfg, PDFRenderingUtil pdfUtil) throws FOPException { Configuration pdfVersion = cfg.getChild(PDFConfigurationConstants.PDF_VERSION, false); if (pdfVersion != null) { String version = pdfVersion.getValue(null); if (version != null && version.length() != 0) { try { pdfUtil.setPDFVersion(version); } catch (IllegalArgumentException e) { throw new FOPException(e.getMessage()); } } else { throw new FOPException("The PDF version has not been set."); } } }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { PDFDocumentHandler pdfDocumentHandler = (PDFDocumentHandler)documentHandler; PDFRenderingUtil pdfUtil = pdfDocumentHandler.getPDFUtil(); configure(cfg, pdfUtil); } }
// in src/java/org/apache/fop/render/pdf/extensions/PDFEmbeddedFileElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if (parent.getNameId() != Constants.FO_DECLARATIONS) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfDeclarations"); } }
// in src/java/org/apache/fop/render/pdf/extensions/PDFEmbeddedFileElement.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { PDFEmbeddedFileExtensionAttachment embeddedFile = (PDFEmbeddedFileExtensionAttachment)getExtensionAttachment(); String desc = attlist.getValue("description"); if (desc != null && desc.length() > 0) { embeddedFile.setDesc(desc); } String src = attlist.getValue("src"); src = URISpecification.getURL(src); if (src != null && src.length() > 0) { embeddedFile.setSrc(src); } else { missingPropertyError("src"); } String filename = attlist.getValue("filename"); if (filename == null || filename.length() == 0) { try { URI uri = new URI(src); String path = uri.getPath(); int idx = path.lastIndexOf('/'); if (idx > 0) { filename = path.substring(idx + 1); } else { filename = path; } embeddedFile.setFilename(filename); } catch (URISyntaxException e) { //Filename could not be deduced from URI missingPropertyError("name"); } } embeddedFile.setFilename(filename); }
// in src/java/org/apache/fop/render/RendererFactory.java
public Renderer createRenderer(FOUserAgent userAgent, String outputFormat) throws FOPException { if (userAgent.getDocumentHandlerOverride() != null) { return createRendererForDocumentHandler(userAgent.getDocumentHandlerOverride()); } else if (userAgent.getRendererOverride() != null) { return userAgent.getRendererOverride(); } else { Renderer renderer; if (isRendererPreferred()) { //Try renderer first renderer = tryRendererMaker(userAgent, outputFormat); if (renderer == null) { renderer = tryIFDocumentHandlerMaker(userAgent, outputFormat); } } else { //Try document handler first renderer = tryIFDocumentHandlerMaker(userAgent, outputFormat); if (renderer == null) { renderer = tryRendererMaker(userAgent, outputFormat); } } if (renderer == null) { throw new UnsupportedOperationException( "No renderer for the requested format available: " + outputFormat); } return renderer; } }
// in src/java/org/apache/fop/render/RendererFactory.java
private Renderer tryIFDocumentHandlerMaker(FOUserAgent userAgent, String outputFormat) throws FOPException { AbstractIFDocumentHandlerMaker documentHandlerMaker = getDocumentHandlerMaker(outputFormat); if (documentHandlerMaker != null) { IFDocumentHandler documentHandler = createDocumentHandler( userAgent, outputFormat); return createRendererForDocumentHandler(documentHandler); } else { return null; } }
// in src/java/org/apache/fop/render/RendererFactory.java
private Renderer tryRendererMaker(FOUserAgent userAgent, String outputFormat) throws FOPException { AbstractRendererMaker maker = getRendererMaker(outputFormat); if (maker != null) { Renderer rend = maker.makeRenderer(userAgent); RendererConfigurator configurator = maker.getConfigurator(userAgent); if (configurator != null) { configurator.configure(rend); } return rend; } else { return null; } }
// in src/java/org/apache/fop/render/RendererFactory.java
public FOEventHandler createFOEventHandler(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { if (userAgent.getFOEventHandlerOverride() != null) { return userAgent.getFOEventHandlerOverride(); } else { AbstractFOEventHandlerMaker maker = getFOEventHandlerMaker(outputFormat); if (maker != null) { return maker.makeFOEventHandler(userAgent, out); } else { AbstractRendererMaker rendMaker = getRendererMaker(outputFormat); AbstractIFDocumentHandlerMaker documentHandlerMaker = null; boolean outputStreamMissing = (userAgent.getRendererOverride() == null) && (userAgent.getDocumentHandlerOverride() == null); if (rendMaker == null) { documentHandlerMaker = getDocumentHandlerMaker(outputFormat); if (documentHandlerMaker != null) { outputStreamMissing &= (out == null) && (documentHandlerMaker.needsOutputStream()); } } else { outputStreamMissing &= (out == null) && (rendMaker.needsOutputStream()); } if (userAgent.getRendererOverride() != null || rendMaker != null || userAgent.getDocumentHandlerOverride() != null || documentHandlerMaker != null) { if (outputStreamMissing) { throw new FOPException( "OutputStream has not been set"); } //Found a Renderer so we need to construct an AreaTreeHandler. return new AreaTreeHandler(userAgent, outputFormat, out); } else { throw new UnsupportedOperationException( "Don't know how to handle \"" + outputFormat + "\" as an output format." + " Neither an FOEventHandler, nor a Renderer could be found" + " for this output format."); } } } }
// in src/java/org/apache/fop/render/RendererFactory.java
public IFDocumentHandler createDocumentHandler(FOUserAgent userAgent, String outputFormat) throws FOPException { if (userAgent.getDocumentHandlerOverride() != null) { return userAgent.getDocumentHandlerOverride(); } AbstractIFDocumentHandlerMaker maker = getDocumentHandlerMaker(outputFormat); if (maker == null) { throw new UnsupportedOperationException( "No IF document handler for the requested format available: " + outputFormat); } IFDocumentHandler documentHandler = maker.makeIFDocumentHandler(userAgent); IFDocumentHandlerConfigurator configurator = documentHandler.getConfigurator(); if (configurator != null) { configurator.configure(documentHandler); } return new EventProducingFilter(documentHandler, userAgent); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
Override public void setupFontInfo(FontInfo inFontInfo) throws FOPException { if (mimic != null) { mimic.setupFontInfo(inFontInfo); } else { super.setupFontInfo(inFontInfo); } }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
Override public void renderPage(PageViewport page) throws IOException, FOPException { atts.clear(); addAttribute("bounds", page.getViewArea()); addAttribute("key", page.getKey()); addAttribute("nr", page.getPageNumber()); addAttribute("formatted-nr", page.getPageNumberString()); if (page.getSimplePageMasterName() != null) { addAttribute("simple-page-master-name", page.getSimplePageMasterName()); } if (page.isBlank()) { addAttribute("blank", "true"); } transferForeignObjects(page); startElement("pageViewport", atts); startElement("page"); handlePageExtensionAttachments(page); super.renderPage(page); endElement("page"); endElement("pageViewport"); }
// in src/java/org/apache/fop/render/intermediate/IFUtil.java
public static void setupFonts(IFDocumentHandler documentHandler, FontInfo fontInfo) throws FOPException { if (fontInfo == null) { fontInfo = new FontInfo(); } if (documentHandler instanceof IFSerializer) { IFSerializer serializer = (IFSerializer)documentHandler; if (serializer.getMimickedDocumentHandler() != null) { //Use the mimicked document handler's configurator to set up fonts documentHandler = serializer.getMimickedDocumentHandler(); } } IFDocumentHandlerConfigurator configurator = documentHandler.getConfigurator(); if (configurator != null) { configurator.setupFontInfo(documentHandler, fontInfo); } else { documentHandler.setDefaultFontInfo(fontInfo); } }
// in src/java/org/apache/fop/render/intermediate/IFUtil.java
public static void setupFonts(IFDocumentHandler documentHandler) throws FOPException { setupFonts(documentHandler, null); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
public void setupFontInfo(FontInfo inFontInfo) throws FOPException { if (this.documentHandler == null) { this.documentHandler = createDefaultDocumentHandler(); } IFUtil.setupFonts(this.documentHandler, inFontInfo); this.fontInfo = inFontInfo; }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
public void renderPage(PageViewport page) throws IOException, FOPException { if (log.isTraceEnabled()) { log.trace("renderPage() " + page); } try { pageIndices.put(page.getKey(), new Integer(page.getPageIndex())); Rectangle viewArea = page.getViewArea(); Dimension dim = new Dimension(viewArea.width, viewArea.height); establishForeignAttributes(page.getForeignAttributes()); documentHandler.startPage(page.getPageIndex(), page.getPageNumberString(), page.getSimplePageMasterName(), dim); resetForeignAttributes(); documentHandler.startPageHeader(); //Add page attachments to page header processExtensionAttachments(page); documentHandler.endPageHeader(); this.painter = documentHandler.startPageContent(); super.renderPage(page); this.painter = null; documentHandler.endPageContent(); documentHandler.startPageTrailer(); if (hasDocumentNavigation()) { Iterator iter = this.deferredLinks.iterator(); while (iter.hasNext()) { Link link = (Link)iter.next(); iter.remove(); getDocumentNavigationHandler().renderLink(link); } } documentHandler.endPageTrailer(); establishForeignAttributes(page.getForeignAttributes()); documentHandler.endPage(); resetForeignAttributes(); } catch (IFException e) { handleIFException(e); } }
// in src/java/org/apache/fop/render/PrintRenderer.java
public void setupFontInfo(FontInfo inFontInfo) throws FOPException { this.fontInfo = inFontInfo; FontManager fontManager = userAgent.getFactory().getFontManager(); FontCollection[] fontCollections = new FontCollection[] { new Base14FontCollection(fontManager.isBase14KerningEnabled()), new CustomFontCollection(getFontResolver(), getFontList(), userAgent.isComplexScriptFeaturesEnabled()) }; fontManager.setup(getFontInfo(), fontCollections); }
// in src/java/org/apache/fop/render/txt/TXTRenderer.java
public void renderPage(PageViewport page) throws IOException, FOPException { if (firstPage) { firstPage = false; } else { currentStream.add(pageEnding); } Rectangle2D bounds = page.getViewArea(); double width = bounds.getWidth(); double height = bounds.getHeight(); pageWidth = Helper.ceilPosition((int) width, CHAR_WIDTH); pageHeight = Helper.ceilPosition((int) height, CHAR_HEIGHT + 2 * LINE_LEADING); // init buffers charData = new StringBuffer[pageHeight]; decoData = new StringBuffer[pageHeight]; for (int i = 0; i < pageHeight; i++) { charData[i] = new StringBuffer(); decoData[i] = new StringBuffer(); } bm = new BorderManager(pageWidth, pageHeight, currentState); super.renderPage(page); flushBorderToBuffer(); flushBuffer(); }
// in src/java/org/apache/fop/render/txt/TXTRendererConfigurator.java
public void configure(Renderer renderer) throws FOPException { Configuration cfg = super.getRendererConfig(renderer); if (cfg != null) { TXTRenderer txtRenderer = (TXTRenderer)renderer; txtRenderer.setEncoding(cfg.getChild("encoding", true).getValue(null)); } }
// in src/java/org/apache/fop/render/AbstractRenderer.java
public void renderPage(PageViewport page) throws IOException, FOPException { this.currentPageViewport = page; try { Page p = page.getPage(); renderPageAreas(p); } finally { this.currentPageViewport = null; } }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
private void configure(Configuration cfg, PCLRenderingUtil pclUtil) throws FOPException { String rendering = cfg.getChild("rendering").getValue(null); if (rendering != null) { try { pclUtil.setRenderingMode(PCLRenderingMode.valueOf(rendering)); } catch (IllegalArgumentException e) { throw new FOPException( "Valid values for 'rendering' are 'quality', 'speed' and 'bitmap'." + " Value found: " + rendering); } } String textRendering = cfg.getChild("text-rendering").getValue(null); if ("bitmap".equalsIgnoreCase(textRendering)) { pclUtil.setAllTextAsBitmaps(true); } else if ("auto".equalsIgnoreCase(textRendering)) { pclUtil.setAllTextAsBitmaps(false); } else if (textRendering != null) { throw new FOPException( "Valid values for 'text-rendering' are 'auto' and 'bitmap'. Value found: " + textRendering); } pclUtil.setPJLDisabled(cfg.getChild("disable-pjl").getValueAsBoolean(false)); }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { PCLDocumentHandler pclDocumentHandler = (PCLDocumentHandler)documentHandler; PCLRenderingUtil pclUtil = pclDocumentHandler.getPCLUtil(); configure(cfg, pclUtil); } }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo) throws FOPException { FontManager fontManager = userAgent.getFactory().getFontManager(); final Java2DFontMetrics java2DFontMetrics = new Java2DFontMetrics(); final List fontCollections = new java.util.ArrayList(); fontCollections.add(new Base14FontCollection(java2DFontMetrics)); fontCollections.add(new InstalledFontCollection(java2DFontMetrics)); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { FontResolver fontResolver = new DefaultFontResolver(userAgent); FontEventListener listener = new FontEventAdapter( userAgent.getEventBroadcaster()); List fontList = buildFontList(cfg, fontResolver, listener); fontCollections.add(new ConfiguredFontCollection(fontResolver, fontList, userAgent.isComplexScriptFeaturesEnabled())); } fontManager.setup(fontInfo, (FontCollection[])fontCollections.toArray( new FontCollection[fontCollections.size()])); documentHandler.setFontInfo(fontInfo); }
// in src/java/org/apache/fop/render/rtf/ListAttributesConverter.java
static RtfAttributes convertAttributes(ListBlock fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrib.setTwips(RtfListTable.LIST_INDENT, fobj.getCommonMarginBlock().startIndent); attrib.setTwips(RtfText.LEFT_INDENT_BODY, fobj.getCommonMarginBlock().endIndent); /* * set list table defaults */ //set a simple list type attrib.set(RtfListTable.LIST, "simple"); //set following char as tab attrib.set(RtfListTable.LIST_FOLLOWING_CHAR, 0); return attrib; }
// in src/java/org/apache/fop/render/rtf/TableAttributesConverter.java
static RtfAttributes convertTableAttributes(Table fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrib.setTwips(ITableAttributes.ATTR_ROW_LEFT_INDENT, fobj.getCommonMarginBlock().marginLeft); return attrib; }
// in src/java/org/apache/fop/render/rtf/TableAttributesConverter.java
static RtfAttributes convertTablePartAttributes(TablePart part) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); return attrib; }
// in src/java/org/apache/fop/render/rtf/TableAttributesConverter.java
static RtfAttributes convertCellAttributes(TableCell fobj) throws FOPException { //Property p; //RtfColorTable colorTable = RtfColorTable.getInstance(); FOPRtfAttributes attrib = new FOPRtfAttributes(); //boolean isBorderPresent = false; CommonBorderPaddingBackground border = fobj.getCommonBorderPaddingBackground(); // Cell background color Color color = border.backgroundColor; if (color == null) { //If there is no background-color specified for the cell, //then try to read it from table-row or table-header. CommonBorderPaddingBackground brd = null; if (fobj.getParent() instanceof TableRow) { TableRow parentRow = (TableRow)fobj.getParent(); brd = parentRow.getCommonBorderPaddingBackground(); color = brd.backgroundColor; } else if (fobj.getParent() instanceof TableHeader) { TableHeader parentHeader = (TableHeader)fobj.getParent(); brd = parentHeader.getCommonBorderPaddingBackground(); color = brd.backgroundColor; } if (color == null && fobj.getParent() != null && fobj.getParent().getParent() != null && fobj.getParent().getParent().getParent() instanceof Table) { Table table = (Table)fobj.getParent().getParent().getParent(); brd = table.getCommonBorderPaddingBackground(); color = brd.backgroundColor; } } if ((color != null) && (color.getAlpha() != 0 || color.getRed() != 0 || color.getGreen() != 0 || color.getBlue() != 0)) { attrib.set(ITableAttributes.CELL_COLOR_BACKGROUND, color); } BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.BEFORE, attrib, ITableAttributes.CELL_BORDER_TOP); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.AFTER, attrib, ITableAttributes.CELL_BORDER_BOTTOM); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.START, attrib, ITableAttributes.CELL_BORDER_LEFT); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.END, attrib, ITableAttributes.CELL_BORDER_RIGHT); int padding; boolean reproduceMSWordBug = true; //TODO Make this configurable if (reproduceMSWordBug) { //MS Word has a bug where padding left and top are exchanged padding = border.getPaddingStart(false, null); // TODO do we need a real context here? if (padding != 0) { attrib.setTwips(ITableAttributes.ATTR_CELL_PADDING_TOP, padding); attrib.set(ITableAttributes.ATTR_CELL_U_PADDING_TOP, 3 /*=twips*/); } padding = border.getPaddingBefore(false, null); // TODO do we need a real context here? if (padding != 0) { attrib.setTwips(ITableAttributes.ATTR_CELL_PADDING_LEFT, padding); attrib.set(ITableAttributes.ATTR_CELL_U_PADDING_LEFT, 3 /*=twips*/); } } else { padding = border.getPaddingStart(false, null); // TODO do we need a real context here? if (padding != 0) { attrib.setTwips(ITableAttributes.ATTR_CELL_PADDING_LEFT, padding); attrib.set(ITableAttributes.ATTR_CELL_U_PADDING_LEFT, 3 /*=twips*/); } padding = border.getPaddingBefore(false, null); // TODO do we need a real context here? if (padding != 0) { attrib.setTwips(ITableAttributes.ATTR_CELL_PADDING_TOP, padding); attrib.set(ITableAttributes.ATTR_CELL_U_PADDING_TOP, 3 /*=twips*/); } } padding = border.getPaddingEnd(false, null); // TODO do we need a real context here? if (padding != 0) { attrib.setTwips(ITableAttributes.ATTR_CELL_PADDING_RIGHT, padding); attrib.set(ITableAttributes.ATTR_CELL_U_PADDING_RIGHT, 3 /*=twips*/); } padding = border.getPaddingAfter(false, null); // TODO do we need a real context here? if (padding != 0) { attrib.setTwips(ITableAttributes.ATTR_CELL_PADDING_BOTTOM, padding); attrib.set(ITableAttributes.ATTR_CELL_U_PADDING_BOTTOM, 3 /*=twips*/); } int n = fobj.getNumberColumnsSpanned(); // Column spanning : if (n > 1) { attrib.set(ITableAttributes.COLUMN_SPAN, n); } switch (fobj.getDisplayAlign()) { case Constants.EN_BEFORE: attrib.set(ITableAttributes.ATTR_CELL_VERT_ALIGN_TOP); break; case Constants.EN_CENTER: attrib.set(ITableAttributes.ATTR_CELL_VERT_ALIGN_CENTER); break; case Constants.EN_AFTER: attrib.set(ITableAttributes.ATTR_CELL_VERT_ALIGN_BOTTOM); break; default: //nop } return attrib; }
// in src/java/org/apache/fop/render/rtf/TableAttributesConverter.java
static RtfAttributes convertRowAttributes(TableRow fobj, RtfAttributes rtfatts) throws FOPException { //Property p; //RtfColorTable colorTable = RtfColorTable.getInstance(); RtfAttributes attrib = null; if (rtfatts == null) { attrib = new RtfAttributes(); } else { attrib = rtfatts; } //String attrValue; //boolean isBorderPresent = false; //need to set a default width //check for keep-together row attribute if (fobj.getKeepTogether().getWithinPage().getEnum() == Constants.EN_ALWAYS) { attrib.set(ITableAttributes.ROW_KEEP_TOGETHER); } //Check for keep-with-next row attribute. if (fobj.getKeepWithNext().getWithinPage().getEnum() == Constants.EN_ALWAYS) { attrib.set(ITableAttributes.ROW_KEEP_WITH_NEXT); } //Check for keep-with-previous row attribute. if (fobj.getKeepWithPrevious().getWithinPage().getEnum() == Constants.EN_ALWAYS) { attrib.set(ITableAttributes.ROW_KEEP_WITH_PREVIOUS); } //Check for height row attribute. if (fobj.getHeight().getEnum() != Constants.EN_AUTO) { attrib.set(ITableAttributes.ROW_HEIGHT, fobj.getHeight().getValue() / (1000 / 20)); } /* to write a border to a side of a cell one must write the directional * side (ie. left, right) and the inside value if one needs to be taken * out ie if the cell lies on the edge of a table or not, the offending * value will be taken out by RtfTableRow. This is because you can't * say BORDER_TOP and BORDER_HORIZONTAL if the cell lies at the top of * the table. Similarly using BORDER_BOTTOM and BORDER_HORIZONTAL will * not work if the cell lies at th bottom of the table. The same rules * apply for left right and vertical. * Also, the border type must be written after every control word. Thus * it is implemented that the border type is the value of the border * place. */ CommonBorderPaddingBackground border = fobj.getCommonBorderPaddingBackground(); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.BEFORE, attrib, ITableAttributes.CELL_BORDER_TOP); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.AFTER, attrib, ITableAttributes.CELL_BORDER_BOTTOM); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.START, attrib, ITableAttributes.CELL_BORDER_LEFT); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.END, attrib, ITableAttributes.CELL_BORDER_RIGHT); /* ep = (EnumProperty)fobj.getProperty(Constants.PR_BORDER_TOP_STYLE); if (ep != null && ep.getEnum() != Constants.EN_NONE) { attrib.set(ITableAttributes.ROW_BORDER_TOP, "\\" + convertAttributetoRtf(ep.getEnum())); attrib.set(ITableAttributes.ROW_BORDER_HORIZONTAL, "\\" + convertAttributetoRtf(ep.getEnum())); isBorderPresent = true; } ep = (EnumProperty)fobj.getProperty(Constants.PR_BORDER_BOTTOM_STYLE); if (ep != null && ep.getEnum() != Constants.EN_NONE) { attrib.set(ITableAttributes.ROW_BORDER_BOTTOM, "\\" + convertAttributetoRtf(ep.getEnum())); attrib.set(ITableAttributes.ROW_BORDER_HORIZONTAL, "\\" + convertAttributetoRtf(ep.getEnum())); isBorderPresent = true; } ep = (EnumProperty)fobj.getProperty(Constants.PR_BORDER_LEFT_STYLE); if (ep != null && ep.getEnum() != Constants.EN_NONE) { attrib.set(ITableAttributes.ROW_BORDER_LEFT, "\\" + convertAttributetoRtf(ep.getEnum())); attrib.set(ITableAttributes.ROW_BORDER_VERTICAL, "\\" + convertAttributetoRtf(ep.getEnum())); isBorderPresent = true; } ep = (EnumProperty)fobj.getProperty(Constants.PR_BORDER_RIGHT_STYLE); if (ep != null && ep.getEnum() != Constants.EN_NONE) { attrib.set(ITableAttributes.ROW_BORDER_RIGHT, "\\" + convertAttributetoRtf(ep.getEnum())); attrib.set(ITableAttributes.ROW_BORDER_VERTICAL, "\\" + convertAttributetoRtf(ep.getEnum())); isBorderPresent = true; } //Currently there is only one border width supported in each cell. p = fobj.getProperty(Constants.PR_BORDER_LEFT_WIDTH); if(p == null) { p = fobj.getProperty(Constants.PR_BORDER_RIGHT_WIDTH); } if(p == null) { p = fobj.getProperty(Constants.PR_BORDER_TOP_WIDTH); } if(p == null) { p = fobj.getProperty(Constants.PR_BORDER_BOTTOM_WIDTH); } if (p != null) { LengthProperty lengthprop = (LengthProperty)p; Float f = new Float(lengthprop.getLength().getValue() / 1000f); String sValue = f.toString() + FixedLength.POINT; attrib.set(BorderAttributesConverter.BORDER_WIDTH, (int)FoUnitsConverter.getInstance().convertToTwips(sValue)); } else if (isBorderPresent) { //if not defined, set default border width //note 20 twips = 1 point attrib.set(BorderAttributesConverter.BORDER_WIDTH, (int)FoUnitsConverter.getInstance().convertToTwips("1pt")); } */ return attrib; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public RtfTableCell newTableCellMergedHorizontally (int cellWidth, RtfAttributes attrs) throws IOException, FOPException { highestCell++; // Added by Normand Masse // Inherit attributes from base cell for merge RtfAttributes wAttributes = null; if (attrs != null) { try { wAttributes = (RtfAttributes)attrs.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } } cell = new RtfTableCell(this, writer, cellWidth, wAttributes, highestCell); cell.setHMerge(RtfTableCell.MERGE_WITH_PREVIOUS); return cell; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfText.java
public RtfAttributes getTextContainerAttributes() throws FOPException { if (attrib == null) { return null; } try { return (RtfAttributes)this.attrib.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfAttributes getTextContainerAttributes() throws FOPException { if (attrib == null) { return null; } try { return (RtfAttributes)this.attrib.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public RtfAttributes getTextContainerAttributes() throws FOPException { if (attrib == null) { return null; } try { return (RtfAttributes) this.attrib.clone (); } catch (CloneNotSupportedException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
public RtfTableRow newTableRow(RtfAttributes attrs) throws IOException, FOPException { RtfAttributes attr = null; if (attrib != null) { try { attr = (RtfAttributes) attrib.clone (); } catch (CloneNotSupportedException e) { throw new FOPException(e); } attr.set (attrs); } else { attr = attrs; } if (row != null) { row.close(); } highestRow++; row = new RtfTableRow(this, writer, attr, highestRow); return row; }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
float convertToTwips(String foValue) throws FOPException { foValue = foValue.trim(); // break value into number and units final StringBuffer number = new StringBuffer(); final StringBuffer units = new StringBuffer(); for (int i = 0; i < foValue.length(); i++) { final char c = foValue.charAt(i); if (Character.isDigit(c) || c == '.') { number.append(c); } else { // found the end of the digits units.append(foValue.substring(i).trim()); break; } } return numberToTwips(number.toString(), units.toString()); }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
private float numberToTwips(String number, String units) throws FOPException { float result = 0; // convert number to integer try { if (number != null && number.trim().length() > 0) { result = Float.valueOf(number).floatValue(); } } catch (Exception e) { throw new FOPException("number format error: cannot convert '" + number + "' to float value"); } // find conversion factor if (units != null && units.trim().length() > 0) { final Float factor = (Float)TWIP_FACTORS.get(units.toLowerCase()); if (factor == null) { throw new FOPException("conversion factor not found for '" + units + "' units"); } result *= factor.floatValue(); } return result; }
// in src/java/org/apache/fop/render/rtf/FoUnitsConverter.java
int convertFontSize(String size) throws FOPException { size = size.trim(); final String sFONTSUFFIX = FixedLength.POINT; if (!size.endsWith(sFONTSUFFIX)) { throw new FOPException("Invalid font size '" + size + "', must end with '" + sFONTSUFFIX + "'"); } float result = 0; size = size.substring(0, size.length() - sFONTSUFFIX.length()); try { result = (Float.valueOf(size).floatValue()); } catch (Exception e) { throw new FOPException("Invalid font size value '" + size + "'"); } // RTF font size units are in half-points return (int)(result * 2.0); }
// in src/java/org/apache/fop/render/rtf/TextAttributesConverter.java
public static RtfAttributes convertAttributes(Block fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrFont(fobj.getCommonFont(), attrib); attrFontColor(fobj.getColor(), attrib); //attrTextDecoration(fobj.getTextDecoration(), attrib); attrBlockBackgroundColor(fobj.getCommonBorderPaddingBackground(), attrib); attrBlockMargin(fobj.getCommonMarginBlock(), attrib); attrBlockTextAlign(fobj.getTextAlign(), attrib); attrBorder(fobj.getCommonBorderPaddingBackground(), attrib, fobj); attrBreak(fobj, attrib); return attrib; }
// in src/java/org/apache/fop/render/rtf/TextAttributesConverter.java
public static RtfAttributes convertBlockContainerAttributes(BlockContainer fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrBackgroundColor(fobj.getCommonBorderPaddingBackground(), attrib); attrBlockMargin(fobj.getCommonMarginBlock(), attrib); //attrBlockDimension(fobj, attrib); attrBorder(fobj.getCommonBorderPaddingBackground(), attrib, fobj); return attrib; }
// in src/java/org/apache/fop/render/rtf/TextAttributesConverter.java
public static RtfAttributes convertCharacterAttributes( FOText fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrFont(fobj.getCommonFont(), attrib); attrFontColor(fobj.getColor(), attrib); attrTextDecoration(fobj.getTextDecoration(), attrib); attrBaseLineShift(fobj.getBaseLineShift(), attrib); return attrib; }
// in src/java/org/apache/fop/render/rtf/TextAttributesConverter.java
public static RtfAttributes convertCharacterAttributes( PageNumber fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrFont(fobj.getCommonFont(), attrib); attrTextDecoration(fobj.getTextDecoration(), attrib); attrBackgroundColor(fobj.getCommonBorderPaddingBackground(), attrib); return attrib; }
// in src/java/org/apache/fop/render/rtf/TextAttributesConverter.java
public static RtfAttributes convertCharacterAttributes( Inline fobj) throws FOPException { FOPRtfAttributes attrib = new FOPRtfAttributes(); attrFont(fobj.getCommonFont(), attrib); attrFontColor(fobj.getColor(), attrib); attrBackgroundColor(fobj.getCommonBorderPaddingBackground(), attrib); attrInlineBorder(fobj.getCommonBorderPaddingBackground(), attrib); return attrib; }
// in src/java/org/apache/fop/render/rtf/TextAttributesConverter.java
public static RtfAttributes convertLeaderAttributes(Leader fobj, PercentBaseContext context) throws FOPException { boolean tab = false; FOPRtfAttributes attrib = new FOPRtfAttributes(); attrib.set(RtfText.ATTR_FONT_FAMILY, RtfFontManager.getInstance().getFontNumber(fobj.getCommonFont().getFirstFontFamily())); if (fobj.getLeaderLength() != null) { attrib.set(RtfLeader.LEADER_WIDTH, convertMptToTwips(fobj.getLeaderLength().getMaximum( context).getLength().getValue(context))); if (fobj.getLeaderLength().getMaximum(context) instanceof PercentLength) { if (((PercentLength)fobj.getLeaderLength().getMaximum(context)).getString().equals( "100.0%")) { // Use Tab instead of white spaces attrib.set(RtfLeader.LEADER_USETAB, 1); tab = true; } } } attrFontColor(fobj.getColor(), attrib); if (fobj.getLeaderPatternWidth() != null) { //TODO calculate pattern width not possible for white spaces, because its using //underlines for tab it would work with LEADER_PATTERN_WIDTH (expndtw) } switch(fobj.getLeaderPattern()) { case Constants.EN_DOTS: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_DOTTED); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_DOTTED); } break; case Constants.EN_SPACE: //nothing has to be set for spaces break; case Constants.EN_RULE: //Things like start-indent, space-after, ... not supported? //Leader class does not offer these properties //TODO aggregate them with the leader width or // create a second - blank leader - before if (fobj.getRuleThickness() != null) { //TODO See inside RtfLeader, better calculation for //white spaces would be necessary //attrib.set(RtfLeader.LEADER_RULE_THICKNESS, // fobj.getRuleThickness().getValue(context)); log.warn("RTF: fo:leader rule-thickness not supported"); } switch (fobj.getRuleStyle()) { case Constants.EN_SOLID: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_THICK); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_THICK); } break; case Constants.EN_DASHED: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_MIDDLEDOTTED); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_MIDDLEDOTTED); } break; case Constants.EN_DOTTED: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_DOTTED); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_DOTTED); } break; case Constants.EN_DOUBLE: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_EQUAL); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_EQUAL); } break; case Constants.EN_GROOVE: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_HYPHENS); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_HYPHENS); } break; case Constants.EN_RIDGE: if (tab) { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_TAB_UNDERLINE); } else { attrib.set(RtfLeader.LEADER_TABLEAD, RtfLeader.LEADER_UNDERLINE); } break; default: break; } break; case Constants.EN_USECONTENT: log.warn("RTF: fo:leader use-content not supported"); break; default: break; } if (fobj.getLeaderAlignment() == Constants.EN_REFERENCE_AREA) { log.warn("RTF: fo:leader reference-area not supported"); } return attrib; }
// in src/java/org/apache/fop/render/bitmap/BitmapRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { super.configure(documentHandler); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { AbstractBitmapDocumentHandler bitmapHandler = (AbstractBitmapDocumentHandler)documentHandler; BitmapRenderingSettings settings = bitmapHandler.getSettings(); boolean transparent = cfg.getChild( Java2DRenderer.JAVA2D_TRANSPARENT_PAGE_BACKGROUND).getValueAsBoolean( settings.hasTransparentPageBackground()); if (transparent) { settings.setPageBackgroundColor(null); } else { String background = cfg.getChild("background-color").getValue(null); if (background != null) { settings.setPageBackgroundColor( ColorUtil.parseColorString(this.userAgent, background)); } } boolean antiAliasing = cfg.getChild("anti-aliasing").getValueAsBoolean( settings.isAntiAliasingEnabled()); settings.setAntiAliasing(antiAliasing); String optimization = cfg.getChild("rendering").getValue(null); if ("quality".equalsIgnoreCase(optimization)) { settings.setQualityRendering(true); } else if ("speed".equalsIgnoreCase(optimization)) { settings.setQualityRendering(false); } String color = cfg.getChild("color-mode").getValue(null); if (color != null) { if ("rgba".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_INT_ARGB); } else if ("rgb".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_INT_RGB); } else if ("gray".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_BYTE_GRAY); } else if ("binary".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_BYTE_BINARY); } else if ("bi-level".equalsIgnoreCase(color)) { settings.setBufferedImageType(BufferedImage.TYPE_BYTE_BINARY); } else { throw new FOPException("Invalid value for color-mode: " + color); } } } }
// in src/java/org/apache/fop/render/bitmap/BitmapRendererConfigurator.java
public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo) throws FOPException { final FontManager fontManager = userAgent.getFactory().getFontManager(); final Java2DFontMetrics java2DFontMetrics = new Java2DFontMetrics(); final List fontCollections = new java.util.ArrayList(); fontCollections.add(new Base14FontCollection(java2DFontMetrics)); fontCollections.add(new InstalledFontCollection(java2DFontMetrics)); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { FontResolver fontResolver = new DefaultFontResolver(userAgent); FontEventListener listener = new FontEventAdapter( userAgent.getEventBroadcaster()); List fontList = buildFontList(cfg, fontResolver, listener); fontCollections.add(new ConfiguredFontCollection(fontResolver, fontList, userAgent.isComplexScriptFeaturesEnabled())); } fontManager.setup(fontInfo, (FontCollection[])fontCollections.toArray( new FontCollection[fontCollections.size()])); documentHandler.setFontInfo(fontInfo); }
// in src/java/org/apache/fop/render/bitmap/TIFFRendererConfigurator.java
public void configure(Renderer renderer) throws FOPException { Configuration cfg = super.getRendererConfig(renderer); if (cfg != null) { TIFFRenderer tiffRenderer = (TIFFRenderer)renderer; //set compression String name = cfg.getChild("compression").getValue(TIFFConstants.COMPRESSION_PACKBITS); //Some compression formats need a special image format: tiffRenderer.setBufferedImageType(getBufferedImageTypeFor(name)); if (!"NONE".equalsIgnoreCase(name)) { tiffRenderer.getWriterParams().setCompressionMethod(name); } if (log.isInfoEnabled()) { log.info("TIFF compression set to " + name); } } super.configure(renderer); }
// in src/java/org/apache/fop/render/bitmap/TIFFRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { super.configure(documentHandler); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { TIFFDocumentHandler tiffHandler = (TIFFDocumentHandler)documentHandler; BitmapRenderingSettings settings = tiffHandler.getSettings(); //set compression String name = cfg.getChild("compression").getValue(TIFFConstants.COMPRESSION_PACKBITS); //Some compression formats need a special image format: settings.setBufferedImageType(getBufferedImageTypeFor(name)); if (!"NONE".equalsIgnoreCase(name)) { settings.getWriterParams().setCompressionMethod(name); } if (log.isInfoEnabled()) { log.info("TIFF compression set to " + name); } } }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private List<AFPFontInfo> buildFontListFromConfiguration(Configuration cfg, AFPEventProducer eventProducer) throws FOPException, ConfigurationException { Configuration fonts = cfg.getChild("fonts"); FontManager fontManager = this.userAgent.getFactory().getFontManager(); // General matcher FontTriplet.Matcher referencedFontsMatcher = fontManager.getReferencedFontsMatcher(); // Renderer-specific matcher FontTriplet.Matcher localMatcher = null; // Renderer-specific referenced fonts Configuration referencedFontsCfg = fonts.getChild("referenced-fonts", false); if (referencedFontsCfg != null) { localMatcher = FontManagerConfigurator.createFontsMatcher( referencedFontsCfg, this.userAgent.getFactory().validateUserConfigStrictly()); } List<AFPFontInfo> fontList = new java.util.ArrayList<AFPFontInfo>(); Configuration[] font = fonts.getChildren("font"); final String fontPath = null; for (int i = 0; i < font.length; i++) { AFPFontInfo afi = buildFont(font[i], fontPath); if (afi != null) { if (log.isDebugEnabled()) { log.debug("Adding font " + afi.getAFPFont().getFontName()); } List<FontTriplet> fontTriplets = afi.getFontTriplets(); for (int j = 0; j < fontTriplets.size(); ++j) { FontTriplet triplet = fontTriplets.get(j); if (log.isDebugEnabled()) { log.debug(" Font triplet " + triplet.getName() + ", " + triplet.getStyle() + ", " + triplet.getWeight()); } if ((referencedFontsMatcher != null && referencedFontsMatcher.matches(triplet)) || (localMatcher != null && localMatcher.matches(triplet))) { afi.getAFPFont().setEmbeddable(false); break; } } fontList.add(afi); } } return fontList; }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private void configure(AFPCustomizable customizable, Configuration cfg) throws FOPException { // image information Configuration imagesCfg = cfg.getChild("images"); // default to grayscale images String imagesMode = imagesCfg.getAttribute("mode", IMAGES_MODE_GRAYSCALE); if (IMAGES_MODE_COLOR.equals(imagesMode)) { customizable.setColorImages(true); boolean cmyk = imagesCfg.getAttributeAsBoolean("cmyk", false); customizable.setCMYKImagesSupported(cmyk); } else { customizable.setColorImages(false); // default to 8 bits per pixel int bitsPerPixel = imagesCfg.getAttributeAsInteger("bits-per-pixel", 8); customizable.setBitsPerPixel(bitsPerPixel); } String dithering = imagesCfg.getAttribute("dithering-quality", "medium"); float dq = 0.5f; if (dithering.startsWith("min")) { dq = 0.0f; } else if (dithering.startsWith("max")) { dq = 1.0f; } else { try { dq = Float.parseFloat(dithering); } catch (NumberFormatException nfe) { //ignore and leave the default above } } customizable.setDitheringQuality(dq); // native image support boolean nativeImageSupport = imagesCfg.getAttributeAsBoolean("native", false); customizable.setNativeImagesSupported(nativeImageSupport); Configuration jpegConfig = imagesCfg.getChild("jpeg"); boolean allowEmbedding = false; float ieq = 1.0f; if (jpegConfig != null) { allowEmbedding = jpegConfig.getAttributeAsBoolean("allow-embedding", false); String bitmapEncodingQuality = jpegConfig.getAttribute("bitmap-encoding-quality", null); if (bitmapEncodingQuality != null) { try { ieq = Float.parseFloat(bitmapEncodingQuality); } catch (NumberFormatException nfe) { //ignore and leave the default above } } } customizable.canEmbedJpeg(allowEmbedding); customizable.setBitmapEncodingQuality(ieq); //FS11 and FS45 page segment wrapping boolean pSeg = imagesCfg.getAttributeAsBoolean("pseg", false); customizable.setWrapPSeg(pSeg); //FS45 image forcing boolean fs45 = imagesCfg.getAttributeAsBoolean("fs45", false); customizable.setFS45(fs45); // shading (filled rectangles) Configuration shadingCfg = cfg.getChild("shading"); AFPShadingMode shadingMode = AFPShadingMode.valueOf( shadingCfg.getValue(AFPShadingMode.COLOR.getName())); customizable.setShadingMode(shadingMode); // GOCA Support Configuration gocaCfg = cfg.getChild("goca"); boolean gocaEnabled = gocaCfg.getAttributeAsBoolean( "enabled", customizable.isGOCAEnabled()); customizable.setGOCAEnabled(gocaEnabled); String gocaText = gocaCfg.getAttribute( "text", customizable.isStrokeGOCAText() ? "stroke" : "default"); customizable.setStrokeGOCAText("stroke".equalsIgnoreCase(gocaText) || "shapes".equalsIgnoreCase(gocaText)); // renderer resolution Configuration rendererResolutionCfg = cfg.getChild("renderer-resolution", false); if (rendererResolutionCfg != null) { customizable.setResolution(rendererResolutionCfg.getValueAsInteger(240)); } // renderer resolution Configuration lineWidthCorrectionCfg = cfg.getChild("line-width-correction", false); if (lineWidthCorrectionCfg != null) { customizable.setLineWidthCorrection(lineWidthCorrectionCfg .getValueAsFloat(AFPConstants.LINE_WIDTH_CORRECTION)); } // a default external resource group file setting Configuration resourceGroupFileCfg = cfg.getChild("resource-group-file", false); if (resourceGroupFileCfg != null) { String resourceGroupDest = null; try { resourceGroupDest = resourceGroupFileCfg.getValue(); if (resourceGroupDest != null) { File resourceGroupFile = new File(resourceGroupDest); boolean created = resourceGroupFile.createNewFile(); if (created && resourceGroupFile.canWrite()) { customizable.setDefaultResourceGroupFilePath(resourceGroupDest); } else { log.warn("Unable to write to default external resource group file '" + resourceGroupDest + "'"); } } } catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); } catch (IOException ioe) { throw new FOPException("Could not create default external resource group file" , ioe); } } Configuration defaultResourceLevelCfg = cfg.getChild("default-resource-levels", false); if (defaultResourceLevelCfg != null) { AFPResourceLevelDefaults defaults = new AFPResourceLevelDefaults(); String[] types = defaultResourceLevelCfg.getAttributeNames(); for (int i = 0, c = types.length; i < c; i++) { String type = types[i]; try { String level = defaultResourceLevelCfg.getAttribute(type); defaults.setDefaultResourceLevel(type, AFPResourceLevel.valueOf(level)); } catch (IllegalArgumentException iae) { LogUtil.handleException(log, iae, userAgent.getFactory().validateUserConfigStrictly()); } catch (ConfigurationException e) { LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); } } customizable.setResourceLevelDefaults(defaults); } }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
Override public void configure(IFDocumentHandler documentHandler) throws FOPException { Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { AFPDocumentHandler afpDocumentHandler = (AFPDocumentHandler) documentHandler; configure(afpDocumentHandler, cfg); } }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
Override public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo) throws FOPException { FontManager fontManager = userAgent.getFactory().getFontManager(); List<AFPFontCollection> fontCollections = new ArrayList<AFPFontCollection>(); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { try { List<AFPFontInfo> fontList = buildFontListFromConfiguration(cfg, eventProducer); fontCollections.add(new AFPFontCollection( userAgent.getEventBroadcaster(), fontList)); } catch (ConfigurationException e) { eventProducer.invalidConfiguration(this, e); LogUtil.handleException(log, e, userAgent.getFactory().validateUserConfigStrictly()); } } else { fontCollections.add(new AFPFontCollection(userAgent.getEventBroadcaster(), null)); } fontManager.setup(fontInfo, fontCollections.toArray( new FontCollection[fontCollections.size()])); documentHandler.setFontInfo(fontInfo); }
// in src/java/org/apache/fop/render/afp/extensions/AFPInvokeMediumMapElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if (parent.getNameId() != Constants.FO_PAGE_SEQUENCE && parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfPageSequence"); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageOverlayElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if (AFPElementMapping.INCLUDE_PAGE_OVERLAY.equals(getLocalName())) { if (parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER && parent.getNameId() != Constants.FO_PAGE_SEQUENCE) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfPageSequenceOrSPM"); } } else { if (parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfSPM"); } } }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageOverlayElement.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { super.processNode(elementName, locator, attlist, propertyList); AFPPageOverlay pageOverlay = getPageSetupAttachment(); if (AFPElementMapping.INCLUDE_PAGE_OVERLAY.equals(elementName)) { // convert user specific units to mpts and set the coordinates for the page overlay AFPPaintingState paintingState = new AFPPaintingState(); AFPUnitConverter unitConverter = new AFPUnitConverter(paintingState); int x = (int)unitConverter.mpt2units(UnitConv.convert(attlist.getValue(ATT_X))); int y = (int)unitConverter.mpt2units(UnitConv.convert(attlist.getValue(ATT_Y))); pageOverlay.setX(x); pageOverlay.setY(y); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPIncludeFormMapElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if (parent.getNameId() != Constants.FO_DECLARATIONS) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfDeclarations"); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPIncludeFormMapElement.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { super.processNode(elementName, locator, attlist, propertyList); AFPIncludeFormMap formMap = getFormMapAttachment(); String attr = attlist.getValue(ATT_SRC); if (attr != null && attr.length() > 0) { try { formMap.setSrc(new URI(attr)); } catch (URISyntaxException e) { getFOValidationEventProducer().invalidPropertyValue(this, elementName, ATT_SRC, attr, null, getLocator()); } } else { missingPropertyError(ATT_SRC); } }
// in src/java/org/apache/fop/render/afp/extensions/AbstractAFPExtensionObject.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { getExtensionAttachment(); String attr = attlist.getValue("name"); if (attr != null && attr.length() > 0) { extensionAttachment.setName(attr); } else { throw new FOPException(elementName + " must have a name attribute."); } }
// in src/java/org/apache/fop/render/afp/extensions/AbstractAFPExtensionObject.java
protected void endOfNode() throws FOPException { super.endOfNode(); }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSetupElement.java
Override protected void startOfNode() throws FOPException { super.startOfNode(); if (AFPElementMapping.TAG_LOGICAL_ELEMENT.equals(getLocalName())) { if (parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER && parent.getNameId() != Constants.FO_PAGE_SEQUENCE) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfPageSequenceOrSPM"); } } else { if (parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER && parent.getNameId() != Constants.FO_PAGE_SEQUENCE && parent.getNameId() != Constants.FO_DECLARATIONS) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfSPMorPSorDeclarations"); } } }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSetupElement.java
Override protected void characters(char[] data, int start, int length, PropertyList pList, Locator locator) throws FOPException { StringBuffer sb = new StringBuffer(); AFPPageSetup pageSetup = getPageSetupAttachment(); if (pageSetup.getContent() != null) { sb.append(pageSetup.getContent()); } sb.append(data, start, length); pageSetup.setContent(sb.toString()); }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSetupElement.java
Override public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { super.processNode(elementName, locator, attlist, propertyList); AFPPageSetup pageSetup = getPageSetupAttachment(); if (AFPElementMapping.INCLUDE_PAGE_SEGMENT.equals(elementName)) { String attr = attlist.getValue(ATT_SRC); if (attr != null && attr.length() > 0) { pageSetup.setValue(attr); } else { missingPropertyError(ATT_SRC); } } else if (AFPElementMapping.TAG_LOGICAL_ELEMENT.equals(elementName)) { String attr = attlist.getValue(AFPPageSetup.ATT_VALUE); if (attr != null && attr.length() > 0) { pageSetup.setValue(attr); } else { missingPropertyError(AFPPageSetup.ATT_VALUE); } } String placement = attlist.getValue(AFPPageSetup.ATT_PLACEMENT); if (placement != null && placement.length() > 0) { pageSetup.setPlacement(ExtensionPlacement.fromXMLValue(placement)); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSegmentElement.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { AFPPageSegmentSetup pageSetup = getPageSetupAttachment(); super.processNode(elementName, locator, attlist, propertyList); String attr = attlist.getValue(ATT_RESOURCE_SRC); if (attr != null && attr.length() > 0) { pageSetup.setResourceSrc(attr); } }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public void renderPage(PageViewport pageViewport) throws IOException, FOPException { super.renderPage(pageViewport); if (statusListener != null) { statusListener.notifyPageRendered(); } }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public Dimension getPageImageSize(int pageNum) throws FOPException { Rectangle2D bounds = getPageViewport(pageNum).getViewArea(); pageWidth = (int) Math.round(bounds.getWidth() / 1000f); pageHeight = (int) Math.round(bounds.getHeight() / 1000f); double scaleX = scaleFactor * (UnitConv.IN2MM / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION) / userAgent.getTargetPixelUnitToMillimeter(); double scaleY = scaleFactor * (UnitConv.IN2MM / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION) / userAgent.getTargetPixelUnitToMillimeter(); if (getPageViewport(pageNum).getForeignAttributes() != null) { String scale = (String) getPageViewport(pageNum).getForeignAttributes().get( PageScale.EXT_PAGE_SCALE); Point2D scales = PageScale.getScale(scale); if (scales != null) { scaleX *= scales.getX(); scaleY *= scales.getY(); } } int bitmapWidth = (int) ((pageWidth * scaleX) + 0.5); int bitmapHeight = (int) ((pageHeight * scaleY) + 0.5); return new Dimension(bitmapWidth, bitmapHeight); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java
public double getScaleToFitWindow() throws FOPException { Dimension extents = previewArea.getViewport().getExtentSize(); return getScaleToFit(extents.getWidth() - 2 * BORDER_SPACING, extents.getHeight() - 2 * BORDER_SPACING); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java
public double getScaleToFitWidth() throws FOPException { Dimension extents = previewArea.getViewport().getExtentSize(); return getScaleToFit(extents.getWidth() - 2 * BORDER_SPACING, Double.MAX_VALUE); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java
public double getScaleToFit(double viewWidth, double viewHeight) throws FOPException { PageViewport pageViewport = renderer.getPageViewport(currentPage); Rectangle2D pageSize = pageViewport.getViewArea(); float screenResolution = Toolkit.getDefaultToolkit().getScreenResolution(); float screenFactor = screenResolution / UnitConv.IN2PT; double widthScale = viewWidth / (pageSize.getWidth() / 1000f) / screenFactor; double heightScale = viewHeight / (pageSize.getHeight() / 1000f) / screenFactor; return Math.min(displayMode == CONT_FACING ? widthScale / 2 : widthScale, heightScale); }
// in src/java/org/apache/fop/render/ps/PSRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { PSDocumentHandler psDocumentHandler = (PSDocumentHandler)documentHandler; configure(psDocumentHandler.getPSUtil(), cfg); } }
// in src/java/org/apache/fop/render/ps/extensions/AbstractPSExtensionElement.java
protected void endOfNode() throws FOPException { super.endOfNode(); String s = ((PSExtensionAttachment)getExtensionAttachment()).getContent(); if (s == null || s.length() == 0) { missingChildElementError("#PCDATA"); } }
// in src/java/org/apache/fop/render/ps/extensions/AbstractPSExtensionObject.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { String name = attlist.getValue("name"); if (name != null && name.length() > 0) { setupCode.setName(name); } }
// in src/java/org/apache/fop/render/ps/extensions/AbstractPSExtensionObject.java
protected void endOfNode() throws FOPException { super.endOfNode(); String s = setupCode.getContent(); if (s == null || s.length() == 0) { missingChildElementError("#PCDATA"); } }
// in src/java/org/apache/fop/render/ps/extensions/AbstractPSCommentElement.java
protected void startOfNode() throws FOPException { if (parent.getNameId() != Constants.FO_DECLARATIONS && parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfSPMorDeclarations"); } }
// in src/java/org/apache/fop/render/ps/extensions/PSSetPageDeviceElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if ( !((parent.getNameId() == Constants.FO_DECLARATIONS) || (parent.getNameId() == Constants.FO_SIMPLE_PAGE_MASTER)) ) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfSPMorDeclarations"); } }
// in src/java/org/apache/fop/render/ps/extensions/PSSetPageDeviceElement.java
public void processNode(String elementName, Locator locator, Attributes attlist, PropertyList propertyList) throws FOPException { String name = attlist.getValue("name"); if (name != null && name.length() > 0) { ((PSSetPageDevice)getExtensionAttachment()).setName(name); } }
// in src/java/org/apache/fop/render/ps/extensions/PSPageSetupCodeElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if (parent.getNameId() != Constants.FO_SIMPLE_PAGE_MASTER) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfSPM"); } }
// in src/java/org/apache/fop/render/ps/extensions/PSSetupCodeElement.java
protected void startOfNode() throws FOPException { super.startOfNode(); if (parent.getNameId() != Constants.FO_DECLARATIONS) { invalidChildError(getLocator(), parent.getName(), getNamespaceURI(), getName(), "rule.childOfDeclarations"); } }
// in src/java/org/apache/fop/render/java2d/Java2DRendererConfigurator.java
public void configure(Renderer renderer) throws FOPException { Configuration cfg = super.getRendererConfig(renderer); if (cfg != null) { Java2DRenderer java2dRenderer = (Java2DRenderer)renderer; String value = cfg.getChild( Java2DRenderer.JAVA2D_TRANSPARENT_PAGE_BACKGROUND, true).getValue(null); if (value != null) { java2dRenderer.setTransparentPageBackground("true".equalsIgnoreCase(value)); } } super.configure(renderer); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public void renderPage(PageViewport pageViewport) throws IOException, FOPException { try { rememberPage((PageViewport)pageViewport.clone()); } catch (CloneNotSupportedException e) { throw new FOPException(e); } //The clone() call is necessary as we store the page for later. Otherwise, the //RenderPagesModel calls PageViewport.clear() to release memory as early as possible. currentPageNumber++; }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public PageViewport getPageViewport(int pageIndex) throws FOPException { if (pageIndex < 0 || pageIndex >= pageViewportList.size()) { throw new FOPException("Requested page number is out of range: " + pageIndex + "; only " + pageViewportList.size() + " page(s) available."); } return (PageViewport) pageViewportList.get(pageIndex); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public BufferedImage getPageImage(int pageNum) throws FOPException { return getPageImage(getPageViewport(pageNum)); }
// in src/java/org/apache/fop/render/PrintRendererConfigurator.java
public void configure(Renderer renderer) throws FOPException { Configuration cfg = getRendererConfig(renderer); if (cfg == null) { log.trace("no configuration found for " + renderer); return; } PrintRenderer printRenderer = (PrintRenderer)renderer; FontResolver fontResolver = printRenderer.getFontResolver(); FontEventListener listener = new FontEventAdapter( renderer.getUserAgent().getEventBroadcaster()); List<EmbedFontInfo> embedFontInfoList = buildFontList(cfg, fontResolver, listener); printRenderer.addFontList(embedFontInfoList); }
// in src/java/org/apache/fop/render/PrintRendererConfigurator.java
protected List<EmbedFontInfo> buildFontList(Configuration cfg, FontResolver fontResolver, FontEventListener listener) throws FOPException { FopFactory factory = userAgent.getFactory(); FontManager fontManager = factory.getFontManager(); if (fontResolver == null) { //Ensure that we have minimal font resolution capabilities fontResolver = FontManager.createMinimalFontResolver ( userAgent.isComplexScriptFeaturesEnabled() ); } boolean strict = factory.validateUserConfigStrictly(); //Read font configuration FontInfoConfigurator fontInfoConfigurator = new FontInfoConfigurator(cfg, fontManager, fontResolver, listener, strict); List<EmbedFontInfo> fontInfoList = new ArrayList<EmbedFontInfo>(); fontInfoConfigurator.configure(fontInfoList); return fontInfoList; }
// in src/java/org/apache/fop/render/PrintRendererConfigurator.java
public void configure(IFDocumentHandler documentHandler) throws FOPException { //nop }
// in src/java/org/apache/fop/render/PrintRendererConfigurator.java
public void setupFontInfo(IFDocumentHandler documentHandler, FontInfo fontInfo) throws FOPException { FontManager fontManager = userAgent.getFactory().getFontManager(); List<FontCollection> fontCollections = new ArrayList<FontCollection>(); fontCollections.add(new Base14FontCollection(fontManager.isBase14KerningEnabled())); Configuration cfg = super.getRendererConfig(documentHandler.getMimeType()); if (cfg != null) { FontResolver fontResolver = new DefaultFontResolver(userAgent); FontEventListener listener = new FontEventAdapter( userAgent.getEventBroadcaster()); List<EmbedFontInfo> fontList = buildFontList(cfg, fontResolver, listener); fontCollections.add(new CustomFontCollection(fontResolver, fontList, userAgent.isComplexScriptFeaturesEnabled())); } fontManager.setup(fontInfo, (FontCollection[])fontCollections.toArray( new FontCollection[fontCollections.size()])); documentHandler.setFontInfo(fontInfo); }
// in src/java/org/apache/fop/area/AreaTreeHandler.java
protected void setupModel(FOUserAgent userAgent, String outputFormat, OutputStream stream) throws FOPException { if (userAgent.isConserveMemoryPolicyEnabled()) { this.model = new CachedRenderPagesModel(userAgent, outputFormat, fontInfo, stream); } else { this.model = new RenderPagesModel(userAgent, outputFormat, fontInfo, stream); } }
// in src/java/org/apache/fop/util/LogUtil.java
public static void handleError(Log log, String errorStr, boolean strict) throws FOPException { handleException(log, new FOPException(errorStr), strict); }
// in src/java/org/apache/fop/util/LogUtil.java
public static void handleException(Log log, Exception e, boolean strict) throws FOPException { if (strict) { if (e instanceof FOPException) { throw (FOPException)e; } throw new FOPException(e); } log.error(e.getMessage()); }
// in src/java/org/apache/fop/cli/AreaTreeInputHandler.java
public void renderTo(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { FontInfo fontInfo = new FontInfo(); AreaTreeModel treeModel = new RenderPagesModel(userAgent, outputFormat, fontInfo, out); //Iterate over all intermediate files AreaTreeParser parser = new AreaTreeParser(); // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(parser.getContentHandler(treeModel, userAgent)); transformTo(res); try { treeModel.endDocument(); } catch (SAXException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/cli/InputHandler.java
public void renderTo(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { FopFactory factory = userAgent.getFactory(); Fop fop; if (out != null) { fop = factory.newFop(outputFormat, userAgent, out); } else { fop = factory.newFop(outputFormat, userAgent); } // if base URL was not explicitly set in FOUserAgent, obtain here if (fop.getUserAgent().getBaseURL() == null && sourcefile != null) { String baseURL = null; try { baseURL = new File(sourcefile.getAbsolutePath()) .getParentFile().toURI().toURL().toExternalForm(); } catch (Exception e) { baseURL = ""; } fop.getUserAgent().setBaseURL(baseURL); } // Resulting SAX events (the generated FO) must be piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); transformTo(res); }
// in src/java/org/apache/fop/cli/InputHandler.java
public void renderTo(FOUserAgent userAgent, String outputFormat) throws FOPException { renderTo(userAgent, outputFormat, null); }
// in src/java/org/apache/fop/cli/InputHandler.java
public void transformTo(OutputStream out) throws FOPException { Result res = new StreamResult(out); transformTo(res); }
// in src/java/org/apache/fop/cli/InputHandler.java
protected void transformTo(Result result) throws FOPException { try { // Setup XSLT TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer; Source xsltSource = createXSLTSource(); if (xsltSource == null) { // FO Input transformer = factory.newTransformer(); } else { // XML/XSLT input transformer = factory.newTransformer(xsltSource); // Set the value of parameters, if any, defined for stylesheet if (xsltParams != null) { for (int i = 0; i < xsltParams.size(); i += 2) { transformer.setParameter((String) xsltParams.elementAt(i), (String) xsltParams.elementAt(i + 1)); } } if (uriResolver != null) { transformer.setURIResolver(uriResolver); } } transformer.setErrorListener(this); // Create a SAXSource from the input Source file Source src = createMainSource(); // Start XSLT transformation and FOP processing transformer.transform(src, result); } catch (Exception e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
public boolean parse(String[] args) throws FOPException, IOException { boolean optionsParsed = true; try { optionsParsed = parseOptions(args); if (optionsParsed) { if (showConfiguration == Boolean.TRUE) { dumpConfiguration(); } checkSettings(); setUserConfig(); if (flushCache) { flushCache(); } //Factory config is set up, now we can create the user agent foUserAgent = factory.newFOUserAgent(); foUserAgent.getRendererOptions().putAll(renderingOptions); if (targetResolution != 0) { foUserAgent.setTargetResolution(targetResolution); } addXSLTParameter("fop-output-format", getOutputFormat()); addXSLTParameter("fop-version", Version.getVersion()); foUserAgent.setConserveMemoryPolicy(conserveMemoryPolicy); if (!useComplexScriptFeatures) { foUserAgent.setComplexScriptFeaturesEnabled(false); } } else { return false; } } catch (FOPException e) { printUsage(System.err); throw e; } catch (java.io.FileNotFoundException e) { printUsage(System.err); throw e; } inputHandler = createInputHandler(); if (MimeConstants.MIME_FOP_AWT_PREVIEW.equals(outputmode)) { //set the system look&feel for the preview dialog try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println("Couldn't set system look & feel!"); } AWTRenderer renderer = new AWTRenderer(foUserAgent, inputHandler, true, true); foUserAgent.setRendererOverride(renderer); } else if (MimeConstants.MIME_FOP_AREA_TREE.equals(outputmode) && mimicRenderer != null) { // render from FO to Intermediate Format Renderer targetRenderer = foUserAgent.getRendererFactory().createRenderer( foUserAgent, mimicRenderer); XMLRenderer xmlRenderer = new XMLRenderer(foUserAgent); //Tell the XMLRenderer to mimic the target renderer xmlRenderer.mimicRenderer(targetRenderer); //Make sure the prepared XMLRenderer is used foUserAgent.setRendererOverride(xmlRenderer); } else if (MimeConstants.MIME_FOP_IF.equals(outputmode) && mimicRenderer != null) { // render from FO to Intermediate Format IFSerializer serializer = new IFSerializer(); serializer.setContext(new IFContext(foUserAgent)); IFDocumentHandler targetHandler = foUserAgent.getRendererFactory().createDocumentHandler( foUserAgent, mimicRenderer); serializer.mimicDocumentHandler(targetHandler); //Make sure the prepared serializer is used foUserAgent.setDocumentHandlerOverride(serializer); } return true; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private boolean parseOptions(String[] args) throws FOPException { // do not throw an exception for no args if (args.length == 0) { printVersion(); printUsage(System.out); return false; } for (int i = 0; i < args.length; i++) { if (args[i].equals("-x") || args[i].equals("--dump-config")) { showConfiguration = Boolean.TRUE; } else if (args[i].equals("-c")) { i = i + parseConfigurationOption(args, i); } else if (args[i].equals("-l")) { i = i + parseLanguageOption(args, i); } else if (args[i].equals("-s")) { suppressLowLevelAreas = Boolean.TRUE; } else if (args[i].equals("-d")) { setLogOption("debug", "debug"); } else if (args[i].equals("-r")) { factory.setStrictValidation(false); } else if (args[i].equals("-conserve")) { conserveMemoryPolicy = true; } else if (args[i].equals("-flush")) { flushCache = true; } else if (args[i].equals("-cache")) { parseCacheOption(args, i); } else if (args[i].equals("-dpi")) { i = i + parseResolution(args, i); } else if (args[i].equals("-q") || args[i].equals("--quiet")) { setLogOption("quiet", "error"); } else if (args[i].equals("-fo")) { i = i + parseFOInputOption(args, i); } else if (args[i].equals("-xsl")) { i = i + parseXSLInputOption(args, i); } else if (args[i].equals("-xml")) { i = i + parseXMLInputOption(args, i); } else if (args[i].equals("-atin")) { i = i + parseAreaTreeInputOption(args, i); } else if (args[i].equals("-ifin")) { i = i + parseIFInputOption(args, i); } else if (args[i].equals("-imagein")) { i = i + parseImageInputOption(args, i); } else if (args[i].equals("-awt")) { i = i + parseAWTOutputOption(args, i); } else if (args[i].equals("-pdf")) { i = i + parsePDFOutputOption(args, i, null); } else if (args[i].equals("-pdfa1b")) { i = i + parsePDFOutputOption(args, i, "PDF/A-1b"); } else if (args[i].equals("-mif")) { i = i + parseMIFOutputOption(args, i); } else if (args[i].equals("-rtf")) { i = i + parseRTFOutputOption(args, i); } else if (args[i].equals("-tiff")) { i = i + parseTIFFOutputOption(args, i); } else if (args[i].equals("-png")) { i = i + parsePNGOutputOption(args, i); } else if (args[i].equals("-print")) { // show print help if (i + 1 < args.length) { if (args[i + 1].equals("help")) { printUsagePrintOutput(); return false; } } i = i + parsePrintOutputOption(args, i); } else if (args[i].equals("-copies")) { i = i + parseCopiesOption(args, i); } else if (args[i].equals("-pcl")) { i = i + parsePCLOutputOption(args, i); } else if (args[i].equals("-ps")) { i = i + parsePostscriptOutputOption(args, i); } else if (args[i].equals("-txt")) { i = i + parseTextOutputOption(args, i); } else if (args[i].equals("-svg")) { i = i + parseSVGOutputOption(args, i); } else if (args[i].equals("-afp")) { i = i + parseAFPOutputOption(args, i); } else if (args[i].equals("-foout")) { i = i + parseFOOutputOption(args, i); } else if (args[i].equals("-out")) { i = i + parseCustomOutputOption(args, i); } else if (args[i].equals("-at")) { i = i + parseAreaTreeOption(args, i); } else if (args[i].equals("-if")) { i = i + parseIntermediateFormatOption(args, i); } else if (args[i].equals("-a")) { this.renderingOptions.put(Accessibility.ACCESSIBILITY, Boolean.TRUE); } else if (args[i].equals("-v")) { /* verbose mode although users may expect version; currently just print the version */ printVersion(); if (args.length == 1) { return false; } } else if (args[i].equals("-param")) { if (i + 2 < args.length) { String name = args[++i]; String expression = args[++i]; addXSLTParameter(name, expression); } else { throw new FOPException("invalid param usage: use -param <name> <value>"); } } else if (args[i].equals("-catalog")) { useCatalogResolver = true; } else if (args[i].equals("-o")) { i = i + parsePDFOwnerPassword(args, i); } else if (args[i].equals("-u")) { i = i + parsePDFUserPassword(args, i); } else if (args[i].equals("-pdfprofile")) { i = i + parsePDFProfile(args, i); } else if (args[i].equals("-noprint")) { getPDFEncryptionParams().setAllowPrint(false); } else if (args[i].equals("-nocopy")) { getPDFEncryptionParams().setAllowCopyContent(false); } else if (args[i].equals("-noedit")) { getPDFEncryptionParams().setAllowEditContent(false); } else if (args[i].equals("-noannotations")) { getPDFEncryptionParams().setAllowEditAnnotations(false); } else if (args[i].equals("-nocs")) { useComplexScriptFeatures = false; } else if (args[i].equals("-nofillinforms")) { getPDFEncryptionParams().setAllowFillInForms(false); } else if (args[i].equals("-noaccesscontent")) { getPDFEncryptionParams().setAllowAccessContent(false); } else if (args[i].equals("-noassembledoc")) { getPDFEncryptionParams().setAllowAssembleDocument(false); } else if (args[i].equals("-noprinthq")) { getPDFEncryptionParams().setAllowPrintHq(false); } else if (args[i].equals("-version")) { printVersion(); return false; } else if (!isOption(args[i])) { i = i + parseUnknownOption(args, i); } else { printUsage(System.err); System.exit(1); } } return true; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseCacheOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("if you use '-cache', you must specify " + "the name of the font cache file"); } else { factory.getFontManager().setCacheFile(new File(args[i + 1])); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseConfigurationOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("if you use '-c', you must specify " + "the name of the configuration file"); } else { userConfigFile = new File(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseLanguageOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("if you use '-l', you must specify a language"); } else { Locale.setDefault(new Locale(args[i + 1], "")); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseResolution(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException( "if you use '-dpi', you must specify a resolution (dots per inch)"); } else { this.targetResolution = Integer.parseInt(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseFOInputOption(String[] args, int i) throws FOPException { setInputFormat(FO_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the fo file for the '-fo' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { fofile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseXSLInputOption(String[] args, int i) throws FOPException { setInputFormat(XSLT_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the stylesheet " + "file for the '-xsl' option"); } else { xsltfile = new File(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseXMLInputOption(String[] args, int i) throws FOPException { setInputFormat(XSLT_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the input file " + "for the '-xml' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { xmlfile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAWTOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_FOP_AWT_PREVIEW); return 0; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePDFOutputOption(String[] args, int i, String pdfAMode) throws FOPException { setOutputMode(MimeConstants.MIME_PDF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PDF output file"); } else { setOutputFile(args[i + 1]); if (pdfAMode != null) { if (renderingOptions.get("pdf-a-mode") != null) { throw new FOPException("PDF/A mode already set"); } renderingOptions.put("pdf-a-mode", pdfAMode); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseMIFOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_MIF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the MIF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseRTFOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_RTF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the RTF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseTIFFOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_TIFF); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the TIFF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePNGOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_PNG); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PNG output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePrintOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_FOP_PRINT); if ((i + 1 < args.length) && (args[i + 1].charAt(0) != '-')) { String arg = args[i + 1]; String[] parts = arg.split(","); for (int j = 0; j < parts.length; j++) { String s = parts[j]; if (s.matches("\\d+")) { renderingOptions.put(PrintRenderer.START_PAGE, new Integer(s)); } else if (s.matches("\\d+-\\d+")) { String[] startend = s.split("-"); renderingOptions.put(PrintRenderer.START_PAGE, new Integer(startend[0])); renderingOptions.put(PrintRenderer.END_PAGE, new Integer(startend[1])); } else { PagesMode mode = PagesMode.byName(s); renderingOptions.put(PrintRenderer.PAGES_MODE, mode); } } return 1; } else { return 0; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseCopiesOption(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the number of copies"); } else { renderingOptions.put(PrintRenderer.COPIES, new Integer(args[i + 1])); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePCLOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_PCL); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PDF output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePostscriptOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_POSTSCRIPT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the PostScript output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseTextOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_PLAIN_TEXT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the text output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseSVGOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_SVG); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the SVG output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAFPOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_AFP); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the AFP output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseFOOutputOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_XSL_FO); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the FO output file"); } else { setOutputFile(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseCustomOutputOption(String[] args, int i) throws FOPException { String mime = null; if ((i + 1 < args.length) || (args[i + 1].charAt(0) != '-')) { mime = args[i + 1]; if ("list".equals(mime)) { String[] mimes = factory.getRendererFactory().listSupportedMimeTypes(); System.out.println("Supported MIME types:"); for (int j = 0; j < mimes.length; j++) { System.out.println(" " + mimes[j]); } System.exit(0); } } if ((i + 2 >= args.length) || (isOption(args[i + 1])) || (isOption(args[i + 2]))) { throw new FOPException("you must specify the output format and the output file"); } else { setOutputMode(mime); setOutputFile(args[i + 2]); return 2; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseUnknownOption(String[] args, int i) throws FOPException { if (inputmode == NOT_SET) { inputmode = FO_INPUT; String filename = args[i]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { fofile = new File(filename); } } else if (outputmode == null) { outputmode = MimeConstants.MIME_PDF; setOutputFile(args[i]); } else { throw new FOPException("Don't know what to do with " + args[i]); } return 0; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAreaTreeOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_FOP_AREA_TREE); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the area-tree output file"); } else if ((i + 2 == args.length) || (isOption(args[i + 2]))) { // only output file is specified setOutputFile(args[i + 1]); return 1; } else { // mimic format and output file have been specified mimicRenderer = args[i + 1]; setOutputFile(args[i + 2]); return 2; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseIntermediateFormatOption(String[] args, int i) throws FOPException { setOutputMode(MimeConstants.MIME_FOP_IF); if ((i + 1 == args.length) || (args[i + 1].charAt(0) == '-')) { throw new FOPException("you must specify the intermediate format output file"); } else if ((i + 2 == args.length) || (args[i + 2].charAt(0) == '-')) { // only output file is specified setOutputFile(args[i + 1]); return 1; } else { // mimic format and output file have been specified mimicRenderer = args[i + 1]; setOutputFile(args[i + 2]); return 2; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseAreaTreeInputOption(String[] args, int i) throws FOPException { setInputFormat(AREATREE_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the Area Tree file for the '-atin' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { areatreefile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseIFInputOption(String[] args, int i) throws FOPException { setInputFormat(IF_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the intermediate file for the '-ifin' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { iffile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parseImageInputOption(String[] args, int i) throws FOPException { setInputFormat(IMAGE_INPUT); if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("you must specify the image file for the '-imagein' option"); } else { String filename = args[i + 1]; if (isSystemInOutFile(filename)) { this.useStdIn = true; } else { imagefile = new File(filename); } return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private PDFEncryptionParams getPDFEncryptionParams() throws FOPException { PDFEncryptionParams params = (PDFEncryptionParams)renderingOptions.get( PDFConfigurationConstants.ENCRYPTION_PARAMS); if (params == null) { if (!PDFEncryptionManager.checkAvailableAlgorithms()) { throw new FOPException("PDF encryption requested but it is not available." + " Please make sure MD5 and RC4 algorithms are available."); } params = new PDFEncryptionParams(); renderingOptions.put(PDFConfigurationConstants.ENCRYPTION_PARAMS, params); } return params; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePDFOwnerPassword(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { getPDFEncryptionParams().setOwnerPassword(""); return 0; } else { getPDFEncryptionParams().setOwnerPassword(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePDFUserPassword(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { getPDFEncryptionParams().setUserPassword(""); return 0; } else { getPDFEncryptionParams().setUserPassword(args[i + 1]); return 1; } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private int parsePDFProfile(String[] args, int i) throws FOPException { if ((i + 1 == args.length) || (isOption(args[i + 1]))) { throw new FOPException("You must specify a PDF profile"); } else { String profile = args[i + 1]; PDFAMode pdfAMode = PDFAMode.valueOf(profile); if (pdfAMode != null && pdfAMode != PDFAMode.DISABLED) { if (renderingOptions.get("pdf-a-mode") != null) { throw new FOPException("PDF/A mode already set"); } renderingOptions.put("pdf-a-mode", pdfAMode.getName()); return 1; } else { PDFXMode pdfXMode = PDFXMode.valueOf(profile); if (pdfXMode != null && pdfXMode != PDFXMode.DISABLED) { if (renderingOptions.get("pdf-x-mode") != null) { throw new FOPException("PDF/X mode already set"); } renderingOptions.put("pdf-x-mode", pdfXMode.getName()); return 1; } } throw new FOPException("Unsupported PDF profile: " + profile); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setOutputMode(String mime) throws FOPException { if (outputmode == null) { outputmode = mime; } else { throw new FOPException("you can only set one output method"); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setInputFormat(int format) throws FOPException { if (inputmode == NOT_SET || inputmode == format) { inputmode = format; } else { throw new FOPException("Only one input mode can be specified!"); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void checkSettings() throws FOPException, FileNotFoundException { if (inputmode == NOT_SET) { throw new FOPException("No input file specified"); } if (outputmode == null) { throw new FOPException("No output file specified"); } if ((outputmode.equals(MimeConstants.MIME_FOP_AWT_PREVIEW) || outputmode.equals(MimeConstants.MIME_FOP_PRINT)) && outfile != null) { throw new FOPException("Output file may not be specified " + "for AWT or PRINT output"); } if (inputmode == XSLT_INPUT) { // check whether xml *and* xslt file have been set if (xmlfile == null && !this.useStdIn) { throw new FOPException("XML file must be specified for the transform mode"); } if (xsltfile == null) { throw new FOPException("XSLT file must be specified for the transform mode"); } // warning if fofile has been set in xslt mode if (fofile != null) { log.warn("Can't use fo file with transform mode! Ignoring.\n" + "Your input is " + "\n xmlfile: " + xmlfile.getAbsolutePath() + "\nxsltfile: " + xsltfile.getAbsolutePath() + "\n fofile: " + fofile.getAbsolutePath()); } if (xmlfile != null && !xmlfile.exists()) { throw new FileNotFoundException("Error: xml file " + xmlfile.getAbsolutePath() + " not found "); } if (!xsltfile.exists()) { throw new FileNotFoundException("Error: xsl file " + xsltfile.getAbsolutePath() + " not found "); } } else if (inputmode == FO_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (fofile != null && !fofile.exists()) { throw new FileNotFoundException("Error: fo file " + fofile.getAbsolutePath() + " not found "); } } else if (inputmode == AREATREE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Area Tree is used as input!"); } if (areatreefile != null && !areatreefile.exists()) { throw new FileNotFoundException("Error: area tree file " + areatreefile.getAbsolutePath() + " not found "); } } else if (inputmode == IF_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Intermediate Format" + " is used as input!"); } else if (outputmode.equals(MimeConstants.MIME_FOP_IF)) { throw new FOPException( "Intermediate Output is not available if Intermediate Format" + " is used as input!"); } if (iffile != null && !iffile.exists()) { throw new FileNotFoundException("Error: intermediate format file " + iffile.getAbsolutePath() + " not found "); } } else if (inputmode == IMAGE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (imagefile != null && !imagefile.exists()) { throw new FileNotFoundException("Error: image file " + imagefile.getAbsolutePath() + " not found "); } } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setUserConfig() throws FOPException, IOException { if (userConfigFile == null) { return; } try { factory.setUserConfig(userConfigFile); } catch (SAXException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
protected String getOutputFormat() throws FOPException { if (outputmode == null) { throw new FOPException("Renderer has not been set!"); } if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { renderingOptions.put("fineDetail", isCoarseAreaXml()); } return outputmode; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void flushCache() throws FOPException { FontManager fontManager = factory.getFontManager(); File cacheFile = fontManager.getCacheFile(); if (!fontManager.deleteCache()) { System.err.println("Failed to flush the font cache file '" + cacheFile + "'."); System.exit(1); } }
// in src/java/org/apache/fop/cli/IFInputHandler.java
public void renderTo(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { IFDocumentHandler documentHandler = userAgent.getFactory().getRendererFactory().createDocumentHandler( userAgent, outputFormat); try { documentHandler.setResult(new StreamResult(out)); IFUtil.setupFonts(documentHandler); //Create IF parser IFParser parser = new IFParser(); // Resulting SAX events are sent to the parser Result res = new SAXResult(parser.getContentHandler(documentHandler, userAgent)); transformTo(res); } catch (IFException ife) { throw new FOPException(ife); } }
19
            
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (FOPException ex) { throw new BuildException(ex); }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
catch (FOPException exc) { getFOValidationEventProducer().markerCloningFailed(this, marker.getMarkerClassName(), exc, getLocator()); }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java
catch (FOPException e) { throw new ConfigurationException("Error while setting up fonts", e); }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (FOPException fopex) { log.error("Failed to read font metrics file " + metricsFileName, fopex); if (fail) { throw new RuntimeException(fopex.getMessage()); } }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startInline:" + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startList: " + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
catch (FOPException e) { throw new NoSuchElementException(e.getMessage()); }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
// in src/java/org/apache/fop/render/awt/viewer/ImageProxyPanel.java
catch (FOPException fopEx) { // Arbitary size. Doesn't really matter what's returned here. return new Dimension(10, 10); }
// in src/java/org/apache/fop/render/awt/viewer/ImageProxyPanel.java
catch (FOPException fopEx) { fopEx.printStackTrace(); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewPanel.java
catch (FOPException e) { e.printStackTrace(); // FIXME Should show exception in gui - was reportException(e); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewDialog.java
catch (FOPException fopEx) { fopEx.printStackTrace(); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewDialog.java
catch (FOPException fopEx) { fopEx.printStackTrace(); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (FOPException fe) { throw new TranscoderException(fe); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (FOPException e) { log.error(e); return NO_SUCH_PAGE; }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (FOPException e) { //TODO use error handler to handle this FOPException or propagate exception String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, e); throw new IllegalStateException("Fatal error occurred. Cannot continue. " + e.getClass().getName() + ": " + err); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (FOPException e) { printUsage(System.err); throw e; }
12
            
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (FOPException ex) { throw new BuildException(ex); }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2DConfigurator.java
catch (FOPException e) { throw new ConfigurationException("Error while setting up fonts", e); }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (FOPException fopex) { log.error("Failed to read font metrics file " + metricsFileName, fopex); if (fail) { throw new RuntimeException(fopex.getMessage()); } }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startInline:" + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startList: " + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
catch (FOPException e) { throw new NoSuchElementException(e.getMessage()); }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (FOPException fe) { throw new TranscoderException(fe); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (FOPException e) { //TODO use error handler to handle this FOPException or propagate exception String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, e); throw new IllegalStateException("Fatal error occurred. Cannot continue. " + e.getClass().getName() + ": " + err); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (FOPException e) { printUsage(System.err); throw e; }
5
unknown (Lib) FileNotFoundException 15
            
// in src/java/org/apache/fop/pdf/PDFDocument.java
protected InputStream resolveURI(String uri) throws java.io.FileNotFoundException { try { /* TODO: Temporary hack to compile, improve later */ return new java.net.URL(uri).openStream(); } catch (Exception e) { throw new java.io.FileNotFoundException( "URI could not be resolved (" + e.getMessage() + "): " + uri); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void generateXML(SortedMap fontFamilies, File outFile, String singleFamily) throws TransformerConfigurationException, SAXException, IOException { SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler handler; if (this.mode == GENERATE_XML) { handler = tFactory.newTransformerHandler(); } else { URL url = getClass().getResource("fonts2fo.xsl"); if (url == null) { throw new FileNotFoundException("Did not find resource: fonts2fo.xsl"); } handler = tFactory.newTransformerHandler(new StreamSource(url.toExternalForm())); } if (singleFamily != null) { Transformer transformer = handler.getTransformer(); transformer.setParameter("single-family", singleFamily); } OutputStream out = new java.io.FileOutputStream(outFile); out = new java.io.BufferedOutputStream(out); if (this.mode == GENERATE_RENDERED) { handler.setResult(new SAXResult(getFOPContentHandler(out))); } else { handler.setResult(new StreamResult(out)); } try { GenerationHelperContentHandler helper = new GenerationHelperContentHandler( handler, null); FontListSerializer serializer = new FontListSerializer(); serializer.generateSAX(fontFamilies, singleFamily, helper); } finally { IOUtils.closeQuietly(out); } }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
Override protected void read() throws IOException { AFMFile afm = null; PFMFile pfm = null; InputStream afmIn = null; String afmUri = null; for (int i = 0; i < AFM_EXTENSIONS.length; i++) { try { afmUri = this.fontFileURI.substring(0, this.fontFileURI.length() - 4) + AFM_EXTENSIONS[i]; afmIn = openFontUri(resolver, afmUri); if (afmIn != null) { break; } } catch (IOException ioe) { // Ignore, AFM probably not available under the URI } } if (afmIn != null) { try { AFMParser afmParser = new AFMParser(); afm = afmParser.parse(afmIn, afmUri); } finally { IOUtils.closeQuietly(afmIn); } } String pfmUri = getPFMURI(this.fontFileURI); InputStream pfmIn = null; try { pfmIn = openFontUri(resolver, pfmUri); } catch (IOException ioe) { // Ignore, PFM probably not available under the URI } if (pfmIn != null) { try { pfm = new PFMFile(); pfm.load(pfmIn); } catch (IOException ioe) { if (afm == null) { // Ignore the exception if we have a valid PFM. PFM is only the fallback. throw ioe; } } finally { IOUtils.closeQuietly(pfmIn); } } if (afm == null && pfm == null) { throw new java.io.FileNotFoundException( "Neither an AFM nor a PFM file was found for " + this.fontFileURI); } buildFont(afm, pfm); this.loaded = true; }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
public void addEmbeddedFile(PDFEmbeddedFileExtensionAttachment embeddedFile) throws IOException { this.pdfDoc.getProfile().verifyEmbeddedFilesAllowed(); PDFNames names = this.pdfDoc.getRoot().getNames(); if (names == null) { //Add Names if not already present names = this.pdfDoc.getFactory().makeNames(); this.pdfDoc.getRoot().setNames(names); } //Create embedded file PDFEmbeddedFile file = new PDFEmbeddedFile(); this.pdfDoc.registerObject(file); Source src = getUserAgent().resolveURI(embeddedFile.getSrc()); InputStream in = ImageUtil.getInputStream(src); if (in == null) { throw new FileNotFoundException(embeddedFile.getSrc()); } try { OutputStream out = file.getBufferOutputStream(); IOUtils.copyLarge(in, out); } finally { IOUtils.closeQuietly(in); } PDFDictionary dict = new PDFDictionary(); dict.put("F", file); String filename = PDFText.toPDFString(embeddedFile.getFilename(), '_'); PDFFileSpec fileSpec = new PDFFileSpec(filename); fileSpec.setEmbeddedFile(dict); if (embeddedFile.getDesc() != null) { fileSpec.setDescription(embeddedFile.getDesc()); } this.pdfDoc.registerObject(fileSpec); //Make sure there is an EmbeddedFiles in the Names dictionary PDFEmbeddedFiles embeddedFiles = names.getEmbeddedFiles(); if (embeddedFiles == null) { embeddedFiles = new PDFEmbeddedFiles(); this.pdfDoc.assignObjectNumber(embeddedFiles); this.pdfDoc.addTrailerObject(embeddedFiles); names.setEmbeddedFiles(embeddedFiles); } //Add to EmbeddedFiles in the Names dictionary PDFArray nameArray = embeddedFiles.getNames(); if (nameArray == null) { nameArray = new PDFArray(); embeddedFiles.setNames(nameArray); } String name = PDFText.toPDFString(filename); nameArray.add(name); nameArray.add(new PDFReference(fileSpec)); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected InputStream openInputStream(ResourceAccessor accessor, String filename, AFPEventProducer eventProducer) throws IOException { URI uri; try { uri = new URI(filename.trim()); } catch (URISyntaxException e) { throw new FileNotFoundException("Invalid filename: " + filename + " (" + e.getMessage() + ")"); } if (LOG.isDebugEnabled()) { LOG.debug("Opening " + uri); } InputStream inputStream = accessor.createInputStream(uri); return inputStream; }
// in src/java/org/apache/fop/afp/util/DefaultFOPResourceAccessor.java
public InputStream createInputStream(URI uri) throws IOException { //Step 1: resolve against local base URI --> URI URI resolved = resolveAgainstBase(uri); //Step 2: resolve against the user agent --> stream String base = (this.categoryBaseURI != null ? this.categoryBaseURI : this.userAgent.getBaseURL()); Source src = userAgent.resolveURI(resolved.toASCIIString(), base); if (src == null) { throw new FileNotFoundException("Resource not found: " + uri.toASCIIString()); } else if (src instanceof StreamSource) { StreamSource ss = (StreamSource)src; InputStream in = ss.getInputStream(); if (in != null) { return in; } if (ss.getReader() != null) { //Don't support reader, retry using system ID below IOUtils.closeQuietly(ss.getReader()); } } URL url = new URL(src.getSystemId()); return url.openStream(); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void checkSettings() throws FOPException, FileNotFoundException { if (inputmode == NOT_SET) { throw new FOPException("No input file specified"); } if (outputmode == null) { throw new FOPException("No output file specified"); } if ((outputmode.equals(MimeConstants.MIME_FOP_AWT_PREVIEW) || outputmode.equals(MimeConstants.MIME_FOP_PRINT)) && outfile != null) { throw new FOPException("Output file may not be specified " + "for AWT or PRINT output"); } if (inputmode == XSLT_INPUT) { // check whether xml *and* xslt file have been set if (xmlfile == null && !this.useStdIn) { throw new FOPException("XML file must be specified for the transform mode"); } if (xsltfile == null) { throw new FOPException("XSLT file must be specified for the transform mode"); } // warning if fofile has been set in xslt mode if (fofile != null) { log.warn("Can't use fo file with transform mode! Ignoring.\n" + "Your input is " + "\n xmlfile: " + xmlfile.getAbsolutePath() + "\nxsltfile: " + xsltfile.getAbsolutePath() + "\n fofile: " + fofile.getAbsolutePath()); } if (xmlfile != null && !xmlfile.exists()) { throw new FileNotFoundException("Error: xml file " + xmlfile.getAbsolutePath() + " not found "); } if (!xsltfile.exists()) { throw new FileNotFoundException("Error: xsl file " + xsltfile.getAbsolutePath() + " not found "); } } else if (inputmode == FO_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (fofile != null && !fofile.exists()) { throw new FileNotFoundException("Error: fo file " + fofile.getAbsolutePath() + " not found "); } } else if (inputmode == AREATREE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Area Tree is used as input!"); } if (areatreefile != null && !areatreefile.exists()) { throw new FileNotFoundException("Error: area tree file " + areatreefile.getAbsolutePath() + " not found "); } } else if (inputmode == IF_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Intermediate Format" + " is used as input!"); } else if (outputmode.equals(MimeConstants.MIME_FOP_IF)) { throw new FOPException( "Intermediate Output is not available if Intermediate Format" + " is used as input!"); } if (iffile != null && !iffile.exists()) { throw new FileNotFoundException("Error: intermediate format file " + iffile.getAbsolutePath() + " not found "); } } else if (inputmode == IMAGE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (imagefile != null && !imagefile.exists()) { throw new FileNotFoundException("Error: image file " + imagefile.getAbsolutePath() + " not found "); } } }
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void fromUCD(boolean hexcode, String unidataPath, String outfilePath) throws IOException, URISyntaxException { URI unidata; if (unidataPath.endsWith("/")) { unidata = new URI(unidataPath); } else { unidata = new URI(unidataPath + "/"); } String scheme = unidata.getScheme(); if (scheme == null || !(scheme.equals("file") || scheme.equals("http"))) { throw new FileNotFoundException ("URI with file or http scheme required for UNIDATA input directory"); } File f = new File(outfilePath); if (f.exists()) { f.delete(); } f.createNewFile(); FileOutputStream fw = new FileOutputStream(f); OutputStreamWriter ow = new OutputStreamWriter(fw, "utf-8"); URI inuri = unidata.resolve("Blocks.txt"); InputStream inis = null; if (scheme.equals("file")) { File in = new File(inuri); inis = new FileInputStream(in); } else if (scheme.equals("http")) { inis = inuri.toURL().openStream(); } InputStreamReader insr = new InputStreamReader(inis, "utf-8"); BufferedReader inbr = new BufferedReader(insr); Map blocks = new HashMap(); for (String line = inbr.readLine(); line != null; line = inbr.readLine()) { if (line.startsWith("#") || line.matches("^\\s*$")) { continue; } String[] parts = line.split(";"); String block = parts[1].trim(); String[] indices = parts[0].split("\\.\\."); int[] ind = {Integer.parseInt(indices[0], 16), Integer.parseInt(indices[1], 16)}; blocks.put(block, ind); } inbr.close(); inuri = unidata.resolve("UnicodeData.txt"); if (scheme.equals("file")) { File in = new File(inuri); inis = new FileInputStream(in); } else if (scheme.equals("http")) { inis = inuri.toURL().openStream(); } insr = new InputStreamReader(inis, "utf-8"); inbr = new BufferedReader(insr); int maxChar; maxChar = Character.MAX_VALUE; ow.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); License.writeXMLLicenseId(ow); ow.write("\n"); writeGenerated(ow); ow.write("\n"); ow.write("<classes>\n"); for (String line = inbr.readLine(); line != null; line = inbr.readLine()) { String[] fields = line.split(";", NUM_FIELDS); int code = Integer.parseInt(fields[UNICODE], 16); if (code > maxChar) { break; } if (((fields[GENERAL_CATEGORY].equals("Ll") || fields[GENERAL_CATEGORY].equals("Lu") || fields[GENERAL_CATEGORY].equals("Lt")) && ("".equals(fields[SIMPLE_LOWERCASE_MAPPING]) || fields[UNICODE].equals(fields[SIMPLE_LOWERCASE_MAPPING]))) || fields[GENERAL_CATEGORY].equals("Lo")) { String[] blockNames = {"Superscripts and Subscripts", "Letterlike Symbols", "Alphabetic Presentation Forms", "Halfwidth and Fullwidth Forms", "CJK Unified Ideographs", "CJK Unified Ideographs Extension A", "Hangul Syllables"}; int j; for (j = 0; j < blockNames.length; ++j) { int[] ind = (int[]) blocks.get(blockNames[j]); if (code >= ind[0] && code <= ind[1]) { break; } } if (j < blockNames.length) { continue; } int uppercode = -1; int titlecode = -1; if (!"".equals(fields[SIMPLE_UPPERCASE_MAPPING])) { uppercode = Integer.parseInt(fields[SIMPLE_UPPERCASE_MAPPING], 16); } if (!"".equals(fields[SIMPLE_TITLECASE_MAPPING])) { titlecode = Integer.parseInt(fields[SIMPLE_TITLECASE_MAPPING], 16); } StringBuilder s = new StringBuilder(); if (hexcode) { s.append("0x" + fields[UNICODE].replaceFirst("^0+", "").toLowerCase() + " "); } s.append(Character.toChars(code)); if (uppercode != -1 && uppercode != code) { s.append(Character.toChars(uppercode)); } if (titlecode != -1 && titlecode != code && titlecode != uppercode) { s.append(Character.toChars(titlecode)); } ow.write(s.toString() + "\n"); } } ow.write("</classes>\n"); ow.flush(); ow.close(); inbr.close(); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
protected void updateTranslationFile(File modelFile) throws IOException { try { boolean resultExists = getTranslationFile().exists(); SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); //Generate fresh generated translation file as template Source src = new StreamSource(modelFile.toURI().toURL().toExternalForm()); StreamSource xslt1 = new StreamSource( getClass().getResourceAsStream(MODEL2TRANSLATION)); if (xslt1.getInputStream() == null) { throw new FileNotFoundException(MODEL2TRANSLATION + " not found"); } DOMResult domres = new DOMResult(); Transformer transformer = tFactory.newTransformer(xslt1); transformer.transform(src, domres); final Node generated = domres.getNode(); Node sourceDocument; if (resultExists) { //Load existing translation file into memory (because we overwrite it later) src = new StreamSource(getTranslationFile().toURI().toURL().toExternalForm()); domres = new DOMResult(); transformer = tFactory.newTransformer(); transformer.transform(src, domres); sourceDocument = domres.getNode(); } else { //Simply use generated as source document sourceDocument = generated; } //Generate translation file (with potentially new translations) src = new DOMSource(sourceDocument); //The following triggers a bug in older Xalan versions //Result res = new StreamResult(getTranslationFile()); OutputStream out = new java.io.FileOutputStream(getTranslationFile()); out = new java.io.BufferedOutputStream(out); Result res = new StreamResult(out); try { StreamSource xslt2 = new StreamSource( getClass().getResourceAsStream(MERGETRANSLATION)); if (xslt2.getInputStream() == null) { throw new FileNotFoundException(MERGETRANSLATION + " not found"); } transformer = tFactory.newTransformer(xslt2); transformer.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { if ("my:dom".equals(href)) { return new DOMSource(generated); } return null; } }); if (resultExists) { transformer.setParameter("generated-url", "my:dom"); } transformer.transform(src, res); if (resultExists) { log("Translation file updated: " + getTranslationFile()); } else { log("Translation file generated: " + getTranslationFile()); } } finally { IOUtils.closeQuietly(out); } } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
2
            
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (Exception e) { throw new java.io.FileNotFoundException( "URI could not be resolved (" + e.getMessage() + "): " + uri); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (URISyntaxException e) { throw new FileNotFoundException("Invalid filename: " + filename + " (" + e.getMessage() + ")"); }
2
            
// in src/java/org/apache/fop/pdf/PDFDocument.java
protected InputStream resolveURI(String uri) throws java.io.FileNotFoundException { try { /* TODO: Temporary hack to compile, improve later */ return new java.net.URL(uri).openStream(); } catch (Exception e) { throw new java.io.FileNotFoundException( "URI could not be resolved (" + e.getMessage() + "): " + uri); } }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void checkSettings() throws FOPException, FileNotFoundException { if (inputmode == NOT_SET) { throw new FOPException("No input file specified"); } if (outputmode == null) { throw new FOPException("No output file specified"); } if ((outputmode.equals(MimeConstants.MIME_FOP_AWT_PREVIEW) || outputmode.equals(MimeConstants.MIME_FOP_PRINT)) && outfile != null) { throw new FOPException("Output file may not be specified " + "for AWT or PRINT output"); } if (inputmode == XSLT_INPUT) { // check whether xml *and* xslt file have been set if (xmlfile == null && !this.useStdIn) { throw new FOPException("XML file must be specified for the transform mode"); } if (xsltfile == null) { throw new FOPException("XSLT file must be specified for the transform mode"); } // warning if fofile has been set in xslt mode if (fofile != null) { log.warn("Can't use fo file with transform mode! Ignoring.\n" + "Your input is " + "\n xmlfile: " + xmlfile.getAbsolutePath() + "\nxsltfile: " + xsltfile.getAbsolutePath() + "\n fofile: " + fofile.getAbsolutePath()); } if (xmlfile != null && !xmlfile.exists()) { throw new FileNotFoundException("Error: xml file " + xmlfile.getAbsolutePath() + " not found "); } if (!xsltfile.exists()) { throw new FileNotFoundException("Error: xsl file " + xsltfile.getAbsolutePath() + " not found "); } } else if (inputmode == FO_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (fofile != null && !fofile.exists()) { throw new FileNotFoundException("Error: fo file " + fofile.getAbsolutePath() + " not found "); } } else if (inputmode == AREATREE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Area Tree is used as input!"); } if (areatreefile != null && !areatreefile.exists()) { throw new FileNotFoundException("Error: area tree file " + areatreefile.getAbsolutePath() + " not found "); } } else if (inputmode == IF_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } else if (outputmode.equals(MimeConstants.MIME_FOP_AREA_TREE)) { throw new FOPException( "Area Tree Output is not available if Intermediate Format" + " is used as input!"); } else if (outputmode.equals(MimeConstants.MIME_FOP_IF)) { throw new FOPException( "Intermediate Output is not available if Intermediate Format" + " is used as input!"); } if (iffile != null && !iffile.exists()) { throw new FileNotFoundException("Error: intermediate format file " + iffile.getAbsolutePath() + " not found "); } } else if (inputmode == IMAGE_INPUT) { if (outputmode.equals(MimeConstants.MIME_XSL_FO)) { throw new FOPException( "FO output mode is only available if you use -xml and -xsl"); } if (imagefile != null && !imagefile.exists()) { throw new FileNotFoundException("Error: image file " + imagefile.getAbsolutePath() + " not found "); } } }
17
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (FileNotFoundException fnfe) { // Note: This is on "debug" level since the caller is // supposed to handle this log.debug("File not found: " + effURL); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(fobj, uri, fnfe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, url, fnfe, getLocator()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (FileNotFoundException fnfe) { throw new HyphenationException("File not found: " + fnfe.getMessage()); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), fe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (FileNotFoundException e) { eventProducer.codePageNotFound(this, e); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (FileNotFoundException e) { eventProducer.codePageNotFound(this, e); }
// in src/java/org/apache/fop/afp/AFPStreamer.java
catch (FileNotFoundException fnfe) { LOG.error("Failed to create/open external resource group file '" + filePath + "'"); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fnfe, getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (FileNotFoundException fnfe) { getResourceEventProducer().imageNotFound(this, uri, fnfe, getExternalDocument().getLocator()); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (FileNotFoundException e) { //handled elsewhere return new StreamSource(this.sourcefile); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (java.io.FileNotFoundException e) { printUsage(System.err); throw e; }
2
            
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (FileNotFoundException fnfe) { throw new HyphenationException("File not found: " + fnfe.getMessage()); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (java.io.FileNotFoundException e) { printUsage(System.err); throw e; }
0
runtime (Domain) FontRuntimeException
public class FontRuntimeException extends RuntimeException {

    private static final long serialVersionUID = -2217420523816384707L;

    /**
     * Constructs a FontRuntimeException with the specified message.
     * @param msg the exception mesaage
     */
    public FontRuntimeException(String msg) {
        super(msg);
    }

    /**
     * Constructs a FontRuntimeException with the specified message
     * wrapping the underlying exception.
     * @param msg the exception mesaage
     * @param t the underlying exception
     */
    public FontRuntimeException(String msg, Throwable t) {
        super(msg, t);
    }

}
9
            
// in src/java/org/apache/fop/afp/fonts/RasterFont.java
public CharacterSet getCharacterSet(int sizeInMpt) { Integer requestedSize = Integer.valueOf(sizeInMpt); CharacterSet csm = (CharacterSet) charSets.get(requestedSize); double sizeInPt = sizeInMpt / 1000.0; if (csm != null) { return csm; } if (substitutionCharSets != null) { //Check first if a substitution has already been added csm = (CharacterSet) substitutionCharSets.get(requestedSize); } if (csm == null && !charSets.isEmpty()) { // No match or substitution found, but there exist entries // for other sizes // Get char set with nearest, smallest font size SortedMap<Integer, CharacterSet> smallerSizes = charSets.headMap(requestedSize); SortedMap<Integer, CharacterSet> largerSizes = charSets.tailMap(requestedSize); int smallerSize = smallerSizes.isEmpty() ? 0 : ((Integer)smallerSizes.lastKey()).intValue(); int largerSize = largerSizes.isEmpty() ? Integer.MAX_VALUE : ((Integer)largerSizes.firstKey()).intValue(); Integer fontSize; if (!smallerSizes.isEmpty() && (sizeInMpt - smallerSize) <= (largerSize - sizeInMpt)) { fontSize = Integer.valueOf(smallerSize); } else { fontSize = Integer.valueOf(largerSize); } csm = (CharacterSet) charSets.get(fontSize); if (csm != null) { // Add the substitute mapping, so subsequent calls will // find it immediately if (substitutionCharSets == null) { substitutionCharSets = new HashMap<Integer, CharacterSet>(); } substitutionCharSets.put(requestedSize, csm); // do not output the warning if the font size is closer to an integer less than 0.1 if (!(Math.abs(fontSize.intValue() / 1000.0 - sizeInPt) < 0.1)) { String msg = "No " + sizeInPt + "pt font " + getFontName() + " found, substituted with " + fontSize.intValue() / 1000f + "pt font"; LOG.warn(msg); } } } if (csm == null) { // Still no match -> error String msg = "No font found for font " + getFontName() + " with point size " + sizeInPt; LOG.error(msg); throw new FontRuntimeException(msg); } return csm; }
// in src/java/org/apache/fop/afp/fonts/RasterFont.java
public int getFirstChar() { Iterator<CharacterSet> it = charSets.values().iterator(); if (it.hasNext()) { CharacterSet csm = it.next(); return csm.getFirstChar(); } else { String msg = "getFirstChar() - No character set found for font:" + getFontName(); LOG.error(msg); throw new FontRuntimeException(msg); } }
// in src/java/org/apache/fop/afp/fonts/RasterFont.java
public int getLastChar() { Iterator<CharacterSet> it = charSets.values().iterator(); if (it.hasNext()) { CharacterSet csm = it.next(); return csm.getLastChar(); } else { String msg = "getLastChar() - No character set found for font:" + getFontName(); LOG.error(msg); throw new FontRuntimeException(msg); } }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
public void addFont(int fontReference, AFPFont font, int size, int orientation) throws MaximumSizeExceededException { FontDefinition fontDefinition = new FontDefinition(); fontDefinition.fontReferenceKey = BinaryUtils.convert(fontReference)[0]; switch (orientation) { case 90: fontDefinition.orientation = 0x2D; break; case 180: fontDefinition.orientation = 0x5A; break; case 270: fontDefinition.orientation = (byte) 0x87; break; default: fontDefinition.orientation = 0x00; break; } try { if (font instanceof RasterFont) { RasterFont raster = (RasterFont) font; CharacterSet cs = raster.getCharacterSet(size); if (cs == null) { String msg = "Character set not found for font " + font.getFontName() + " with point size " + size; LOG.error(msg); throw new FontRuntimeException(msg); } fontDefinition.characterSet = cs.getNameBytes(); if (fontDefinition.characterSet.length != 8) { throw new IllegalArgumentException("The character set " + new String(fontDefinition.characterSet, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof OutlineFont) { OutlineFont outline = (OutlineFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof DoubleByteFont) { DoubleByteFont outline = (DoubleByteFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); //TODO Relax requirement for 8 characters if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else { String msg = "Font of type " + font.getClass().getName() + " not recognized."; LOG.error(msg); throw new FontRuntimeException(msg); } if (fontList.size() > 253) { // Throw an exception if the size is exceeded throw new MaximumSizeExceededException(); } else { fontList.add(fontDefinition); } } catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); } }
// in src/java/org/apache/fop/afp/util/DTDEntityResolver.java
public InputSource resolveEntity(String publicId, String systemId) throws IOException { URL resource = null; if ( AFP_DTD_1_2_ID.equals(publicId) ) { resource = getResource( AFP_DTD_1_2_RESOURCE ); } else if ( AFP_DTD_1_1_ID.equals(publicId) ) { resource = getResource( AFP_DTD_1_1_RESOURCE ); } else if ( AFP_DTD_1_0_ID.equals(publicId) ) { throw new FontRuntimeException( "The AFP Installed Font Definition 1.0 DTD is not longer supported" ); } else if (systemId != null && systemId.indexOf("afp-fonts.dtd") >= 0 ) { throw new FontRuntimeException( "The AFP Installed Font Definition DTD must be specified using the public id" ); } else { return null; } InputSource inputSource = new InputSource( resource.openStream() ); inputSource.setPublicId( publicId ); inputSource.setSystemId( systemId ); return inputSource; }
// in src/java/org/apache/fop/afp/util/DTDEntityResolver.java
private URL getResource(String resourcePath) { ClassLoader cl = Thread.currentThread().getContextClassLoader(); if (cl == null) { cl = ClassLoader.getSystemClassLoader(); } URL resource = cl.getResource( resourcePath ); if (resource == null) { throw new FontRuntimeException( "Resource " + resourcePath + "could not be found on the classpath" ); } return resource; }
1
            
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); }
0 0 0 0
checked (Domain) HyphenationException
public class HyphenationException extends Exception {

    /**
     * Construct a hyphenation exception.
     * @param msg a message string
     * @see java.lang.Throwable#Throwable(String)
     */
    public HyphenationException(String msg) {
        super(msg);
    }

}
5
            
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
public void loadPatterns(String filename) throws HyphenationException { File f = new File(filename); try { InputSource src = new InputSource(f.toURI().toURL().toExternalForm()); loadPatterns(src); } catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + f + "' to a URL: " + e.getMessage()); } }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void parse(File file) throws HyphenationException { try { InputSource src = new InputSource(file.toURI().toURL().toExternalForm()); parse(src); } catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + file + "' to a URL: " + e.getMessage()); } }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void parse(InputSource source) throws HyphenationException { try { parser.parse(source); } catch (FileNotFoundException fnfe) { throw new HyphenationException("File not found: " + fnfe.getMessage()); } catch (IOException ioe) { throw new HyphenationException(ioe.getMessage()); } catch (SAXException e) { throw new HyphenationException(errMsg); } }
5
            
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + f + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + file + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (FileNotFoundException fnfe) { throw new HyphenationException("File not found: " + fnfe.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new HyphenationException(ioe.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (SAXException e) { throw new HyphenationException(errMsg); }
7
            
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
public void loadPatterns(String filename) throws HyphenationException { File f = new File(filename); try { InputSource src = new InputSource(f.toURI().toURL().toExternalForm()); loadPatterns(src); } catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + f + "' to a URL: " + e.getMessage()); } }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
public void loadPatterns(InputSource source) throws HyphenationException { PatternParser pp = new PatternParser(this); ivalues = new TernaryTree(); pp.parse(source); // patterns/values should be now in the tree // let's optimize a bit trimToSize(); vspace.trimToSize(); classmap.trimToSize(); // get rid of the auxiliary map ivalues = null; }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void parse(String filename) throws HyphenationException { parse(new File(filename)); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void parse(File file) throws HyphenationException { try { InputSource src = new InputSource(file.toURI().toURL().toExternalForm()); parse(src); } catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + file + "' to a URL: " + e.getMessage()); } }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void parse(InputSource source) throws HyphenationException { try { parser.parse(source); } catch (FileNotFoundException fnfe) { throw new HyphenationException("File not found: " + fnfe.getMessage()); } catch (IOException ioe) { throw new HyphenationException(ioe.getMessage()); } catch (SAXException e) { throw new HyphenationException(errMsg); } }
2
            
// in src/java/org/apache/fop/hyphenation/SerializeHyphPattern.java
catch (HyphenationException ex) { System.err.println("Can't load patterns from xml file " + infile + " - Maybe hyphenation.dtd is missing?"); if (errorDump) { System.err.println(ex.toString()); } }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (HyphenationException ex) { log.error("Can't load user patterns from XML file " + source.getSystemId() + ": " + ex.getMessage()); return null; }
0 0
checked (Domain) IFException
public class IFException extends Exception {

    private static final long serialVersionUID = 0L;

    /**
     * Constructs a new exception with the specified detail message and
     * cause.  <p>Note that the detail message associated with
     * <code>cause</code> is <i>not</i> automatically incorporated in
     * this exception's detail message.
     *
     * @param  message the detail message (which is saved for later retrieval
     *         by the {@link #getMessage()} method).
     * @param  cause the cause (which is saved for later retrieval by the
     *         {@link #getCause()} method).  (A <code>null</code> value is
     *         permitted, and indicates that the cause is nonexistent or
     *         unknown.)
     */
    public IFException(String message, Exception cause) {
        super(message, cause);
    }

}
139
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void startViewport(String transform, Dimension size, Rectangle clipRect) throws IFException { try { establish(MODE_NORMAL); AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { XMLUtil.addAttribute(atts, "transform", transform); } handler.startElement("g", atts); atts.clear(); XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(size.width)); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(size.height)); if (clipRect != null) { int[] v = new int[] { clipRect.y, -clipRect.x + size.width - clipRect.width, -clipRect.y + size.height - clipRect.height, clipRect.x}; int sum = 0; for (int i = 0; i < 4; i++) { sum += Math.abs(v[i]); } if (sum != 0) { StringBuffer sb = new StringBuffer("rect("); sb.append(SVGUtil.formatMptToPt(v[0])).append(','); sb.append(SVGUtil.formatMptToPt(v[1])).append(','); sb.append(SVGUtil.formatMptToPt(v[2])).append(','); sb.append(SVGUtil.formatMptToPt(v[3])).append(')'); XMLUtil.addAttribute(atts, "clip", sb.toString()); } XMLUtil.addAttribute(atts, "overflow", "hidden"); } else { XMLUtil.addAttribute(atts, "overflow", "visible"); } handler.startElement("svg", atts); } catch (SAXException e) { throw new IFException("SAX error in startBox()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void endViewport() throws IFException { try { establish(MODE_NORMAL); handler.endElement("svg"); handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endBox()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void startGroup(String transform) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { XMLUtil.addAttribute(atts, "transform", transform); } handler.startElement("g", atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void endGroup() throws IFException { try { establish(MODE_NORMAL); handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { try { establish(MODE_NORMAL); ImageManager manager = getUserAgent().getFactory().getImageManager(); ImageInfo info = null; try { ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); info = manager.getImageInfo(uri, sessionContext); String mime = info.getMimeType(); Map foreignAttributes = getContext().getForeignAttributes(); String conversionMode = (String)foreignAttributes.get( ImageHandlerUtil.CONVERSION_MODE); if ("reference".equals(conversionMode) && (MimeConstants.MIME_GIF.equals(mime) || MimeConstants.MIME_JPEG.equals(mime) || MimeConstants.MIME_PNG.equals(mime) || MimeConstants.MIME_SVG.equals(mime))) { //Just reference the image //TODO Some additional URI rewriting might be necessary AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, IFConstants.XLINK_HREF, uri); XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(rect.x)); XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(rect.y)); XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(rect.width)); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(rect.height)); handler.element("image", atts); } else { drawImageUsingImageHandler(info, rect); } } catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); } catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); } } catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { try { establish(MODE_NORMAL); drawImageUsingDocument(doc, rect); } catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } try { establish(MODE_NORMAL); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(rect.x)); XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(rect.y)); XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(rect.width)); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(rect.height)); if (fill != null) { XMLUtil.addAttribute(atts, "fill", toString(fill)); } /* disabled if (stroke != null) { XMLUtil.addAttribute(atts, "stroke", toString(stroke)); }*/ handler.element("rect", atts); } catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { establish(MODE_NORMAL); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "x1", SVGUtil.formatMptToPt(start.x)); XMLUtil.addAttribute(atts, "y1", SVGUtil.formatMptToPt(start.y)); XMLUtil.addAttribute(atts, "x2", SVGUtil.formatMptToPt(end.x)); XMLUtil.addAttribute(atts, "y2", SVGUtil.formatMptToPt(end.y)); XMLUtil.addAttribute(atts, "stroke-width", toString(color)); XMLUtil.addAttribute(atts, "fill", toString(color)); //TODO Handle style parameter handler.element("line", atts); } catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { establish(MODE_TEXT); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, XMLConstants.XML_SPACE, "preserve"); XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(x)); XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(y)); if (letterSpacing != 0) { XMLUtil.addAttribute(atts, "letter-spacing", SVGUtil.formatMptToPt(letterSpacing)); } if (wordSpacing != 0) { XMLUtil.addAttribute(atts, "word-spacing", SVGUtil.formatMptToPt(wordSpacing)); } if (dp != null) { int[] dx = IFUtil.convertDPToDX(dp); XMLUtil.addAttribute(atts, "dx", SVGUtil.formatMptArrayToPt(dx)); } handler.startElement("text", atts); char[] chars = text.toCharArray(); handler.characters(chars, 0, chars.length); handler.endElement("text"); } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof Metadata) { Metadata meta = (Metadata)extension; try { establish(MODE_NORMAL); handler.startElement("metadata"); meta.toSAX(this.handler); handler.endElement("metadata"); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { throw new UnsupportedOperationException( "Don't know how to handle extension object: " + extension); } }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
public void startDocumentHeader() throws IFException { try { handler.startElement("defs"); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
public void endDocumentHeader() throws IFException { try { handler.endElement("defs"); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof Metadata) { Metadata meta = (Metadata)extension; try { handler.startElement("metadata"); meta.toSAX(this.handler); handler.endElement("metadata"); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { log.debug("Don't know how to handle extension object. Ignoring: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); builderFactory.setValidating(false); try { DocumentBuilder builder = builderFactory.newDocumentBuilder(); this.reusedParts = builder.newDocument(); } catch (ParserConfigurationException e) { throw new IFException("Error while setting up a DOM for SVG generation", e); } try { TransformerHandler toDOMHandler = tFactory.newTransformerHandler(); toDOMHandler.setResult(new DOMResult(this.reusedParts)); this.handler = decorate(toDOMHandler); this.handler.startDocument(); } catch (SAXException se) { throw new IFException("SAX error in startDocument()", se); } catch (TransformerConfigurationException e) { throw new IFException( "Error while setting up a TransformerHandler for SVG generation", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endDocumentHeader() throws IFException { super.endDocumentHeader(); try { //Stop recording parts reused for each page this.handler.endDocument(); this.handler = null; } catch (SAXException e) { throw new IFException("SAX error in endDocumentHeader()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { if (this.multiFileUtil != null) { prepareHandlerWithOutputStream(index); } else { if (this.simpleResult == null) { //Only one page is supported with this approach at the moment throw new IFException( "Only one page is supported for output with the given Result instance!", null); } super.setResult(this.simpleResult); this.simpleResult = null; } try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "version", "1.1"); //SVG 1.1 /* XMLUtil.addAttribute(atts, "index", Integer.toString(index)); XMLUtil.addAttribute(atts, "name", name); */ XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(size.width) + "pt"); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(size.height) + "pt"); XMLUtil.addAttribute(atts, "viewBox", "0 0 " + SVGUtil.formatMptToPt(size.width) + " " + SVGUtil.formatMptToPt(size.height)); handler.startElement("svg", atts); try { Transformer transformer = tFactory.newTransformer(); Source src = new DOMSource(this.reusedParts.getDocumentElement()); Result res = new SAXResult(new DelegatingFragmentContentHandler(this.handler)); transformer.transform(src, res); } catch (TransformerConfigurationException tce) { throw new IFException("Error setting up a Transformer", tce); } catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException)te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } } } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
private void prepareHandlerWithOutputStream(int index) throws IFException { OutputStream out; try { if (index == 0) { out = null; } else { out = this.multiFileUtil.createOutputStream(index); if (out == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.stoppingAfterFirstPageNoFilename(this); } } } catch (IOException ioe) { throw new IFException("I/O exception while setting up output file", ioe); } if (out == null) { this.handler = decorate(createContentHandler(this.firstStream)); } else { this.currentStream = new StreamResult(out); this.handler = decorate(createContentHandler(this.currentStream)); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public IFPainter startPageContent() throws IFException { try { handler.startElement("g"); } catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); } return new SVGPainter(this, handler); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endPageContent() throws IFException { try { handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endPage() throws IFException { try { handler.endElement("svg"); this.handler.endDocument(); } catch (SAXException e) { throw new IFException("SAX error in endPage()", e); } closeCurrentStream(); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); handler.startPrefixMapping("if", IFConstants.NAMESPACE); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "version", "1.2"); //SVG Print is SVG 1.2 handler.startElement("svg", atts); } catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endDocument() throws IFException { try { handler.endElement("svg"); handler.endDocument(); } catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startPageSequence(String id) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (id != null) { atts.addAttribute(XML_NAMESPACE, "id", "xml:id", CDATA, id); } handler.startElement("pageSet", atts); } catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPageSequence() throws IFException { try { handler.endElement("pageSet"); } catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { AttributesImpl atts = new AttributesImpl(); /* XMLUtil.addAttribute(atts, "index", Integer.toString(index)); XMLUtil.addAttribute(atts, "name", name); */ //NOTE: SVG Print doesn't support individual page sizes for each page atts.addAttribute(IFConstants.NAMESPACE, "width", "if:width", CDATA, Integer.toString(size.width)); atts.addAttribute(IFConstants.NAMESPACE, "height", "if:height", CDATA, Integer.toString(size.height)); atts.addAttribute(IFConstants.NAMESPACE, "viewBox", "if:viewBox", CDATA, "0 0 " + Integer.toString(size.width) + " " + Integer.toString(size.height)); handler.startElement("page", atts); } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public IFPainter startPageContent() throws IFException { try { handler.startElement("g"); } catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); } return new SVGPainter(this, handler); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPageContent() throws IFException { try { handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPage() throws IFException { try { handler.endElement("page"); } catch (SAXException e) { throw new IFException("SAX error in endPage()", e); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
private void flushPDFDoc() throws IFException { // output new data try { generator.flushPDFDoc(); } catch (IOException ioe) { throw new IFException("I/O error flushing the PDF document", ioe); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
Override public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { generator.endTextObject(); try { this.borderPainter.drawBorders(rect, top, bottom, left, right); } catch (IOException ioe) { throw new IFException("I/O error while drawing borders", ioe); } } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); try { this.pdfDoc = pdfUtil.setupPDFDocument(this.outputStream); this.accessEnabled = getUserAgent().isAccessibilityEnabled(); if (accessEnabled) { setupAccessibility(); } } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endDocument() throws IFException { try { pdfDoc.getResources().addFonts(pdfDoc, fontInfo); pdfDoc.outputTrailer(this.outputStream); this.pdfDoc = null; pdfResources = null; this.generator = null; currentContext = null; currentPage = null; } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endPage() throws IFException { if (accessEnabled) { logicalStructureHandler.endPage(); } try { this.documentNavigationHandler.commit(); this.pdfDoc.registerObject(generator.getStream()); currentPage.setContents(generator.getStream()); PDFAnnotList annots = currentPage.getAnnotations(); if (annots != null) { this.pdfDoc.addObject(annots); } this.pdfDoc.addObject(currentPage); this.generator.flushPDFDoc(); this.generator = null; } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof XMPMetadata) { pdfUtil.renderXMPMetadata((XMPMetadata) extension); } else if (extension instanceof Metadata) { XMPMetadata wrapper = new XMPMetadata(((Metadata) extension)); pdfUtil.renderXMPMetadata(wrapper); } else if (extension instanceof PDFEmbeddedFileExtensionAttachment) { PDFEmbeddedFileExtensionAttachment embeddedFile = (PDFEmbeddedFileExtensionAttachment)extension; try { pdfUtil.addEmbeddedFile(embeddedFile); } catch (IOException ioe) { throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe); } } else { log.debug("Don't know how to handle extension object. Ignoring: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { String family = attributes.getValue("family"); String style = attributes.getValue("style"); Integer weight = XMLUtil.getAttributeAsInteger(attributes, "weight"); String variant = attributes.getValue("variant"); Integer size = XMLUtil.getAttributeAsInteger(attributes, "size"); Color color; try { color = getAttributeAsColor(attributes, "color"); } catch (PropertyException pe) { throw new IFException("Error parsing the color attribute", pe); } painter.setFont(family, style, weight, variant, size, color); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int x = Integer.parseInt(attributes.getValue("x")); int y = Integer.parseInt(attributes.getValue("y")); int width = Integer.parseInt(attributes.getValue("width")); int height = Integer.parseInt(attributes.getValue("height")); Color fillColor; try { fillColor = getAttributeAsColor(attributes, "fill"); } catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); } painter.fillRect(new Rectangle(x, y, width, height), fillColor); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int x1 = Integer.parseInt(attributes.getValue("x1")); int y1 = Integer.parseInt(attributes.getValue("y1")); int x2 = Integer.parseInt(attributes.getValue("x2")); int y2 = Integer.parseInt(attributes.getValue("y2")); int width = Integer.parseInt(attributes.getValue("stroke-width")); Color color; try { color = getAttributeAsColor(attributes, "color"); } catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); } RuleStyle style = RuleStyle.valueOf(attributes.getValue("style")); painter.drawLine(new Point(x1, y1), new Point(x2, y2), width, color, style); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { int x = Integer.parseInt(lastAttributes.getValue("x")); int y = Integer.parseInt(lastAttributes.getValue("y")); int width = Integer.parseInt(lastAttributes.getValue("width")); int height = Integer.parseInt(lastAttributes.getValue("height")); Map<QName, String> foreignAttributes = getForeignAttributes(lastAttributes); establishForeignAttributes(foreignAttributes); establishStructureTreeElement(lastAttributes); if (foreignObject != null) { painter.drawImage(foreignObject, new Rectangle(x, y, width, height)); foreignObject = null; } else { String uri = lastAttributes.getValue( XLINK_HREF.getNamespaceURI(), XLINK_HREF.getLocalName()); if (uri == null) { throw new IFException("xlink:href is missing on image", null); } painter.drawImage(uri, new Rectangle(x, y, width, height)); } resetForeignAttributes(); resetStructureTreeElement(); inForeignObject = false; }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startDocument() throws IFException { super.startDocument(); try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); handler.startPrefixMapping(DocumentNavigationExtensionConstants.PREFIX, DocumentNavigationExtensionConstants.NAMESPACE); handler.startPrefixMapping(InternalElementMapping.STANDARD_PREFIX, InternalElementMapping.URI); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "version", VERSION); handler.startElement(EL_DOCUMENT, atts); } catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startDocumentHeader() throws IFException { try { handler.startElement(EL_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endDocumentHeader() throws IFException { try { handler.endElement(EL_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startDocumentTrailer() throws IFException { try { handler.startElement(EL_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endDocumentTrailer() throws IFException { try { handler.endElement(EL_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in endDocumentTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endDocument() throws IFException { try { handler.endElement(EL_DOCUMENT); handler.endDocument(); finishDocumentNavigation(); } catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startPageSequence(String id) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (id != null) { atts.addAttribute(XML_NAMESPACE, "id", "xml:id", XMLUtil.CDATA, id); } Locale lang = getContext().getLanguage(); if (lang != null) { atts.addAttribute(XML_NAMESPACE, "lang", "xml:lang", XMLUtil.CDATA, LanguageTags.toLanguageTag(lang)); } XMLUtil.addAttribute(atts, XMLConstants.XML_SPACE, "preserve"); addForeignAttributes(atts); handler.startElement(EL_PAGE_SEQUENCE, atts); if (this.getUserAgent().isAccessibilityEnabled()) { assert (structureTreeBuilder != null); structureTreeBuilder.replayEventsForPageSequence(handler, pageSequenceIndex++); } } catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endPageSequence() throws IFException { try { handler.endElement(EL_PAGE_SEQUENCE); } catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "index", Integer.toString(index)); addAttribute(atts, "name", name); addAttribute(atts, "page-master-name", pageMasterName); addAttribute(atts, "width", Integer.toString(size.width)); addAttribute(atts, "height", Integer.toString(size.height)); addForeignAttributes(atts); handler.startElement(EL_PAGE, atts); } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startPageHeader() throws IFException { try { handler.startElement(EL_PAGE_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startPageHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endPageHeader() throws IFException { try { handler.endElement(EL_PAGE_HEADER); } catch (SAXException e) { throw new IFException("SAX error in endPageHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public IFPainter startPageContent() throws IFException { try { handler.startElement(EL_PAGE_CONTENT); this.state = IFState.create(); return this; } catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endPageContent() throws IFException { try { this.state = null; currentID = ""; handler.endElement(EL_PAGE_CONTENT); } catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startPageTrailer() throws IFException { try { handler.startElement(EL_PAGE_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in startPageTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endPageTrailer() throws IFException { try { commitNavigation(); handler.endElement(EL_PAGE_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in endPageTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endPage() throws IFException { try { handler.endElement(EL_PAGE); } catch (SAXException e) { throw new IFException("SAX error in endPage()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void startViewport(String transform, Dimension size, Rectangle clipRect) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { addAttribute(atts, "transform", transform); } addAttribute(atts, "width", Integer.toString(size.width)); addAttribute(atts, "height", Integer.toString(size.height)); if (clipRect != null) { addAttribute(atts, "clip-rect", IFUtil.toString(clipRect)); } handler.startElement(EL_VIEWPORT, atts); } catch (SAXException e) { throw new IFException("SAX error in startViewport()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endViewport() throws IFException { try { handler.endElement(EL_VIEWPORT); } catch (SAXException e) { throw new IFException("SAX error in endViewport()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void startGroup(String transform) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { addAttribute(atts, "transform", transform); } handler.startElement(EL_GROUP, atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endGroup() throws IFException { try { handler.endElement(EL_GROUP); } catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawImage(String uri, Rectangle rect) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, XLINK_HREF, uri); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addForeignAttributes(atts); addStructureReference(atts); handler.element(EL_IMAGE, atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawImage(Document doc, Rectangle rect) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addForeignAttributes(atts); addStructureReference(atts); handler.startElement(EL_IMAGE, atts); new DOM2SAX(handler).writeDocument(doc, true); handler.endElement(EL_IMAGE); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void clipRect(Rectangle rect) throws IFException { try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); handler.element(EL_CLIP_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in clipRect()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addAttribute(atts, "fill", toString(fill)); handler.element(EL_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top == null && bottom == null && left == null && right == null) { return; } try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); if (top != null) { addAttribute(atts, "top", top.toString()); } if (bottom != null) { addAttribute(atts, "bottom", bottom.toString()); } if (left != null) { addAttribute(atts, "left", left.toString()); } if (right != null) { addAttribute(atts, "right", right.toString()); } handler.element(EL_BORDER_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in drawBorderRect()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x1", Integer.toString(start.x)); addAttribute(atts, "y1", Integer.toString(start.y)); addAttribute(atts, "x2", Integer.toString(end.x)); addAttribute(atts, "y2", Integer.toString(end.y)); addAttribute(atts, "stroke-width", Integer.toString(width)); addAttribute(atts, "color", ColorUtil.colorToString(color)); addAttribute(atts, "style", style.getName()); handler.element(EL_LINE, atts); } catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(x)); addAttribute(atts, "y", Integer.toString(y)); if (letterSpacing != 0) { addAttribute(atts, "letter-spacing", Integer.toString(letterSpacing)); } if (wordSpacing != 0) { addAttribute(atts, "word-spacing", Integer.toString(wordSpacing)); } if (dp != null) { if ( IFUtil.isDPIdentity(dp) ) { // don't add dx or dp attribute } else if ( IFUtil.isDPOnlyDX(dp) ) { // add dx attribute only int[] dx = IFUtil.convertDPToDX(dp); addAttribute(atts, "dx", IFUtil.toString(dx)); } else { // add dp attribute only addAttribute(atts, "dp", XMLUtil.encodePositionAdjustments(dp)); } } addStructureReference(atts); handler.startElement(EL_TEXT, atts); char[] chars = text.toCharArray(); handler.characters(chars, 0, chars.length); handler.endElement(EL_TEXT); } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void setFont(String family, String style, Integer weight, String variant, Integer size, Color color) throws IFException { try { AttributesImpl atts = new AttributesImpl(); boolean changed; if (family != null) { changed = !family.equals(state.getFontFamily()); if (changed) { state.setFontFamily(family); addAttribute(atts, "family", family); } } if (style != null) { changed = !style.equals(state.getFontStyle()); if (changed) { state.setFontStyle(style); addAttribute(atts, "style", style); } } if (weight != null) { changed = (weight.intValue() != state.getFontWeight()); if (changed) { state.setFontWeight(weight.intValue()); addAttribute(atts, "weight", weight.toString()); } } if (variant != null) { changed = !variant.equals(state.getFontVariant()); if (changed) { state.setFontVariant(variant); addAttribute(atts, "variant", variant); } } if (size != null) { changed = (size.intValue() != state.getFontSize()); if (changed) { state.setFontSize(size.intValue()); addAttribute(atts, "size", size.toString()); } } if (color != null) { changed = !org.apache.xmlgraphics.java2d.color.ColorUtil.isSameColor( color, state.getTextColor()); if (changed) { state.setTextColor(color); addAttribute(atts, "color", toString(color)); } } if (atts.getLength() > 0) { handler.element(EL_FONT, atts); } } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof XMLizable) { try { ((XMLizable)extension).toSAX(this.handler); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { throw new UnsupportedOperationException( "Extension must implement XMLizable: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void renderNamedDestination(NamedDestination destination) throws IFException { noteAction(destination.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute(null, "name", "name", XMLConstants.CDATA, destination.getName()); try { handler.startElement(DocumentNavigationExtensionConstants.NAMED_DESTINATION, atts); serializeXMLizable(destination.getAction()); handler.endElement(DocumentNavigationExtensionConstants.NAMED_DESTINATION); } catch (SAXException e) { throw new IFException("SAX error serializing named destination", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void renderBookmarkTree(BookmarkTree tree) throws IFException { AttributesImpl atts = new AttributesImpl(); try { handler.startElement(DocumentNavigationExtensionConstants.BOOKMARK_TREE, atts); Iterator iter = tree.getBookmarks().iterator(); while (iter.hasNext()) { Bookmark b = (Bookmark)iter.next(); if (b.getAction() != null) { serializeBookmark(b); } } handler.endElement(DocumentNavigationExtensionConstants.BOOKMARK_TREE); } catch (SAXException e) { throw new IFException("SAX error serializing bookmark tree", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void renderLink(Link link) throws IFException { noteAction(link.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute(null, "rect", "rect", XMLConstants.CDATA, IFUtil.toString(link.getTargetRect())); if (getUserAgent().isAccessibilityEnabled()) { addStructRefAttribute(atts, ((IFStructureTreeElement) link.getAction().getStructureTreeElement()).getId()); } try { handler.startElement(DocumentNavigationExtensionConstants.LINK, atts); serializeXMLizable(link.getAction()); handler.endElement(DocumentNavigationExtensionConstants.LINK); } catch (SAXException e) { throw new IFException("SAX error serializing link", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void serializeXMLizable(XMLizable object) throws IFException { try { object.toSAX(handler); } catch (SAXException e) { throw new IFException("SAX error serializing object", e); } }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void setResult(Result result) throws IFException { if (result instanceof StreamResult) { StreamResult streamResult = (StreamResult)result; OutputStream out = streamResult.getOutputStream(); if (out == null) { if (streamResult.getWriter() != null) { throw new IllegalArgumentException( "FOP cannot use a Writer. Please supply an OutputStream!"); } try { URL url = new URL(streamResult.getSystemId()); File f = FileUtils.toFile(url); if (f != null) { out = new java.io.FileOutputStream(f); } else { out = url.openConnection().getOutputStream(); } } catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); } out = new java.io.BufferedOutputStream(out); this.ownOutputStream = true; } if (out == null) { throw new IllegalArgumentException("Need a StreamResult with an OutputStream"); } this.outputStream = out; } else { throw new UnsupportedOperationException( "Unsupported Result subclass: " + result.getClass().getName()); } }
// in src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
protected ContentHandler createContentHandler(Result result) throws IFException { try { TransformerHandler tHandler = tFactory.newTransformerHandler(); Transformer transformer = tHandler.getTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); tHandler.setResult(result); return tHandler; } catch (TransformerConfigurationException tce) { throw new IFException( "Error while setting up the serializer for XML output", tce); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
Override public void startDocument() throws IFException { super.startDocument(); try { this.gen = new PCLGenerator(this.outputStream, getResolution()); this.gen.setDitheringQuality(pclUtil.getDitheringQuality()); if (!pclUtil.isPJLDisabled()) { gen.universalEndOfLanguage(); gen.writeText("@PJL COMMENT Produced by " + getUserAgent().getProducer() + "\n"); if (getUserAgent().getTitle() != null) { gen.writeText("@PJL JOB NAME = \"" + getUserAgent().getTitle() + "\"\n"); } gen.writeText("@PJL SET RESOLUTION = " + getResolution() + "\n"); gen.writeText("@PJL ENTER LANGUAGE = PCL\n"); } gen.resetPrinter(); gen.setUnitOfMeasure(getResolution()); gen.setRasterGraphicsResolution(getResolution()); } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
Override public void endDocument() throws IFException { try { gen.separateJobs(); gen.resetPrinter(); if (!pclUtil.isPJLDisabled()) { gen.universalEndOfLanguage(); } } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { //Paper source Object paperSource = getContext().getForeignAttribute( PCLElementMapping.PCL_PAPER_SOURCE); if (paperSource != null) { gen.selectPaperSource(Integer.parseInt(paperSource.toString())); } //Output bin Object outputBin = getContext().getForeignAttribute( PCLElementMapping.PCL_OUTPUT_BIN); if (outputBin != null) { gen.selectOutputBin(Integer.parseInt(outputBin.toString())); } // Is Page duplex? Object pageDuplex = getContext().getForeignAttribute( PCLElementMapping.PCL_DUPLEX_MODE); if (pageDuplex != null) { gen.selectDuplexMode(Integer.parseInt(pageDuplex.toString())); } //Page size final long pagewidth = size.width; final long pageheight = size.height; selectPageFormat(pagewidth, pageheight); } catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void endPageContent() throws IFException { if (this.currentImage != null) { try { //ImageWriterUtil.saveAsPNG(this.currentImage, new java.io.File("D:/page.png")); Rectangle printArea = this.currentPageDefinition.getLogicalPageRect(); gen.setCursorPos(0, 0); gen.paintBitmap(this.currentImage, printArea.getSize(), true); } catch (IOException ioe) { throw new IFException("I/O error while encoding page image", ioe); } finally { this.currentImage = null; } } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void endPage() throws IFException { try { //Eject page gen.formFeed(); } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); /* PCL cannot clip! if (clipRect != null) { clipRect(clipRect); }*/ } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void startGroup(AffineTransform transform) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { Color fillColor = null; if (fill != null) { if (fill instanceof Color) { fillColor = (Color)fill; } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } try { setCursorPos(rect.x, rect.y); gen.fillRect(rect.width, rect.height, fillColor); } catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); } } } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
private void paintMarksAsBitmap(Graphics2DImagePainter painter, Rectangle boundingBox) throws IFException { ImageInfo info = new ImageInfo(null, null); ImageSize size = new ImageSize(); size.setSizeInMillipoints(boundingBox.width, boundingBox.height); info.setSize(size); ImageGraphics2D img = new ImageGraphics2D(info, painter); Map hints = new java.util.HashMap(); if (isSpeedOptimized()) { //Gray text may not be painted in this case! We don't get dithering in Sun JREs. //But this approach is about twice as fast as the grayscale image. hints.put(ImageProcessingHints.BITMAP_TYPE_INTENT, ImageProcessingHints.BITMAP_TYPE_INTENT_MONO); } else { hints.put(ImageProcessingHints.BITMAP_TYPE_INTENT, ImageProcessingHints.BITMAP_TYPE_INTENT_GRAY); } hints.put(ImageHandlerUtil.CONVERSION_MODE, ImageHandlerUtil.CONVERSION_MODE_BITMAP); PCLRenderingContext context = (PCLRenderingContext)createRenderingContext(); context.setSourceTransparencyEnabled(true); try { drawImage(img, boundingBox, context, true, hints); } catch (IOException ioe) { throw new IFException( "I/O error while painting marks using a bitmap", ioe); } catch (ImageException ie) { throw new IFException( "Error while painting marks using a bitmap", ie); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() //TODO Opportunity for font caching if font state is more heavily used String fontKey = parent.getFontInfo().getInternalFontKey(triplet); boolean pclFont = getPCLUtil().isAllTextAsBitmaps() ? false : HardcodedFonts.setFont(gen, fontKey, state.getFontSize(), text); if (pclFont) { drawTextNative(x, y, letterSpacing, wordSpacing, dp, text, triplet); } else { drawTextAsBitmap(x, y, letterSpacing, wordSpacing, dp, text, triplet); if (DEBUG) { state.setTextColor(Color.GRAY); HardcodedFonts.setFont(gen, "F1", state.getFontSize(), text); drawTextNative(x, y, letterSpacing, wordSpacing, dp, text, triplet); } } } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); try { // Creates writer this.imageWriter = ImageWriterRegistry.getInstance().getWriterFor(getMimeType()); if (this.imageWriter == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noImageWriterFound(this, getMimeType()); } if (this.imageWriter.supportsMultiImageWriter()) { this.multiImageWriter = this.imageWriter.createMultiImageWriter(outputStream); } else { this.multiFileUtil = new MultiFileRenderingUtil(getDefaultExtension(), getUserAgent().getOutputFile()); } this.pageCount = 0; } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endDocument() throws IFException { try { if (this.multiImageWriter != null) { this.multiImageWriter.close(); } this.multiImageWriter = null; this.imageWriter = null; } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endPageContent() throws IFException { try { if (this.multiImageWriter == null) { switch (this.pageCount) { case 1: this.imageWriter.writeImage( this.currentImage, this.outputStream, getSettings().getWriterParams()); IOUtils.closeQuietly(this.outputStream); this.outputStream = null; break; default: OutputStream out = this.multiFileUtil.createOutputStream(this.pageCount - 1); if (out == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.stoppingAfterFirstPageNoFilename(this); } else { try { this.imageWriter.writeImage( this.currentImage, out, getSettings().getWriterParams()); } finally { IOUtils.closeQuietly(out); } } } } else { this.multiImageWriter.writeImage(this.currentImage, getSettings().getWriterParams()); } this.currentImage = null; } catch (IOException ioe) { throw new IFException("I/O error while encoding BufferedImage", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void startDocument() throws IFException { super.startDocument(); try { paintingState.setColor(Color.WHITE); this.dataStream = resourceManager.createDataStream(paintingState, outputStream); this.dataStream.startDocument(); } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void endDocument() throws IFException { try { this.dataStream.endDocument(); this.dataStream = null; this.resourceManager.writeToStream(); this.resourceManager = null; } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void startPageSequence(String id) throws IFException { try { dataStream.startPageGroup(); } catch (IOException ioe) { throw new IFException("I/O error in startPageSequence()", ioe); } this.location = Location.FOLLOWING_PAGE_SEQUENCE; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void endPageSequence() throws IFException { try { //Process deferred page-sequence-level extensions Iterator<AFPPageSetup> iter = this.deferredPageSequenceExtensions.iterator(); while (iter.hasNext()) { AFPPageSetup aps = iter.next(); iter.remove(); if (AFPElementMapping.NO_OPERATION.equals(aps.getElementName())) { handleNOP(aps); } else { throw new UnsupportedOperationException("Don't know how to handle " + aps); } } //End page sequence dataStream.endPageGroup(); } catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); } this.location = Location.ELSEWHERE; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void endPage() throws IFException { try { AFPPageFonts pageFonts = paintingState.getPageFonts(); if (pageFonts != null && !pageFonts.isEmpty()) { dataStream.addFontsToCurrentPage(pageFonts); } dataStream.endPage(); } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof AFPPageSetup) { AFPPageSetup aps = (AFPPageSetup)extension; String element = aps.getElementName(); if (AFPElementMapping.TAG_LOGICAL_ELEMENT.equals(element)) { switch (this.location) { case FOLLOWING_PAGE_SEQUENCE: case IN_PAGE_HEADER: String name = aps.getName(); String value = aps.getValue(); dataStream.createTagLogicalElement(name, value); break; default: throw new IFException( "TLE extension must be in the page header or between page-sequence" + " and the first page: " + aps, null); } } else if (AFPElementMapping.NO_OPERATION.equals(element)) { switch (this.location) { case FOLLOWING_PAGE_SEQUENCE: if (aps.getPlacement() == ExtensionPlacement.BEFORE_END) { this.deferredPageSequenceExtensions.add(aps); break; } case IN_DOCUMENT_HEADER: case IN_PAGE_HEADER: handleNOP(aps); break; default: throw new IFException( "NOP extension must be in the document header, the page header" + " or between page-sequence" + " and the first page: " + aps, null); } } else { if (this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP page setup extension encountered outside the page header: " + aps, null); } if (AFPElementMapping.INCLUDE_PAGE_SEGMENT.equals(element)) { AFPPageSegmentElement.AFPPageSegmentSetup apse = (AFPPageSegmentElement.AFPPageSegmentSetup)aps; String name = apse.getName(); String source = apse.getValue(); String uri = apse.getResourceSrc(); pageSegmentMap.put(source, new PageSegmentDescriptor(name, uri)); } } } else if (extension instanceof AFPPageOverlay) { AFPPageOverlay ipo = (AFPPageOverlay)extension; if (this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP page overlay extension encountered outside the page header: " + ipo, null); } String overlay = ipo.getName(); if (overlay != null) { dataStream.createIncludePageOverlay(overlay, ipo.getX(), ipo.getY()); } } else if (extension instanceof AFPInvokeMediumMap) { if (this.location != Location.FOLLOWING_PAGE_SEQUENCE && this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP IMM extension must be between page-sequence" + " and the first page or child of page-header: " + extension, null); } AFPInvokeMediumMap imm = (AFPInvokeMediumMap)extension; String mediumMap = imm.getName(); if (mediumMap != null) { dataStream.createInvokeMediumMap(mediumMap); } } else if (extension instanceof AFPIncludeFormMap) { AFPIncludeFormMap formMap = (AFPIncludeFormMap)extension; ResourceAccessor accessor = new DefaultFOPResourceAccessor( getUserAgent(), null, null); try { getResourceManager().createIncludedResource(formMap.getName(), formMap.getSrc(), accessor, ResourceObject.TYPE_FORMDEF); } catch (IOException ioe) { throw new IFException( "I/O error while embedding form map resource: " + formMap.getName(), ioe); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { //AFP doesn't support clipping, so we treat viewport like a group //this is the same code as for startGroup() try { saveGraphicsState(); concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void endViewport() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void startGroup(AffineTransform transform) throws IFException { try { saveGraphicsState(); concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void endGroup() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { PageSegmentDescriptor pageSegment = documentHandler.getPageSegmentNameFor(uri); if (pageSegment != null) { float[] srcPts = {rect.x, rect.y}; int[] coords = unitConv.mpts2units(srcPts); int width = Math.round(unitConv.mpt2units(rect.width)); int height = Math.round(unitConv.mpt2units(rect.height)); getDataStream().createIncludePageSegment(pageSegment.getName(), coords[X], coords[Y], width, height); //Do we need to embed an external page segment? if (pageSegment.getURI() != null) { ResourceAccessor accessor = new DefaultFOPResourceAccessor ( documentHandler.getUserAgent(), null, null); try { URI resourceUri = new URI(pageSegment.getURI()); documentHandler.getResourceManager().createIncludedResourceFromExternal( pageSegment.getName(), resourceUri, accessor); } catch (URISyntaxException urie) { throw new IFException("Could not handle resource url" + pageSegment.getURI(), urie); } catch (IOException ioe) { throw new IFException("Could not handle resource" + pageSegment.getURI(), ioe); } } } else { drawImageUsingURI(uri, rect); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { if (fill instanceof Color) { getPaintingState().setColor((Color)fill); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } RectanglePaintingInfo rectanglePaintInfo = new RectanglePaintingInfo( toPoint(rect.x), toPoint(rect.y), toPoint(rect.width), toPoint(rect.height)); try { rectanglePainter.paint(rectanglePaintInfo); } catch (IOException ioe) { throw new IFException("IO error while painting rectangle", ioe); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { try { this.borderPainter.drawBorders(rect, top, bottom, left, right); } catch (IOException ife) { throw new IFException("IO error while painting borders", ife); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { this.borderPainter.drawLine(start, end, width, color, style); } catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void drawText( // CSOK: MethodLength int x, int y, final int letterSpacing, final int wordSpacing, final int[][] dp, final String text) throws IFException { final int fontSize = this.state.getFontSize(); getPaintingState().setFontSize(fontSize); FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() String fontKey = getFontInfo().getInternalFontKey(triplet); if (fontKey == null) { triplet = new FontTriplet("any", Font.STYLE_NORMAL, Font.WEIGHT_NORMAL); fontKey = getFontInfo().getInternalFontKey(triplet); } // register font as necessary Map<String, Typeface> fontMetricMap = documentHandler.getFontInfo().getFonts(); final AFPFont afpFont = (AFPFont)fontMetricMap.get(fontKey); final Font font = getFontInfo().getFontInstance(triplet, fontSize); AFPPageFonts pageFonts = getPaintingState().getPageFonts(); AFPFontAttributes fontAttributes = pageFonts.registerFont(fontKey, afpFont, fontSize); final int fontReference = fontAttributes.getFontReference(); final int[] coords = unitConv.mpts2units(new float[] {x, y} ); final CharacterSet charSet = afpFont.getCharacterSet(fontSize); if (afpFont.isEmbeddable()) { try { documentHandler.getResourceManager().embedFont(afpFont, charSet); } catch (IOException ioe) { throw new IFException("Error while embedding font resources", ioe); } } AbstractPageObject page = getDataStream().getCurrentPage(); PresentationTextObject pto = page.getPresentationTextObject(); try { pto.createControlSequences(new PtocaProducer() { public void produce(PtocaBuilder builder) throws IOException { Point p = getPaintingState().getPoint(coords[X], coords[Y]); builder.setTextOrientation(getPaintingState().getRotation()); builder.absoluteMoveBaseline(p.y); builder.absoluteMoveInline(p.x); builder.setExtendedTextColor(state.getTextColor()); builder.setCodedFont((byte)fontReference); int l = text.length(); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); StringBuffer sb = new StringBuffer(); if (dxl > 0 && dx[0] != 0) { int dxu = Math.round(unitConv.mpt2units(dx[0])); builder.relativeMoveInline(-dxu); } //Following are two variants for glyph placement. //SVI does not seem to be implemented in the same way everywhere, so //a fallback alternative is preserved here. final boolean usePTOCAWordSpacing = true; if (usePTOCAWordSpacing) { int interCharacterAdjustment = 0; if (letterSpacing != 0) { interCharacterAdjustment = Math.round(unitConv.mpt2units( letterSpacing)); } builder.setInterCharacterAdjustment(interCharacterAdjustment); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + letterSpacing)); int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement; if (wordSpacing != 0) { varSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + wordSpacing + letterSpacing)); } builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement); boolean fixedSpaceMode = false; for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( fixedSpaceCharacterIncrement); fixedSpaceMode = true; sb.append(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { if (fixedSpaceMode) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( varSpaceCharacterIncrement); fixedSpaceMode = false; } char ch; if (orgChar == CharUtilities.NBSPACE) { ch = ' '; //converted to normal space to allow word spacing } else { ch = orgChar; } sb.append(ch); } if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } else { for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { sb.append(CharUtilities.SPACE); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { sb.append(orgChar); } if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust += wordSpacing; } glyphAdjust += letterSpacing; if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } flushText(builder, sb, charSet); } private void flushText(PtocaBuilder builder, StringBuffer sb, final CharacterSet charSet) throws IOException { if (sb.length() > 0) { builder.addTransparentData(charSet.encodeChars(sb)); sb.setLength(0); } } }); } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); this.fontResources = new FontResourceCache(getFontInfo()); try { OutputStream out; if (psUtil.isOptimizeResources()) { this.tempFile = File.createTempFile("fop", null); out = new java.io.FileOutputStream(this.tempFile); out = new java.io.BufferedOutputStream(out); } else { out = this.outputStream; } //Setup for PostScript generation this.gen = new PSGenerator(out) { /** Need to subclass PSGenerator to have better URI resolution */ public Source resolveURI(String uri) { return getUserAgent().resolveURI(uri); } }; this.gen.setPSLevel(psUtil.getLanguageLevel()); this.currentPageNumber = 0; this.documentBoundingBox = new Rectangle2D.Double(); //Initial default page device dictionary settings this.pageDeviceDictionary = new PSPageDeviceDictionary(); pageDeviceDictionary.setFlushOnRetrieval(!psUtil.isDSCComplianceEnabled()); pageDeviceDictionary.put("/ImagingBBox", "null"); } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endDocumentHeader() throws IFException { try { writeHeader(); } catch (IOException ioe) { throw new IFException("I/O error writing the PostScript header", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endDocument() throws IFException { try { //Write trailer gen.writeDSCComment(DSCConstants.TRAILER); writeExtensions(COMMENT_DOCUMENT_TRAILER); gen.writeDSCComment(DSCConstants.PAGES, new Integer(this.currentPageNumber)); new DSCCommentBoundingBox(this.documentBoundingBox).generate(gen); new DSCCommentHiResBoundingBox(this.documentBoundingBox).generate(gen); gen.getResourceTracker().writeResources(false, gen); gen.writeDSCComment(DSCConstants.EOF); gen.flush(); log.debug("Rendering to PostScript complete."); if (psUtil.isOptimizeResources()) { IOUtils.closeQuietly(gen.getOutputStream()); rewritePostScriptFile(); } if (pageDeviceDictionary != null) { pageDeviceDictionary.clear(); } } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { if (this.currentPageNumber == 0) { //writeHeader(); } this.currentPageNumber++; gen.getResourceTracker().notifyStartNewPage(); gen.getResourceTracker().notifyResourceUsageOnPage(PSProcSets.STD_PROCSET); gen.writeDSCComment(DSCConstants.PAGE, new Object[] {name, new Integer(this.currentPageNumber)}); double pageWidth = size.width / 1000.0; double pageHeight = size.height / 1000.0; boolean rotate = false; List pageSizes = new java.util.ArrayList(); if (this.psUtil.isAutoRotateLandscape() && (pageHeight < pageWidth)) { rotate = true; pageSizes.add(new Long(Math.round(pageHeight))); pageSizes.add(new Long(Math.round(pageWidth))); } else { pageSizes.add(new Long(Math.round(pageWidth))); pageSizes.add(new Long(Math.round(pageHeight))); } pageDeviceDictionary.put("/PageSize", pageSizes); this.currentPageDefinition = new PageDefinition( new Dimension2DDouble(pageWidth, pageHeight), rotate); //TODO Handle extension attachments for the page!!!!!!! /* if (page.hasExtensionAttachments()) { for (Iterator iter = page.getExtensionAttachments().iterator(); iter.hasNext();) { ExtensionAttachment attachment = (ExtensionAttachment) iter.next(); if (attachment instanceof PSSetPageDevice) {*/ /** * Extract all PSSetPageDevice instances from the * attachment list on the s-p-m and add all * dictionary entries to our internal representation * of the the page device dictionary. *//* PSSetPageDevice setPageDevice = (PSSetPageDevice)attachment; String content = setPageDevice.getContent(); if (content != null) { try { pageDeviceDictionary.putAll(PSDictionary.valueOf(content)); } catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); } } } } }*/ final Integer zero = new Integer(0); Rectangle2D pageBoundingBox = new Rectangle2D.Double(); if (rotate) { pageBoundingBox.setRect(0, 0, pageHeight, pageWidth); gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[] { zero, zero, new Long(Math.round(pageHeight)), new Long(Math.round(pageWidth)) }); gen.writeDSCComment(DSCConstants.PAGE_HIRES_BBOX, new Object[] { zero, zero, new Double(pageHeight), new Double(pageWidth) }); gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Landscape"); } else { pageBoundingBox.setRect(0, 0, pageWidth, pageHeight); gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[] { zero, zero, new Long(Math.round(pageWidth)), new Long(Math.round(pageHeight)) }); gen.writeDSCComment(DSCConstants.PAGE_HIRES_BBOX, new Object[] { zero, zero, new Double(pageWidth), new Double(pageHeight) }); if (psUtil.isAutoRotateLandscape()) { gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Portrait"); } } this.documentBoundingBox.add(pageBoundingBox); gen.writeDSCComment(DSCConstants.PAGE_RESOURCES, new Object[] {DSCConstants.ATEND}); gen.commentln("%FOPSimplePageMaster: " + pageMasterName); } catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPageHeader() throws IFException { super.startPageHeader(); try { gen.writeDSCComment(DSCConstants.BEGIN_PAGE_SETUP); } catch (IOException ioe) { throw new IFException("I/O error in startPageHeader()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageHeader() throws IFException { try { // Write any unwritten changes to page device dictionary if (!pageDeviceDictionary.isEmpty()) { String content = pageDeviceDictionary.getContent(); if (psUtil.isSafeSetPageDevice()) { content += " SSPD"; } else { content += " setpagedevice"; } PSRenderingUtil.writeEnclosedExtensionAttachment(gen, new PSSetPageDevice(content)); } double pageHeight = this.currentPageDefinition.dimensions.getHeight(); if (this.currentPageDefinition.rotate) { gen.writeln(gen.formatDouble(pageHeight) + " 0 translate"); gen.writeln("90 rotate"); } gen.concatMatrix(1, 0, 0, -1, 0, pageHeight); gen.writeDSCComment(DSCConstants.END_PAGE_SETUP); } catch (IOException ioe) { throw new IFException("I/O error in endPageHeader()", ioe); } super.endPageHeader(); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageContent() throws IFException { try { gen.showPage(); } catch (IOException ioe) { throw new IFException("I/O error in endPageContent()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPageTrailer() throws IFException { try { writeExtensions(PAGE_TRAILER_CODE_BEFORE); super.startPageTrailer(); gen.writeDSCComment(DSCConstants.PAGE_TRAILER); } catch (IOException ioe) { throw new IFException("I/O error in startPageTrailer()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageTrailer() throws IFException { try { writeExtensions(COMMENT_PAGE_TRAILER); } catch (IOException ioe) { throw new IFException("I/O error in endPageTrailer()", ioe); } super.endPageTrailer(); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPage() throws IFException { try { gen.getResourceTracker().writeResources(true, gen); } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } this.currentPageDefinition = null; }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { try { if (extension instanceof PSSetupCode) { if (inPage()) { PSRenderingUtil.writeEnclosedExtensionAttachment(gen, (PSSetupCode)extension); } else { //A special collection for setup code as it's put in a different place //than the "before comments". if (setupCodeList == null) { setupCodeList = new java.util.ArrayList(); } if (!setupCodeList.contains(extension)) { setupCodeList.add(extension); } } } else if (extension instanceof PSSetPageDevice) { /** * Extract all PSSetPageDevice instances from the * attachment list on the s-p-m and add all dictionary * entries to our internal representation of the the * page device dictionary. */ PSSetPageDevice setPageDevice = (PSSetPageDevice)extension; String content = setPageDevice.getContent(); if (content != null) { try { this.pageDeviceDictionary.putAll(PSDictionary.valueOf(content)); } catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); } } } else if (extension instanceof PSCommentBefore) { if (inPage()) { PSRenderingUtil.writeEnclosedExtensionAttachment( gen, (PSCommentBefore)extension); } else { if (comments[COMMENT_DOCUMENT_HEADER] == null) { comments[COMMENT_DOCUMENT_HEADER] = new java.util.ArrayList(); } comments[COMMENT_DOCUMENT_HEADER].add(extension); } } else if (extension instanceof PSCommentAfter) { int targetCollection = (inPage() ? COMMENT_PAGE_TRAILER : COMMENT_DOCUMENT_TRAILER); if (comments[targetCollection] == null) { comments[targetCollection] = new java.util.ArrayList(); } comments[targetCollection].add(extension); } else if (extension instanceof PSPageTrailerCodeBefore) { if (comments[PAGE_TRAILER_CODE_BEFORE] == null) { comments[PAGE_TRAILER_CODE_BEFORE] = new ArrayList(); } comments[PAGE_TRAILER_CODE_BEFORE].add(extension); } } catch (IOException ioe) { throw new IFException("I/O error in handleExtensionObject()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { try { PSGenerator generator = getGenerator(); saveGraphicsState(); generator.concatMatrix(toPoints(transform)); } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } if (clipRect != null) { clipRect(clipRect); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void endViewport() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void startGroup(AffineTransform transform) throws IFException { try { PSGenerator generator = getGenerator(); saveGraphicsState(); generator.concatMatrix(toPoints(transform)); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void endGroup() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { try { endTextObject(); } catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); } drawImageUsingURI(uri, rect); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { try { endTextObject(); } catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); } drawImageUsingDocument(doc, rect); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void clipRect(Rectangle rect) throws IFException { try { PSGenerator generator = getGenerator(); endTextObject(); generator.defineRect(rect.x / 1000.0, rect.y / 1000.0, rect.width / 1000.0, rect.height / 1000.0); generator.writeln(generator.mapCommand("clip") + " " + generator.mapCommand("newpath")); } catch (IOException ioe) { throw new IFException("I/O error in clipRect()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { try { endTextObject(); PSGenerator generator = getGenerator(); if (fill != null) { if (fill instanceof Color) { generator.useColor((Color)fill); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } } generator.defineRect(rect.x / 1000.0, rect.y / 1000.0, rect.width / 1000.0, rect.height / 1000.0); generator.writeln(generator.mapCommand("fill")); } catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); } } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { try { endTextObject(); if (getPSUtil().getRenderingMode() == PSRenderingMode.SIZE && hasOnlySolidBorders(top, bottom, left, right)) { super.drawBorderRect(rect, top, bottom, left, right); } else { this.borderPainter.drawBorders(rect, top, bottom, left, right); } } catch (IOException ioe) { throw new IFException("I/O error in drawBorderRect()", ioe); } } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { endTextObject(); this.borderPainter.drawLine(start, end, width, color, style); } catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { //Do not draw text if font-size is 0 as it creates an invalid PostScript file if (state.getFontSize() == 0) { return; } PSGenerator generator = getGenerator(); generator.useColor(state.getTextColor()); beginTextObject(); FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() //TODO Opportunity for font caching if font state is more heavily used String fontKey = getFontInfo().getInternalFontKey(triplet); if (fontKey == null) { throw new IFException("Font not available: " + triplet, null); } int sizeMillipoints = state.getFontSize(); // This assumes that *all* CIDFonts use a /ToUnicode mapping Typeface tf = getTypeface(fontKey); SingleByteFont singleByteFont = null; if (tf instanceof SingleByteFont) { singleByteFont = (SingleByteFont)tf; } Font font = getFontInfo().getFontInstance(triplet, sizeMillipoints); useFont(fontKey, sizeMillipoints); generator.writeln("1 0 0 -1 " + formatMptAsPt(generator, x) + " " + formatMptAsPt(generator, y) + " Tm"); int textLen = text.length(); int start = 0; if (singleByteFont != null) { //Analyze string and split up in order to paint in different sub-fonts/encodings int currentEncoding = -1; for (int i = 0; i < textLen; i++) { char c = text.charAt(i); char mapped = tf.mapChar(c); int encoding = mapped / 256; if (currentEncoding != encoding) { if (i > 0) { writeText(text, start, i - start, letterSpacing, wordSpacing, dp, font, tf); } if (encoding == 0) { useFont(fontKey, sizeMillipoints); } else { useFont(fontKey + "_" + Integer.toString(encoding), sizeMillipoints); } currentEncoding = encoding; start = i; } } } else { //Simple single-font painting useFont(fontKey, sizeMillipoints); } writeText(text, start, textLen - start, letterSpacing, wordSpacing, dp, font, tf); } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); clipRect(clipRect); } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void startGroup(AffineTransform transform) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
131
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (ParserConfigurationException e) { throw new IFException("Error while setting up a DOM for SVG generation", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException se) { throw new IFException("SAX error in startDocument()", se); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException e) { throw new IFException( "Error while setting up a TransformerHandler for SVG generation", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException("Error setting up a Transformer", tce); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException)te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O exception while setting up output file", ioe); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error flushing the PDF document", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error while drawing borders", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the color attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in clipRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawBorderRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing named destination", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing bookmark tree", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing link", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing object", e); }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); }
// in src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException( "Error while setting up the serializer for XML output", tce); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding page image", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException( "I/O error while painting marks using a bitmap", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (ImageException ie) { throw new IFException( "Error while painting marks using a bitmap", ie); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding BufferedImage", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException( "I/O error while embedding form map resource: " + formMap.getName(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (URISyntaxException urie) { throw new IFException("Could not handle resource url" + pageSegment.getURI(), urie); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Could not handle resource" + pageSegment.getURI(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("IO error while painting rectangle", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ife) { throw new IFException("IO error while painting borders", ife); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Error while embedding font resources", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error writing the PostScript header", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageContent()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in handleExtensionObject()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in clipRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawBorderRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
296
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { startViewport(SVGUtil.formatAffineTransformMptToPt(transform), size, clipRect); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void startViewport(AffineTransform[] transforms, Dimension size, Rectangle clipRect) throws IFException { startViewport(SVGUtil.formatAffineTransformsMptToPt(transforms), size, clipRect); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void startViewport(String transform, Dimension size, Rectangle clipRect) throws IFException { try { establish(MODE_NORMAL); AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { XMLUtil.addAttribute(atts, "transform", transform); } handler.startElement("g", atts); atts.clear(); XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(size.width)); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(size.height)); if (clipRect != null) { int[] v = new int[] { clipRect.y, -clipRect.x + size.width - clipRect.width, -clipRect.y + size.height - clipRect.height, clipRect.x}; int sum = 0; for (int i = 0; i < 4; i++) { sum += Math.abs(v[i]); } if (sum != 0) { StringBuffer sb = new StringBuffer("rect("); sb.append(SVGUtil.formatMptToPt(v[0])).append(','); sb.append(SVGUtil.formatMptToPt(v[1])).append(','); sb.append(SVGUtil.formatMptToPt(v[2])).append(','); sb.append(SVGUtil.formatMptToPt(v[3])).append(')'); XMLUtil.addAttribute(atts, "clip", sb.toString()); } XMLUtil.addAttribute(atts, "overflow", "hidden"); } else { XMLUtil.addAttribute(atts, "overflow", "visible"); } handler.startElement("svg", atts); } catch (SAXException e) { throw new IFException("SAX error in startBox()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void endViewport() throws IFException { try { establish(MODE_NORMAL); handler.endElement("svg"); handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endBox()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void startGroup(AffineTransform[] transforms) throws IFException { startGroup(SVGUtil.formatAffineTransformsMptToPt(transforms)); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void startGroup(AffineTransform transform) throws IFException { startGroup(SVGUtil.formatAffineTransformMptToPt(transform)); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void startGroup(String transform) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { XMLUtil.addAttribute(atts, "transform", transform); } handler.startElement("g", atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void endGroup() throws IFException { try { establish(MODE_NORMAL); handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { try { establish(MODE_NORMAL); ImageManager manager = getUserAgent().getFactory().getImageManager(); ImageInfo info = null; try { ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); info = manager.getImageInfo(uri, sessionContext); String mime = info.getMimeType(); Map foreignAttributes = getContext().getForeignAttributes(); String conversionMode = (String)foreignAttributes.get( ImageHandlerUtil.CONVERSION_MODE); if ("reference".equals(conversionMode) && (MimeConstants.MIME_GIF.equals(mime) || MimeConstants.MIME_JPEG.equals(mime) || MimeConstants.MIME_PNG.equals(mime) || MimeConstants.MIME_SVG.equals(mime))) { //Just reference the image //TODO Some additional URI rewriting might be necessary AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, IFConstants.XLINK_HREF, uri); XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(rect.x)); XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(rect.y)); XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(rect.width)); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(rect.height)); handler.element("image", atts); } else { drawImageUsingImageHandler(info, rect); } } catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); } catch (FileNotFoundException fe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(this, (info != null ? info.toString() : uri), fe, null); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); } } catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { try { establish(MODE_NORMAL); drawImageUsingDocument(doc, rect); } catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void clipRect(Rectangle rect) throws IFException { //TODO Implement me!!! }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } try { establish(MODE_NORMAL); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(rect.x)); XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(rect.y)); XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(rect.width)); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(rect.height)); if (fill != null) { XMLUtil.addAttribute(atts, "fill", toString(fill)); } /* disabled if (stroke != null) { XMLUtil.addAttribute(atts, "stroke", toString(stroke)); }*/ handler.element("rect", atts); } catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawBorderRect(Rectangle rect, BorderProps before, BorderProps after, BorderProps start, BorderProps end) throws IFException { // TODO Auto-generated method stub }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { establish(MODE_NORMAL); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "x1", SVGUtil.formatMptToPt(start.x)); XMLUtil.addAttribute(atts, "y1", SVGUtil.formatMptToPt(start.y)); XMLUtil.addAttribute(atts, "x2", SVGUtil.formatMptToPt(end.x)); XMLUtil.addAttribute(atts, "y2", SVGUtil.formatMptToPt(end.y)); XMLUtil.addAttribute(atts, "stroke-width", toString(color)); XMLUtil.addAttribute(atts, "fill", toString(color)); //TODO Handle style parameter handler.element("line", atts); } catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { establish(MODE_TEXT); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, XMLConstants.XML_SPACE, "preserve"); XMLUtil.addAttribute(atts, "x", SVGUtil.formatMptToPt(x)); XMLUtil.addAttribute(atts, "y", SVGUtil.formatMptToPt(y)); if (letterSpacing != 0) { XMLUtil.addAttribute(atts, "letter-spacing", SVGUtil.formatMptToPt(letterSpacing)); } if (wordSpacing != 0) { XMLUtil.addAttribute(atts, "word-spacing", SVGUtil.formatMptToPt(wordSpacing)); } if (dp != null) { int[] dx = IFUtil.convertDPToDX(dp); XMLUtil.addAttribute(atts, "dx", SVGUtil.formatMptArrayToPt(dx)); } handler.startElement("text", atts); char[] chars = text.toCharArray(); handler.characters(chars, 0, chars.length); handler.endElement("text"); } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof Metadata) { Metadata meta = (Metadata)extension; try { establish(MODE_NORMAL); handler.startElement("metadata"); meta.toSAX(this.handler); handler.endElement("metadata"); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { throw new UnsupportedOperationException( "Don't know how to handle extension object: " + extension); } }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
public void startDocumentHeader() throws IFException { try { handler.startElement("defs"); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
public void endDocumentHeader() throws IFException { try { handler.endElement("defs"); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof Metadata) { Metadata meta = (Metadata)extension; try { handler.startElement("metadata"); meta.toSAX(this.handler); handler.endElement("metadata"); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { log.debug("Don't know how to handle extension object. Ignoring: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void setResult(Result result) throws IFException { if (result instanceof StreamResult) { multiFileUtil = new MultiFileRenderingUtil(FILE_EXTENSION_SVG, getUserAgent().getOutputFile()); this.firstStream = (StreamResult)result; } else { this.simpleResult = result; } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); builderFactory.setValidating(false); try { DocumentBuilder builder = builderFactory.newDocumentBuilder(); this.reusedParts = builder.newDocument(); } catch (ParserConfigurationException e) { throw new IFException("Error while setting up a DOM for SVG generation", e); } try { TransformerHandler toDOMHandler = tFactory.newTransformerHandler(); toDOMHandler.setResult(new DOMResult(this.reusedParts)); this.handler = decorate(toDOMHandler); this.handler.startDocument(); } catch (SAXException se) { throw new IFException("SAX error in startDocument()", se); } catch (TransformerConfigurationException e) { throw new IFException( "Error while setting up a TransformerHandler for SVG generation", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endDocument() throws IFException { //nop }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endDocumentHeader() throws IFException { super.endDocumentHeader(); try { //Stop recording parts reused for each page this.handler.endDocument(); this.handler = null; } catch (SAXException e) { throw new IFException("SAX error in endDocumentHeader()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void startPageSequence(String id) throws IFException { //nop }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endPageSequence() throws IFException { //nop }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { if (this.multiFileUtil != null) { prepareHandlerWithOutputStream(index); } else { if (this.simpleResult == null) { //Only one page is supported with this approach at the moment throw new IFException( "Only one page is supported for output with the given Result instance!", null); } super.setResult(this.simpleResult); this.simpleResult = null; } try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "version", "1.1"); //SVG 1.1 /* XMLUtil.addAttribute(atts, "index", Integer.toString(index)); XMLUtil.addAttribute(atts, "name", name); */ XMLUtil.addAttribute(atts, "width", SVGUtil.formatMptToPt(size.width) + "pt"); XMLUtil.addAttribute(atts, "height", SVGUtil.formatMptToPt(size.height) + "pt"); XMLUtil.addAttribute(atts, "viewBox", "0 0 " + SVGUtil.formatMptToPt(size.width) + " " + SVGUtil.formatMptToPt(size.height)); handler.startElement("svg", atts); try { Transformer transformer = tFactory.newTransformer(); Source src = new DOMSource(this.reusedParts.getDocumentElement()); Result res = new SAXResult(new DelegatingFragmentContentHandler(this.handler)); transformer.transform(src, res); } catch (TransformerConfigurationException tce) { throw new IFException("Error setting up a Transformer", tce); } catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException)te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } } } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
private void prepareHandlerWithOutputStream(int index) throws IFException { OutputStream out; try { if (index == 0) { out = null; } else { out = this.multiFileUtil.createOutputStream(index); if (out == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.stoppingAfterFirstPageNoFilename(this); } } } catch (IOException ioe) { throw new IFException("I/O exception while setting up output file", ioe); } if (out == null) { this.handler = decorate(createContentHandler(this.firstStream)); } else { this.currentStream = new StreamResult(out); this.handler = decorate(createContentHandler(this.currentStream)); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public IFPainter startPageContent() throws IFException { try { handler.startElement("g"); } catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); } return new SVGPainter(this, handler); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endPageContent() throws IFException { try { handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
public void endPage() throws IFException { try { handler.endElement("svg"); this.handler.endDocument(); } catch (SAXException e) { throw new IFException("SAX error in endPage()", e); } closeCurrentStream(); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); handler.startPrefixMapping("if", IFConstants.NAMESPACE); AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "version", "1.2"); //SVG Print is SVG 1.2 handler.startElement("svg", atts); } catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endDocument() throws IFException { try { handler.endElement("svg"); handler.endDocument(); } catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startPageSequence(String id) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (id != null) { atts.addAttribute(XML_NAMESPACE, "id", "xml:id", CDATA, id); } handler.startElement("pageSet", atts); } catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPageSequence() throws IFException { try { handler.endElement("pageSet"); } catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { AttributesImpl atts = new AttributesImpl(); /* XMLUtil.addAttribute(atts, "index", Integer.toString(index)); XMLUtil.addAttribute(atts, "name", name); */ //NOTE: SVG Print doesn't support individual page sizes for each page atts.addAttribute(IFConstants.NAMESPACE, "width", "if:width", CDATA, Integer.toString(size.width)); atts.addAttribute(IFConstants.NAMESPACE, "height", "if:height", CDATA, Integer.toString(size.height)); atts.addAttribute(IFConstants.NAMESPACE, "viewBox", "if:viewBox", CDATA, "0 0 " + Integer.toString(size.width) + " " + Integer.toString(size.height)); handler.startElement("page", atts); } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startPageHeader() throws IFException { }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPageHeader() throws IFException { }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public IFPainter startPageContent() throws IFException { try { handler.startElement("g"); } catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); } return new SVGPainter(this, handler); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPageContent() throws IFException { try { handler.endElement("g"); } catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void startPageTrailer() throws IFException { }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPageTrailer() throws IFException { }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
public void endPage() throws IFException { try { handler.endElement("page"); } catch (SAXException e) { throw new IFException("SAX error in endPage()", e); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
public void renderNamedDestination(NamedDestination destination) throws IFException { PDFAction action = getAction(destination.getAction()); getPDFDoc().getFactory().makeDestination( destination.getName(), action.makeReference()); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
public void renderBookmarkTree(BookmarkTree tree) throws IFException { Iterator iter = tree.getBookmarks().iterator(); while (iter.hasNext()) { Bookmark b = (Bookmark)iter.next(); renderBookmark(b, null); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
private void renderBookmark(Bookmark bookmark, PDFOutline parent) throws IFException { if (parent == null) { parent = getPDFDoc().getOutlineRoot(); } PDFAction action = getAction(bookmark.getAction()); String actionRef = (action != null ? action.makeReference().toString() : null); PDFOutline pdfOutline = getPDFDoc().getFactory().makeOutline(parent, bookmark.getTitle(), actionRef, bookmark.isShown()); Iterator iter = bookmark.getChildBookmarks().iterator(); while (iter.hasNext()) { Bookmark b = (Bookmark)iter.next(); renderBookmark(b, pdfOutline); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
public void renderLink(Link link) throws IFException { Rectangle targetRect = link.getTargetRect(); int pageHeight = documentHandler.currentPageRef.getPageDimension().height; Rectangle2D targetRect2D = new Rectangle2D.Double( targetRect.getMinX() / 1000.0, (pageHeight - targetRect.getMinY() - targetRect.getHeight()) / 1000.0, targetRect.getWidth() / 1000.0, targetRect.getHeight() / 1000.0); PDFAction pdfAction = getAction(link.getAction()); //makeLink() currently needs a PDFAction and not a reference //TODO Revisit when PDFLink is converted to a PDFDictionary PDFLink pdfLink = getPDFDoc().getFactory().makeLink( targetRect2D, pdfAction); if (pdfLink != null) { PDFStructElem structure = (PDFStructElem) link.getAction().getStructureTreeElement(); if (documentHandler.getUserAgent().isAccessibilityEnabled() && structure != null) { documentHandler.getLogicalStructureHandler().addLinkContentItem(pdfLink, structure); } documentHandler.currentPage.addAnnotation(pdfLink); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
public void addResolvedAction(AbstractAction action) throws IFException { assert action.isComplete(); PDFAction pdfAction = (PDFAction)this.incompleteActions.remove(action.getID()); if (pdfAction == null) { getAction(action); } else if (pdfAction instanceof PDFGoTo) { PDFGoTo pdfGoTo = (PDFGoTo)pdfAction; updateTargetLocation(pdfGoTo, (GoToXYAction)action); } else { throw new UnsupportedOperationException( "Action type not supported: " + pdfAction.getClass().getName()); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
private PDFAction getAction(AbstractAction action) throws IFException { if (action == null) { return null; } PDFAction pdfAction = (PDFAction)this.completeActions.get(action.getID()); if (pdfAction != null) { return pdfAction; } else if (action instanceof GoToXYAction) { pdfAction = (PDFAction) incompleteActions.get(action.getID()); if (pdfAction != null) { return pdfAction; } else { GoToXYAction a = (GoToXYAction)action; PDFGoTo pdfGoTo = new PDFGoTo(null); getPDFDoc().assignObjectNumber(pdfGoTo); if (action.isComplete()) { updateTargetLocation(pdfGoTo, a); } else { this.incompleteActions.put(action.getID(), pdfGoTo); } return pdfGoTo; } } else if (action instanceof URIAction) { URIAction u = (URIAction)action; assert u.isComplete(); String uri = u.getURI(); PDFFactory factory = getPDFDoc().getFactory(); pdfAction = factory.getExternalAction(uri, u.isNewWindow()); if (!pdfAction.hasObjectNumber()) { //Some PDF actions are pooled getPDFDoc().registerObject(pdfAction); } this.completeActions.put(action.getID(), pdfAction); return pdfAction; } else { throw new UnsupportedOperationException("Unsupported action type: " + action + " (" + action.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
private void updateTargetLocation(PDFGoTo pdfGoTo, GoToXYAction action) throws IFException { PageReference pageRef = this.documentHandler.getPageReference(action.getPageIndex()); if ( pageRef == null ) { throw new IFException("Can't resolve page reference @ index: " + action.getPageIndex(), null); } else { //Convert target location from millipoints to points and adjust for different //page origin Point2D p2d = null; p2d = new Point2D.Double( action.getTargetLocation().x / 1000.0, (pageRef.getPageDimension().height - action.getTargetLocation().y) / 1000.0); String pdfPageRef = pageRef.getPageRef(); pdfGoTo.setPageReference(pdfPageRef); pdfGoTo.setPosition(p2d); //Queue this object now that it's complete getPDFDoc().addObject(pdfGoTo); this.completeActions.put(action.getID(), pdfGoTo); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { generator.saveGraphicsState(); generator.concatenate(toPoints(transform)); if (clipRect != null) { clipRect(clipRect); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void endViewport() throws IFException { generator.restoreGraphicsState(); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void startGroup(AffineTransform transform) throws IFException { generator.saveGraphicsState(); generator.concatenate(toPoints(transform)); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void endGroup() throws IFException { generator.restoreGraphicsState(); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { PDFXObject xobject = getPDFDoc().getXObject(uri); if (xobject != null) { if (accessEnabled) { PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement(); prepareImageMCID(structElem); placeImageAccess(rect, xobject); } else { placeImage(rect, xobject); } } else { if (accessEnabled) { PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement(); prepareImageMCID(structElem); } drawImageUsingURI(uri, rect); flushPDFDoc(); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { if (accessEnabled) { PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement(); prepareImageMCID(structElem); } drawImageUsingDocument(doc, rect); flushPDFDoc(); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
private void flushPDFDoc() throws IFException { // output new data try { generator.flushPDFDoc(); } catch (IOException ioe) { throw new IFException("I/O error flushing the PDF document", ioe); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void clipRect(Rectangle rect) throws IFException { generator.endTextObject(); generator.clipRect(rect); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { generator.endTextObject(); if (fill != null) { if (fill instanceof Color) { generator.updateColor((Color)fill, true, null); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } } StringBuffer sb = new StringBuffer(); sb.append(format(rect.x)).append(' '); sb.append(format(rect.y)).append(' '); sb.append(format(rect.width)).append(' '); sb.append(format(rect.height)).append(" re"); if (fill != null) { sb.append(" f"); } /* Removed from method signature as it is currently not used if (stroke != null) { sb.append(" S"); }*/ sb.append('\n'); generator.add(sb.toString()); } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
Override public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { generator.endTextObject(); try { this.borderPainter.drawBorders(rect, top, bottom, left, right); } catch (IOException ioe) { throw new IFException("I/O error while drawing borders", ioe); } } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
Override public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { generator.endTextObject(); this.borderPainter.drawLine(start, end, width, color, style); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { if (accessEnabled) { PDFStructElem structElem = (PDFStructElem) getContext().getStructureTreeElement(); MarkedContentInfo mci = logicalStructureHandler.addTextContentItem(structElem); if (generator.getTextUtil().isInTextObject()) { generator.separateTextElements(mci.tag, mci.mcid); } generator.updateColor(state.getTextColor(), true, null); generator.beginTextObject(mci.tag, mci.mcid); } else { generator.updateColor(state.getTextColor(), true, null); generator.beginTextObject(); } FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); if ( ( dp == null ) || IFUtil.isDPOnlyDX ( dp ) ) { drawTextWithDX ( x, y, text, triplet, letterSpacing, wordSpacing, IFUtil.convertDPToDX ( dp ) ); } else { drawTextWithDP ( x, y, text, triplet, letterSpacing, wordSpacing, dp ); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); try { this.pdfDoc = pdfUtil.setupPDFDocument(this.outputStream); this.accessEnabled = getUserAgent().isAccessibilityEnabled(); if (accessEnabled) { setupAccessibility(); } } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endDocumentHeader() throws IFException { pdfUtil.generateDefaultXMPMetadata(); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endDocument() throws IFException { try { pdfDoc.getResources().addFonts(pdfDoc, fontInfo); pdfDoc.outputTrailer(this.outputStream); this.pdfDoc = null; pdfResources = null; this.generator = null; currentContext = null; currentPage = null; } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void startPageSequence(String id) throws IFException { //nop }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endPageSequence() throws IFException { //nop }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { this.pdfResources = this.pdfDoc.getResources(); PageBoundaries boundaries = new PageBoundaries(size, getContext().getForeignAttributes()); Rectangle trimBox = boundaries.getTrimBox(); Rectangle bleedBox = boundaries.getBleedBox(); Rectangle mediaBox = boundaries.getMediaBox(); Rectangle cropBox = boundaries.getCropBox(); // set scale attributes double scaleX = 1; double scaleY = 1; String scale = (String) getContext().getForeignAttribute( PageScale.EXT_PAGE_SCALE); Point2D scales = PageScale.getScale(scale); if (scales != null) { scaleX = scales.getX(); scaleY = scales.getY(); } //PDF uses the lower left as origin, need to transform from FOP's internal coord system AffineTransform boxTransform = new AffineTransform( scaleX / 1000, 0, 0, -scaleY / 1000, 0, scaleY * size.getHeight() / 1000); this.currentPage = this.pdfDoc.getFactory().makePage( this.pdfResources, index, toPDFCoordSystem(mediaBox, boxTransform), toPDFCoordSystem(cropBox, boxTransform), toPDFCoordSystem(bleedBox, boxTransform), toPDFCoordSystem(trimBox, boxTransform)); if (accessEnabled) { logicalStructureHandler.startPage(currentPage); } pdfUtil.generatePageLabel(index, name); currentPageRef = new PageReference(currentPage, size); this.pageReferences.put(Integer.valueOf(index), currentPageRef); this.generator = new PDFContentGenerator(this.pdfDoc, this.outputStream, this.currentPage); // Transform the PDF's default coordinate system (0,0 at lower left) to the PDFPainter's AffineTransform basicPageTransform = new AffineTransform(1, 0, 0, -1, 0, (scaleY * size.height) / 1000f); basicPageTransform.scale(scaleX, scaleY); generator.saveGraphicsState(); generator.concatenate(basicPageTransform); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public IFPainter startPageContent() throws IFException { return new PDFPainter(this, logicalStructureHandler); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endPageContent() throws IFException { generator.restoreGraphicsState(); //for top-level transform to change the default coordinate system }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void endPage() throws IFException { if (accessEnabled) { logicalStructureHandler.endPage(); } try { this.documentNavigationHandler.commit(); this.pdfDoc.registerObject(generator.getStream()); currentPage.setContents(generator.getStream()); PDFAnnotList annots = currentPage.getAnnotations(); if (annots != null) { this.pdfDoc.addObject(annots); } this.pdfDoc.addObject(currentPage); this.generator.flushPDFDoc(); this.generator = null; } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof XMPMetadata) { pdfUtil.renderXMPMetadata((XMPMetadata) extension); } else if (extension instanceof Metadata) { XMPMetadata wrapper = new XMPMetadata(((Metadata) extension)); pdfUtil.renderXMPMetadata(wrapper); } else if (extension instanceof PDFEmbeddedFileExtensionAttachment) { PDFEmbeddedFileExtensionAttachment embeddedFile = (PDFEmbeddedFileExtensionAttachment)extension; try { pdfUtil.addEmbeddedFile(embeddedFile); } catch (IOException ioe) { throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe); } } else { log.debug("Don't know how to handle extension object. Ignoring: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void parse(Source src, IFDocumentHandler documentHandler, FOUserAgent userAgent) throws TransformerException, IFException { try { Transformer transformer = tFactory.newTransformer(); transformer.setErrorListener(new DefaultErrorListener(log)); SAXResult res = new SAXResult(getContentHandler(documentHandler, userAgent)); transformer.transform(src, res); } catch (TransformerException te) { //Unpack original IFException if applicable if (te.getCause() instanceof SAXException) { SAXException se = (SAXException)te.getCause(); if (se.getCause() instanceof IFException) { throw (IFException)se.getCause(); } } else if (te.getCause() instanceof IFException) { throw (IFException)te.getCause(); } throw te; } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException, SAXException { //nop }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { documentHandler.startDocument(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endDocument(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { documentHandler.startDocumentHeader(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endDocumentHeader(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { documentHandler.setDocumentLocale(getLanguage(attributes)); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { documentHandler.startDocumentTrailer(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endDocumentTrailer(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { String id = attributes.getValue("id"); Locale language = getLanguage(attributes); if (language != null) { documentHandler.getContext().setLanguage(language); } Map<QName, String> foreignAttributes = getForeignAttributes(lastAttributes); establishForeignAttributes(foreignAttributes); documentHandler.startPageSequence(id); resetForeignAttributes(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endPageSequence(); documentHandler.getContext().setLanguage(null); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int index = Integer.parseInt(attributes.getValue("index")); String name = attributes.getValue("name"); String pageMasterName = attributes.getValue("page-master-name"); int width = Integer.parseInt(attributes.getValue("width")); int height = Integer.parseInt(attributes.getValue("height")); Map<QName, String> foreignAttributes = getForeignAttributes(lastAttributes); establishForeignAttributes(foreignAttributes); documentHandler.startPage(index, name, pageMasterName, new Dimension(width, height)); resetForeignAttributes(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endPage(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { documentHandler.startPageHeader(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endPageHeader(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { painter = documentHandler.startPageContent(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { painter = null; documentHandler.getContext().setID(""); documentHandler.endPageContent(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { documentHandler.startPageTrailer(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { documentHandler.endPageTrailer(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { String transform = attributes.getValue("transform"); AffineTransform[] transforms = AffineTransformArrayParser.createAffineTransform(transform); int width = Integer.parseInt(attributes.getValue("width")); int height = Integer.parseInt(attributes.getValue("height")); Rectangle clipRect = XMLUtil.getAttributeAsRectangle(attributes, "clip-rect"); painter.startViewport(transforms, new Dimension(width, height), clipRect); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { painter.endViewport(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { String transform = attributes.getValue("transform"); AffineTransform[] transforms = AffineTransformArrayParser.createAffineTransform(transform); painter.startGroup(transforms); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { painter.endGroup(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
Override public void startElement(Attributes attributes) throws IFException, SAXException { String id = attributes.getValue("name"); documentHandler.getContext().setID(id); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { String family = attributes.getValue("family"); String style = attributes.getValue("style"); Integer weight = XMLUtil.getAttributeAsInteger(attributes, "weight"); String variant = attributes.getValue("variant"); Integer size = XMLUtil.getAttributeAsInteger(attributes, "size"); Color color; try { color = getAttributeAsColor(attributes, "color"); } catch (PropertyException pe) { throw new IFException("Error parsing the color attribute", pe); } painter.setFont(family, style, weight, variant, size, color); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { int x = Integer.parseInt(lastAttributes.getValue("x")); int y = Integer.parseInt(lastAttributes.getValue("y")); String s = lastAttributes.getValue("letter-spacing"); int letterSpacing = (s != null ? Integer.parseInt(s) : 0); s = lastAttributes.getValue("word-spacing"); int wordSpacing = (s != null ? Integer.parseInt(s) : 0); int[] dx = XMLUtil.getAttributeAsIntArray(lastAttributes, "dx"); int[][] dp = XMLUtil.getAttributeAsPositionAdjustments(lastAttributes, "dp"); // if only DX present, then convert DX to DP; otherwise use only DP, // effectively ignoring DX if ( ( dp == null ) && ( dx != null ) ) { dp = IFUtil.convertDXToDP ( dx ); } establishStructureTreeElement(lastAttributes); painter.drawText(x, y, letterSpacing, wordSpacing, dp, content.toString()); resetStructureTreeElement(); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int x = Integer.parseInt(attributes.getValue("x")); int y = Integer.parseInt(attributes.getValue("y")); int width = Integer.parseInt(attributes.getValue("width")); int height = Integer.parseInt(attributes.getValue("height")); painter.clipRect(new Rectangle(x, y, width, height)); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int x = Integer.parseInt(attributes.getValue("x")); int y = Integer.parseInt(attributes.getValue("y")); int width = Integer.parseInt(attributes.getValue("width")); int height = Integer.parseInt(attributes.getValue("height")); Color fillColor; try { fillColor = getAttributeAsColor(attributes, "fill"); } catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); } painter.fillRect(new Rectangle(x, y, width, height), fillColor); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int x1 = Integer.parseInt(attributes.getValue("x1")); int y1 = Integer.parseInt(attributes.getValue("y1")); int x2 = Integer.parseInt(attributes.getValue("x2")); int y2 = Integer.parseInt(attributes.getValue("y2")); int width = Integer.parseInt(attributes.getValue("stroke-width")); Color color; try { color = getAttributeAsColor(attributes, "color"); } catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); } RuleStyle style = RuleStyle.valueOf(attributes.getValue("style")); painter.drawLine(new Point(x1, y1), new Point(x2, y2), width, color, style); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { int x = Integer.parseInt(attributes.getValue("x")); int y = Integer.parseInt(attributes.getValue("y")); int width = Integer.parseInt(attributes.getValue("width")); int height = Integer.parseInt(attributes.getValue("height")); BorderProps[] borders = new BorderProps[4]; for (int i = 0; i < 4; i++) { String b = attributes.getValue(SIDES[i]); if (b != null) { borders[i] = BorderProps.valueOf(userAgent, b); } } painter.drawBorderRect(new Rectangle(x, y, width, height), borders[0], borders[1], borders[2], borders[3]); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException { inForeignObject = true; }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement() throws IFException { int x = Integer.parseInt(lastAttributes.getValue("x")); int y = Integer.parseInt(lastAttributes.getValue("y")); int width = Integer.parseInt(lastAttributes.getValue("width")); int height = Integer.parseInt(lastAttributes.getValue("height")); Map<QName, String> foreignAttributes = getForeignAttributes(lastAttributes); establishForeignAttributes(foreignAttributes); establishStructureTreeElement(lastAttributes); if (foreignObject != null) { painter.drawImage(foreignObject, new Rectangle(x, y, width, height)); foreignObject = null; } else { String uri = lastAttributes.getValue( XLINK_HREF.getNamespaceURI(), XLINK_HREF.getLocalName()); if (uri == null) { throw new IFException("xlink:href is missing on image", null); } painter.drawImage(uri, new Rectangle(x, y, width, height)); } resetForeignAttributes(); resetStructureTreeElement(); inForeignObject = false; }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
public void startViewport(AffineTransform[] transforms, Dimension size, Rectangle clipRect) throws IFException { startViewport(combine(transforms), size, clipRect); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
public void startGroup(AffineTransform[] transforms) throws IFException { startGroup(combine(transforms)); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null) { Rectangle b = new Rectangle( rect.x, rect.y, rect.width, top.width); fillRect(b, top.color); } if (right != null) { Rectangle b = new Rectangle( rect.x + rect.width - right.width, rect.y, right.width, rect.height); fillRect(b, right.color); } if (bottom != null) { Rectangle b = new Rectangle( rect.x, rect.y + rect.height - bottom.width, rect.width, bottom.width); fillRect(b, bottom.color); } if (left != null) { Rectangle b = new Rectangle( rect.x, rect.y, left.width, rect.height); fillRect(b, left.color); } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { Rectangle rect = getLineBoundingBox(start, end, width); fillRect(rect, color); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
public void setFont(String family, String style, Integer weight, String variant, Integer size, Color color) throws IFException { if (family != null) { state.setFontFamily(family); } if (style != null) { state.setFontStyle(style); } if (weight != null) { state.setFontWeight(weight.intValue()); } if (variant != null) { state.setFontVariant(variant); } if (size != null) { state.setFontSize(size.intValue()); } if (color != null) { state.setTextColor(color); } }
// in src/java/org/apache/fop/render/intermediate/EventProducingFilter.java
Override public void endPage() throws IFException { super.endPage(); pageNumberEnded++; RendererEventProducer.Provider.get(userAgent.getEventBroadcaster()) .endPage(this, pageNumberEnded); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startDocument() throws IFException { super.startDocument(); try { handler.startDocument(); handler.startPrefixMapping("", NAMESPACE); handler.startPrefixMapping(XLINK_PREFIX, XLINK_NAMESPACE); handler.startPrefixMapping(DocumentNavigationExtensionConstants.PREFIX, DocumentNavigationExtensionConstants.NAMESPACE); handler.startPrefixMapping(InternalElementMapping.STANDARD_PREFIX, InternalElementMapping.URI); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "version", VERSION); handler.startElement(EL_DOCUMENT, atts); } catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startDocumentHeader() throws IFException { try { handler.startElement(EL_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endDocumentHeader() throws IFException { try { handler.endElement(EL_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startDocumentTrailer() throws IFException { try { handler.startElement(EL_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in startDocumentTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endDocumentTrailer() throws IFException { try { handler.endElement(EL_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in endDocumentTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endDocument() throws IFException { try { handler.endElement(EL_DOCUMENT); handler.endDocument(); finishDocumentNavigation(); } catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startPageSequence(String id) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (id != null) { atts.addAttribute(XML_NAMESPACE, "id", "xml:id", XMLUtil.CDATA, id); } Locale lang = getContext().getLanguage(); if (lang != null) { atts.addAttribute(XML_NAMESPACE, "lang", "xml:lang", XMLUtil.CDATA, LanguageTags.toLanguageTag(lang)); } XMLUtil.addAttribute(atts, XMLConstants.XML_SPACE, "preserve"); addForeignAttributes(atts); handler.startElement(EL_PAGE_SEQUENCE, atts); if (this.getUserAgent().isAccessibilityEnabled()) { assert (structureTreeBuilder != null); structureTreeBuilder.replayEventsForPageSequence(handler, pageSequenceIndex++); } } catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endPageSequence() throws IFException { try { handler.endElement(EL_PAGE_SEQUENCE); } catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "index", Integer.toString(index)); addAttribute(atts, "name", name); addAttribute(atts, "page-master-name", pageMasterName); addAttribute(atts, "width", Integer.toString(size.width)); addAttribute(atts, "height", Integer.toString(size.height)); addForeignAttributes(atts); handler.startElement(EL_PAGE, atts); } catch (SAXException e) { throw new IFException("SAX error in startPage()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startPageHeader() throws IFException { try { handler.startElement(EL_PAGE_HEADER); } catch (SAXException e) { throw new IFException("SAX error in startPageHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endPageHeader() throws IFException { try { handler.endElement(EL_PAGE_HEADER); } catch (SAXException e) { throw new IFException("SAX error in endPageHeader()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public IFPainter startPageContent() throws IFException { try { handler.startElement(EL_PAGE_CONTENT); this.state = IFState.create(); return this; } catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endPageContent() throws IFException { try { this.state = null; currentID = ""; handler.endElement(EL_PAGE_CONTENT); } catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void startPageTrailer() throws IFException { try { handler.startElement(EL_PAGE_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in startPageTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void endPageTrailer() throws IFException { try { commitNavigation(); handler.endElement(EL_PAGE_TRAILER); } catch (SAXException e) { throw new IFException("SAX error in endPageTrailer()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endPage() throws IFException { try { handler.endElement(EL_PAGE); } catch (SAXException e) { throw new IFException("SAX error in endPage()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { startViewport(IFUtil.toString(transform), size, clipRect); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startViewport(AffineTransform[] transforms, Dimension size, Rectangle clipRect) throws IFException { startViewport(IFUtil.toString(transforms), size, clipRect); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void startViewport(String transform, Dimension size, Rectangle clipRect) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { addAttribute(atts, "transform", transform); } addAttribute(atts, "width", Integer.toString(size.width)); addAttribute(atts, "height", Integer.toString(size.height)); if (clipRect != null) { addAttribute(atts, "clip-rect", IFUtil.toString(clipRect)); } handler.startElement(EL_VIEWPORT, atts); } catch (SAXException e) { throw new IFException("SAX error in startViewport()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endViewport() throws IFException { try { handler.endElement(EL_VIEWPORT); } catch (SAXException e) { throw new IFException("SAX error in endViewport()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startGroup(AffineTransform[] transforms) throws IFException { startGroup(IFUtil.toString(transforms)); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void startGroup(AffineTransform transform) throws IFException { startGroup(IFUtil.toString(transform)); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void startGroup(String transform) throws IFException { try { AttributesImpl atts = new AttributesImpl(); if (transform != null && transform.length() > 0) { addAttribute(atts, "transform", transform); } handler.startElement(EL_GROUP, atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void endGroup() throws IFException { try { handler.endElement(EL_GROUP); } catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawImage(String uri, Rectangle rect) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, XLINK_HREF, uri); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addForeignAttributes(atts); addStructureReference(atts); handler.element(EL_IMAGE, atts); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawImage(Document doc, Rectangle rect) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addForeignAttributes(atts); addStructureReference(atts); handler.startElement(EL_IMAGE, atts); new DOM2SAX(handler).writeDocument(doc, true); handler.endElement(EL_IMAGE); } catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void clipRect(Rectangle rect) throws IFException { try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); handler.element(EL_CLIP_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in clipRect()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); addAttribute(atts, "fill", toString(fill)); handler.element(EL_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top == null && bottom == null && left == null && right == null) { return; } try { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(rect.x)); addAttribute(atts, "y", Integer.toString(rect.y)); addAttribute(atts, "width", Integer.toString(rect.width)); addAttribute(atts, "height", Integer.toString(rect.height)); if (top != null) { addAttribute(atts, "top", top.toString()); } if (bottom != null) { addAttribute(atts, "bottom", bottom.toString()); } if (left != null) { addAttribute(atts, "left", left.toString()); } if (right != null) { addAttribute(atts, "right", right.toString()); } handler.element(EL_BORDER_RECT, atts); } catch (SAXException e) { throw new IFException("SAX error in drawBorderRect()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x1", Integer.toString(start.x)); addAttribute(atts, "y1", Integer.toString(start.y)); addAttribute(atts, "x2", Integer.toString(end.x)); addAttribute(atts, "y2", Integer.toString(end.y)); addAttribute(atts, "stroke-width", Integer.toString(width)); addAttribute(atts, "color", ColorUtil.colorToString(color)); addAttribute(atts, "style", style.getName()); handler.element(EL_LINE, atts); } catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { addID(); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "x", Integer.toString(x)); addAttribute(atts, "y", Integer.toString(y)); if (letterSpacing != 0) { addAttribute(atts, "letter-spacing", Integer.toString(letterSpacing)); } if (wordSpacing != 0) { addAttribute(atts, "word-spacing", Integer.toString(wordSpacing)); } if (dp != null) { if ( IFUtil.isDPIdentity(dp) ) { // don't add dx or dp attribute } else if ( IFUtil.isDPOnlyDX(dp) ) { // add dx attribute only int[] dx = IFUtil.convertDPToDX(dp); addAttribute(atts, "dx", IFUtil.toString(dx)); } else { // add dp attribute only addAttribute(atts, "dp", XMLUtil.encodePositionAdjustments(dp)); } } addStructureReference(atts); handler.startElement(EL_TEXT, atts); char[] chars = text.toCharArray(); handler.characters(chars, 0, chars.length); handler.endElement(EL_TEXT); } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void setFont(String family, String style, Integer weight, String variant, Integer size, Color color) throws IFException { try { AttributesImpl atts = new AttributesImpl(); boolean changed; if (family != null) { changed = !family.equals(state.getFontFamily()); if (changed) { state.setFontFamily(family); addAttribute(atts, "family", family); } } if (style != null) { changed = !style.equals(state.getFontStyle()); if (changed) { state.setFontStyle(style); addAttribute(atts, "style", style); } } if (weight != null) { changed = (weight.intValue() != state.getFontWeight()); if (changed) { state.setFontWeight(weight.intValue()); addAttribute(atts, "weight", weight.toString()); } } if (variant != null) { changed = !variant.equals(state.getFontVariant()); if (changed) { state.setFontVariant(variant); addAttribute(atts, "variant", variant); } } if (size != null) { changed = (size.intValue() != state.getFontSize()); if (changed) { state.setFontSize(size.intValue()); addAttribute(atts, "size", size.toString()); } } if (color != null) { changed = !org.apache.xmlgraphics.java2d.color.ColorUtil.isSameColor( color, state.getTextColor()); if (changed) { state.setTextColor(color); addAttribute(atts, "color", toString(color)); } } if (atts.getLength() > 0) { handler.element(EL_FONT, atts); } } catch (SAXException e) { throw new IFException("SAX error in setFont()", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof XMLizable) { try { ((XMLizable)extension).toSAX(this.handler); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { throw new UnsupportedOperationException( "Extension must implement XMLizable: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void renderNamedDestination(NamedDestination destination) throws IFException { noteAction(destination.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute(null, "name", "name", XMLConstants.CDATA, destination.getName()); try { handler.startElement(DocumentNavigationExtensionConstants.NAMED_DESTINATION, atts); serializeXMLizable(destination.getAction()); handler.endElement(DocumentNavigationExtensionConstants.NAMED_DESTINATION); } catch (SAXException e) { throw new IFException("SAX error serializing named destination", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void renderBookmarkTree(BookmarkTree tree) throws IFException { AttributesImpl atts = new AttributesImpl(); try { handler.startElement(DocumentNavigationExtensionConstants.BOOKMARK_TREE, atts); Iterator iter = tree.getBookmarks().iterator(); while (iter.hasNext()) { Bookmark b = (Bookmark)iter.next(); if (b.getAction() != null) { serializeBookmark(b); } } handler.endElement(DocumentNavigationExtensionConstants.BOOKMARK_TREE); } catch (SAXException e) { throw new IFException("SAX error serializing bookmark tree", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void serializeBookmark(Bookmark bookmark) throws SAXException, IFException { noteAction(bookmark.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute(null, "title", "title", XMLUtil.CDATA, bookmark.getTitle()); atts.addAttribute(null, "starting-state", "starting-state", XMLUtil.CDATA, bookmark.isShown() ? "show" : "hide"); handler.startElement(DocumentNavigationExtensionConstants.BOOKMARK, atts); serializeXMLizable(bookmark.getAction()); Iterator iter = bookmark.getChildBookmarks().iterator(); while (iter.hasNext()) { Bookmark b = (Bookmark)iter.next(); if (b.getAction() != null) { serializeBookmark(b); } } handler.endElement(DocumentNavigationExtensionConstants.BOOKMARK); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void renderLink(Link link) throws IFException { noteAction(link.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute(null, "rect", "rect", XMLConstants.CDATA, IFUtil.toString(link.getTargetRect())); if (getUserAgent().isAccessibilityEnabled()) { addStructRefAttribute(atts, ((IFStructureTreeElement) link.getAction().getStructureTreeElement()).getId()); } try { handler.startElement(DocumentNavigationExtensionConstants.LINK, atts); serializeXMLizable(link.getAction()); handler.endElement(DocumentNavigationExtensionConstants.LINK); } catch (SAXException e) { throw new IFException("SAX error serializing link", e); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void addResolvedAction(AbstractAction action) throws IFException { assert action.isComplete(); assert action.hasID(); AbstractAction noted = (AbstractAction)incompleteActions.remove(action.getID()); if (noted != null) { completeActions.add(action); } else { //ignore as it was already complete when it was first used. } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void commitNavigation() throws IFException { Iterator iter = this.completeActions.iterator(); while (iter.hasNext()) { AbstractAction action = (AbstractAction)iter.next(); iter.remove(); serializeXMLizable(action); } assert this.completeActions.size() == 0; }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void serializeXMLizable(XMLizable object) throws IFException { try { object.toSAX(handler); } catch (SAXException e) { throw new IFException("SAX error serializing object", e); } }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void setResult(Result result) throws IFException { if (result instanceof StreamResult) { StreamResult streamResult = (StreamResult)result; OutputStream out = streamResult.getOutputStream(); if (out == null) { if (streamResult.getWriter() != null) { throw new IllegalArgumentException( "FOP cannot use a Writer. Please supply an OutputStream!"); } try { URL url = new URL(streamResult.getSystemId()); File f = FileUtils.toFile(url); if (f != null) { out = new java.io.FileOutputStream(f); } else { out = url.openConnection().getOutputStream(); } } catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); } out = new java.io.BufferedOutputStream(out); this.ownOutputStream = true; } if (out == null) { throw new IllegalArgumentException("Need a StreamResult with an OutputStream"); } this.outputStream = out; } else { throw new UnsupportedOperationException( "Unsupported Result subclass: " + result.getClass().getName()); } }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); if (this.outputStream == null) { throw new IllegalStateException("OutputStream hasn't been set through setResult()"); } }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void endDocument() throws IFException { if (this.ownOutputStream) { IOUtils.closeQuietly(this.outputStream); this.outputStream = null; } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void startDocument() throws IFException { if (getUserAgent() == null) { throw new IllegalStateException( "User agent must be set before starting document generation"); } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void startDocumentHeader() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void endDocumentHeader() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void startDocumentTrailer() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void endDocumentTrailer() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void startPageHeader() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void endPageHeader() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void startPageTrailer() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void endPageTrailer() throws IFException { //nop }
// in src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
public void setResult(Result result) throws IFException { if (result instanceof SAXResult) { SAXResult saxResult = (SAXResult)result; this.handler = new GenerationHelperContentHandler( saxResult.getHandler(), getMainNamespace()); } else { this.handler = new GenerationHelperContentHandler( createContentHandler(result), getMainNamespace()); } }
// in src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
protected ContentHandler createContentHandler(Result result) throws IFException { try { TransformerHandler tHandler = tFactory.newTransformerHandler(); Transformer transformer = tHandler.getTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty(OutputKeys.METHOD, "xml"); tHandler.setResult(result); return tHandler; } catch (TransformerConfigurationException tce) { throw new IFException( "Error while setting up the serializer for XML output", tce); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
private void processExtensionAttachments(AreaTreeObject area) throws IFException { if (area.hasExtensionAttachments()) { for (Iterator iter = area.getExtensionAttachments().iterator(); iter.hasNext();) { ExtensionAttachment attachment = (ExtensionAttachment) iter.next(); this.documentHandler.handleExtensionObject(attachment); } } }
// in src/java/org/apache/fop/render/intermediate/IFGraphicContext.java
public void start(IFPainter painter) throws IFException { painter.startGroup(transforms); }
// in src/java/org/apache/fop/render/intermediate/IFGraphicContext.java
public void end(IFPainter painter) throws IFException { painter.endGroup(); }
// in src/java/org/apache/fop/render/intermediate/IFGraphicContext.java
public void start(IFPainter painter) throws IFException { painter.startViewport(getTransforms(), size, clipRect); }
// in src/java/org/apache/fop/render/intermediate/IFGraphicContext.java
public void end(IFPainter painter) throws IFException { painter.endViewport(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void setResult(Result result) throws IFException { this.delegate.setResult(result); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startDocument() throws IFException { this.delegate.startDocument(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startDocumentHeader() throws IFException { this.delegate.startDocumentHeader(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endDocumentHeader() throws IFException { this.delegate.endDocumentHeader(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startPageSequence(String id) throws IFException { this.delegate.startPageSequence(id); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { this.delegate.startPage(index, name, pageMasterName, size); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startPageHeader() throws IFException { this.delegate.startPageHeader(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endPageHeader() throws IFException { this.delegate.endPageHeader(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public IFPainter startPageContent() throws IFException { return this.delegate.startPageContent(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endPageContent() throws IFException { this.delegate.endPageContent(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startPageTrailer() throws IFException { this.delegate.startPageTrailer(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endPageTrailer() throws IFException { this.delegate.endPageTrailer(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endPage() throws IFException { this.delegate.endPage(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endPageSequence() throws IFException { this.delegate.endPageSequence(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void startDocumentTrailer() throws IFException { this.delegate.startDocumentTrailer(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endDocumentTrailer() throws IFException { this.delegate.endDocumentTrailer(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void endDocument() throws IFException { this.delegate.endDocument(); }
// in src/java/org/apache/fop/render/intermediate/util/IFDocumentHandlerProxy.java
public void handleExtensionObject(Object extension) throws IFException { this.delegate.handleExtensionObject(extension); }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
private void startDocument(Metadata metadata) throws IFException { this.targetHandler.startDocument(); this.targetHandler.startDocumentHeader(); if (metadata != null) { this.targetHandler.handleExtensionObject(metadata); } this.targetHandler.endDocumentHeader(); }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
private void endDocument() throws IFException { this.targetHandler.startPageTrailer(); this.targetHandler.endPageTrailer(); this.targetHandler.endDocument(); }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void finish() throws IFException { endDocument(); }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void appendDocument(Source src) throws TransformerException, IFException { IFParser parser = new IFParser(); parser.parse(src, new IFPageSequenceFilter(getTargetHandler()), getTargetHandler().getContext().getUserAgent()); }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void startDocument() throws IFException { //ignore }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void startDocumentHeader() throws IFException { //ignore }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void endDocumentHeader() throws IFException { //ignore }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void startPageSequence(String id) throws IFException { assert !this.inPageSequence; this.inPageSequence = true; super.startPageSequence(id); }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { //Adjust page indices super.startPage(nextPageIndex, name, pageMasterName, size); nextPageIndex++; }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void endPageSequence() throws IFException { super.endPageSequence(); assert this.inPageSequence; this.inPageSequence = false; }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void startDocumentTrailer() throws IFException { //ignore }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void endDocumentTrailer() throws IFException { //ignore }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void endDocument() throws IFException { //ignore inFirstDocument = false; }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void handleExtensionObject(Object extension) throws IFException { if (inPageSequence || inFirstDocument) { //Only pass through when inside page-sequence //or for the first document (for document-level extensions). super.handleExtensionObject(extension); } //Note:Extensions from non-first documents are ignored! }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
Override public void startDocument() throws IFException { super.startDocument(); try { this.gen = new PCLGenerator(this.outputStream, getResolution()); this.gen.setDitheringQuality(pclUtil.getDitheringQuality()); if (!pclUtil.isPJLDisabled()) { gen.universalEndOfLanguage(); gen.writeText("@PJL COMMENT Produced by " + getUserAgent().getProducer() + "\n"); if (getUserAgent().getTitle() != null) { gen.writeText("@PJL JOB NAME = \"" + getUserAgent().getTitle() + "\"\n"); } gen.writeText("@PJL SET RESOLUTION = " + getResolution() + "\n"); gen.writeText("@PJL ENTER LANGUAGE = PCL\n"); } gen.resetPrinter(); gen.setUnitOfMeasure(getResolution()); gen.setRasterGraphicsResolution(getResolution()); } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
Override public void endDocumentHeader() throws IFException { }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
Override public void endDocument() throws IFException { try { gen.separateJobs(); gen.resetPrinter(); if (!pclUtil.isPJLDisabled()) { gen.universalEndOfLanguage(); } } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void startPageSequence(String id) throws IFException { //nop }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void endPageSequence() throws IFException { //nop }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { //Paper source Object paperSource = getContext().getForeignAttribute( PCLElementMapping.PCL_PAPER_SOURCE); if (paperSource != null) { gen.selectPaperSource(Integer.parseInt(paperSource.toString())); } //Output bin Object outputBin = getContext().getForeignAttribute( PCLElementMapping.PCL_OUTPUT_BIN); if (outputBin != null) { gen.selectOutputBin(Integer.parseInt(outputBin.toString())); } // Is Page duplex? Object pageDuplex = getContext().getForeignAttribute( PCLElementMapping.PCL_DUPLEX_MODE); if (pageDuplex != null) { gen.selectDuplexMode(Integer.parseInt(pageDuplex.toString())); } //Page size final long pagewidth = size.width; final long pageheight = size.height; selectPageFormat(pagewidth, pageheight); } catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public IFPainter startPageContent() throws IFException { if (pclUtil.getRenderingMode() == PCLRenderingMode.BITMAP) { return createAllBitmapPainter(); } else { return new PCLPainter(this, this.currentPageDefinition); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void endPageContent() throws IFException { if (this.currentImage != null) { try { //ImageWriterUtil.saveAsPNG(this.currentImage, new java.io.File("D:/page.png")); Rectangle printArea = this.currentPageDefinition.getLogicalPageRect(); gen.setCursorPos(0, 0); gen.paintBitmap(this.currentImage, printArea.getSize(), true); } catch (IOException ioe) { throw new IFException("I/O error while encoding page image", ioe); } finally { this.currentImage = null; } } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void endPage() throws IFException { try { //Eject page gen.formFeed(); } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (false) { //TODO Handle extensions } else { log.debug("Don't know how to handle extension object. Ignoring: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); /* PCL cannot clip! if (clipRect != null) { clipRect(clipRect); }*/ } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void endViewport() throws IFException { restoreGraphicsState(); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void startGroup(AffineTransform transform) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void endGroup() throws IFException { restoreGraphicsState(); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { drawImageUsingURI(uri, rect); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { drawImageUsingDocument(doc, rect); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void clipRect(Rectangle rect) throws IFException { //PCL cannot clip (only HP GL/2 can) //If you need clipping support, switch to RenderingMode.BITMAP. }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { Color fillColor = null; if (fill != null) { if (fill instanceof Color) { fillColor = (Color)fill; } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } try { setCursorPos(rect.x, rect.y); gen.fillRect(rect.width, rect.height, fillColor); } catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); } } } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void drawBorderRect(final Rectangle rect, final BorderProps top, final BorderProps bottom, final BorderProps left, final BorderProps right) throws IFException { if (isSpeedOptimized()) { super.drawBorderRect(rect, top, bottom, left, right); return; } if (top != null || bottom != null || left != null || right != null) { final Rectangle boundingBox = rect; final Dimension dim = boundingBox.getSize(); Graphics2DImagePainter painter = new Graphics2DImagePainter() { public void paint(Graphics2D g2d, Rectangle2D area) { g2d.translate(-rect.x, -rect.y); Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state); try { painter.drawBorderRect(rect, top, bottom, left, right); } catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting borders", e); } } public Dimension getImageSize() { return dim.getSize(); } }; paintMarksAsBitmap(painter, boundingBox); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void drawLine(final Point start, final Point end, final int width, final Color color, final RuleStyle style) throws IFException { if (isSpeedOptimized()) { super.drawLine(start, end, width, color, style); return; } final Rectangle boundingBox = getLineBoundingBox(start, end, width); final Dimension dim = boundingBox.getSize(); Graphics2DImagePainter painter = new Graphics2DImagePainter() { public void paint(Graphics2D g2d, Rectangle2D area) { g2d.translate(-boundingBox.x, -boundingBox.y); Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state); try { painter.drawLine(start, end, width, color, style); } catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting a line", e); } } public Dimension getImageSize() { return dim.getSize(); } }; paintMarksAsBitmap(painter, boundingBox); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
private void paintMarksAsBitmap(Graphics2DImagePainter painter, Rectangle boundingBox) throws IFException { ImageInfo info = new ImageInfo(null, null); ImageSize size = new ImageSize(); size.setSizeInMillipoints(boundingBox.width, boundingBox.height); info.setSize(size); ImageGraphics2D img = new ImageGraphics2D(info, painter); Map hints = new java.util.HashMap(); if (isSpeedOptimized()) { //Gray text may not be painted in this case! We don't get dithering in Sun JREs. //But this approach is about twice as fast as the grayscale image. hints.put(ImageProcessingHints.BITMAP_TYPE_INTENT, ImageProcessingHints.BITMAP_TYPE_INTENT_MONO); } else { hints.put(ImageProcessingHints.BITMAP_TYPE_INTENT, ImageProcessingHints.BITMAP_TYPE_INTENT_GRAY); } hints.put(ImageHandlerUtil.CONVERSION_MODE, ImageHandlerUtil.CONVERSION_MODE_BITMAP); PCLRenderingContext context = (PCLRenderingContext)createRenderingContext(); context.setSourceTransparencyEnabled(true); try { drawImage(img, boundingBox, context, true, hints); } catch (IOException ioe) { throw new IFException( "I/O error while painting marks using a bitmap", ioe); } catch (ImageException ie) { throw new IFException( "Error while painting marks using a bitmap", ie); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() //TODO Opportunity for font caching if font state is more heavily used String fontKey = parent.getFontInfo().getInternalFontKey(triplet); boolean pclFont = getPCLUtil().isAllTextAsBitmaps() ? false : HardcodedFonts.setFont(gen, fontKey, state.getFontSize(), text); if (pclFont) { drawTextNative(x, y, letterSpacing, wordSpacing, dp, text, triplet); } else { drawTextAsBitmap(x, y, letterSpacing, wordSpacing, dp, text, triplet); if (DEBUG) { state.setTextColor(Color.GRAY); HardcodedFonts.setFont(gen, "F1", state.getFontSize(), text); drawTextNative(x, y, letterSpacing, wordSpacing, dp, text, triplet); } } } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
private void drawTextAsBitmap(final int x, final int y, final int letterSpacing, final int wordSpacing, final int[][] dp, final String text, FontTriplet triplet) throws IFException { //Use Java2D to paint different fonts via bitmap final Font font = parent.getFontInfo().getFontInstance(triplet, state.getFontSize()); //for cursive fonts, so the text isn't clipped final FontMetricsMapper mapper = (FontMetricsMapper)parent.getFontInfo().getMetricsFor( font.getFontName()); final int maxAscent = mapper.getMaxAscent(font.getFontSize()) / 1000; final int ascent = mapper.getAscender(font.getFontSize()) / 1000; final int descent = mapper.getDescender(font.getFontSize()) / 1000; int safetyMargin = (int)(SAFETY_MARGIN_FACTOR * font.getFontSize()); final int baselineOffset = maxAscent + safetyMargin; final Rectangle boundingBox = getTextBoundingBox(x, y, letterSpacing, wordSpacing, dp, text, font, mapper); final Dimension dim = boundingBox.getSize(); Graphics2DImagePainter painter = new Graphics2DImagePainter() { public void paint(Graphics2D g2d, Rectangle2D area) { if (DEBUG) { g2d.setBackground(Color.LIGHT_GRAY); g2d.clearRect(0, 0, (int)area.getWidth(), (int)area.getHeight()); } g2d.translate(-x, -y + baselineOffset); if (DEBUG) { Rectangle rect = new Rectangle(x, y - maxAscent, 3000, maxAscent); g2d.draw(rect); rect = new Rectangle(x, y - ascent, 2000, ascent); g2d.draw(rect); rect = new Rectangle(x, y, 1000, -descent); g2d.draw(rect); } Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state); try { painter.drawText(x, y, letterSpacing, wordSpacing, dp, text); } catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting text", e); } } public Dimension getImageSize() { return dim.getSize(); } }; paintMarksAsBitmap(painter, boundingBox); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); try { // Creates writer this.imageWriter = ImageWriterRegistry.getInstance().getWriterFor(getMimeType()); if (this.imageWriter == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noImageWriterFound(this, getMimeType()); } if (this.imageWriter.supportsMultiImageWriter()) { this.multiImageWriter = this.imageWriter.createMultiImageWriter(outputStream); } else { this.multiFileUtil = new MultiFileRenderingUtil(getDefaultExtension(), getUserAgent().getOutputFile()); } this.pageCount = 0; } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endDocumentHeader() throws IFException { }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endDocument() throws IFException { try { if (this.multiImageWriter != null) { this.multiImageWriter.close(); } this.multiImageWriter = null; this.imageWriter = null; } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void startPageSequence(String id) throws IFException { //nop }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endPageSequence() throws IFException { //nop }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { this.pageCount++; this.currentPageDimensions = new Dimension(size); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public IFPainter startPageContent() throws IFException { int bitmapWidth; int bitmapHeight; double scale; Point2D offset = null; if (targetBitmapSize != null) { //Fit the generated page proportionally into the given rectangle (in pixels) double scale2w = 1000 * targetBitmapSize.width / this.currentPageDimensions.getWidth(); double scale2h = 1000 * targetBitmapSize.height / this.currentPageDimensions.getHeight(); bitmapWidth = targetBitmapSize.width; bitmapHeight = targetBitmapSize.height; //Centering the page in the given bitmap offset = new Point2D.Double(); if (scale2w < scale2h) { scale = scale2w; double h = this.currentPageDimensions.height * scale / 1000; offset.setLocation(0, (bitmapHeight - h) / 2.0); } else { scale = scale2h; double w = this.currentPageDimensions.width * scale / 1000; offset.setLocation((bitmapWidth - w) / 2.0, 0); } } else { //Normal case: just scale according to the target resolution scale = scaleFactor * getUserAgent().getTargetResolution() / FopFactoryConfigurator.DEFAULT_TARGET_RESOLUTION; bitmapWidth = (int) ((this.currentPageDimensions.width * scale / 1000f) + 0.5f); bitmapHeight = (int) ((this.currentPageDimensions.height * scale / 1000f) + 0.5f); } //Set up bitmap to paint on this.currentImage = createBufferedImage(bitmapWidth, bitmapHeight); Graphics2D graphics2D = this.currentImage.createGraphics(); // draw page background if (!getSettings().hasTransparentPageBackground()) { graphics2D.setBackground(getSettings().getPageBackgroundColor()); graphics2D.setPaint(getSettings().getPageBackgroundColor()); graphics2D.fillRect(0, 0, bitmapWidth, bitmapHeight); } //Set rendering hints graphics2D.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON); if (getSettings().isAntiAliasingEnabled() && this.currentImage.getColorModel().getPixelSize() > 1) { graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); } else { graphics2D.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_OFF); graphics2D.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_OFF); } if (getSettings().isQualityRenderingEnabled()) { graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); } else { graphics2D.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_SPEED); } graphics2D.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE); //Set up initial coordinate system for the page if (offset != null) { graphics2D.translate(offset.getX(), offset.getY()); } graphics2D.scale(scale / 1000f, scale / 1000f); return new Java2DPainter(graphics2D, getContext(), getFontInfo()); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endPageContent() throws IFException { try { if (this.multiImageWriter == null) { switch (this.pageCount) { case 1: this.imageWriter.writeImage( this.currentImage, this.outputStream, getSettings().getWriterParams()); IOUtils.closeQuietly(this.outputStream); this.outputStream = null; break; default: OutputStream out = this.multiFileUtil.createOutputStream(this.pageCount - 1); if (out == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.stoppingAfterFirstPageNoFilename(this); } else { try { this.imageWriter.writeImage( this.currentImage, out, getSettings().getWriterParams()); } finally { IOUtils.closeQuietly(out); } } } } else { this.multiImageWriter.writeImage(this.currentImage, getSettings().getWriterParams()); } this.currentImage = null; } catch (IOException ioe) { throw new IFException("I/O error while encoding BufferedImage", ioe); } }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void endPage() throws IFException { this.currentPageDimensions = null; }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { log.debug("Don't know how to handle extension object. Ignoring: " + extension + " (" + extension.getClass().getName() + ")"); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void startDocument() throws IFException { super.startDocument(); try { paintingState.setColor(Color.WHITE); this.dataStream = resourceManager.createDataStream(paintingState, outputStream); this.dataStream.startDocument(); } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void startDocumentHeader() throws IFException { super.startDocumentHeader(); this.location = Location.IN_DOCUMENT_HEADER; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void endDocumentHeader() throws IFException { super.endDocumentHeader(); this.location = Location.ELSEWHERE; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void endDocument() throws IFException { try { this.dataStream.endDocument(); this.dataStream = null; this.resourceManager.writeToStream(); this.resourceManager = null; } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void startPageSequence(String id) throws IFException { try { dataStream.startPageGroup(); } catch (IOException ioe) { throw new IFException("I/O error in startPageSequence()", ioe); } this.location = Location.FOLLOWING_PAGE_SEQUENCE; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void endPageSequence() throws IFException { try { //Process deferred page-sequence-level extensions Iterator<AFPPageSetup> iter = this.deferredPageSequenceExtensions.iterator(); while (iter.hasNext()) { AFPPageSetup aps = iter.next(); iter.remove(); if (AFPElementMapping.NO_OPERATION.equals(aps.getElementName())) { handleNOP(aps); } else { throw new UnsupportedOperationException("Don't know how to handle " + aps); } } //End page sequence dataStream.endPageGroup(); } catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); } this.location = Location.ELSEWHERE; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { this.location = Location.ELSEWHERE; paintingState.clear(); AffineTransform baseTransform = getBaseTransform(); paintingState.concatenate(baseTransform); int pageWidth = Math.round(unitConv.mpt2units(size.width)); paintingState.setPageWidth(pageWidth); int pageHeight = Math.round(unitConv.mpt2units(size.height)); paintingState.setPageHeight(pageHeight); int pageRotation = paintingState.getPageRotation(); int resolution = paintingState.getResolution(); dataStream.startPage(pageWidth, pageHeight, pageRotation, resolution, resolution); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void startPageHeader() throws IFException { super.startPageHeader(); this.location = Location.IN_PAGE_HEADER; }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
Override public void endPageHeader() throws IFException { this.location = Location.ELSEWHERE; super.endPageHeader(); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public IFPainter startPageContent() throws IFException { return new AFPPainter(this); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void endPageContent() throws IFException { }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void endPage() throws IFException { try { AFPPageFonts pageFonts = paintingState.getPageFonts(); if (pageFonts != null && !pageFonts.isEmpty()) { dataStream.addFontsToCurrentPage(pageFonts); } dataStream.endPage(); } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof AFPPageSetup) { AFPPageSetup aps = (AFPPageSetup)extension; String element = aps.getElementName(); if (AFPElementMapping.TAG_LOGICAL_ELEMENT.equals(element)) { switch (this.location) { case FOLLOWING_PAGE_SEQUENCE: case IN_PAGE_HEADER: String name = aps.getName(); String value = aps.getValue(); dataStream.createTagLogicalElement(name, value); break; default: throw new IFException( "TLE extension must be in the page header or between page-sequence" + " and the first page: " + aps, null); } } else if (AFPElementMapping.NO_OPERATION.equals(element)) { switch (this.location) { case FOLLOWING_PAGE_SEQUENCE: if (aps.getPlacement() == ExtensionPlacement.BEFORE_END) { this.deferredPageSequenceExtensions.add(aps); break; } case IN_DOCUMENT_HEADER: case IN_PAGE_HEADER: handleNOP(aps); break; default: throw new IFException( "NOP extension must be in the document header, the page header" + " or between page-sequence" + " and the first page: " + aps, null); } } else { if (this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP page setup extension encountered outside the page header: " + aps, null); } if (AFPElementMapping.INCLUDE_PAGE_SEGMENT.equals(element)) { AFPPageSegmentElement.AFPPageSegmentSetup apse = (AFPPageSegmentElement.AFPPageSegmentSetup)aps; String name = apse.getName(); String source = apse.getValue(); String uri = apse.getResourceSrc(); pageSegmentMap.put(source, new PageSegmentDescriptor(name, uri)); } } } else if (extension instanceof AFPPageOverlay) { AFPPageOverlay ipo = (AFPPageOverlay)extension; if (this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP page overlay extension encountered outside the page header: " + ipo, null); } String overlay = ipo.getName(); if (overlay != null) { dataStream.createIncludePageOverlay(overlay, ipo.getX(), ipo.getY()); } } else if (extension instanceof AFPInvokeMediumMap) { if (this.location != Location.FOLLOWING_PAGE_SEQUENCE && this.location != Location.IN_PAGE_HEADER) { throw new IFException( "AFP IMM extension must be between page-sequence" + " and the first page or child of page-header: " + extension, null); } AFPInvokeMediumMap imm = (AFPInvokeMediumMap)extension; String mediumMap = imm.getName(); if (mediumMap != null) { dataStream.createInvokeMediumMap(mediumMap); } } else if (extension instanceof AFPIncludeFormMap) { AFPIncludeFormMap formMap = (AFPIncludeFormMap)extension; ResourceAccessor accessor = new DefaultFOPResourceAccessor( getUserAgent(), null, null); try { getResourceManager().createIncludedResource(formMap.getName(), formMap.getSrc(), accessor, ResourceObject.TYPE_FORMDEF); } catch (IOException ioe) { throw new IFException( "I/O error while embedding form map resource: " + formMap.getName(), ioe); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { //AFP doesn't support clipping, so we treat viewport like a group //this is the same code as for startGroup() try { saveGraphicsState(); concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void endViewport() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void startGroup(AffineTransform transform) throws IFException { try { saveGraphicsState(); concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void endGroup() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { PageSegmentDescriptor pageSegment = documentHandler.getPageSegmentNameFor(uri); if (pageSegment != null) { float[] srcPts = {rect.x, rect.y}; int[] coords = unitConv.mpts2units(srcPts); int width = Math.round(unitConv.mpt2units(rect.width)); int height = Math.round(unitConv.mpt2units(rect.height)); getDataStream().createIncludePageSegment(pageSegment.getName(), coords[X], coords[Y], width, height); //Do we need to embed an external page segment? if (pageSegment.getURI() != null) { ResourceAccessor accessor = new DefaultFOPResourceAccessor ( documentHandler.getUserAgent(), null, null); try { URI resourceUri = new URI(pageSegment.getURI()); documentHandler.getResourceManager().createIncludedResourceFromExternal( pageSegment.getName(), resourceUri, accessor); } catch (URISyntaxException urie) { throw new IFException("Could not handle resource url" + pageSegment.getURI(), urie); } catch (IOException ioe) { throw new IFException("Could not handle resource" + pageSegment.getURI(), ioe); } } } else { drawImageUsingURI(uri, rect); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { drawImageUsingDocument(doc, rect); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void clipRect(Rectangle rect) throws IFException { //Not supported! }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { if (fill instanceof Color) { getPaintingState().setColor((Color)fill); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } RectanglePaintingInfo rectanglePaintInfo = new RectanglePaintingInfo( toPoint(rect.x), toPoint(rect.y), toPoint(rect.width), toPoint(rect.height)); try { rectanglePainter.paint(rectanglePaintInfo); } catch (IOException ioe) { throw new IFException("IO error while painting rectangle", ioe); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { try { this.borderPainter.drawBorders(rect, top, bottom, left, right); } catch (IOException ife) { throw new IFException("IO error while painting borders", ife); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { this.borderPainter.drawLine(start, end, width, color, style); } catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void drawText( // CSOK: MethodLength int x, int y, final int letterSpacing, final int wordSpacing, final int[][] dp, final String text) throws IFException { final int fontSize = this.state.getFontSize(); getPaintingState().setFontSize(fontSize); FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() String fontKey = getFontInfo().getInternalFontKey(triplet); if (fontKey == null) { triplet = new FontTriplet("any", Font.STYLE_NORMAL, Font.WEIGHT_NORMAL); fontKey = getFontInfo().getInternalFontKey(triplet); } // register font as necessary Map<String, Typeface> fontMetricMap = documentHandler.getFontInfo().getFonts(); final AFPFont afpFont = (AFPFont)fontMetricMap.get(fontKey); final Font font = getFontInfo().getFontInstance(triplet, fontSize); AFPPageFonts pageFonts = getPaintingState().getPageFonts(); AFPFontAttributes fontAttributes = pageFonts.registerFont(fontKey, afpFont, fontSize); final int fontReference = fontAttributes.getFontReference(); final int[] coords = unitConv.mpts2units(new float[] {x, y} ); final CharacterSet charSet = afpFont.getCharacterSet(fontSize); if (afpFont.isEmbeddable()) { try { documentHandler.getResourceManager().embedFont(afpFont, charSet); } catch (IOException ioe) { throw new IFException("Error while embedding font resources", ioe); } } AbstractPageObject page = getDataStream().getCurrentPage(); PresentationTextObject pto = page.getPresentationTextObject(); try { pto.createControlSequences(new PtocaProducer() { public void produce(PtocaBuilder builder) throws IOException { Point p = getPaintingState().getPoint(coords[X], coords[Y]); builder.setTextOrientation(getPaintingState().getRotation()); builder.absoluteMoveBaseline(p.y); builder.absoluteMoveInline(p.x); builder.setExtendedTextColor(state.getTextColor()); builder.setCodedFont((byte)fontReference); int l = text.length(); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); StringBuffer sb = new StringBuffer(); if (dxl > 0 && dx[0] != 0) { int dxu = Math.round(unitConv.mpt2units(dx[0])); builder.relativeMoveInline(-dxu); } //Following are two variants for glyph placement. //SVI does not seem to be implemented in the same way everywhere, so //a fallback alternative is preserved here. final boolean usePTOCAWordSpacing = true; if (usePTOCAWordSpacing) { int interCharacterAdjustment = 0; if (letterSpacing != 0) { interCharacterAdjustment = Math.round(unitConv.mpt2units( letterSpacing)); } builder.setInterCharacterAdjustment(interCharacterAdjustment); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + letterSpacing)); int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement; if (wordSpacing != 0) { varSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + wordSpacing + letterSpacing)); } builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement); boolean fixedSpaceMode = false; for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( fixedSpaceCharacterIncrement); fixedSpaceMode = true; sb.append(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { if (fixedSpaceMode) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( varSpaceCharacterIncrement); fixedSpaceMode = false; } char ch; if (orgChar == CharUtilities.NBSPACE) { ch = ' '; //converted to normal space to allow word spacing } else { ch = orgChar; } sb.append(ch); } if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } else { for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { sb.append(CharUtilities.SPACE); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { sb.append(orgChar); } if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust += wordSpacing; } glyphAdjust += letterSpacing; if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } flushText(builder, sb, charSet); } private void flushText(PtocaBuilder builder, StringBuffer sb, final CharacterSet charSet) throws IOException { if (sb.length() > 0) { builder.addTransparentData(charSet.encodeChars(sb)); sb.setLength(0); } } }); } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); this.fontResources = new FontResourceCache(getFontInfo()); try { OutputStream out; if (psUtil.isOptimizeResources()) { this.tempFile = File.createTempFile("fop", null); out = new java.io.FileOutputStream(this.tempFile); out = new java.io.BufferedOutputStream(out); } else { out = this.outputStream; } //Setup for PostScript generation this.gen = new PSGenerator(out) { /** Need to subclass PSGenerator to have better URI resolution */ public Source resolveURI(String uri) { return getUserAgent().resolveURI(uri); } }; this.gen.setPSLevel(psUtil.getLanguageLevel()); this.currentPageNumber = 0; this.documentBoundingBox = new Rectangle2D.Double(); //Initial default page device dictionary settings this.pageDeviceDictionary = new PSPageDeviceDictionary(); pageDeviceDictionary.setFlushOnRetrieval(!psUtil.isDSCComplianceEnabled()); pageDeviceDictionary.put("/ImagingBBox", "null"); } catch (IOException e) { throw new IFException("I/O error in startDocument()", e); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endDocumentHeader() throws IFException { try { writeHeader(); } catch (IOException ioe) { throw new IFException("I/O error writing the PostScript header", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endDocument() throws IFException { try { //Write trailer gen.writeDSCComment(DSCConstants.TRAILER); writeExtensions(COMMENT_DOCUMENT_TRAILER); gen.writeDSCComment(DSCConstants.PAGES, new Integer(this.currentPageNumber)); new DSCCommentBoundingBox(this.documentBoundingBox).generate(gen); new DSCCommentHiResBoundingBox(this.documentBoundingBox).generate(gen); gen.getResourceTracker().writeResources(false, gen); gen.writeDSCComment(DSCConstants.EOF); gen.flush(); log.debug("Rendering to PostScript complete."); if (psUtil.isOptimizeResources()) { IOUtils.closeQuietly(gen.getOutputStream()); rewritePostScriptFile(); } if (pageDeviceDictionary != null) { pageDeviceDictionary.clear(); } } catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); } super.endDocument(); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPageSequence(String id) throws IFException { //nop }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageSequence() throws IFException { //nop }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPage(int index, String name, String pageMasterName, Dimension size) throws IFException { try { if (this.currentPageNumber == 0) { //writeHeader(); } this.currentPageNumber++; gen.getResourceTracker().notifyStartNewPage(); gen.getResourceTracker().notifyResourceUsageOnPage(PSProcSets.STD_PROCSET); gen.writeDSCComment(DSCConstants.PAGE, new Object[] {name, new Integer(this.currentPageNumber)}); double pageWidth = size.width / 1000.0; double pageHeight = size.height / 1000.0; boolean rotate = false; List pageSizes = new java.util.ArrayList(); if (this.psUtil.isAutoRotateLandscape() && (pageHeight < pageWidth)) { rotate = true; pageSizes.add(new Long(Math.round(pageHeight))); pageSizes.add(new Long(Math.round(pageWidth))); } else { pageSizes.add(new Long(Math.round(pageWidth))); pageSizes.add(new Long(Math.round(pageHeight))); } pageDeviceDictionary.put("/PageSize", pageSizes); this.currentPageDefinition = new PageDefinition( new Dimension2DDouble(pageWidth, pageHeight), rotate); //TODO Handle extension attachments for the page!!!!!!! /* if (page.hasExtensionAttachments()) { for (Iterator iter = page.getExtensionAttachments().iterator(); iter.hasNext();) { ExtensionAttachment attachment = (ExtensionAttachment) iter.next(); if (attachment instanceof PSSetPageDevice) {*/ /** * Extract all PSSetPageDevice instances from the * attachment list on the s-p-m and add all * dictionary entries to our internal representation * of the the page device dictionary. *//* PSSetPageDevice setPageDevice = (PSSetPageDevice)attachment; String content = setPageDevice.getContent(); if (content != null) { try { pageDeviceDictionary.putAll(PSDictionary.valueOf(content)); } catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); } } } } }*/ final Integer zero = new Integer(0); Rectangle2D pageBoundingBox = new Rectangle2D.Double(); if (rotate) { pageBoundingBox.setRect(0, 0, pageHeight, pageWidth); gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[] { zero, zero, new Long(Math.round(pageHeight)), new Long(Math.round(pageWidth)) }); gen.writeDSCComment(DSCConstants.PAGE_HIRES_BBOX, new Object[] { zero, zero, new Double(pageHeight), new Double(pageWidth) }); gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Landscape"); } else { pageBoundingBox.setRect(0, 0, pageWidth, pageHeight); gen.writeDSCComment(DSCConstants.PAGE_BBOX, new Object[] { zero, zero, new Long(Math.round(pageWidth)), new Long(Math.round(pageHeight)) }); gen.writeDSCComment(DSCConstants.PAGE_HIRES_BBOX, new Object[] { zero, zero, new Double(pageWidth), new Double(pageHeight) }); if (psUtil.isAutoRotateLandscape()) { gen.writeDSCComment(DSCConstants.PAGE_ORIENTATION, "Portrait"); } } this.documentBoundingBox.add(pageBoundingBox); gen.writeDSCComment(DSCConstants.PAGE_RESOURCES, new Object[] {DSCConstants.ATEND}); gen.commentln("%FOPSimplePageMaster: " + pageMasterName); } catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPageHeader() throws IFException { super.startPageHeader(); try { gen.writeDSCComment(DSCConstants.BEGIN_PAGE_SETUP); } catch (IOException ioe) { throw new IFException("I/O error in startPageHeader()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageHeader() throws IFException { try { // Write any unwritten changes to page device dictionary if (!pageDeviceDictionary.isEmpty()) { String content = pageDeviceDictionary.getContent(); if (psUtil.isSafeSetPageDevice()) { content += " SSPD"; } else { content += " setpagedevice"; } PSRenderingUtil.writeEnclosedExtensionAttachment(gen, new PSSetPageDevice(content)); } double pageHeight = this.currentPageDefinition.dimensions.getHeight(); if (this.currentPageDefinition.rotate) { gen.writeln(gen.formatDouble(pageHeight) + " 0 translate"); gen.writeln("90 rotate"); } gen.concatMatrix(1, 0, 0, -1, 0, pageHeight); gen.writeDSCComment(DSCConstants.END_PAGE_SETUP); } catch (IOException ioe) { throw new IFException("I/O error in endPageHeader()", ioe); } super.endPageHeader(); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public IFPainter startPageContent() throws IFException { return new PSPainter(this); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageContent() throws IFException { try { gen.showPage(); } catch (IOException ioe) { throw new IFException("I/O error in endPageContent()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void startPageTrailer() throws IFException { try { writeExtensions(PAGE_TRAILER_CODE_BEFORE); super.startPageTrailer(); gen.writeDSCComment(DSCConstants.PAGE_TRAILER); } catch (IOException ioe) { throw new IFException("I/O error in startPageTrailer()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPageTrailer() throws IFException { try { writeExtensions(COMMENT_PAGE_TRAILER); } catch (IOException ioe) { throw new IFException("I/O error in endPageTrailer()", ioe); } super.endPageTrailer(); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void endPage() throws IFException { try { gen.getResourceTracker().writeResources(true, gen); } catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); } this.currentPageDefinition = null; }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
public void handleExtensionObject(Object extension) throws IFException { try { if (extension instanceof PSSetupCode) { if (inPage()) { PSRenderingUtil.writeEnclosedExtensionAttachment(gen, (PSSetupCode)extension); } else { //A special collection for setup code as it's put in a different place //than the "before comments". if (setupCodeList == null) { setupCodeList = new java.util.ArrayList(); } if (!setupCodeList.contains(extension)) { setupCodeList.add(extension); } } } else if (extension instanceof PSSetPageDevice) { /** * Extract all PSSetPageDevice instances from the * attachment list on the s-p-m and add all dictionary * entries to our internal representation of the the * page device dictionary. */ PSSetPageDevice setPageDevice = (PSSetPageDevice)extension; String content = setPageDevice.getContent(); if (content != null) { try { this.pageDeviceDictionary.putAll(PSDictionary.valueOf(content)); } catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); } } } else if (extension instanceof PSCommentBefore) { if (inPage()) { PSRenderingUtil.writeEnclosedExtensionAttachment( gen, (PSCommentBefore)extension); } else { if (comments[COMMENT_DOCUMENT_HEADER] == null) { comments[COMMENT_DOCUMENT_HEADER] = new java.util.ArrayList(); } comments[COMMENT_DOCUMENT_HEADER].add(extension); } } else if (extension instanceof PSCommentAfter) { int targetCollection = (inPage() ? COMMENT_PAGE_TRAILER : COMMENT_DOCUMENT_TRAILER); if (comments[targetCollection] == null) { comments[targetCollection] = new java.util.ArrayList(); } comments[targetCollection].add(extension); } else if (extension instanceof PSPageTrailerCodeBefore) { if (comments[PAGE_TRAILER_CODE_BEFORE] == null) { comments[PAGE_TRAILER_CODE_BEFORE] = new ArrayList(); } comments[PAGE_TRAILER_CODE_BEFORE].add(extension); } } catch (IOException ioe) { throw new IFException("I/O error in handleExtensionObject()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { try { PSGenerator generator = getGenerator(); saveGraphicsState(); generator.concatMatrix(toPoints(transform)); } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } if (clipRect != null) { clipRect(clipRect); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void endViewport() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void startGroup(AffineTransform transform) throws IFException { try { PSGenerator generator = getGenerator(); saveGraphicsState(); generator.concatMatrix(toPoints(transform)); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void endGroup() throws IFException { try { restoreGraphicsState(); } catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { try { endTextObject(); } catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); } drawImageUsingURI(uri, rect); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { try { endTextObject(); } catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); } drawImageUsingDocument(doc, rect); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void clipRect(Rectangle rect) throws IFException { try { PSGenerator generator = getGenerator(); endTextObject(); generator.defineRect(rect.x / 1000.0, rect.y / 1000.0, rect.width / 1000.0, rect.height / 1000.0); generator.writeln(generator.mapCommand("clip") + " " + generator.mapCommand("newpath")); } catch (IOException ioe) { throw new IFException("I/O error in clipRect()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { try { endTextObject(); PSGenerator generator = getGenerator(); if (fill != null) { if (fill instanceof Color) { generator.useColor((Color)fill); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } } generator.defineRect(rect.x / 1000.0, rect.y / 1000.0, rect.width / 1000.0, rect.height / 1000.0); generator.writeln(generator.mapCommand("fill")); } catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); } } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { try { endTextObject(); if (getPSUtil().getRenderingMode() == PSRenderingMode.SIZE && hasOnlySolidBorders(top, bottom, left, right)) { super.drawBorderRect(rect, top, bottom, left, right); } else { this.borderPainter.drawBorders(rect, top, bottom, left, right); } } catch (IOException ioe) { throw new IFException("I/O error in drawBorderRect()", ioe); } } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { try { endTextObject(); this.borderPainter.drawLine(start, end, width, color, style); } catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { try { //Do not draw text if font-size is 0 as it creates an invalid PostScript file if (state.getFontSize() == 0) { return; } PSGenerator generator = getGenerator(); generator.useColor(state.getTextColor()); beginTextObject(); FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() //TODO Opportunity for font caching if font state is more heavily used String fontKey = getFontInfo().getInternalFontKey(triplet); if (fontKey == null) { throw new IFException("Font not available: " + triplet, null); } int sizeMillipoints = state.getFontSize(); // This assumes that *all* CIDFonts use a /ToUnicode mapping Typeface tf = getTypeface(fontKey); SingleByteFont singleByteFont = null; if (tf instanceof SingleByteFont) { singleByteFont = (SingleByteFont)tf; } Font font = getFontInfo().getFontInstance(triplet, sizeMillipoints); useFont(fontKey, sizeMillipoints); generator.writeln("1 0 0 -1 " + formatMptAsPt(generator, x) + " " + formatMptAsPt(generator, y) + " Tm"); int textLen = text.length(); int start = 0; if (singleByteFont != null) { //Analyze string and split up in order to paint in different sub-fonts/encodings int currentEncoding = -1; for (int i = 0; i < textLen; i++) { char c = text.charAt(i); char mapped = tf.mapChar(c); int encoding = mapped / 256; if (currentEncoding != encoding) { if (i > 0) { writeText(text, start, i - start, letterSpacing, wordSpacing, dp, font, tf); } if (encoding == 0) { useFont(fontKey, sizeMillipoints); } else { useFont(fontKey + "_" + Integer.toString(encoding), sizeMillipoints); } currentEncoding = encoding; start = i; } } } else { //Simple single-font painting useFont(fontKey, sizeMillipoints); } writeText(text, start, textLen - start, letterSpacing, wordSpacing, dp, font, tf); } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void startViewport(AffineTransform transform, Dimension size, Rectangle clipRect) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); clipRect(clipRect); } catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void endViewport() throws IFException { restoreGraphicsState(); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void startGroup(AffineTransform transform) throws IFException { saveGraphicsState(); try { concatenateTransformationMatrix(transform); } catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void endGroup() throws IFException { restoreGraphicsState(); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void drawImage(String uri, Rectangle rect) throws IFException { drawImageUsingURI(uri, rect); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void drawImage(Document doc, Rectangle rect) throws IFException { drawImageUsingDocument(doc, rect); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void clipRect(Rectangle rect) throws IFException { getState().updateClip(rect); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { g2dState.updatePaint(fill); g2dState.getGraph().fill(rect); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { try { this.borderPainter.drawBorders(rect, top, bottom, left, right); } catch (IOException e) { //Won't happen with Java2D throw new IllegalStateException("Unexpected I/O error"); } } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IFException { this.borderPainter.drawLine(start, end, width, color, style); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void drawText(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text) throws IFException { g2dState.updateColor(state.getTextColor()); FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() //TODO Opportunity for font caching if font state is more heavily used Font font = getFontInfo().getFontInstance(triplet, state.getFontSize()); //String fontName = font.getFontName(); //float fontSize = state.getFontSize() / 1000f; g2dState.updateFont(font.getFontName(), state.getFontSize() * 1000); Graphics2D g2d = this.g2dState.getGraph(); GlyphVector gv = g2d.getFont().createGlyphVector(g2d.getFontRenderContext(), text); Point2D cursor = new Point2D.Float(0, 0); int l = text.length(); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); if (dx != null && dxl > 0 && dx[0] != 0) { cursor.setLocation(cursor.getX() - (dx[0] / 10f), cursor.getY()); gv.setGlyphPosition(0, cursor); } for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; int cw = font.getCharWidth(orgChar); if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust += wordSpacing; } glyphAdjust += letterSpacing; if (dx != null && i < dxl - 1) { glyphAdjust += dx[i + 1]; } cursor.setLocation(cursor.getX() + cw + glyphAdjust, cursor.getY()); gv.setGlyphPosition(i + 1, cursor); } g2d.drawGlyphVector(gv, x, y); }
27
            
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFExceptionWithIOException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFExceptionWithIOException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException ife) { handleIFException(ife); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
catch (IFException e) { handleIFException(e); }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
catch (IFException ife) { throw new SAXException(ife); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting borders", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting a line", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting text", e); }
// in src/java/org/apache/fop/cli/IFInputHandler.java
catch (IFException ife) { throw new FOPException(ife); }
5
            
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
catch (IFException ife) { throw new SAXException(ife); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting borders", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting a line", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting text", e); }
// in src/java/org/apache/fop/cli/IFInputHandler.java
catch (IFException ife) { throw new FOPException(ife); }
3
checked (Lib) IOException 46
            
// in src/sandbox/org/apache/fop/render/svg/SVGDataUrlImageHandler.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { SVGRenderingContext svgContext = (SVGRenderingContext)context; ImageRawStream raw = (ImageRawStream)image; InputStream in = raw.createInputStream(); try { ContentHandler handler = svgContext.getContentHandler(); String url = DataURLUtil.createDataURL(in, raw.getMimeType()); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, IFConstants.XLINK_HREF, url); atts.addAttribute("", "x", "x", CDATA, Integer.toString(pos.x)); atts.addAttribute("", "y", "y", CDATA, Integer.toString(pos.y)); atts.addAttribute("", "width", "width", CDATA, Integer.toString(pos.width)); atts.addAttribute("", "height", "height", CDATA, Integer.toString(pos.height)); try { handler.startElement(NAMESPACE, "image", "image", atts); handler.endElement(NAMESPACE, "image", "image"); } catch (SAXException e) { throw new IOException(e.getMessage()); } } finally { IOUtils.closeQuietly(in); } }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
public void handleImage(RenderingContext context, Image image, final Rectangle pos) throws IOException { SVGRenderingContext svgContext = (SVGRenderingContext)context; ImageXMLDOM svg = (ImageXMLDOM)image; ContentHandler handler = svgContext.getContentHandler(); AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "x", "x", CDATA, SVGUtil.formatMptToPt(pos.x)); atts.addAttribute("", "y", "y", CDATA, SVGUtil.formatMptToPt(pos.y)); atts.addAttribute("", "width", "width", CDATA, SVGUtil.formatMptToPt(pos.width)); atts.addAttribute("", "height", "height", CDATA, SVGUtil.formatMptToPt(pos.height)); try { Document doc = (Document)svg.getDocument(); Element svgEl = (Element)doc.getDocumentElement(); if (svgEl.getAttribute("viewBox").length() == 0) { log.warn("SVG doesn't have a viewBox. The result might not be scaled correctly!"); } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource src = new DOMSource(svg.getDocument()); SAXResult res = new SAXResult(new DelegatingFragmentContentHandler(handler) { private boolean topLevelSVGFound = false; private void setAttribute(AttributesImpl atts, String localName, String value) { int index; index = atts.getIndex("", localName); if (index < 0) { atts.addAttribute("", localName, localName, CDATA, value); } else { atts.setAttribute(index, "", localName, localName, CDATA, value); } } public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { if (!topLevelSVGFound && SVG_ELEMENT.getNamespaceURI().equals(uri) && SVG_ELEMENT.getLocalName().equals(localName)) { topLevelSVGFound = true; AttributesImpl modAtts = new AttributesImpl(atts); setAttribute(modAtts, "x", SVGUtil.formatMptToPt(pos.x)); setAttribute(modAtts, "y", SVGUtil.formatMptToPt(pos.y)); setAttribute(modAtts, "width", SVGUtil.formatMptToPt(pos.width)); setAttribute(modAtts, "height", SVGUtil.formatMptToPt(pos.height)); super.startElement(uri, localName, name, modAtts); } else { super.startElement(uri, localName, name, atts); } } }); transformer.transform(src, res); } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
protected void outputRawStreamData(OutputStream out) throws IOException { try { XMPSerializer.writeXMPPacket(xmpMetadata, out, this.readOnly); } catch (TransformerConfigurationException tce) { throw new IOException("Error setting up Transformer for XMP stream serialization: " + tce.getMessage()); } catch (SAXException saxe) { throw new IOException("Error while serializing XMP stream: " + saxe.getMessage()); } }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceTable.java
private void outputXref() throws IOException { pdf.append("xref\n0 "); pdf.append(objectReferences.size() + 1); pdf.append("\n0000000000 65535 f \n"); for (Long objectReference : objectReferences) { final String padding = "0000000000"; String s = String.valueOf(objectReference); if (s.length() > 10) { throw new IOException("PDF file too large." + " PDF 1.4 cannot grow beyond approx. 9.3GB."); } String loc = padding.substring(s.length()) + s; pdf.append(loc).append(" 00000 n \n"); } }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static InputStream openFontUri(FontResolver resolver, String uri) throws IOException, MalformedURLException { InputStream in = null; if (resolver != null) { Source source = resolver.resolve(uri); if (source == null) { String err = "Cannot load font: failed to create Source for font file " + uri; throw new IOException(err); } if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null && source.getSystemId() != null) { in = new java.net.URL(source.getSystemId()).openStream(); } if (in == null) { String err = "Cannot load font: failed to create InputStream from" + " Source for font file " + uri; throw new IOException(err); } } else { in = new URL(uri).openStream(); } return in; }
// in src/java/org/apache/fop/fonts/CustomFont.java
public Source getEmbedFileSource() throws IOException { Source result = null; if (resolver != null && embedFileName != null) { result = resolver.resolve(embedFileName); if (result == null) { throw new IOException("Unable to resolve Source '" + embedFileName + "' for embedded font"); } } return result; }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
private void parsePCFormat(PFBData pfb, DataInputStream din) throws IOException { int segmentHead; int segmentType; int bytesRead; //Read first segment segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); //Read int len1 = swapInteger(din.readInt()); byte[] headerSegment = new byte[len1]; din.readFully(headerSegment); pfb.setHeaderSegment(headerSegment); //Read second segment segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); int len2 = swapInteger(din.readInt()); byte[] encryptedSegment = new byte[len2]; din.readFully(encryptedSegment); pfb.setEncryptedSegment(encryptedSegment); //Read third segment segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); int len3 = swapInteger(din.readInt()); byte[] trailerSegment = new byte[len3]; din.readFully(trailerSegment); pfb.setTrailerSegment(trailerSegment); //Read EOF indicator segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); if (segmentType != 3) { throw new IOException("Expected segment type 3, but found: " + segmentType); } }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
public void load(InputStream inStream) throws IOException { byte[] pfmBytes = IOUtils.toByteArray(inStream); InputStream bufin = inStream; bufin = new ByteArrayInputStream(pfmBytes); PFMInputStream in = new PFMInputStream(bufin); bufin.mark(512); short sh1 = in.readByte(); short sh2 = in.readByte(); if (sh1 == 128 && sh2 == 1) { //Found the first section header of a PFB file! throw new IOException("Cannot parse PFM file. You probably specified the PFB file" + " of a Type 1 font as parameter instead of the PFM."); } bufin.reset(); byte[] b = new byte[16]; bufin.read(b); if (new String(b, "US-ASCII").equalsIgnoreCase("StartFontMetrics")) { //Found the header of a AFM file! throw new IOException("Cannot parse PFM file. You probably specified the AFM file" + " of a Type 1 font as parameter instead of the PFM."); } bufin.reset(); final int version = in.readShort(); if (version != 256) { log.warn("PFM version expected to be '256' but got '" + version + "'." + " Please make sure you specify the PFM as parameter" + " and not the PFB or the AFM."); } //final long filesize = in.readInt(); bufin.reset(); loadHeader(in); loadExtension(in); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { int endpos = findValue(line, startpos); double version = Double.parseDouble(line.substring(startpos, endpos)); if (version < 2) { throw new IOException( "AFM version must be at least 2.0 but it is " + version + "!"); } AFMFile afm = new AFMFile(); stack.push(afm); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { if (getBooleanValue(line, startpos).booleanValue()) { throw new IOException("Only base fonts are currently supported!"); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { if (getBooleanValue(line, startpos).booleanValue()) { throw new IOException("CID fonts are currently not supported!"); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { if (!(stack.pop() instanceof AFMWritingDirectionMetrics)) { throw new IOException("AFM format error: nesting incorrect"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
public boolean readFont(FontFileReader in, String name) throws IOException { /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(in, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(in); readFontHeader(in); getNumGlyphs(in); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(in); readHorizontalMetrics(in); initAnsiWidths(); readPostScript(in); readOS2(in); determineAscDesc(); if (!isCFF) { readIndexToLocation(in); readGlyf(in); } readName(in); boolean pcltFound = readPCLT(in); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(in); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); if ( useKerning ) { readKerning(in); } // Read advanced typographic tables. if ( useAdvanced ) { try { OTFAdvancedTypographicTableReader atr = new OTFAdvancedTypographicTableReader ( this, in ); atr.readAll(); this.advancedTableReader = atr; } catch ( AdvancedTypographicTableFormatException e ) { log.warn ( "Encountered format constraint violation in advanced (typographic) table (AT) " + "in font '" + getFullName() + "', ignoring AT data: " + e.getMessage() ); } } guessVerticalMetricsFromGlyphBBox(); return true; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected final void readIndexToLocation(FontFileReader in) throws IOException { if (!seekTab(in, "loca", 0)) { throw new IOException("'loca' table not found, happens when the font file doesn't" + " contain TrueType outlines (trying to read an OpenType CFF font maybe?)"); } for (int i = 0; i < numberOfGlyphs; i++) { mtxTab[i].setOffset(locaFormat == 1 ? in.readTTFULong() : (in.readTTFUShort() << 1)); } lastLoca = (locaFormat == 1 ? in.readTTFULong() : (in.readTTFUShort() << 1)); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private void readGlyf(FontFileReader in) throws IOException { TTFDirTabEntry dirTab = getDirectoryEntry ( "glyf" ); if (dirTab == null) { throw new IOException("glyf table not found, cannot continue"); } for (int i = 0; i < (numberOfGlyphs - 1); i++) { if (mtxTab[i].getOffset() != mtxTab[i + 1].getOffset()) { in.seekSet(dirTab.getOffset() + mtxTab[i].getOffset()); in.skip(2); final int[] bbox = { in.readTTFShort(), in.readTTFShort(), in.readTTFShort(), in.readTTFShort()}; mtxTab[i].setBoundingBox(bbox); } else { mtxTab[i].setBoundingBox(mtxTab[0].getBoundingBox()); } } long n = dirTab.getOffset(); for (int i = 0; i < numberOfGlyphs; i++) { if ((i + 1) >= mtxTab.length || mtxTab[i].getOffset() != mtxTab[i + 1].getOffset()) { in.seekSet(n + mtxTab[i].getOffset()); in.skip(2); final int[] bbox = { in.readTTFShort(), in.readTTFShort(), in.readTTFShort(), in.readTTFShort()}; mtxTab[i].setBoundingBox(bbox); } else { /**@todo Verify that this is correct, looks like a copy/paste bug (jm)*/ final int bbox0 = mtxTab[0].getBoundingBox()[0]; final int[] bbox = {bbox0, bbox0, bbox0, bbox0}; mtxTab[i].setBoundingBox(bbox); /* Original code mtxTab[i].bbox[0] = mtxTab[0].bbox[0]; mtxTab[i].bbox[1] = mtxTab[0].bbox[0]; mtxTab[i].bbox[2] = mtxTab[0].bbox[0]; mtxTab[i].bbox[3] = mtxTab[0].bbox[0]; */ } if (log.isTraceEnabled()) { log.trace(mtxTab[i].toString(this)); } } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private Integer unicodeToGlyph(int unicodeIndex) throws IOException { final Integer result = (Integer) unicodeToGlyphMap.get(new Integer(unicodeIndex)); if (result == null) { throw new IOException( "Glyph index not found for unicode value " + unicodeIndex); } return result; }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createMaxp(FontFileReader in, int size) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("maxp"); if (entry != null) { pad4(); seekTab(in, "maxp", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); writeUShort(currentPos + 4, size); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(maxpDirOffset, checksum); writeULong(maxpDirOffset + 4, currentPos); writeULong(maxpDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); } else { throw new IOException("Can't find maxp table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createHhea(FontFileReader in, int size) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("hhea"); if (entry != null) { pad4(); seekTab(in, "hhea", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); writeUShort((int)entry.getLength() + currentPos - 2, size); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(hheaDirOffset, checksum); writeULong(hheaDirOffset + 4, currentPos); writeULong(hheaDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); } else { throw new IOException("Can't find hhea table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createHead(FontFileReader in) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("head"); if (entry != null) { pad4(); seekTab(in, "head", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); checkSumAdjustmentOffset = currentPos + 8; output[currentPos + 8] = 0; // Set checkSumAdjustment to 0 output[currentPos + 9] = 0; output[currentPos + 10] = 0; output[currentPos + 11] = 0; output[currentPos + 50] = 0; // long locaformat output[currentPos + 51] = 1; // long locaformat int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(headDirOffset, checksum); writeULong(headDirOffset + 4, currentPos); writeULong(headDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); } else { throw new IOException("Can't find head table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createGlyf(FontFileReader in, Map glyphs) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("glyf"); int size = 0; int start = 0; int endOffset = 0; // Store this as the last loca if (entry != null) { pad4(); start = currentPos; /* Loca table must be in order by glyph index, so build * an array first and then write the glyph info and * location offset. */ int[] origIndexes = new int[glyphs.size()]; Iterator e = glyphs.keySet().iterator(); while (e.hasNext()) { Integer origIndex = (Integer)e.next(); Integer subsetIndex = (Integer)glyphs.get(origIndex); origIndexes[subsetIndex.intValue()] = origIndex.intValue(); } for (int i = 0; i < origIndexes.length; i++) { int glyphLength = 0; int nextOffset = 0; int origGlyphIndex = origIndexes[i]; if (origGlyphIndex >= (mtxTab.length - 1)) { nextOffset = (int)lastLoca; } else { nextOffset = (int)mtxTab[origGlyphIndex + 1].getOffset(); } glyphLength = nextOffset - (int)mtxTab[origGlyphIndex].getOffset(); // Copy glyph System.arraycopy( in.getBytes((int)entry.getOffset() + (int)mtxTab[origGlyphIndex].getOffset(), glyphLength), 0, output, currentPos, glyphLength); // Update loca table writeULong(locaOffset + i * 4, currentPos - start); if ((currentPos - start + glyphLength) > endOffset) { endOffset = (currentPos - start + glyphLength); } currentPos += glyphLength; realSize += glyphLength; } size = currentPos - start; int checksum = getCheckSum(start, size); writeULong(glyfDirOffset, checksum); writeULong(glyfDirOffset + 4, start); writeULong(glyfDirOffset + 8, size); currentPos += 12; realSize += 12; // Update loca checksum and last loca index writeULong(locaOffset + glyphs.size() * 4, endOffset); checksum = getCheckSum(locaOffset, glyphs.size() * 4 + 4); writeULong(locaDirOffset, checksum); } else { throw new IOException("Can't find glyf table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createHmtx(FontFileReader in, Map glyphs) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("hmtx"); int longHorMetricSize = glyphs.size() * 2; int leftSideBearingSize = glyphs.size() * 2; int hmtxSize = longHorMetricSize + leftSideBearingSize; if (entry != null) { pad4(); //int offset = (int)entry.offset; Iterator e = glyphs.keySet().iterator(); while (e.hasNext()) { Integer origIndex = (Integer)e.next(); Integer subsetIndex = (Integer)glyphs.get(origIndex); writeUShort(currentPos + subsetIndex.intValue() * 4, mtxTab[origIndex.intValue()].getWx()); writeUShort(currentPos + subsetIndex.intValue() * 4 + 2, mtxTab[origIndex.intValue()].getLsb()); } int checksum = getCheckSum(currentPos, hmtxSize); writeULong(hmtxDirOffset, checksum); writeULong(hmtxDirOffset + 4, currentPos); writeULong(hmtxDirOffset + 8, hmtxSize); currentPos += hmtxSize; realSize += hmtxSize; } else { throw new IOException("Can't find hmtx table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
public byte[] readFont(FontFileReader in, String name, Map<Integer, Integer> glyphs) throws IOException { //Check if TrueType collection, and that the name exists in the collection if (!checkTTC(in, name)) { throw new IOException("Failed to read font"); } //Copy the Map as we're going to modify it Map<Integer, Integer> subsetGlyphs = new java.util.HashMap<Integer, Integer>(glyphs); output = new byte[in.getFileSize()]; readDirTabs(in); readFontHeader(in); getNumGlyphs(in); readHorizontalHeader(in); readHorizontalMetrics(in); readIndexToLocation(in); scanGlyphs(in, subsetGlyphs); createDirectory(); // Create the TrueType header and directory createHead(in); createHhea(in, subsetGlyphs.size()); // Create the hhea table createHmtx(in, subsetGlyphs); // Create hmtx table createMaxp(in, subsetGlyphs.size()); // copy the maxp table boolean optionalTableFound; optionalTableFound = createCvt(in); // copy the cvt table if (!optionalTableFound) { // cvt is optional (used in TrueType fonts only) log.debug("TrueType: ctv table not present. Skipped."); } optionalTableFound = createFpgm(in); // copy fpgm table if (!optionalTableFound) { // fpgm is optional (used in TrueType fonts only) log.debug("TrueType: fpgm table not present. Skipped."); } optionalTableFound = createPrep(in); // copy prep table if (!optionalTableFound) { // prep is optional (used in TrueType fonts only) log.debug("TrueType: prep table not present. Skipped."); } createLoca(subsetGlyphs.size()); // create empty loca table createGlyf(in, subsetGlyphs); //create glyf table and update loca table pad4(); createCheckSumAdjustment(); byte[] ret = new byte[realSize]; System.arraycopy(output, 0, ret, 0, realSize); return ret; }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void scanGlyphs(FontFileReader in, Map<Integer, Integer> subsetGlyphs) throws IOException { TTFDirTabEntry glyfTableInfo = (TTFDirTabEntry) dirTabs.get("glyf"); if (glyfTableInfo == null) { throw new IOException("Glyf table could not be found"); } GlyfTable glyfTable = new GlyfTable(in, mtxTab, glyfTableInfo, subsetGlyphs); glyfTable.populateGlyphsWithComposites(); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public byte[] getBytes(int offset, int length) throws IOException { if ((offset + length) > fsize) { throw new java.io.IOException("Reached EOF"); } byte[] ret = new byte[length]; System.arraycopy(file, offset, ret, 0, length); return ret; }
// in src/java/org/apache/fop/fonts/truetype/TTFFontLoader.java
private void read(String ttcFontName) throws IOException { InputStream in = openFontUri(resolver, this.fontFileURI); try { TTFFile ttf = new TTFFile(useKerning, useAdvanced); FontFileReader reader = new FontFileReader(in); boolean supported = ttf.readFont(reader, ttcFontName); if (!supported) { throw new IOException("TrueType font is not supported: " + fontFileURI); } buildFont(ttf, ttcFontName); loaded = true; } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/render/print/PrintRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); try { printerJob.print(); } catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); } clearViewportList(); }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addDefaultOutputProfile() throws IOException { if (this.outputProfile != null) { return; } ICC_Profile profile; InputStream in = null; if (this.outputProfileURI != null) { this.outputProfile = pdfDoc.getFactory().makePDFICCStream(); Source src = getUserAgent().resolveURI(this.outputProfileURI); if (src == null) { throw new IOException("Output profile not found: " + this.outputProfileURI); } if (src instanceof StreamSource) { in = ((StreamSource)src).getInputStream(); } else { in = new URL(src.getSystemId()).openStream(); } try { profile = ColorProfileUtil.getICC_Profile(in); } finally { IOUtils.closeQuietly(in); } this.outputProfile.setColorSpace(profile, null); } else { //Fall back to sRGB profile outputProfile = sRGBColorSpace.getICCStream(); } }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PCLRenderingContext pclContext = (PCLRenderingContext)context; ImageGraphics2D imageG2D = (ImageGraphics2D)image; Dimension imageDim = imageG2D.getSize().getDimensionMpt(); PCLGenerator gen = pclContext.getPCLGenerator(); Point2D transPoint = pclContext.transformedPoint(pos.x, pos.y); gen.setCursorPos(transPoint.getX(), transPoint.getY()); boolean painted = false; ByteArrayOutputStream baout = new ByteArrayOutputStream(); PCLGenerator tempGen = new PCLGenerator(baout, gen.getMaximumBitmapResolution()); tempGen.setDitheringQuality(gen.getDitheringQuality()); try { GraphicContext ctx = (GraphicContext)pclContext.getGraphicContext().clone(); AffineTransform prepareHPGL2 = new AffineTransform(); prepareHPGL2.scale(0.001, 0.001); ctx.setTransform(prepareHPGL2); PCLGraphics2D graphics = new PCLGraphics2D(tempGen); graphics.setGraphicContext(ctx); graphics.setClippingDisabled(false /*pclContext.isClippingDisabled()*/); Rectangle2D area = new Rectangle2D.Double( 0.0, 0.0, imageDim.getWidth(), imageDim.getHeight()); imageG2D.getGraphics2DImagePainter().paint(graphics, area); //If we arrive here, the graphic is natively paintable, so write the graphic gen.writeCommand("*c" + gen.formatDouble4(pos.width / 100f) + "x" + gen.formatDouble4(pos.height / 100f) + "Y"); gen.writeCommand("*c0T"); gen.enterHPGL2Mode(false); gen.writeText("\nIN;"); gen.writeText("SP1;"); //One Plotter unit is 0.025mm! double scale = imageDim.getWidth() / UnitConv.mm2pt(imageDim.getWidth() * 0.025); gen.writeText("SC0," + gen.formatDouble4(scale) + ",0,-" + gen.formatDouble4(scale) + ",2;"); gen.writeText("IR0,100,0,100;"); gen.writeText("PU;PA0,0;\n"); baout.writeTo(gen.getOutputStream()); //Buffer is written to output stream gen.writeText("\n"); gen.enterPCLMode(false); painted = true; } catch (UnsupportedOperationException uoe) { log.debug( "Cannot paint graphic natively. Falling back to bitmap painting. Reason: " + uoe.getMessage()); } if (!painted) { //Fallback solution: Paint to a BufferedImage FOUserAgent ua = context.getUserAgent(); ImageManager imageManager = ua.getFactory().getImageManager(); ImageRendered imgRend; try { imgRend = (ImageRendered)imageManager.convertImage( imageG2D, new ImageFlavor[] {ImageFlavor.RENDERED_IMAGE}/*, hints*/); } catch (ImageException e) { throw new IOException( "Image conversion error while converting the image to a bitmap" + " as a fallback measure: " + e.getMessage()); } gen.paintBitmap(imgRend.getRenderedImage(), new Dimension(pos.width, pos.height), pclContext.isSourceTransparencyEnabled()); } }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
public void processEvent(DSCEvent event, DSCParser parser) throws IOException, DSCException { if (event.isDSCComment() && event instanceof DSCCommentIncludeResource) { DSCCommentIncludeResource include = (DSCCommentIncludeResource)event; PSResource res = include.getResource(); if (res.getType().equals(PSResource.TYPE_FORM)) { if (inlineFormResources.containsValue(res)) { PSImageFormResource form = (PSImageFormResource) inlineFormResources.get(res); //Create an inline form //Wrap in save/restore pair to release memory gen.writeln("save"); generateFormForImage(gen, form); boolean execformFound = false; DSCEvent next = parser.nextEvent(); if (next.isLine()) { PostScriptLine line = next.asLine(); if (line.getLine().endsWith(" execform")) { line.generate(gen); execformFound = true; } } if (!execformFound) { throw new IOException( "Expected a PostScript line in the form: <form> execform"); } gen.writeln("restore"); } else { //Do nothing } parser.next(); } } }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
private CharacterSet processFont(String characterSetName, String codePageName, String encoding, CharacterSetType charsetType, ResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException { // check for cached version of the characterset String descriptor = characterSetName + "_" + encoding + "_" + codePageName; CharacterSet characterSet = (CharacterSet) characterSetsCache.get(descriptor); if (characterSet != null) { return characterSet; } // characterset not in the cache, so recreating characterSet = new CharacterSet(codePageName, encoding, charsetType, characterSetName, accessor, eventProducer); InputStream inputStream = null; try { /** * Get the code page which contains the character mapping * information to map the unicode character id to the graphic * chracter global identifier. */ Map<String, String> codePage; synchronized (codePagesCache) { codePage = codePagesCache.get(codePageName); if (codePage == null) { codePage = loadCodePage(codePageName, encoding, accessor, eventProducer); codePagesCache.put(codePageName, codePage); } } inputStream = openInputStream(accessor, characterSetName, eventProducer); StructuredFieldReader structuredFieldReader = new StructuredFieldReader(inputStream); // Process D3A689 Font Descriptor FontDescriptor fontDescriptor = processFontDescriptor(structuredFieldReader); characterSet.setNominalVerticalSize(fontDescriptor.getNominalFontSizeInMillipoints()); // Process D3A789 Font Control FontControl fontControl = processFontControl(structuredFieldReader); if (fontControl != null) { //process D3AE89 Font Orientation CharacterSetOrientation[] characterSetOrientations = processFontOrientation(structuredFieldReader); double metricNormalizationFactor; if (fontControl.isRelative()) { metricNormalizationFactor = 1; } else { int dpi = fontControl.getDpi(); metricNormalizationFactor = 1000.0d * 72000.0d / fontDescriptor.getNominalFontSizeInMillipoints() / dpi; } //process D3AC89 Font Position processFontPosition(structuredFieldReader, characterSetOrientations, metricNormalizationFactor); //process D38C89 Font Index (per orientation) for (int i = 0; i < characterSetOrientations.length; i++) { processFontIndex(structuredFieldReader, characterSetOrientations[i], codePage, metricNormalizationFactor); characterSet.addCharacterSetOrientation(characterSetOrientations[i]); } } else { throw new IOException("Missing D3AE89 Font Control structured field."); } } finally { closeInputStream(inputStream); } characterSetsCache.put(descriptor, characterSet); return characterSet; }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void createIncludedResource(String resourceName, ResourceAccessor accessor, byte resourceObjectType) throws IOException { URI uri; try { uri = new URI(resourceName.trim()); } catch (URISyntaxException e) { throw new IOException("Could not create URI from resource name: " + resourceName + " (" + e.getMessage() + ")"); } createIncludedResource(resourceName, uri, accessor, resourceObjectType); }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
public static void copyNamedResource(String name, final InputStream in, final OutputStream out) throws IOException { final MODCAParser parser = new MODCAParser(in); Collection<String> resourceNames = new java.util.HashSet<String>(); //Find matching "Begin" field final UnparsedStructuredField fieldBegin; while (true) { final UnparsedStructuredField field = parser.readNextStructuredField(); if (field == null) { throw new IOException("Requested resource '" + name + "' not found. Encountered resource names: " + resourceNames); } if (field.getSfTypeCode() != TYPE_CODE_BEGIN) { //0xA8=Begin continue; //Not a "Begin" field } final String resourceName = getResourceName(field); resourceNames.add(resourceName); if (resourceName.equals(name)) { if (LOG.isDebugEnabled()) { LOG.debug("Start of requested structured field found:\n" + field); } fieldBegin = field; break; //Name doesn't match } } //Decide whether the resource file has to be wrapped in a resource object boolean wrapInResource; if (fieldBegin.getSfCategoryCode() == Category.PAGE_SEGMENT) { //A naked page segment must be wrapped in a resource object wrapInResource = true; } else if (fieldBegin.getSfCategoryCode() == Category.NAME_RESOURCE) { //A resource object can be copied directly wrapInResource = false; } else { throw new IOException("Cannot handle resource: " + fieldBegin); } //Copy structured fields (wrapped or as is) if (wrapInResource) { ResourceObject resourceObject = new ResourceObject(name) { protected void writeContent(OutputStream os) throws IOException { copyNamedStructuredFields(name, fieldBegin, parser, out); } }; resourceObject.setType(ResourceObject.TYPE_PAGE_SEGMENT); resourceObject.writeToStream(out); } else { copyNamedStructuredFields(name, fieldBegin, parser, out); } }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
private static void copyNamedStructuredFields(final String name, UnparsedStructuredField fieldBegin, MODCAParser parser, OutputStream out) throws IOException { UnparsedStructuredField field = fieldBegin; while (true) { if (field == null) { throw new IOException("Ending structured field not found for resource " + name); } out.write(MODCAParser.CARRIAGE_CONTROL_CHAR); field.writeTo(out); if (field.getSfTypeCode() == TYPE_CODE_END && fieldBegin.getSfCategoryCode() == field.getSfCategoryCode() && name.equals(getResourceName(field))) { break; } field = parser.readNextStructuredField(); } }
// in src/java/org/apache/fop/events/model/EventModel.java
private void writeXMLizable(XMLizable object, File outputFile) throws IOException { //These two approaches do not seem to work in all environments: //Result res = new StreamResult(outputFile); //Result res = new StreamResult(outputFile.toURI().toURL().toExternalForm()); //With an old Xalan version: file:/C:/.... --> file:\C:\..... OutputStream out = new java.io.FileOutputStream(outputFile); out = new java.io.BufferedOutputStream(out); Result res = new StreamResult(out); try { SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler handler = tFactory.newTransformerHandler(); Transformer transformer = handler.getTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); handler.setResult(res); handler.startDocument(); object.toSAX(handler); handler.endDocument(); } catch (TransformerConfigurationException e) { throw new IOException(e.getMessage()); } catch (TransformerFactoryConfigurationError e) { throw new IOException(e.getMessage()); } catch (SAXException e) { throw new IOException(e.getMessage()); } finally { IOUtils.closeQuietly(out); } }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
protected void updateTranslationFile(File modelFile) throws IOException { try { boolean resultExists = getTranslationFile().exists(); SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); //Generate fresh generated translation file as template Source src = new StreamSource(modelFile.toURI().toURL().toExternalForm()); StreamSource xslt1 = new StreamSource( getClass().getResourceAsStream(MODEL2TRANSLATION)); if (xslt1.getInputStream() == null) { throw new FileNotFoundException(MODEL2TRANSLATION + " not found"); } DOMResult domres = new DOMResult(); Transformer transformer = tFactory.newTransformer(xslt1); transformer.transform(src, domres); final Node generated = domres.getNode(); Node sourceDocument; if (resultExists) { //Load existing translation file into memory (because we overwrite it later) src = new StreamSource(getTranslationFile().toURI().toURL().toExternalForm()); domres = new DOMResult(); transformer = tFactory.newTransformer(); transformer.transform(src, domres); sourceDocument = domres.getNode(); } else { //Simply use generated as source document sourceDocument = generated; } //Generate translation file (with potentially new translations) src = new DOMSource(sourceDocument); //The following triggers a bug in older Xalan versions //Result res = new StreamResult(getTranslationFile()); OutputStream out = new java.io.FileOutputStream(getTranslationFile()); out = new java.io.BufferedOutputStream(out); Result res = new StreamResult(out); try { StreamSource xslt2 = new StreamSource( getClass().getResourceAsStream(MERGETRANSLATION)); if (xslt2.getInputStream() == null) { throw new FileNotFoundException(MERGETRANSLATION + " not found"); } transformer = tFactory.newTransformer(xslt2); transformer.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { if ("my:dom".equals(href)) { return new DOMSource(generated); } return null; } }); if (resultExists) { transformer.setParameter("generated-url", "my:dom"); } transformer.transform(src, res); if (resultExists) { log("Translation file updated: " + getTranslationFile()); } else { log("Translation file generated: " + getTranslationFile()); } } finally { IOUtils.closeQuietly(out); } } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
12
            
// in src/sandbox/org/apache/fop/render/svg/SVGDataUrlImageHandler.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (TransformerConfigurationException tce) { throw new IOException("Error setting up Transformer for XMP stream serialization: " + tce.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (SAXException saxe) { throw new IOException("Error while serializing XMP stream: " + saxe.getMessage()); }
// in src/java/org/apache/fop/render/print/PrintRenderer.java
catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
catch (ImageException e) { throw new IOException( "Image conversion error while converting the image to a bitmap" + " as a fallback measure: " + e.getMessage()); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
catch (URISyntaxException e) { throw new IOException("Could not create URI from resource name: " + resourceName + " (" + e.getMessage() + ")"); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerConfigurationException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerFactoryConfigurationError e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (TransformerException e) { throw new IOException("Error while parsing XML resource bundle: " + e.getMessage()); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
1022
            
// in src/sandbox/org/apache/fop/render/svg/SVGRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { this.firstOutputStream = outputStream; this.multiFileUtil = new MultiFileRenderingUtil(SVG_FILE_EXTENSION, getUserAgent().getOutputFile()); super.startRenderer(this.firstOutputStream); }
// in src/sandbox/org/apache/fop/render/svg/SVGRenderer.java
public void renderPage(PageViewport pageViewport) throws IOException { log.debug("Rendering page: " + pageViewport.getPageNumberString()); // Get a DOMImplementation DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); // Create an instance of org.w3c.dom.Document this.document = domImpl.createDocument(null, "svg", null); // Create an SVGGeneratorContext to customize SVG generation SVGGeneratorContext ctx = SVGGeneratorContext.createDefault(this.document); ctx.setComment("Generated by " + userAgent.getProducer() + " with Batik SVG Generator"); ctx.setEmbeddedFontsOn(true); // Create an instance of the SVG Generator this.svgGenerator = new SVGGraphics2D(ctx, true); Rectangle2D viewArea = pageViewport.getViewArea(); Dimension dim = new Dimension(); dim.setSize(viewArea.getWidth() / 1000, viewArea.getHeight() / 1000); this.svgGenerator.setSVGCanvasSize(dim); AffineTransform at = this.svgGenerator.getTransform(); this.state = new Java2DGraphicsState(this.svgGenerator, this.fontInfo, at); try { //super.renderPage(pageViewport); renderPageAreas(pageViewport.getPage()); } finally { this.state = null; } writeSVGFile(pageViewport.getPageIndex()); this.svgGenerator = null; this.document = null; }
// in src/sandbox/org/apache/fop/render/svg/SVGRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); // Cleaning clearViewportList(); log.debug("SVG generation complete."); }
// in src/sandbox/org/apache/fop/render/svg/SVGRenderer.java
private void writeSVGFile(int pageNumber) throws IOException { log.debug("Writing out SVG file..."); // Finally, stream out SVG to the standard output using UTF-8 // character to byte encoding boolean useCSS = true; // we want to use CSS style attribute OutputStream out = getCurrentOutputStream(pageNumber); if (out == null) { log.warn("No filename information available." + " Stopping early after the first page."); return; } try { Writer writer = new java.io.OutputStreamWriter(out, "UTF-8"); this.svgGenerator.stream(writer, useCSS); } finally { if (out != this.firstOutputStream) { IOUtils.closeQuietly(out); } else { out.flush(); } } }
// in src/sandbox/org/apache/fop/render/svg/SVGRenderer.java
protected OutputStream getCurrentOutputStream(int pageNumber) throws IOException { if (pageNumber == 0) { return firstOutputStream; } else { return multiFileUtil.createOutputStream(pageNumber); } }
// in src/sandbox/org/apache/fop/render/svg/SVGDataUrlImageHandler.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { SVGRenderingContext svgContext = (SVGRenderingContext)context; ImageRawStream raw = (ImageRawStream)image; InputStream in = raw.createInputStream(); try { ContentHandler handler = svgContext.getContentHandler(); String url = DataURLUtil.createDataURL(in, raw.getMimeType()); AttributesImpl atts = new AttributesImpl(); addAttribute(atts, IFConstants.XLINK_HREF, url); atts.addAttribute("", "x", "x", CDATA, Integer.toString(pos.x)); atts.addAttribute("", "y", "y", CDATA, Integer.toString(pos.y)); atts.addAttribute("", "width", "width", CDATA, Integer.toString(pos.width)); atts.addAttribute("", "height", "height", CDATA, Integer.toString(pos.height)); try { handler.startElement(NAMESPACE, "image", "image", atts); handler.endElement(NAMESPACE, "image", "image"); } catch (SAXException e) { throw new IOException(e.getMessage()); } } finally { IOUtils.closeQuietly(in); } }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
public void handleImage(RenderingContext context, Image image, final Rectangle pos) throws IOException { SVGRenderingContext svgContext = (SVGRenderingContext)context; ImageXMLDOM svg = (ImageXMLDOM)image; ContentHandler handler = svgContext.getContentHandler(); AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "x", "x", CDATA, SVGUtil.formatMptToPt(pos.x)); atts.addAttribute("", "y", "y", CDATA, SVGUtil.formatMptToPt(pos.y)); atts.addAttribute("", "width", "width", CDATA, SVGUtil.formatMptToPt(pos.width)); atts.addAttribute("", "height", "height", CDATA, SVGUtil.formatMptToPt(pos.height)); try { Document doc = (Document)svg.getDocument(); Element svgEl = (Element)doc.getDocumentElement(); if (svgEl.getAttribute("viewBox").length() == 0) { log.warn("SVG doesn't have a viewBox. The result might not be scaled correctly!"); } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource src = new DOMSource(svg.getDocument()); SAXResult res = new SAXResult(new DelegatingFragmentContentHandler(handler) { private boolean topLevelSVGFound = false; private void setAttribute(AttributesImpl atts, String localName, String value) { int index; index = atts.getIndex("", localName); if (index < 0) { atts.addAttribute("", localName, localName, CDATA, value); } else { atts.setAttribute(index, "", localName, localName, CDATA, value); } } public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { if (!topLevelSVGFound && SVG_ELEMENT.getNamespaceURI().equals(uri) && SVG_ELEMENT.getLocalName().equals(localName)) { topLevelSVGFound = true; AttributesImpl modAtts = new AttributesImpl(atts); setAttribute(modAtts, "x", SVGUtil.formatMptToPt(pos.x)); setAttribute(modAtts, "y", SVGUtil.formatMptToPt(pos.y)); setAttribute(modAtts, "width", SVGUtil.formatMptToPt(pos.width)); setAttribute(modAtts, "height", SVGUtil.formatMptToPt(pos.height)); super.startElement(uri, localName, name, modAtts); } else { super.startElement(uri, localName, name, atts); } } }); transformer.transform(src, res); } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
// in src/sandbox/org/apache/fop/render/mif/MIFFile.java
public void output(OutputStream os) throws IOException { if (finished) { return; } if (!started) { os.write(("<MIFFile 5.00> # Generated by FOP\n"/* + getVersion()*/).getBytes()); started = true; } boolean done = true; for (Iterator iter = valueElements.iterator(); iter.hasNext();) { MIFElement el = (MIFElement)iter.next(); boolean d = el.output(os, 0); if (d) { iter.remove(); } else { done = false; break; } } if (done && finish) { os.write(("# end of MIFFile").getBytes()); } }
// in src/sandbox/org/apache/fop/render/mif/MIFElement.java
public boolean output(OutputStream os, int indent) throws IOException { if (finished) { return true; } if (valueElements == null && valueStr == null) { return false; } String indentStr = ""; for (int c = 0; c < indent; c++) { indentStr += " "; } if (!started) { os.write((indentStr + "<" + name).getBytes()); if (valueElements != null) { os.write(("\n").getBytes()); } started = true; } if (valueElements != null) { boolean done = true; for (Iterator iter = valueElements.iterator(); iter.hasNext();) { MIFElement el = (MIFElement)iter.next(); boolean d = el.output(os, indent + 1); if (d) { iter.remove(); } else { done = false; break; } } if (!finish || !done) { return false; } os.write((indentStr + "> # end of " + name + "\n").getBytes()); } else { os.write((" " + valueStr + ">\n").getBytes()); } finished = true; return true; }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setUserConfig(File userConfigFile) throws SAXException, IOException { config.setUserConfig(userConfigFile); }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setUserConfig(String uri) throws SAXException, IOException { config.setUserConfig(uri); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(File userConfigFile) throws SAXException, IOException { try { DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); setUserConfig(cfgBuilder.buildFromFile(userConfigFile)); } catch (ConfigurationException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(String uri) throws SAXException, IOException { try { DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); setUserConfig(cfgBuilder.build(uri)); } catch (ConfigurationException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
public OutputStream applyFilter(OutputStream out) throws IOException { byte[] key = createEncryptionKey(streamNumber, streamGeneration); Cipher cipher = initCipher(key); return new CipherOutputStream(out, cipher); }
// in src/java/org/apache/fop/pdf/PDFCMap.java
public int output(OutputStream stream) throws IOException { CMapBuilder builder = createCMapBuilder(getBufferWriter()); builder.writeCMap(); return super.output(stream); }
// in src/java/org/apache/fop/pdf/PDFObject.java
public int output(OutputStream stream) throws IOException { byte[] pdf = this.toPDF(); stream.write(pdf); return pdf.length; }
// in src/java/org/apache/fop/pdf/PDFObject.java
public void outputInline(OutputStream out, Writer writer) throws IOException { throw new UnsupportedOperationException("Don't use anymore: " + getClass().getName()); }
// in src/java/org/apache/fop/pdf/PDFObject.java
public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { if (hasObjectNumber()) { textBuffer.append(referencePDF()); } else { PDFDocument.flushTextBuffer(textBuffer, out); output(out); } }
// in src/java/org/apache/fop/pdf/PDFObject.java
protected void encodeBinaryToHexString(byte[] data, OutputStream out) throws IOException { out.write('<'); if (getDocumentSafely().isEncryptionActive()) { data = getDocument().getEncryption().encrypt(data, this); } String hex = PDFText.toHex(data, false); byte[] encoded = hex.getBytes("US-ASCII"); out.write(encoded); out.write('>'); }
// in src/java/org/apache/fop/pdf/PDFObject.java
protected void formatObject(Object obj, OutputStream out, StringBuilder textBuffer) throws IOException { if (obj == null) { textBuffer.append("null"); } else if (obj instanceof PDFWritable) { ((PDFWritable)obj).outputInline(out, textBuffer); } else if (obj instanceof Number) { if (obj instanceof Double || obj instanceof Float) { textBuffer.append(PDFNumber.doubleOut(((Number)obj).doubleValue())); } else { textBuffer.append(obj.toString()); } } else if (obj instanceof Boolean) { textBuffer.append(obj.toString()); } else if (obj instanceof byte[]) { PDFDocument.flushTextBuffer(textBuffer, out); encodeBinaryToHexString((byte[])obj, out); } else { PDFDocument.flushTextBuffer(textBuffer, out); out.write(encodeText(obj.toString())); } }
// in src/java/org/apache/fop/pdf/PDFFormXObject.java
public void setData(byte[] data) throws IOException { this.contents.setData(data); }
// in src/java/org/apache/fop/pdf/PDFFormXObject.java
protected void outputRawStreamData(OutputStream out) throws IOException { contents.outputRawStreamData(out); }
// in src/java/org/apache/fop/pdf/PDFFormXObject.java
public int output(OutputStream stream) throws IOException { final int len = super.output(stream); //Now that the data has been written, it can be discarded. this.contents = null; return len; }
// in src/java/org/apache/fop/pdf/PDFRoot.java
public int output(OutputStream stream) throws IOException { getDocument().getProfile().verifyTaggedPDF(); return super.output(stream); }
// in src/java/org/apache/fop/pdf/ASCII85Filter.java
public OutputStream applyFilter(OutputStream out) throws IOException { if (isApplied()) { return out; } else { return new ASCII85OutputStream(out); } }
// in src/java/org/apache/fop/pdf/PDFRectangle.java
public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { format(textBuffer); }
// in src/java/org/apache/fop/pdf/PDFPattern.java
public int output(OutputStream stream) throws IOException { int vectorSize = 0; int tempInt = 0; byte[] buffer; StringBuffer p = new StringBuffer(64); p.append("<< \n/Type /Pattern \n"); if (this.resources != null) { p.append("/Resources " + this.resources.referencePDF() + " \n"); } p.append("/PatternType " + this.patternType + " \n"); PDFStream pdfStream = null; StreamCache encodedStream = null; if (this.patternType == 1) { p.append("/PaintType " + this.paintType + " \n"); p.append("/TilingType " + this.tilingType + " \n"); if (this.bBox != null) { vectorSize = this.bBox.size(); p.append("/BBox [ "); for (tempInt = 0; tempInt < vectorSize; tempInt++) { p.append(PDFNumber.doubleOut((Double)this.bBox.get(tempInt))); p.append(" "); } p.append("] \n"); } p.append("/XStep " + PDFNumber.doubleOut(new Double(this.xStep)) + " \n"); p.append("/YStep " + PDFNumber.doubleOut(new Double(this.yStep)) + " \n"); if (this.matrix != null) { vectorSize = this.matrix.size(); p.append("/Matrix [ "); for (tempInt = 0; tempInt < vectorSize; tempInt++) { p.append(PDFNumber.doubleOut( ((Double)this.matrix.get(tempInt)).doubleValue(), 8)); p.append(" "); } p.append("] \n"); } if (this.xUID != null) { vectorSize = this.xUID.size(); p.append("/XUID [ "); for (tempInt = 0; tempInt < vectorSize; tempInt++) { p.append(((Integer)this.xUID.get(tempInt)) + " "); } p.append("] \n"); } // don't forget the length of the stream. if (this.patternDataStream != null) { pdfStream = new PDFStream(); pdfStream.setDocument(getDocumentSafely()); pdfStream.add(this.patternDataStream.toString()); pdfStream.getFilterList().addDefaultFilters( getDocument().getFilterMap(), PDFFilterList.CONTENT_FILTER); encodedStream = pdfStream.encodeStream(); p.append(pdfStream.getFilterList().buildFilterDictEntries()); p.append("/Length " + (encodedStream.getSize() + 1) + " \n"); } } else { // if (this.patternType ==2) // Smooth Shading... if (this.shading != null) { p.append("/Shading " + this.shading.referencePDF() + " \n"); } if (this.xUID != null) { vectorSize = this.xUID.size(); p.append("/XUID [ "); for (tempInt = 0; tempInt < vectorSize; tempInt++) { p.append(((Integer)this.xUID.get(tempInt)) + " "); } p.append("] \n"); } if (this.extGState != null) { p.append("/ExtGState " + this.extGState + " \n"); } if (this.matrix != null) { vectorSize = this.matrix.size(); p.append("/Matrix [ "); for (tempInt = 0; tempInt < vectorSize; tempInt++) { p.append(PDFNumber.doubleOut( ((Double)this.matrix.get(tempInt)).doubleValue(), 8)); p.append(" "); } p.append("] \n"); } } // end of if patterntype =1...else 2. p.append(">> \n"); buffer = encode(p.toString()); int length = buffer.length; stream.write(buffer); // stream representing the function if (pdfStream != null) { length += pdfStream.outputStreamData(encodedStream, stream); } return length; }
// in src/java/org/apache/fop/pdf/FlateFilter.java
public OutputStream applyFilter(OutputStream out) throws IOException { if (isApplied()) { return out; } else { return new FlateEncodeOutputStream(out); } }
// in src/java/org/apache/fop/pdf/PDFEmbeddedFiles.java
protected void writeDictionary(OutputStream out, StringBuilder textBuffer) throws IOException { sortNames(); //Sort the names before writing them out super.writeDictionary(out, textBuffer); }
// in src/java/org/apache/fop/pdf/PDFStream.java
private void flush() throws IOException { this.streamWriter.flush(); }
// in src/java/org/apache/fop/pdf/PDFStream.java
public OutputStream getBufferOutputStream() throws IOException { if (this.streamWriter != null) { flush(); //Just to be sure } return this.data.getOutputStream(); }
// in src/java/org/apache/fop/pdf/PDFStream.java
public void setData(byte[] data) throws IOException { this.data.clear(); this.data.write(data); }
// in src/java/org/apache/fop/pdf/PDFStream.java
protected int getSizeHint() throws IOException { flush(); return data.getSize(); }
// in src/java/org/apache/fop/pdf/PDFStream.java
protected void outputRawStreamData(OutputStream out) throws IOException { flush(); data.outputContents(out); }
// in src/java/org/apache/fop/pdf/PDFStream.java
public int output(OutputStream stream) throws IOException { final int len = super.output(stream); //Now that the data has been written, it can be discarded. this.data = null; return len; }
// in src/java/org/apache/fop/pdf/PDFICCStream.java
Override public int output(java.io.OutputStream stream) throws java.io.IOException { int length = super.output(stream); this.cp = null; //Free ICC stream when it's not used anymore return length; }
// in src/java/org/apache/fop/pdf/PDFICCStream.java
Override protected void outputRawStreamData(OutputStream out) throws IOException { cp.write(out); }
// in src/java/org/apache/fop/pdf/PDFFont.java
public int output(OutputStream stream) throws IOException { validate(); return super.output(stream); }
// in src/java/org/apache/fop/pdf/ObjectStream.java
Override protected void outputRawStreamData(OutputStream out) throws IOException { int currentOffset = 0; StringBuilder offsetsPart = new StringBuilder(); ByteArrayOutputStream streamContent = new ByteArrayOutputStream(); for (CompressedObject object : objects) { offsetsPart.append(object.getObjectNumber()) .append(' ') .append(currentOffset) .append('\n'); currentOffset += object.output(streamContent); } byte[] offsets = PDFDocument.encode(offsetsPart.toString()); firstObjectOffset = offsets.length; out.write(offsets); streamContent.writeTo(out); }
// in src/java/org/apache/fop/pdf/PDFStructElem.java
Override protected void writeDictionary(OutputStream out, StringBuilder textBuffer) throws IOException { attachKids(); super.writeDictionary(out, textBuffer); }
// in src/java/org/apache/fop/pdf/PDFStructElem.java
Override public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { if (kids != null) { assert kids.size() > 0; for (int i = 0; i < kids.size(); i++) { if (i > 0) { textBuffer.append(' '); } Object obj = kids.get(i); formatObject(obj, out, textBuffer); } } }
// in src/java/org/apache/fop/pdf/PDFDestination.java
Override public int output(OutputStream stream) throws IOException { CountingOutputStream cout = new CountingOutputStream(stream); StringBuilder textBuffer = new StringBuilder(64); formatObject(getIDRef(), cout, textBuffer); textBuffer.append(' '); formatObject(goToReference, cout, textBuffer); PDFDocument.flushTextBuffer(textBuffer, cout); return cout.getCount(); }
// in src/java/org/apache/fop/pdf/PDFResources.java
Override public int output(OutputStream stream) throws IOException { populateDictionary(); return super.output(stream); }
// in src/java/org/apache/fop/pdf/StreamCacheFactory.java
public StreamCache createStreamCache() throws IOException { if (this.cacheToFile) { return new TempFileStreamCache(); } else { return new InMemoryStreamCache(); } }
// in src/java/org/apache/fop/pdf/StreamCacheFactory.java
public StreamCache createStreamCache(int hintSize) throws IOException { if (this.cacheToFile) { return new TempFileStreamCache(); } else { return new InMemoryStreamCache(hintSize); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public static void flushTextBuffer(StringBuilder textBuffer, OutputStream out) throws IOException { out.write(encode(textBuffer.toString())); textBuffer.setLength(0); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void output(OutputStream stream) throws IOException { //Write out objects until the list is empty. This approach (used with a //LinkedList) allows for output() methods to create and register objects //on the fly even during serialization. while (this.objects.size() > 0) { PDFObject object = this.objects.remove(0); streamIndirectObject(object, stream); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
private void streamIndirectObject(PDFObject o, OutputStream stream) throws IOException { recordObjectOffset(o); this.position += outputIndirectObject(o, stream); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
private void streamIndirectObjects(Collection<? extends PDFObject> objects, OutputStream stream) throws IOException { for (PDFObject o : objects) { streamIndirectObject(o, stream); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public static int outputIndirectObject(PDFObject object, OutputStream stream) throws IOException { if (!object.hasObjectNumber()) { throw new IllegalArgumentException("Not an indirect object"); } byte[] obj = encode(object.getObjectID()); stream.write(obj); int length = object.output(stream); byte[] endobj = encode("\nendobj\n"); stream.write(endobj); return obj.length + length + endobj.length; }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void outputHeader(OutputStream stream) throws IOException { this.position = 0; getProfile().verifyPDFVersion(); byte[] pdf = encode("%PDF-" + getPDFVersionString() + "\n"); stream.write(pdf); this.position += pdf.length; // output a binary comment as recommended by the PDF spec (3.4.1) byte[] bin = { (byte)'%', (byte)0xAA, (byte)0xAB, (byte)0xAC, (byte)0xAD, (byte)'\n' }; stream.write(bin); this.position += bin.length; }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void outputTrailer(OutputStream stream) throws IOException { createDestinations(); output(stream); outputTrailerObjectsAndXref(stream); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
private void outputTrailerObjectsAndXref(OutputStream stream) throws IOException { TrailerOutputHelper trailerOutputHelper = mayCompressStructureTreeElements() ? new CompressedTrailerOutputHelper() : new UncompressedTrailerOutputHelper(); if (structureTreeElements != null) { trailerOutputHelper.outputStructureTreeElements(stream); } streamIndirectObjects(trailerObjects, stream); TrailerDictionary trailerDictionary = createTrailerDictionary(); long startxref = trailerOutputHelper.outputCrossReferenceObject(stream, trailerDictionary); String trailer = "startxref\n" + startxref + "\n%%EOF\n"; stream.write(encode(trailer)); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void outputStructureTreeElements(OutputStream stream) throws IOException { streamIndirectObjects(structureTreeElements, stream); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public long outputCrossReferenceObject(OutputStream stream, TrailerDictionary trailerDictionary) throws IOException { new CrossReferenceTable(trailerDictionary, position, indirectObjectOffsets).output(stream); return position; }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void outputStructureTreeElements(OutputStream stream) throws IOException { assert structureTreeElements.size() > 0; structureTreeObjectStreams = new ObjectStreamManager(PDFDocument.this); for (PDFStructElem structElem : structureTreeElements) { structureTreeObjectStreams.add(structElem); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public long outputCrossReferenceObject(OutputStream stream, TrailerDictionary trailerDictionary) throws IOException { // Outputting the object streams should not have created new indirect objects assert objects.isEmpty(); new CrossReferenceStream(PDFDocument.this, ++objectcount, trailerDictionary, position, indirectObjectOffsets, structureTreeObjectStreams.getCompressedObjectReferences()) .output(stream); return position; }
// in src/java/org/apache/fop/pdf/PDFNumsArray.java
Override public int output(OutputStream stream) throws IOException { CountingOutputStream cout = new CountingOutputStream(stream); StringBuilder textBuffer = new StringBuilder(64); textBuffer.append('['); boolean first = true; for (Map.Entry<Integer, Object> entry : this.map.entrySet()) { if (!first) { textBuffer.append(" "); } first = false; formatObject(entry.getKey(), cout, textBuffer); textBuffer.append(" "); formatObject(entry.getValue(), cout, textBuffer); } textBuffer.append(']'); PDFDocument.flushTextBuffer(textBuffer, cout); return cout.getCount(); }
// in src/java/org/apache/fop/pdf/PDFNull.java
public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { textBuffer.append(toString()); }
// in src/java/org/apache/fop/pdf/ASCIIHexFilter.java
public OutputStream applyFilter(OutputStream out) throws IOException { if (isApplied()) { return out; } else { return new ASCIIHexOutputStream(out); } }
// in src/java/org/apache/fop/pdf/PDFToUnicodeCMap.java
public void writeCMap() throws IOException { writeCIDInit(); writeCIDSystemInfo("Adobe", "UCS", 0); writeName("Adobe-Identity-UCS"); writeType("2"); writeCodeSpaceRange(singleByte); writeBFEntries(); writeWrapUp(); }
// in src/java/org/apache/fop/pdf/PDFToUnicodeCMap.java
protected void writeBFEntries() throws IOException { if (unicodeCharMap != null) { writeBFCharEntries(unicodeCharMap); writeBFRangeEntries(unicodeCharMap); } }
// in src/java/org/apache/fop/pdf/PDFToUnicodeCMap.java
protected void writeBFCharEntries(char[] charArray) throws IOException { int totalEntries = 0; for (int i = 0; i < charArray.length; i++) { if (!partOfRange(charArray, i)) { totalEntries++; } } if (totalEntries < 1) { return; } int remainingEntries = totalEntries; int charIndex = 0; do { /* Limited to 100 entries in each section */ int entriesThisSection = Math.min(remainingEntries, 100); writer.write(entriesThisSection + " beginbfchar\n"); for (int i = 0; i < entriesThisSection; i++) { /* Go to the next char not in a range */ while (partOfRange(charArray, charIndex)) { charIndex++; } writer.write("<" + padCharIndex(charIndex) + "> "); writer.write("<" + padHexString(Integer.toHexString(charArray[charIndex]), 4) + ">\n"); charIndex++; } remainingEntries -= entriesThisSection; writer.write("endbfchar\n"); } while (remainingEntries > 0); }
// in src/java/org/apache/fop/pdf/PDFToUnicodeCMap.java
protected void writeBFRangeEntries(char[] charArray) throws IOException { int totalEntries = 0; for (int i = 0; i < charArray.length; i++) { if (startOfRange(charArray, i)) { totalEntries++; } } if (totalEntries < 1) { return; } int remainingEntries = totalEntries; int charIndex = 0; do { /* Limited to 100 entries in each section */ int entriesThisSection = Math.min(remainingEntries, 100); writer.write(entriesThisSection + " beginbfrange\n"); for (int i = 0; i < entriesThisSection; i++) { /* Go to the next start of a range */ while (!startOfRange(charArray, charIndex)) { charIndex++; } writer.write("<" + padCharIndex(charIndex) + "> "); writer.write("<" + padCharIndex(endOfRange(charArray, charIndex)) + "> "); writer.write("<" + padHexString(Integer.toHexString(charArray[charIndex]), 4) + ">\n"); charIndex++; } remainingEntries -= entriesThisSection; writer.write("endbfrange\n"); } while (remainingEntries > 0); }
// in src/java/org/apache/fop/pdf/PDFTTFStream.java
protected int getSizeHint() throws IOException { if (this.ttfData != null) { return ttfData.length; } else { return 0; //no hint available } }
// in src/java/org/apache/fop/pdf/PDFTTFStream.java
public int output(java.io.OutputStream stream) throws java.io.IOException { if (log.isDebugEnabled()) { log.debug("Writing " + origLength + " bytes of TTF font data"); } int length = super.output(stream); log.debug("Embedded TrueType/OpenType font"); return length; }
// in src/java/org/apache/fop/pdf/PDFTTFStream.java
protected void outputRawStreamData(OutputStream out) throws IOException { out.write(this.ttfData); }
// in src/java/org/apache/fop/pdf/PDFTTFStream.java
public void setData(byte[] data, int size) throws IOException { this.ttfData = new byte[size]; System.arraycopy(data, 0, this.ttfData, 0, size); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
public void writeCMap() throws IOException { writePreStream(); writeStreamComments(); writeCIDInit(); writeCIDSystemInfo(); writeVersion("1"); writeType("1"); writeName(name); writeCodeSpaceRange(); writeCIDRange(); writeBFEntries(); writeWrapUp(); writeStreamAfterComments(); writeUseCMap(); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writePreStream() throws IOException { // writer.write("/Type /CMap\n"); // writer.write(sysInfo.toPDFString()); // writer.write("/CMapName /" + name + EOL); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeStreamComments() throws IOException { writer.write("%!PS-Adobe-3.0 Resource-CMap\n"); writer.write("%%DocumentNeededResources: ProcSet (CIDInit)\n"); writer.write("%%IncludeResource: ProcSet (CIDInit)\n"); writer.write("%%BeginResource: CMap (" + name + ")\n"); writer.write("%%EndComments\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeCIDInit() throws IOException { writer.write("/CIDInit /ProcSet findresource begin\n"); writer.write("12 dict begin\n"); writer.write("begincmap\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeCIDSystemInfo(String registry, String ordering, int supplement) throws IOException { writer.write("/CIDSystemInfo 3 dict dup begin\n"); writer.write(" /Registry ("); writer.write(registry); writer.write(") def\n"); writer.write(" /Ordering ("); writer.write(ordering); writer.write(") def\n"); writer.write(" /Supplement "); writer.write(Integer.toString(supplement)); writer.write(" def\n"); writer.write("end def\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeCIDSystemInfo() throws IOException { writeCIDSystemInfo("Adobe", "Identity", 0); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeVersion(String version) throws IOException { writer.write("/CMapVersion "); writer.write(version); writer.write(" def\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeType(String type) throws IOException { writer.write("/CMapType "); writer.write(type); writer.write(" def\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeName(String name) throws IOException { writer.write("/CMapName /"); writer.write(name); writer.write(" def\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeCodeSpaceRange() throws IOException { writeCodeSpaceRange(false); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeCodeSpaceRange(boolean singleByte) throws IOException { writer.write("1 begincodespacerange\n"); if (singleByte) { writer.write("<00> <FF>\n"); } else { writer.write("<0000> <FFFF>\n"); } writer.write("endcodespacerange\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeCIDRange() throws IOException { writer.write("1 begincidrange\n"); writer.write("<0000> <FFFF> 0\n"); writer.write("endcidrange\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeBFEntries() throws IOException { // writer.write("1 beginbfrange\n"); // writer.write("<0020> <0100> <0000>\n"); // writer.write("endbfrange\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeWrapUp() throws IOException { writer.write("endcmap\n"); writer.write("CMapName currentdict /CMap defineresource pop\n"); writer.write("end\n"); writer.write("end\n"); }
// in src/java/org/apache/fop/pdf/CMapBuilder.java
protected void writeStreamAfterComments() throws IOException { writer.write("%%EndResource\n"); writer.write("%%EOF\n"); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
public int output(java.io.OutputStream stream) throws java.io.IOException { int length = super.output(stream); this.xmpMetadata = null; //Release DOM when it's not used anymore return length; }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
protected void outputRawStreamData(OutputStream out) throws IOException { try { XMPSerializer.writeXMPPacket(xmpMetadata, out, this.readOnly); } catch (TransformerConfigurationException tce) { throw new IOException("Error setting up Transformer for XMP stream serialization: " + tce.getMessage()); } catch (SAXException saxe) { throw new IOException("Error while serializing XMP stream: " + saxe.getMessage()); } }
// in src/java/org/apache/fop/pdf/AlphaRasterImage.java
public void outputContents(OutputStream out) throws IOException { int w = getWidth(); int h = getHeight(); //Check Raster int nbands = alpha.getNumBands(); if (nbands != 1) { throw new UnsupportedOperationException( "Expected only one band/component for the alpha channel"); } //...and write the Raster line by line with a reusable buffer int dataType = alpha.getDataBuffer().getDataType(); if (dataType == DataBuffer.TYPE_BYTE) { byte[] line = new byte[nbands * w]; for (int y = 0; y < h; y++) { alpha.getDataElements(0, y, w, 1, line); out.write(line); } } else if (dataType == DataBuffer.TYPE_USHORT) { short[] sline = new short[nbands * w]; byte[] line = new byte[nbands * w]; for (int y = 0; y < h; y++) { alpha.getDataElements(0, y, w, 1, sline); for (int i = 0; i < w; i++) { //this compresses a 16-bit alpha channel to 8 bits! //we probably don't ever need a 16-bit channel line[i] = (byte)(sline[i] >> 8); } out.write(line); } } else if (dataType == DataBuffer.TYPE_INT) { //Is there an better way to get a 8bit raster from a TYPE_INT raster? int shift = 24; SampleModel sampleModel = alpha.getSampleModel(); if (sampleModel instanceof SinglePixelPackedSampleModel) { SinglePixelPackedSampleModel m = (SinglePixelPackedSampleModel)sampleModel; shift = m.getBitOffsets()[0]; } int[] iline = new int[nbands * w]; byte[] line = new byte[nbands * w]; for (int y = 0; y < h; y++) { alpha.getDataElements(0, y, w, 1, iline); for (int i = 0; i < w; i++) { line[i] = (byte)(iline[i] >> shift); } out.write(line); } } else { throw new UnsupportedOperationException("Unsupported DataBuffer type: " + alpha.getDataBuffer().getClass().getName()); } }
// in src/java/org/apache/fop/pdf/TempFileStreamCache.java
public OutputStream getOutputStream() throws IOException { if (output == null) { output = new java.io.BufferedOutputStream( new java.io.FileOutputStream(tempFile)); } return output; }
// in src/java/org/apache/fop/pdf/TempFileStreamCache.java
public void write(byte[] data) throws IOException { getOutputStream().write(data); }
// in src/java/org/apache/fop/pdf/TempFileStreamCache.java
public int outputContents(OutputStream out) throws IOException { if (output == null) { return 0; } output.close(); output = null; // don't need a buffer because copy() is buffered InputStream input = new java.io.FileInputStream(tempFile); try { return IOUtils.copy(input, out); } finally { IOUtils.closeQuietly(input); } }
// in src/java/org/apache/fop/pdf/TempFileStreamCache.java
public int getSize() throws IOException { if (output != null) { output.flush(); } return (int) tempFile.length(); }
// in src/java/org/apache/fop/pdf/TempFileStreamCache.java
public void clear() throws IOException { if (output != null) { output.close(); output = null; } if (tempFile.exists()) { tempFile.delete(); } }
// in src/java/org/apache/fop/pdf/PDFXObject.java
protected int getSizeHint() throws IOException { return 0; }
// in src/java/org/apache/fop/pdf/PDFFilterList.java
public OutputStream applyFilters(OutputStream stream) throws IOException { OutputStream out = stream; if (!isDisableAllFilters()) { for (int count = filters.size() - 1; count >= 0; count--) { PDFFilter filter = (PDFFilter)filters.get(count); out = filter.applyFilter(out); } } return out; }
// in src/java/org/apache/fop/pdf/PDFImageXObject.java
public int output(OutputStream stream) throws IOException { int length = super.output(stream); // let it gc // this object is retained as a reference to inserting // the same image but the image data is no longer needed pdfimage = null; return length; }
// in src/java/org/apache/fop/pdf/PDFImageXObject.java
protected void outputRawStreamData(OutputStream out) throws IOException { pdfimage.outputContents(out); }
// in src/java/org/apache/fop/pdf/PDFImageXObject.java
protected int getSizeHint() throws IOException { return 0; }
// in src/java/org/apache/fop/pdf/AbstractPDFStream.java
protected int outputStreamData(StreamCache encodedStream, OutputStream out) throws IOException { int length = 0; byte[] p = encode("stream\n"); out.write(p); length += p.length; encodedStream.outputContents(out); length += encodedStream.getSize(); p = encode("\nendstream"); out.write(p); length += p.length; return length; }
// in src/java/org/apache/fop/pdf/AbstractPDFStream.java
protected StreamCache encodeStream() throws IOException { //Allocate a temporary buffer to find out the size of the encoded stream final StreamCache encodedStream = StreamCacheFactory.getInstance() .createStreamCache(getSizeHint()); OutputStream filteredOutput = getFilterList().applyFilters(encodedStream.getOutputStream()); outputRawStreamData(filteredOutput); filteredOutput.flush(); filteredOutput.close(); return encodedStream; }
// in src/java/org/apache/fop/pdf/AbstractPDFStream.java
protected int encodeAndWriteStream(OutputStream out, PDFNumber refLength) throws IOException { int bytesWritten = 0; //Stream header byte[] buf = encode("stream\n"); out.write(buf); bytesWritten += buf.length; //Stream contents CloseBlockerOutputStream cbout = new CloseBlockerOutputStream(out); CountingOutputStream cout = new CountingOutputStream(cbout); OutputStream filteredOutput = getFilterList().applyFilters(cout); outputRawStreamData(filteredOutput); filteredOutput.close(); refLength.setNumber(Integer.valueOf(cout.getCount())); bytesWritten += cout.getCount(); //Stream trailer buf = encode("\nendstream"); out.write(buf); bytesWritten += buf.length; return bytesWritten; }
// in src/java/org/apache/fop/pdf/AbstractPDFStream.java
Override public int output(OutputStream stream) throws IOException { setupFilterList(); CountingOutputStream cout = new CountingOutputStream(stream); StringBuilder textBuffer = new StringBuilder(64); StreamCache encodedStream = null; PDFNumber refLength = null; final Object lengthEntry; if (encodeOnTheFly) { refLength = new PDFNumber(); getDocumentSafely().registerObject(refLength); lengthEntry = refLength; } else { encodedStream = encodeStream(); lengthEntry = Integer.valueOf(encodedStream.getSize() + 1); } populateStreamDict(lengthEntry); dictionary.writeDictionary(cout, textBuffer); //Send encoded stream to target OutputStream PDFDocument.flushTextBuffer(textBuffer, cout); if (encodedStream == null) { encodeAndWriteStream(cout, refLength); } else { outputStreamData(encodedStream, cout); encodedStream.clear(); //Encoded stream can now be discarded } PDFDocument.flushTextBuffer(textBuffer, cout); return cout.getCount(); }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceStream.java
public void output(OutputStream stream) throws IOException { populateDictionary(); PDFStream helperStream = new PDFStream(trailerDictionary.getDictionary(), false) { @Override protected void setupFilterList() { PDFFilterList filterList = getFilterList(); assert !filterList.isInitialized(); filterList.addDefaultFilters(document.getFilterMap(), getDefaultFilterName()); } }; helperStream.setObjectNumber(objectNumber); helperStream.setDocument(document); ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(byteArray); addFreeEntryForObject0(data); for (ObjectReference objectReference : objectReferences) { assert objectReference != null; objectReference.output(data); } new UncompressedObjectReference(startxref).output(data); data.close(); helperStream.setData(byteArray.toByteArray()); PDFDocument.outputIndirectObject(helperStream, stream); }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceStream.java
private void populateDictionary() throws IOException { int objectCount = objectReferences.size() + 1; PDFDictionary dictionary = trailerDictionary.getDictionary(); dictionary.put("/Type", XREF); dictionary.put("/Size", objectCount + 1); dictionary.put("/W", new PDFArray(1, 8, 2)); }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceStream.java
private void addFreeEntryForObject0(DataOutputStream data) throws IOException { data.write(new byte[] {0, 0, 0, 0, 0, 0, 0, 0, 0, (byte) 0xff, (byte) 0xff}); }
// in src/java/org/apache/fop/pdf/xref/UncompressedObjectReference.java
public void output(DataOutputStream out) throws IOException { out.write(1); out.writeLong(offset); out.write(0); out.write(0); }
// in src/java/org/apache/fop/pdf/xref/CompressedObjectReference.java
public void output(DataOutputStream out) throws IOException { out.write(2); out.writeLong(objectStreamNumber); out.write(0); out.write(index); }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceTable.java
public void output(OutputStream stream) throws IOException { outputXref(); writeTrailer(stream); }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceTable.java
private void outputXref() throws IOException { pdf.append("xref\n0 "); pdf.append(objectReferences.size() + 1); pdf.append("\n0000000000 65535 f \n"); for (Long objectReference : objectReferences) { final String padding = "0000000000"; String s = String.valueOf(objectReference); if (s.length() > 10) { throw new IOException("PDF file too large." + " PDF 1.4 cannot grow beyond approx. 9.3GB."); } String loc = padding.substring(s.length()) + s; pdf.append(loc).append(" 00000 n \n"); } }
// in src/java/org/apache/fop/pdf/xref/CrossReferenceTable.java
private void writeTrailer(OutputStream stream) throws IOException { pdf.append("trailer\n"); stream.write(PDFDocument.encode(pdf.toString())); PDFDictionary dictionary = trailerDictionary.getDictionary(); dictionary.put("/Size", objectReferences.size() + 1); dictionary.output(stream); }
// in src/java/org/apache/fop/pdf/xref/TrailerDictionary.java
public TrailerDictionary setFileID(byte[] originalFileID, byte[] updatedFileID) { // TODO this is ugly! Used to circumvent the fact that the file ID will be // encrypted if directly stored as a byte array class FileID implements PDFWritable { private final byte[] fileID; FileID(byte[] id) { fileID = id; } public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { PDFDocument.flushTextBuffer(textBuffer, out); String hex = PDFText.toHex(fileID, true); byte[] encoded = hex.getBytes("US-ASCII"); out.write(encoded); } } PDFArray fileID = new PDFArray(new FileID(originalFileID), new FileID(updatedFileID)); dictionary.put("/ID", fileID); return this; }
// in src/java/org/apache/fop/pdf/xref/TrailerDictionary.java
public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { PDFDocument.flushTextBuffer(textBuffer, out); String hex = PDFText.toHex(fileID, true); byte[] encoded = hex.getBytes("US-ASCII"); out.write(encoded); }
// in src/java/org/apache/fop/pdf/PDFDictionary.java
Override public int output(OutputStream stream) throws IOException { CountingOutputStream cout = new CountingOutputStream(stream); StringBuilder textBuffer = new StringBuilder(64); writeDictionary(cout, textBuffer); PDFDocument.flushTextBuffer(textBuffer, cout); return cout.getCount(); }
// in src/java/org/apache/fop/pdf/PDFDictionary.java
protected void writeDictionary(OutputStream out, StringBuilder textBuffer) throws IOException { textBuffer.append("<<"); boolean compact = (this.order.size() <= 2); for (String key : this.order) { if (compact) { textBuffer.append(' '); } else { textBuffer.append("\n "); } textBuffer.append(PDFName.escapeName(key)); textBuffer.append(' '); Object obj = this.entries.get(key); formatObject(obj, out, textBuffer); } if (compact) { textBuffer.append(' '); } else { textBuffer.append('\n'); } textBuffer.append(">>\n"); }
// in src/java/org/apache/fop/pdf/BitmapImage.java
public void outputContents(OutputStream out) throws IOException { out.write(bitmaps); }
// in src/java/org/apache/fop/pdf/PDFT1Stream.java
protected int getSizeHint() throws IOException { if (this.pfb != null) { return pfb.getLength(); } else { return 0; //no hint available } }
// in src/java/org/apache/fop/pdf/PDFT1Stream.java
public int output(java.io.OutputStream stream) throws java.io.IOException { if (pfb == null) { throw new IllegalStateException("pfb must not be null at this point"); } if (log.isDebugEnabled()) { log.debug("Writing " + pfb.getLength() + " bytes of Type 1 font data"); } int length = super.output(stream); log.debug("Embedded Type1 font"); return length; }
// in src/java/org/apache/fop/pdf/PDFT1Stream.java
protected void outputRawStreamData(OutputStream out) throws IOException { this.pfb.outputAllParts(out); }
// in src/java/org/apache/fop/pdf/PDFT1Stream.java
public void setData(PFBData pfb) throws IOException { this.pfb = pfb; }
// in src/java/org/apache/fop/pdf/InMemoryStreamCache.java
public OutputStream getOutputStream() throws IOException { if (output == null) { if (this.hintSize <= 0) { output = new ByteArrayOutputStream(512); } else { output = new ByteArrayOutputStream(this.hintSize); } } return output; }
// in src/java/org/apache/fop/pdf/InMemoryStreamCache.java
public void write(byte[] data) throws IOException { getOutputStream().write(data); }
// in src/java/org/apache/fop/pdf/InMemoryStreamCache.java
public int outputContents(OutputStream out) throws IOException { if (output == null) { return 0; } output.writeTo(out); return output.size(); }
// in src/java/org/apache/fop/pdf/InMemoryStreamCache.java
public int getSize() throws IOException { if (output == null) { return 0; } else { return output.size(); } }
// in src/java/org/apache/fop/pdf/InMemoryStreamCache.java
public void clear() throws IOException { if (output != null) { output.close(); output = null; } }
// in src/java/org/apache/fop/pdf/PDFArray.java
Override public int output(OutputStream stream) throws IOException { CountingOutputStream cout = new CountingOutputStream(stream); StringBuilder textBuffer = new StringBuilder(64); textBuffer.append('['); for (int i = 0; i < values.size(); i++) { if (i > 0) { textBuffer.append(' '); } Object obj = this.values.get(i); formatObject(obj, cout, textBuffer); } textBuffer.append(']'); PDFDocument.flushTextBuffer(textBuffer, cout); return cout.getCount(); }
// in src/java/org/apache/fop/pdf/NullFilter.java
public OutputStream applyFilter(OutputStream out) throws IOException { return out; //No active filtering, NullFilter does nothing }
// in src/java/org/apache/fop/pdf/PDFName.java
Override public int output(OutputStream stream) throws IOException { CountingOutputStream cout = new CountingOutputStream(stream); StringBuilder textBuffer = new StringBuilder(64); textBuffer.append(toString()); PDFDocument.flushTextBuffer(textBuffer, cout); return cout.getCount(); }
// in src/java/org/apache/fop/pdf/PDFName.java
Override public void outputInline(OutputStream out, StringBuilder textBuffer) throws IOException { if (hasObjectNumber()) { textBuffer.append(referencePDF()); } else { textBuffer.append(toString()); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void prepare() throws SAXException, IOException { if (this.configFile != null) { fopFactory.setUserConfig(this.configFile); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void generateXML(SortedMap fontFamilies, File outFile, String singleFamily) throws TransformerConfigurationException, SAXException, IOException { SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler handler; if (this.mode == GENERATE_XML) { handler = tFactory.newTransformerHandler(); } else { URL url = getClass().getResource("fonts2fo.xsl"); if (url == null) { throw new FileNotFoundException("Did not find resource: fonts2fo.xsl"); } handler = tFactory.newTransformerHandler(new StreamSource(url.toExternalForm())); } if (singleFamily != null) { Transformer transformer = handler.getTransformer(); transformer.setParameter("single-family", singleFamily); } OutputStream out = new java.io.FileOutputStream(outFile); out = new java.io.BufferedOutputStream(out); if (this.mode == GENERATE_RENDERED) { handler.setResult(new SAXResult(getFOPContentHandler(out))); } else { handler.setResult(new StreamResult(out)); } try { GenerationHelperContentHandler helper = new GenerationHelperContentHandler( handler, null); FontListSerializer serializer = new FontListSerializer(); serializer.generateSAX(fontFamilies, singleFamily, helper); } finally { IOUtils.closeQuietly(out); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void writeToConsole(SortedMap fontFamilies) throws TransformerConfigurationException, SAXException, IOException { Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String firstFamilyName = (String)entry.getKey(); System.out.println(firstFamilyName + ":"); List list = (List)entry.getValue(); Iterator fonts = list.iterator(); while (fonts.hasNext()) { FontSpec f = (FontSpec)fonts.next(); System.out.println(" " + f.getKey() + " " + f.getFamilyNames()); Iterator triplets = f.getTriplets().iterator(); while (triplets.hasNext()) { FontTriplet triplet = (FontTriplet)triplets.next(); System.out.println(" " + triplet.toString()); } } } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void writeOutput(SortedMap fontFamilies) throws TransformerConfigurationException, SAXException, IOException { if (this.outputFile.isDirectory()) { System.out.println("Creating one file for each family..."); Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String familyName = (String)entry.getKey(); System.out.println("Creating output file for " + familyName + "..."); String filename; switch(this.mode) { case GENERATE_RENDERED: filename = familyName + ".pdf"; break; case GENERATE_FO: filename = familyName + ".fo"; break; case GENERATE_XML: filename = familyName + ".xml"; break; default: throw new IllegalStateException("Unsupported mode"); } File outFile = new File(this.outputFile, filename); generateXML(fontFamilies, outFile, familyName); } } else { System.out.println("Creating output file..."); generateXML(fontFamilies, this.outputFile, this.singleFamilyFilter); } System.out.println(this.outputFile + " written."); }
// in src/java/org/apache/fop/tools/anttasks/FileCompare.java
public static boolean compareFiles(File f1, File f2) throws IOException { return (compareFileSize(f1, f2) && compareBytes(f1, f2)); }
// in src/java/org/apache/fop/tools/anttasks/FileCompare.java
private static boolean compareBytes(File file1, File file2) throws IOException { BufferedInputStream file1Input = new BufferedInputStream(new java.io.FileInputStream(file1)); BufferedInputStream file2Input = new BufferedInputStream(new java.io.FileInputStream(file2)); int charact1 = 0; int charact2 = 0; while (charact1 != -1) { if (charact1 == charact2) { charact1 = file1Input.read(); charact2 = file2Input.read(); } else { return false; } } return true; }
// in src/java/org/apache/fop/servlet/FopPrintServlet.java
protected void render(Source src, Transformer transformer, HttpServletResponse response) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_FOP_PRINT, foUserAgent); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer.transform(src, res); //Return the result reportOK(response); }
// in src/java/org/apache/fop/servlet/FopPrintServlet.java
private void reportOK(HttpServletResponse response) throws IOException { String sMsg = "<html><title>Success</title>\n" + "<body><h1>FopPrintServlet: </h1>" + "<h3>The requested data was printed to the default printer.</h3></body></html>"; response.setContentType("text/html"); response.setContentLength(sMsg.length()); PrintWriter out = response.getWriter(); out.println(sMsg); out.flush(); }
// in src/java/org/apache/fop/servlet/FopServlet.java
private void sendPDF(byte[] content, HttpServletResponse response) throws IOException { //Send the result back to the client response.setContentType("application/pdf"); response.setContentLength(content.length); response.getOutputStream().write(content); response.getOutputStream().flush(); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void renderFO(String fo, HttpServletResponse response) throws FOPException, TransformerException, IOException { //Setup source Source foSrc = convertString2Source(fo); //Setup the identity transformation Transformer transformer = this.transFactory.newTransformer(); transformer.setURIResolver(this.uriResolver); //Start transformation and rendering process render(foSrc, transformer, response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void renderXML(String xml, String xslt, HttpServletResponse response) throws FOPException, TransformerException, IOException { //Setup sources Source xmlSrc = convertString2Source(xml); Source xsltSrc = convertString2Source(xslt); //Setup the XSL transformation Transformer transformer = this.transFactory.newTransformer(xsltSrc); transformer.setURIResolver(this.uriResolver); //Start transformation and rendering process render(xmlSrc, transformer, response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void render(Source src, Transformer transformer, HttpServletResponse response) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(); //Setup output ByteArrayOutputStream out = new ByteArrayOutputStream(); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer.transform(src, res); //Return the result sendPDF(out.toByteArray(), response); }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java
public void setupDocument(OutputStream stream, int width, int height) throws IOException { this.width = width; this.height = height; pdfDoc.outputHeader(stream); setOutputStream(stream); }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java
protected void startPage() throws IOException { if (pdfContext.isPagePending()) { throw new IllegalStateException("Close page first before starting another"); } //Start page paintingState = new PDFPaintingState(); if (this.initialTransform == null) { //Save initial transformation matrix this.initialTransform = getTransform(); this.initialClip = getClip(); } else { //Reset transformation matrix setTransform(this.initialTransform); setClip(this.initialClip); } currentFontName = ""; currentFontSize = 0; if (currentStream == null) { currentStream = new StringWriter(); } PDFResources pdfResources = this.pdfDoc.getResources(); PDFPage page = this.pdfDoc.getFactory().makePage(pdfResources, width, height); resourceContext = page; pdfContext.setCurrentPage(page); pageRef = page.referencePDF(); currentStream.write("q\n"); AffineTransform at = new AffineTransform(1.0, 0.0, 0.0, -1.0, 0.0, height); currentStream.write("1 0 0 -1 0 " + height + " cm\n"); if (svgWidth != 0) { double scaleX = width / svgWidth; double scaleY = height / svgHeight; at.scale(scaleX, scaleY); currentStream.write("" + PDFNumber.doubleOut(scaleX) + " 0 0 " + PDFNumber.doubleOut(scaleY) + " 0 0 cm\n"); } if (deviceDPI != NORMAL_PDF_RESOLUTION) { double s = NORMAL_PDF_RESOLUTION / deviceDPI; at.scale(s, s); currentStream.write("" + PDFNumber.doubleOut(s) + " 0 0 " + PDFNumber.doubleOut(s) + " 0 0 cm\n"); scale(1 / s, 1 / s); } // Remember the transform we installed. paintingState.concatenate(at); pdfContext.increasePageCount(); }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java
public void finish() throws IOException { // restorePDFState(); closePage(); if (fontInfo != null) { pdfDoc.getResources().addFonts(pdfDoc, fontInfo); } this.pdfDoc.output(outputStream); pdfDoc.outputTrailer(outputStream); outputStream.flush(); }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
public TTFFile loadTTF(String fileName, String fontName, boolean useKerning, boolean useAdvanced) throws IOException { TTFFile ttfFile = new TTFFile(useKerning, useAdvanced); log.info("Reading " + fileName + "..."); FontFileReader reader = new FontFileReader(fileName); boolean supported = ttfFile.readFont(reader, fontName); if (!supported) { return null; } log.info("Font Family: " + ttfFile.getFamilyNames()); if (ttfFile.isCFF()) { throw new UnsupportedOperationException( "OpenType fonts with CFF data are not supported, yet"); } return ttfFile; }
// in src/java/org/apache/fop/fonts/apps/PFMReader.java
public PFMFile loadPFM(String filename) throws IOException { log.info("Reading " + filename + "..."); log.info(""); InputStream in = new java.io.FileInputStream(filename); try { PFMFile pfm = new PFMFile(); pfm.load(in); return pfm; } finally { in.close(); } }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static CustomFont loadFont(File fontFile, String subFontName, boolean embedded, EncodingMode encodingMode, FontResolver resolver) throws IOException { return loadFont(fontFile.toURI().toURL(), subFontName, embedded, encodingMode, resolver); }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static CustomFont loadFont(URL fontUrl, String subFontName, boolean embedded, EncodingMode encodingMode, FontResolver resolver) throws IOException { return loadFont(fontUrl.toExternalForm(), subFontName, embedded, encodingMode, true, true, resolver); }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static CustomFont loadFont(String fontFileURI, String subFontName, boolean embedded, EncodingMode encodingMode, boolean useKerning, boolean useAdvanced, FontResolver resolver) throws IOException { fontFileURI = fontFileURI.trim(); boolean type1 = isType1(fontFileURI); FontLoader loader; if (type1) { if (encodingMode == EncodingMode.CID) { throw new IllegalArgumentException( "CID encoding mode not supported for Type 1 fonts"); } loader = new Type1FontLoader(fontFileURI, embedded, useKerning, resolver); } else { loader = new TTFFontLoader(fontFileURI, subFontName, embedded, encodingMode, useKerning, useAdvanced, resolver); } return loader.getFont(); }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static InputStream openFontUri(FontResolver resolver, String uri) throws IOException, MalformedURLException { InputStream in = null; if (resolver != null) { Source source = resolver.resolve(uri); if (source == null) { String err = "Cannot load font: failed to create Source for font file " + uri; throw new IOException(err); } if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null && source.getSystemId() != null) { in = new java.net.URL(source.getSystemId()).openStream(); } if (in == null) { String err = "Cannot load font: failed to create InputStream from" + " Source for font file " + uri; throw new IOException(err); } } else { in = new URL(uri).openStream(); } return in; }
// in src/java/org/apache/fop/fonts/FontLoader.java
public CustomFont getFont() throws IOException { if (!loaded) { read(); } return this.returnFont; }
// in src/java/org/apache/fop/fonts/CustomFont.java
public Source getEmbedFileSource() throws IOException { Source result = null; if (resolver != null && embedFileName != null) { result = resolver.resolve(embedFileName); if (result == null) { throw new IOException("Unable to resolve Source '" + embedFileName + "' for embedded font"); } } return result; }
// in src/java/org/apache/fop/fonts/EmbedFontInfo.java
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); this.embedded = true; }
// in src/java/org/apache/fop/fonts/autodetect/WindowsFontDirFinder.java
private String getWinDir(String osName) throws IOException { Process process = null; Runtime runtime = Runtime.getRuntime(); if (osName.startsWith("Windows 9")) { process = runtime.exec("command.com /c echo %windir%"); } else { process = runtime.exec("cmd.exe /c echo %windir%"); } BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream())); return bufferedReader.readLine(); }
// in src/java/org/apache/fop/fonts/autodetect/FontFileFinder.java
public List<URL> find() throws IOException { final FontDirFinder fontDirFinder; final String osName = System.getProperty("os.name"); if (osName.startsWith("Windows")) { fontDirFinder = new WindowsFontDirFinder(); } else { if (osName.startsWith("Mac")) { fontDirFinder = new MacFontDirFinder(); } else { fontDirFinder = new UnixFontDirFinder(); } } List<File> fontDirs = fontDirFinder.find(); List<URL> results = new java.util.ArrayList<URL>(); for (File dir : fontDirs) { super.walk(dir, results); } return results; }
// in src/java/org/apache/fop/fonts/autodetect/FontFileFinder.java
public List<URL> find(String dir) throws IOException { List<URL> results = new java.util.ArrayList<URL>(); File directory = new File(dir); if (!directory.isDirectory()) { eventListener.fontDirectoryNotFound(this, dir); } else { super.walk(directory, results); } return results; }
// in src/java/org/apache/fop/fonts/type1/PFBData.java
public void outputAllParts(OutputStream out) throws IOException { out.write(this.headerSegment); out.write(this.encryptedSegment); out.write(this.trailerSegment); }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
Override protected void read() throws IOException { AFMFile afm = null; PFMFile pfm = null; InputStream afmIn = null; String afmUri = null; for (int i = 0; i < AFM_EXTENSIONS.length; i++) { try { afmUri = this.fontFileURI.substring(0, this.fontFileURI.length() - 4) + AFM_EXTENSIONS[i]; afmIn = openFontUri(resolver, afmUri); if (afmIn != null) { break; } } catch (IOException ioe) { // Ignore, AFM probably not available under the URI } } if (afmIn != null) { try { AFMParser afmParser = new AFMParser(); afm = afmParser.parse(afmIn, afmUri); } finally { IOUtils.closeQuietly(afmIn); } } String pfmUri = getPFMURI(this.fontFileURI); InputStream pfmIn = null; try { pfmIn = openFontUri(resolver, pfmUri); } catch (IOException ioe) { // Ignore, PFM probably not available under the URI } if (pfmIn != null) { try { pfm = new PFMFile(); pfm.load(pfmIn); } catch (IOException ioe) { if (afm == null) { // Ignore the exception if we have a valid PFM. PFM is only the fallback. throw ioe; } } finally { IOUtils.closeQuietly(pfmIn); } } if (afm == null && pfm == null) { throw new java.io.FileNotFoundException( "Neither an AFM nor a PFM file was found for " + this.fontFileURI); } buildFont(afm, pfm); this.loaded = true; }
// in src/java/org/apache/fop/fonts/type1/PFMInputStream.java
public short readByte() throws IOException { short s = datain.readByte(); // Now, we've got to trick Java into forgetting the sign int s1 = (((s & 0xF0) >>> 4) << 4) + (s & 0x0F); return (short)s1; }
// in src/java/org/apache/fop/fonts/type1/PFMInputStream.java
public int readShort() throws IOException { int i = datain.readShort(); // Change byte order int high = (i & 0xFF00) >>> 8; int low = (i & 0x00FF) << 8; return low + high; }
// in src/java/org/apache/fop/fonts/type1/PFMInputStream.java
public long readInt() throws IOException { int i = datain.readInt(); // Change byte order int i1 = (i & 0xFF000000) >>> 24; int i2 = (i & 0x00FF0000) >>> 8; int i3 = (i & 0x0000FF00) << 8; int i4 = (i & 0x000000FF) << 24; return i1 + i2 + i3 + i4; }
// in src/java/org/apache/fop/fonts/type1/PFMInputStream.java
public String readString() throws IOException { InputStreamReader reader = new InputStreamReader(in, "ISO-8859-1"); StringBuffer buf = new StringBuffer(); int ch = reader.read(); while (ch > 0) { buf.append((char)ch); ch = reader.read(); } if (ch == -1) { throw new EOFException("Unexpected end of stream reached"); } return buf.toString(); }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
public PFBData parsePFB(java.net.URL url) throws IOException { InputStream in = url.openStream(); try { return parsePFB(in); } finally { in.close(); } }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
public PFBData parsePFB(java.io.File pfbFile) throws IOException { InputStream in = new java.io.FileInputStream(pfbFile); try { return parsePFB(in); } finally { in.close(); } }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
public PFBData parsePFB(InputStream in) throws IOException { PFBData pfb = new PFBData(); BufferedInputStream bin = new BufferedInputStream(in); DataInputStream din = new DataInputStream(bin); din.mark(32); int firstByte = din.readUnsignedByte(); din.reset(); if (firstByte == 128) { pfb.setPFBFormat(PFBData.PFB_PC); parsePCFormat(pfb, din); } else { pfb.setPFBFormat(PFBData.PFB_RAW); parseRAWFormat(pfb, bin); } return pfb; }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
private void parsePCFormat(PFBData pfb, DataInputStream din) throws IOException { int segmentHead; int segmentType; int bytesRead; //Read first segment segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); //Read int len1 = swapInteger(din.readInt()); byte[] headerSegment = new byte[len1]; din.readFully(headerSegment); pfb.setHeaderSegment(headerSegment); //Read second segment segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); int len2 = swapInteger(din.readInt()); byte[] encryptedSegment = new byte[len2]; din.readFully(encryptedSegment); pfb.setEncryptedSegment(encryptedSegment); //Read third segment segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); int len3 = swapInteger(din.readInt()); byte[] trailerSegment = new byte[len3]; din.readFully(trailerSegment); pfb.setTrailerSegment(trailerSegment); //Read EOF indicator segmentHead = din.readUnsignedByte(); if (segmentHead != 128) { throw new IOException("Invalid file format. Expected ASCII 80hex"); } segmentType = din.readUnsignedByte(); if (segmentType != 3) { throw new IOException("Expected segment type 3, but found: " + segmentType); } }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
private void parseRAWFormat(PFBData pfb, BufferedInputStream bin) throws IOException { calcLengths(pfb, IOUtils.toByteArray(bin)); }
// in src/java/org/apache/fop/fonts/type1/CharMetricsHandler.java
AFMCharMetrics parse(String line, Stack<Object> stack, String afmFileName) throws IOException { AFMCharMetrics chm = new AFMCharMetrics(); stack.push(chm); String[] metrics = SPLIT_REGEX.split(line); for (String metric : metrics) { Matcher matcher = METRICS_REGEX.matcher(metric); if (matcher.matches()) { String operator = matcher.group(1); String operands = matcher.group(2); ValueHandler handler = valueParsers.get(operator); if (handler != null) { handler.parse(operands, 0, stack); } } } stack.pop(); return chm; }
// in src/java/org/apache/fop/fonts/type1/CharMetricsHandler.java
AFMCharMetrics parse(String line, Stack<Object> stack, String afmFileName) throws IOException { AFMCharMetrics chm = defaultHandler.parse(line, stack, afmFileName); NamedCharacter namedChar = chm.getCharacter(); if (namedChar != null) { int codePoint = AdobeStandardEncoding.getAdobeCodePoint(namedChar.getName()); if (chm.getCharCode() != codePoint) { LOG.info(afmFileName + ": named character '" + namedChar.getName() + "'" + " has an incorrect code point: " + chm.getCharCode() + ". Changed to " + codePoint); chm.setCharCode(codePoint); } } return chm; }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
public void load(InputStream inStream) throws IOException { byte[] pfmBytes = IOUtils.toByteArray(inStream); InputStream bufin = inStream; bufin = new ByteArrayInputStream(pfmBytes); PFMInputStream in = new PFMInputStream(bufin); bufin.mark(512); short sh1 = in.readByte(); short sh2 = in.readByte(); if (sh1 == 128 && sh2 == 1) { //Found the first section header of a PFB file! throw new IOException("Cannot parse PFM file. You probably specified the PFB file" + " of a Type 1 font as parameter instead of the PFM."); } bufin.reset(); byte[] b = new byte[16]; bufin.read(b); if (new String(b, "US-ASCII").equalsIgnoreCase("StartFontMetrics")) { //Found the header of a AFM file! throw new IOException("Cannot parse PFM file. You probably specified the AFM file" + " of a Type 1 font as parameter instead of the PFM."); } bufin.reset(); final int version = in.readShort(); if (version != 256) { log.warn("PFM version expected to be '256' but got '" + version + "'." + " Please make sure you specify the PFM as parameter" + " and not the PFB or the AFM."); } //final long filesize = in.readInt(); bufin.reset(); loadHeader(in); loadExtension(in); }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
private void loadHeader(PFMInputStream inStream) throws IOException { inStream.skip(80); dfItalic = inStream.readByte(); inStream.skip(2); dfWeight = inStream.readShort(); dfCharSet = inStream.readByte(); inStream.skip(4); dfPitchAndFamily = inStream.readByte(); dfAvgWidth = inStream.readShort(); dfMaxWidth = inStream.readShort(); dfFirstChar = inStream.readByte(); dfLastChar = inStream.readByte(); inStream.skip(8); long faceOffset = inStream.readInt(); inStream.reset(); inStream.skip(faceOffset); windowsName = inStream.readString(); inStream.reset(); inStream.skip(117); }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
private void loadExtension(PFMInputStream inStream) throws IOException { final int size = inStream.readShort(); if (size != 30) { log.warn("Size of extension block was expected to be " + "30 bytes, but was " + size + " bytes."); } final long extMetricsOffset = inStream.readInt(); final long extentTableOffset = inStream.readInt(); inStream.skip(4); //Skip dfOriginTable final long kernPairOffset = inStream.readInt(); inStream.skip(4); //Skip dfTrackKernTable long driverInfoOffset = inStream.readInt(); if (kernPairOffset > 0) { inStream.reset(); inStream.skip(kernPairOffset); loadKernPairs(inStream); } inStream.reset(); inStream.skip(driverInfoOffset); postscriptName = inStream.readString(); if (extMetricsOffset != 0) { inStream.reset(); inStream.skip(extMetricsOffset); loadExtMetrics(inStream); } if (extentTableOffset != 0) { inStream.reset(); inStream.skip(extentTableOffset); loadExtentTable(inStream); } }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
private void loadKernPairs(PFMInputStream inStream) throws IOException { int i = inStream.readShort(); if (log.isTraceEnabled()) { log.trace(i + " kerning pairs"); } while (i > 0) { int g1 = (int)inStream.readByte(); i--; int g2 = (int)inStream.readByte(); int adj = inStream.readShort(); if (adj > 0x8000) { adj = -(0x10000 - adj); } if (log.isTraceEnabled()) { log.trace("Char no: (" + g1 + ", " + g2 + ") kern: " + adj); final String glyph1 = Glyphs.TEX8R_GLYPH_NAMES[g1]; final String glyph2 = Glyphs.TEX8R_GLYPH_NAMES[g2]; log.trace("glyphs: " + glyph1 + ", " + glyph2); } Map adjTab = (Map)kerningTab.get(new Integer(g1)); if (adjTab == null) { adjTab = new java.util.HashMap(); } adjTab.put(new Integer(g2), new Integer(adj)); kerningTab.put(new Integer(g1), adjTab); } }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
private void loadExtMetrics(PFMInputStream inStream) throws IOException { final int size = inStream.readShort(); if (size != 52) { log.warn("Size of extension block was expected to be " + "52 bytes, but was " + size + " bytes."); } inStream.skip(12); //Skip etmPointSize, etmOrientation, etmMasterHeight, //etmMinScale, etmMaxScale, emtMasterUnits etmCapHeight = inStream.readShort(); etmXHeight = inStream.readShort(); etmLowerCaseAscent = inStream.readShort(); etmLowerCaseDescent = -(inStream.readShort()); //Ignore the rest of the values }
// in src/java/org/apache/fop/fonts/type1/PFMFile.java
private void loadExtentTable(PFMInputStream inStream) throws IOException { extentTable = new int[dfLastChar - dfFirstChar + 1]; dfMinWidth = dfMaxWidth; for (short i = dfFirstChar; i <= dfLastChar; i++) { extentTable[i - dfFirstChar] = inStream.readShort(); if (extentTable[i - dfFirstChar] < dfMinWidth) { dfMinWidth = extentTable[i - dfFirstChar]; } } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public AFMFile parse(InputStream in, String afmFileName) throws IOException { Reader reader = new java.io.InputStreamReader(in, "US-ASCII"); try { return parse(new BufferedReader(reader), afmFileName); } finally { IOUtils.closeQuietly(reader); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public AFMFile parse(BufferedReader reader, String afmFileName) throws IOException { Stack<Object> stack = new Stack<Object>(); int parseMode = PARSE_NORMAL; while (true) { String line = reader.readLine(); if (line == null) { break; } String key = null; switch (parseMode) { case PARSE_NORMAL: key = parseLine(line, stack); break; case PARSE_CHAR_METRICS: key = parseCharMetrics(line, stack, afmFileName); break; default: throw new IllegalStateException("Invalid parse mode"); } Integer newParseMode = PARSE_MODE_CHANGES.get(key); if (newParseMode != null) { parseMode = newParseMode.intValue(); } } return (AFMFile)stack.pop(); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
private String parseLine(String line, Stack<Object> stack) throws IOException { int startpos = 0; //Find key startpos = skipToNonWhiteSpace(line, startpos); int endpos = skipToWhiteSpace(line, startpos); String key = line.substring(startpos, endpos); //Parse value startpos = skipToNonWhiteSpace(line, endpos); ValueHandler vp = VALUE_PARSERS.get(key); if (vp != null) { vp.parse(line, startpos, stack); } return key; }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
private String parseCharMetrics(String line, Stack<Object> stack, String afmFileName) throws IOException { String trimmedLine = line.trim(); if (END_CHAR_METRICS.equals(trimmedLine)) { return trimmedLine; } AFMFile afm = (AFMFile) stack.peek(); String encoding = afm.getEncodingScheme(); CharMetricsHandler charMetricsHandler = CharMetricsHandler.getHandler(VALUE_PARSERS, encoding); AFMCharMetrics chm = charMetricsHandler.parse(trimmedLine, stack, afmFileName); afm.addCharMetrics(chm); return null; }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { int endpos = findValue(line, startpos); double version = Double.parseDouble(line.substring(startpos, endpos)); if (version < 2) { throw new IOException( "AFM version must be at least 2.0 but it is " + version + "!"); } AFMFile afm = new AFMFile(); stack.push(afm); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { String s = getStringValue(line, startpos); Object obj = stack.peek(); setValue(obj, String.class, s); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { NamedCharacter ch = new NamedCharacter(getStringValue(line, startpos)); Object obj = stack.peek(); setValue(obj, NamedCharacter.class, ch); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { Number num = getNumberValue(line, startpos); setValue(getContextObject(stack), Number.class, num); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { int value = getIntegerValue(line, startpos); setValue(getContextObject(stack), int.class, new Integer(value)); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { double value = getDoubleValue(line, startpos); setValue(getContextObject(stack), double.class, new Double(value)); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { double value = getDoubleValue(line, startpos); setValue(getContextObject(stack), double.class, new Double(value)); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { Boolean b = getBooleanValue(line, startpos); Object target = getContextObject(stack); Class<?> c = target.getClass(); try { Method mth = c.getMethod(method, boolean.class); mth.invoke(target, b); } catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { Rectangle rect = parseBBox(line, startpos); AFMFile afm = (AFMFile)stack.peek(); afm.setFontBBox(rect); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { Rectangle rect = parseBBox(line, startpos); AFMCharMetrics metrics = (AFMCharMetrics)stack.peek(); metrics.setBBox(rect); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { if (getBooleanValue(line, startpos).booleanValue()) { throw new IOException("Only base fonts are currently supported!"); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { if (getBooleanValue(line, startpos).booleanValue()) { throw new IOException("CID fonts are currently not supported!"); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack stack) throws IOException { log.warn("Support for '" + key + "' has not been implemented, yet!" + " Some font data in the AFM file will be ignored."); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { int index = getIntegerValue(line, startpos); AFMWritingDirectionMetrics wdm = new AFMWritingDirectionMetrics(); AFMFile afm = (AFMFile)stack.peek(); afm.setWritingDirectionMetrics(index, wdm); stack.push(wdm); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { if (!(stack.pop() instanceof AFMWritingDirectionMetrics)) { throw new IOException("AFM format error: nesting incorrect"); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { AFMFile afm = (AFMFile)stack.peek(); int endpos; endpos = findValue(line, startpos); String name1 = line.substring(startpos, endpos); startpos = skipToNonWhiteSpace(line, endpos); endpos = findValue(line, startpos); String name2 = line.substring(startpos, endpos); startpos = skipToNonWhiteSpace(line, endpos); endpos = findValue(line, startpos); double kx = Double.parseDouble(line.substring(startpos, endpos)); startpos = skipToNonWhiteSpace(line, endpos); afm.addXKerning(name1, name2, kx); }
// in src/java/org/apache/fop/fonts/truetype/TTFDirTabEntry.java
public String read(FontFileReader in) throws IOException { tag[0] = in.readTTFByte(); tag[1] = in.readTTFByte(); tag[2] = in.readTTFByte(); tag[3] = in.readTTFByte(); in.skip(4); // Skip checksum offset = in.readTTFULong(); length = in.readTTFULong(); String tagStr = new String(tag, "ISO-8859-1"); return tagStr; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
public boolean seekTab(FontFileReader in, String name, long offset) throws IOException { TTFDirTabEntry dt = getDirectoryEntry ( name ); if (dt == null) { log.error("Dirtab " + name + " not found."); return false; } else { in.seekSet(dt.getOffset() + offset); this.currentDirTab = dt; } return true; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private boolean readCMAP(FontFileReader in) throws IOException { unicodeMappings = new java.util.TreeSet(); seekTab(in, "cmap", 2); int numCMap = in.readTTFUShort(); // Number of cmap subtables long cmapUniOffset = 0; long symbolMapOffset = 0; if (log.isDebugEnabled()) { log.debug(numCMap + " cmap tables"); } //Read offset for all tables. We are only interested in the unicode table for (int i = 0; i < numCMap; i++) { int cmapPID = in.readTTFUShort(); int cmapEID = in.readTTFUShort(); long cmapOffset = in.readTTFULong(); if (log.isDebugEnabled()) { log.debug("Platform ID: " + cmapPID + " Encoding: " + cmapEID); } if (cmapPID == 3 && cmapEID == 1) { cmapUniOffset = cmapOffset; } if (cmapPID == 3 && cmapEID == 0) { symbolMapOffset = cmapOffset; } } if (cmapUniOffset > 0) { return readUnicodeCmap(in, cmapUniOffset, 1); } else if (symbolMapOffset > 0) { return readUnicodeCmap(in, symbolMapOffset, 0); } else { log.fatal("Unsupported TrueType font: No Unicode or Symbol cmap table" + " not present. Aborting"); return false; } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private boolean readUnicodeCmap // CSOK: MethodLength (FontFileReader in, long cmapUniOffset, int encodingID) throws IOException { //Read CMAP table and correct mtxTab.index int mtxPtr = 0; // Read unicode cmap seekTab(in, "cmap", cmapUniOffset); int cmapFormat = in.readTTFUShort(); /*int cmap_length =*/ in.readTTFUShort(); //skip cmap length if (log.isDebugEnabled()) { log.debug("CMAP format: " + cmapFormat); } if (cmapFormat == 4) { in.skip(2); // Skip version number int cmapSegCountX2 = in.readTTFUShort(); int cmapSearchRange = in.readTTFUShort(); int cmapEntrySelector = in.readTTFUShort(); int cmapRangeShift = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug("segCountX2 : " + cmapSegCountX2); log.debug("searchRange : " + cmapSearchRange); log.debug("entrySelector: " + cmapEntrySelector); log.debug("rangeShift : " + cmapRangeShift); } int[] cmapEndCounts = new int[cmapSegCountX2 / 2]; int[] cmapStartCounts = new int[cmapSegCountX2 / 2]; int[] cmapDeltas = new int[cmapSegCountX2 / 2]; int[] cmapRangeOffsets = new int[cmapSegCountX2 / 2]; for (int i = 0; i < (cmapSegCountX2 / 2); i++) { cmapEndCounts[i] = in.readTTFUShort(); } in.skip(2); // Skip reservedPad for (int i = 0; i < (cmapSegCountX2 / 2); i++) { cmapStartCounts[i] = in.readTTFUShort(); } for (int i = 0; i < (cmapSegCountX2 / 2); i++) { cmapDeltas[i] = in.readTTFShort(); } //int startRangeOffset = in.getCurrentPos(); for (int i = 0; i < (cmapSegCountX2 / 2); i++) { cmapRangeOffsets[i] = in.readTTFUShort(); } int glyphIdArrayOffset = in.getCurrentPos(); BitSet eightBitGlyphs = new BitSet(256); // Insert the unicode id for the glyphs in mtxTab // and fill in the cmaps ArrayList for (int i = 0; i < cmapStartCounts.length; i++) { if (log.isTraceEnabled()) { log.trace(i + ": " + cmapStartCounts[i] + " - " + cmapEndCounts[i]); } if (log.isDebugEnabled()) { if (isInPrivateUseArea(cmapStartCounts[i], cmapEndCounts[i])) { log.debug("Font contains glyphs in the Unicode private use area: " + Integer.toHexString(cmapStartCounts[i]) + " - " + Integer.toHexString(cmapEndCounts[i])); } } for (int j = cmapStartCounts[i]; j <= cmapEndCounts[i]; j++) { // Update lastChar if (j < 256 && j > lastChar) { lastChar = (short)j; } if (j < 256) { eightBitGlyphs.set(j); } if (mtxPtr < mtxTab.length) { int glyphIdx; // the last character 65535 = .notdef // may have a range offset if (cmapRangeOffsets[i] != 0 && j != 65535) { int glyphOffset = glyphIdArrayOffset + ((cmapRangeOffsets[i] / 2) + (j - cmapStartCounts[i]) + (i) - cmapSegCountX2 / 2) * 2; in.seekSet(glyphOffset); glyphIdx = (in.readTTFUShort() + cmapDeltas[i]) & 0xffff; unicodeMappings.add(new UnicodeMapping(glyphIdx, j)); mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j)); // Also add winAnsiWidth List v = (List)ansiIndex.get(new Integer(j)); if (v != null) { Iterator e = v.listIterator(); while (e.hasNext()) { Integer aIdx = (Integer)e.next(); ansiWidth[aIdx.intValue()] = mtxTab[glyphIdx].getWx(); if (log.isTraceEnabled()) { log.trace("Added width " + mtxTab[glyphIdx].getWx() + " uni: " + j + " ansi: " + aIdx.intValue()); } } } if (log.isTraceEnabled()) { log.trace("Idx: " + glyphIdx + " Delta: " + cmapDeltas[i] + " Unicode: " + j + " name: " + mtxTab[glyphIdx].getName()); } } else { glyphIdx = (j + cmapDeltas[i]) & 0xffff; if (glyphIdx < mtxTab.length) { mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j)); } else { log.debug("Glyph " + glyphIdx + " out of range: " + mtxTab.length); } unicodeMappings.add(new UnicodeMapping(glyphIdx, j)); if (glyphIdx < mtxTab.length) { mtxTab[glyphIdx].getUnicodeIndex().add(new Integer(j)); } else { log.debug("Glyph " + glyphIdx + " out of range: " + mtxTab.length); } // Also add winAnsiWidth List v = (List)ansiIndex.get(new Integer(j)); if (v != null) { Iterator e = v.listIterator(); while (e.hasNext()) { Integer aIdx = (Integer)e.next(); ansiWidth[aIdx.intValue()] = mtxTab[glyphIdx].getWx(); } } //getLogger().debug("IIdx: " + // mtxPtr + // " Delta: " + cmap_deltas[i] + // " Unicode: " + j + // " name: " + // mtxTab[(j+cmap_deltas[i]) & 0xffff].name); } if (glyphIdx < mtxTab.length) { if (mtxTab[glyphIdx].getUnicodeIndex().size() < 2) { mtxPtr++; } } } } } } else { log.error("Cmap format not supported: " + cmapFormat); return false; } return true; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
public void readFont(FontFileReader in) throws IOException { readFont(in, (String)null); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
public boolean readFont(FontFileReader in, String name) throws IOException { /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(in, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(in); readFontHeader(in); getNumGlyphs(in); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(in); readHorizontalMetrics(in); initAnsiWidths(); readPostScript(in); readOS2(in); determineAscDesc(); if (!isCFF) { readIndexToLocation(in); readGlyf(in); } readName(in); boolean pcltFound = readPCLT(in); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(in); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); if ( useKerning ) { readKerning(in); } // Read advanced typographic tables. if ( useAdvanced ) { try { OTFAdvancedTypographicTableReader atr = new OTFAdvancedTypographicTableReader ( this, in ); atr.readAll(); this.advancedTableReader = atr; } catch ( AdvancedTypographicTableFormatException e ) { log.warn ( "Encountered format constraint violation in advanced (typographic) table (AT) " + "in font '" + getFullName() + "', ignoring AT data: " + e.getMessage() ); } } guessVerticalMetricsFromGlyphBBox(); return true; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected void readDirTabs(FontFileReader in) throws IOException { int sfntVersion = in.readTTFLong(); // TTF_FIXED_SIZE (4 bytes) switch (sfntVersion) { case 0x10000: log.debug("sfnt version: OpenType 1.0"); break; case 0x4F54544F: //"OTTO" this.isCFF = true; log.debug("sfnt version: OpenType with CFF data"); break; case 0x74727565: //"true" log.debug("sfnt version: Apple TrueType"); break; case 0x74797031: //"typ1" log.debug("sfnt version: Apple Type 1 housed in sfnt wrapper"); break; default: log.debug("Unknown sfnt version: " + Integer.toHexString(sfntVersion)); break; } int ntabs = in.readTTFUShort(); in.skip(6); // 3xTTF_USHORT_SIZE dirTabs = new java.util.HashMap(); TTFDirTabEntry[] pd = new TTFDirTabEntry[ntabs]; log.debug("Reading " + ntabs + " dir tables"); for (int i = 0; i < ntabs; i++) { pd[i] = new TTFDirTabEntry(); dirTabs.put(pd[i].read(in), pd[i]); } log.debug("dir tables: " + dirTabs.keySet()); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected void readFontHeader(FontFileReader in) throws IOException { seekTab(in, "head", 2 * 4 + 2 * 4); int flags = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug("flags: " + flags + " - " + Integer.toString(flags, 2)); } upem = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug("unit per em: " + upem); } in.skip(16); fontBBox1 = in.readTTFShort(); fontBBox2 = in.readTTFShort(); fontBBox3 = in.readTTFShort(); fontBBox4 = in.readTTFShort(); if (log.isDebugEnabled()) { log.debug("font bbox: xMin=" + fontBBox1 + " yMin=" + fontBBox2 + " xMax=" + fontBBox3 + " yMax=" + fontBBox4); } in.skip(2 + 2 + 2); locaFormat = in.readTTFShort(); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected void getNumGlyphs(FontFileReader in) throws IOException { seekTab(in, "maxp", 4); numberOfGlyphs = in.readTTFUShort(); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected void readHorizontalHeader(FontFileReader in) throws IOException { seekTab(in, "hhea", 4); hheaAscender = in.readTTFShort(); hheaDescender = in.readTTFShort(); in.skip(2 + 2 + 3 * 2 + 8 * 2); nhmtx = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug("hhea.Ascender: " + formatUnitsForDebug(hheaAscender)); log.debug("hhea.Descender: " + formatUnitsForDebug(hheaDescender)); log.debug("Number of horizontal metrics: " + nhmtx); } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected void readHorizontalMetrics(FontFileReader in) throws IOException { seekTab(in, "hmtx", 0); int mtxSize = Math.max(numberOfGlyphs, nhmtx); mtxTab = new TTFMtxEntry[mtxSize]; if (log.isTraceEnabled()) { log.trace("*** Widths array: \n"); } for (int i = 0; i < mtxSize; i++) { mtxTab[i] = new TTFMtxEntry(); } for (int i = 0; i < nhmtx; i++) { mtxTab[i].setWx(in.readTTFUShort()); mtxTab[i].setLsb(in.readTTFUShort()); if (log.isTraceEnabled()) { log.trace(" width[" + i + "] = " + convertTTFUnit2PDFUnit(mtxTab[i].getWx()) + ";"); } } if (nhmtx < mtxSize) { // Fill in the missing widths int lastWidth = mtxTab[nhmtx - 1].getWx(); for (int i = nhmtx; i < mtxSize; i++) { mtxTab[i].setWx(lastWidth); mtxTab[i].setLsb(in.readTTFUShort()); } } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private void readPostScript(FontFileReader in) throws IOException { seekTab(in, "post", 0); postFormat = in.readTTFLong(); italicAngle = in.readTTFULong(); underlinePosition = in.readTTFShort(); underlineThickness = in.readTTFShort(); isFixedPitch = in.readTTFULong(); //Skip memory usage values in.skip(4 * 4); log.debug("PostScript format: 0x" + Integer.toHexString(postFormat)); switch (postFormat) { case 0x00010000: log.debug("PostScript format 1"); for (int i = 0; i < Glyphs.MAC_GLYPH_NAMES.length; i++) { mtxTab[i].setName(Glyphs.MAC_GLYPH_NAMES[i]); } break; case 0x00020000: log.debug("PostScript format 2"); int numGlyphStrings = 0; // Read Number of Glyphs int l = in.readTTFUShort(); // Read indexes for (int i = 0; i < l; i++) { mtxTab[i].setIndex(in.readTTFUShort()); if (mtxTab[i].getIndex() > 257) { //Index is not in the Macintosh standard set numGlyphStrings++; } if (log.isTraceEnabled()) { log.trace("PostScript index: " + mtxTab[i].getIndexAsString()); } } // firstChar=minIndex; String[] psGlyphsBuffer = new String[numGlyphStrings]; if (log.isDebugEnabled()) { log.debug("Reading " + numGlyphStrings + " glyphnames, that are not in the standard Macintosh" + " set. Total number of glyphs=" + l); } for (int i = 0; i < psGlyphsBuffer.length; i++) { psGlyphsBuffer[i] = in.readTTFString(in.readTTFUByte()); } //Set glyph names for (int i = 0; i < l; i++) { if (mtxTab[i].getIndex() < NMACGLYPHS) { mtxTab[i].setName(Glyphs.MAC_GLYPH_NAMES[mtxTab[i].getIndex()]); } else { if (!mtxTab[i].isIndexReserved()) { int k = mtxTab[i].getIndex() - NMACGLYPHS; if (log.isTraceEnabled()) { log.trace(k + " i=" + i + " mtx=" + mtxTab.length + " ps=" + psGlyphsBuffer.length); } mtxTab[i].setName(psGlyphsBuffer[k]); } } } break; case 0x00030000: // PostScript format 3 contains no glyph names log.debug("PostScript format 3"); break; default: log.error("Unknown PostScript format: " + postFormat); } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private void readOS2(FontFileReader in) throws IOException { // Check if font is embeddable TTFDirTabEntry os2Entry = getDirectoryEntry ( "OS/2" ); if (os2Entry != null) { seekTab(in, "OS/2", 0); int version = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug("OS/2 table: version=" + version + ", offset=" + os2Entry.getOffset() + ", len=" + os2Entry.getLength()); } in.skip(2); //xAvgCharWidth this.usWeightClass = in.readTTFUShort(); // usWidthClass in.skip(2); int fsType = in.readTTFUShort(); if (fsType == 2) { isEmbeddable = false; } else { isEmbeddable = true; } in.skip(11 * 2); in.skip(10); //panose array in.skip(4 * 4); //unicode ranges in.skip(4); in.skip(3 * 2); int v; os2Ascender = in.readTTFShort(); //sTypoAscender os2Descender = in.readTTFShort(); //sTypoDescender if (log.isDebugEnabled()) { log.debug("sTypoAscender: " + os2Ascender + " -> internal " + convertTTFUnit2PDFUnit(os2Ascender)); log.debug("sTypoDescender: " + os2Descender + " -> internal " + convertTTFUnit2PDFUnit(os2Descender)); } v = in.readTTFShort(); //sTypoLineGap if (log.isDebugEnabled()) { log.debug("sTypoLineGap: " + v); } v = in.readTTFUShort(); //usWinAscent if (log.isDebugEnabled()) { log.debug("usWinAscent: " + formatUnitsForDebug(v)); } v = in.readTTFUShort(); //usWinDescent if (log.isDebugEnabled()) { log.debug("usWinDescent: " + formatUnitsForDebug(v)); } //version 1 OS/2 table might end here if (os2Entry.getLength() >= 78 + (2 * 4) + (2 * 2)) { in.skip(2 * 4); this.os2xHeight = in.readTTFShort(); //sxHeight this.os2CapHeight = in.readTTFShort(); //sCapHeight if (log.isDebugEnabled()) { log.debug("sxHeight: " + this.os2xHeight); log.debug("sCapHeight: " + this.os2CapHeight); } } } else { isEmbeddable = true; } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected final void readIndexToLocation(FontFileReader in) throws IOException { if (!seekTab(in, "loca", 0)) { throw new IOException("'loca' table not found, happens when the font file doesn't" + " contain TrueType outlines (trying to read an OpenType CFF font maybe?)"); } for (int i = 0; i < numberOfGlyphs; i++) { mtxTab[i].setOffset(locaFormat == 1 ? in.readTTFULong() : (in.readTTFUShort() << 1)); } lastLoca = (locaFormat == 1 ? in.readTTFULong() : (in.readTTFUShort() << 1)); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private void readGlyf(FontFileReader in) throws IOException { TTFDirTabEntry dirTab = getDirectoryEntry ( "glyf" ); if (dirTab == null) { throw new IOException("glyf table not found, cannot continue"); } for (int i = 0; i < (numberOfGlyphs - 1); i++) { if (mtxTab[i].getOffset() != mtxTab[i + 1].getOffset()) { in.seekSet(dirTab.getOffset() + mtxTab[i].getOffset()); in.skip(2); final int[] bbox = { in.readTTFShort(), in.readTTFShort(), in.readTTFShort(), in.readTTFShort()}; mtxTab[i].setBoundingBox(bbox); } else { mtxTab[i].setBoundingBox(mtxTab[0].getBoundingBox()); } } long n = dirTab.getOffset(); for (int i = 0; i < numberOfGlyphs; i++) { if ((i + 1) >= mtxTab.length || mtxTab[i].getOffset() != mtxTab[i + 1].getOffset()) { in.seekSet(n + mtxTab[i].getOffset()); in.skip(2); final int[] bbox = { in.readTTFShort(), in.readTTFShort(), in.readTTFShort(), in.readTTFShort()}; mtxTab[i].setBoundingBox(bbox); } else { /**@todo Verify that this is correct, looks like a copy/paste bug (jm)*/ final int bbox0 = mtxTab[0].getBoundingBox()[0]; final int[] bbox = {bbox0, bbox0, bbox0, bbox0}; mtxTab[i].setBoundingBox(bbox); /* Original code mtxTab[i].bbox[0] = mtxTab[0].bbox[0]; mtxTab[i].bbox[1] = mtxTab[0].bbox[0]; mtxTab[i].bbox[2] = mtxTab[0].bbox[0]; mtxTab[i].bbox[3] = mtxTab[0].bbox[0]; */ } if (log.isTraceEnabled()) { log.trace(mtxTab[i].toString(this)); } } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private void readName(FontFileReader in) throws IOException { seekTab(in, "name", 2); int i = in.getCurrentPos(); int n = in.readTTFUShort(); int j = in.readTTFUShort() + i - 2; i += 2 * 2; while (n-- > 0) { // getLogger().debug("Iteration: " + n); in.seekSet(i); final int platformID = in.readTTFUShort(); final int encodingID = in.readTTFUShort(); final int languageID = in.readTTFUShort(); int k = in.readTTFUShort(); int l = in.readTTFUShort(); if (((platformID == 1 || platformID == 3) && (encodingID == 0 || encodingID == 1))) { in.seekSet(j + in.readTTFUShort()); String txt; if (platformID == 3) { txt = in.readTTFString(l, encodingID); } else { txt = in.readTTFString(l); } if (log.isDebugEnabled()) { log.debug(platformID + " " + encodingID + " " + languageID + " " + k + " " + txt); } switch (k) { case 0: if (notice.length() == 0) { notice = txt; } break; case 1: //Font Family Name case 16: //Preferred Family familyNames.add(txt); break; case 2: if (subFamilyName.length() == 0) { subFamilyName = txt; } break; case 4: if (fullName.length() == 0 || (platformID == 3 && languageID == 1033)) { fullName = txt; } break; case 6: if (postScriptName.length() == 0) { postScriptName = txt; } break; default: break; } } i += 6 * 2; } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private boolean readPCLT(FontFileReader in) throws IOException { TTFDirTabEntry dirTab = getDirectoryEntry ( "PCLT" ); if (dirTab != null) { in.seekSet(dirTab.getOffset() + 4 + 4 + 2); xHeight = in.readTTFUShort(); log.debug("xHeight from PCLT: " + formatUnitsForDebug(xHeight)); in.skip(2 * 2); capHeight = in.readTTFUShort(); log.debug("capHeight from PCLT: " + formatUnitsForDebug(capHeight)); in.skip(2 + 16 + 8 + 6 + 1 + 1); int serifStyle = in.readTTFUByte(); serifStyle = serifStyle >> 6; serifStyle = serifStyle & 3; if (serifStyle == 1) { hasSerifs = false; } else { hasSerifs = true; } return true; } else { return false; } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private void readKerning(FontFileReader in) throws IOException { // Read kerning kerningTab = new java.util.HashMap(); ansiKerningTab = new java.util.HashMap(); TTFDirTabEntry dirTab = getDirectoryEntry ( "kern" ); if (dirTab != null) { seekTab(in, "kern", 2); for (int n = in.readTTFUShort(); n > 0; n--) { in.skip(2 * 2); int k = in.readTTFUShort(); if (!((k & 1) != 0) || (k & 2) != 0 || (k & 4) != 0) { return; } if ((k >> 8) != 0) { continue; } k = in.readTTFUShort(); in.skip(3 * 2); while (k-- > 0) { int i = in.readTTFUShort(); int j = in.readTTFUShort(); int kpx = in.readTTFShort(); if (kpx != 0) { // CID kerning table entry, using unicode indexes final Integer iObj = glyphToUnicode(i); final Integer u2 = glyphToUnicode(j); if (iObj == null) { // happens for many fonts (Ubuntu font set), // stray entries in the kerning table?? log.debug("Ignoring kerning pair because no Unicode index was" + " found for the first glyph " + i); } else if (u2 == null) { log.debug("Ignoring kerning pair because Unicode index was" + " found for the second glyph " + i); } else { Map adjTab = kerningTab.get(iObj); if (adjTab == null) { adjTab = new java.util.HashMap(); } adjTab.put(u2, new Integer(convertTTFUnit2PDFUnit(kpx))); kerningTab.put(iObj, adjTab); } } } } // Create winAnsiEncoded kerning table from kerningTab // (could probably be simplified, for now we remap back to CID indexes and // then to winAnsi) Iterator ae = kerningTab.keySet().iterator(); while (ae.hasNext()) { Integer unicodeKey1 = (Integer)ae.next(); Integer cidKey1 = unicodeToGlyph(unicodeKey1.intValue()); Map<Integer, Integer> akpx = new java.util.HashMap(); Map ckpx = kerningTab.get(unicodeKey1); Iterator aee = ckpx.keySet().iterator(); while (aee.hasNext()) { Integer unicodeKey2 = (Integer)aee.next(); Integer cidKey2 = unicodeToGlyph(unicodeKey2.intValue()); Integer kern = (Integer)ckpx.get(unicodeKey2); Iterator uniMap = mtxTab[cidKey2.intValue()].getUnicodeIndex().listIterator(); while (uniMap.hasNext()) { Integer unicodeKey = (Integer)uniMap.next(); Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue()); for (int u = 0; u < ansiKeys.length; u++) { akpx.put(ansiKeys[u], kern); } } } if (akpx.size() > 0) { Iterator uniMap = mtxTab[cidKey1.intValue()].getUnicodeIndex().listIterator(); while (uniMap.hasNext()) { Integer unicodeKey = (Integer)uniMap.next(); Integer[] ansiKeys = unicodeToWinAnsi(unicodeKey.intValue()); for (int u = 0; u < ansiKeys.length; u++) { ansiKerningTab.put(ansiKeys[u], akpx); } } } } } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
protected final boolean checkTTC(FontFileReader in, String name) throws IOException { String tag = in.readTTFString(4); if ("ttcf".equals(tag)) { // This is a TrueType Collection in.skip(4); // Read directory offsets int numDirectories = (int)in.readTTFULong(); // int numDirectories=in.readTTFUShort(); long[] dirOffsets = new long[numDirectories]; for (int i = 0; i < numDirectories; i++) { dirOffsets[i] = in.readTTFULong(); } log.info("This is a TrueType collection file with " + numDirectories + " fonts"); log.info("Containing the following fonts: "); // Read all the directories and name tables to check // If the font exists - this is a bit ugly, but... boolean found = false; // Iterate through all name tables even if font // Is found, just to show all the names long dirTabOffset = 0; for (int i = 0; (i < numDirectories); i++) { in.seekSet(dirOffsets[i]); readDirTabs(in); readName(in); if (fullName.equals(name)) { found = true; dirTabOffset = dirOffsets[i]; log.info(fullName + " <-- selected"); } else { log.info(fullName); } // Reset names notice = ""; fullName = ""; familyNames.clear(); postScriptName = ""; subFamilyName = ""; } in.seekSet(dirTabOffset); return found; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
public final List<String> getTTCnames(FontFileReader in) throws IOException { List<String> fontNames = new java.util.ArrayList<String>(); String tag = in.readTTFString(4); if ("ttcf".equals(tag)) { // This is a TrueType Collection in.skip(4); // Read directory offsets int numDirectories = (int)in.readTTFULong(); long[] dirOffsets = new long[numDirectories]; for (int i = 0; i < numDirectories; i++) { dirOffsets[i] = in.readTTFULong(); } log.info("This is a TrueType collection file with " + numDirectories + " fonts"); log.info("Containing the following fonts: "); for (int i = 0; (i < numDirectories); i++) { in.seekSet(dirOffsets[i]); readDirTabs(in); readName(in); log.info(fullName); fontNames.add(fullName); // Reset names notice = ""; fullName = ""; familyNames.clear(); postScriptName = ""; subFamilyName = ""; } in.seekSet(0); return fontNames; }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
private Integer unicodeToGlyph(int unicodeIndex) throws IOException { final Integer result = (Integer) unicodeToGlyphMap.get(new Integer(unicodeIndex)); if (result == null) { throw new IOException( "Glyph index not found for unicode value " + unicodeIndex); } return result; }
// in src/java/org/apache/fop/fonts/truetype/GlyfTable.java
void populateGlyphsWithComposites() throws IOException { for (int indexInOriginal : subset.keySet()) { scanGlyphsRecursively(indexInOriginal); } addAllComposedGlyphsToSubset(); for (int compositeGlyph : compositeGlyphs) { long offset = tableOffset + mtxTab[compositeGlyph].getOffset() + 10; if (!remappedComposites.contains(offset)) { remapComposite(offset); } } }
// in src/java/org/apache/fop/fonts/truetype/GlyfTable.java
private void scanGlyphsRecursively(int indexInOriginal) throws IOException { if (!subset.containsKey(indexInOriginal)) { composedGlyphs.add(indexInOriginal); } if (isComposite(indexInOriginal)) { compositeGlyphs.add(indexInOriginal); Set<Integer> composedGlyphs = retrieveComposedGlyphs(indexInOriginal); for (Integer composedGlyph : composedGlyphs) { scanGlyphsRecursively(composedGlyph); } } }
// in src/java/org/apache/fop/fonts/truetype/GlyfTable.java
private void remapComposite(long glyphOffset) throws IOException { long currentGlyphOffset = glyphOffset; remappedComposites.add(currentGlyphOffset); int flags = 0; do { flags = in.readTTFUShort(currentGlyphOffset); int glyphIndex = in.readTTFUShort(currentGlyphOffset + 2); Integer indexInSubset = subset.get(glyphIndex); assert indexInSubset != null; /* * TODO: this should not be done here!! We're writing to the stream we're reading from, * this is asking for trouble! What should happen is when the glyph data is copied from * subset, the remapping should be done there. So the original stream is left untouched. */ in.writeTTFUShort(currentGlyphOffset + 2, indexInSubset); currentGlyphOffset += 4 + GlyfFlags.getOffsetToNextComposedGlyf(flags); } while (GlyfFlags.hasMoreComposites(flags)); }
// in src/java/org/apache/fop/fonts/truetype/GlyfTable.java
private boolean isComposite(int indexInOriginal) throws IOException { int numberOfContours = in.readTTFShort(tableOffset + mtxTab[indexInOriginal].getOffset()); return numberOfContours < 0; }
// in src/java/org/apache/fop/fonts/truetype/GlyfTable.java
private Set<Integer> retrieveComposedGlyphs(int indexInOriginal) throws IOException { Set<Integer> composedGlyphs = new HashSet<Integer>(); long offset = tableOffset + mtxTab[indexInOriginal].getOffset() + 10; int flags = 0; do { flags = in.readTTFUShort(offset); composedGlyphs.add(in.readTTFUShort(offset + 2)); offset += 4 + GlyfFlags.getOffsetToNextComposedGlyf(flags); } while (GlyfFlags.hasMoreComposites(flags)); return composedGlyphs; }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private boolean createCvt(FontFileReader in) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("cvt "); if (entry != null) { pad4(); seekTab(in, "cvt ", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(cvtDirOffset, checksum); writeULong(cvtDirOffset + 4, currentPos); writeULong(cvtDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); return true; } else { return false; //throw new IOException("Can't find cvt table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private boolean createFpgm(FontFileReader in) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("fpgm"); if (entry != null) { pad4(); seekTab(in, "fpgm", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(fpgmDirOffset, checksum); writeULong(fpgmDirOffset + 4, currentPos); writeULong(fpgmDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); return true; } else { return false; } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createLoca(int size) throws IOException { pad4(); locaOffset = currentPos; writeULong(locaDirOffset + 4, currentPos); writeULong(locaDirOffset + 8, size * 4 + 4); currentPos += size * 4 + 4; realSize += size * 4 + 4; }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createMaxp(FontFileReader in, int size) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("maxp"); if (entry != null) { pad4(); seekTab(in, "maxp", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); writeUShort(currentPos + 4, size); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(maxpDirOffset, checksum); writeULong(maxpDirOffset + 4, currentPos); writeULong(maxpDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); } else { throw new IOException("Can't find maxp table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private boolean createPrep(FontFileReader in) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("prep"); if (entry != null) { pad4(); seekTab(in, "prep", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(prepDirOffset, checksum); writeULong(prepDirOffset + 4, currentPos); writeULong(prepDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); return true; } else { return false; } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createHhea(FontFileReader in, int size) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("hhea"); if (entry != null) { pad4(); seekTab(in, "hhea", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); writeUShort((int)entry.getLength() + currentPos - 2, size); int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(hheaDirOffset, checksum); writeULong(hheaDirOffset + 4, currentPos); writeULong(hheaDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); } else { throw new IOException("Can't find hhea table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createHead(FontFileReader in) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("head"); if (entry != null) { pad4(); seekTab(in, "head", 0); System.arraycopy(in.getBytes((int)entry.getOffset(), (int)entry.getLength()), 0, output, currentPos, (int)entry.getLength()); checkSumAdjustmentOffset = currentPos + 8; output[currentPos + 8] = 0; // Set checkSumAdjustment to 0 output[currentPos + 9] = 0; output[currentPos + 10] = 0; output[currentPos + 11] = 0; output[currentPos + 50] = 0; // long locaformat output[currentPos + 51] = 1; // long locaformat int checksum = getCheckSum(currentPos, (int)entry.getLength()); writeULong(headDirOffset, checksum); writeULong(headDirOffset + 4, currentPos); writeULong(headDirOffset + 8, (int)entry.getLength()); currentPos += (int)entry.getLength(); realSize += (int)entry.getLength(); } else { throw new IOException("Can't find head table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createGlyf(FontFileReader in, Map glyphs) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("glyf"); int size = 0; int start = 0; int endOffset = 0; // Store this as the last loca if (entry != null) { pad4(); start = currentPos; /* Loca table must be in order by glyph index, so build * an array first and then write the glyph info and * location offset. */ int[] origIndexes = new int[glyphs.size()]; Iterator e = glyphs.keySet().iterator(); while (e.hasNext()) { Integer origIndex = (Integer)e.next(); Integer subsetIndex = (Integer)glyphs.get(origIndex); origIndexes[subsetIndex.intValue()] = origIndex.intValue(); } for (int i = 0; i < origIndexes.length; i++) { int glyphLength = 0; int nextOffset = 0; int origGlyphIndex = origIndexes[i]; if (origGlyphIndex >= (mtxTab.length - 1)) { nextOffset = (int)lastLoca; } else { nextOffset = (int)mtxTab[origGlyphIndex + 1].getOffset(); } glyphLength = nextOffset - (int)mtxTab[origGlyphIndex].getOffset(); // Copy glyph System.arraycopy( in.getBytes((int)entry.getOffset() + (int)mtxTab[origGlyphIndex].getOffset(), glyphLength), 0, output, currentPos, glyphLength); // Update loca table writeULong(locaOffset + i * 4, currentPos - start); if ((currentPos - start + glyphLength) > endOffset) { endOffset = (currentPos - start + glyphLength); } currentPos += glyphLength; realSize += glyphLength; } size = currentPos - start; int checksum = getCheckSum(start, size); writeULong(glyfDirOffset, checksum); writeULong(glyfDirOffset + 4, start); writeULong(glyfDirOffset + 8, size); currentPos += 12; realSize += 12; // Update loca checksum and last loca index writeULong(locaOffset + glyphs.size() * 4, endOffset); checksum = getCheckSum(locaOffset, glyphs.size() * 4 + 4); writeULong(locaDirOffset, checksum); } else { throw new IOException("Can't find glyf table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void createHmtx(FontFileReader in, Map glyphs) throws IOException { TTFDirTabEntry entry = (TTFDirTabEntry)dirTabs.get("hmtx"); int longHorMetricSize = glyphs.size() * 2; int leftSideBearingSize = glyphs.size() * 2; int hmtxSize = longHorMetricSize + leftSideBearingSize; if (entry != null) { pad4(); //int offset = (int)entry.offset; Iterator e = glyphs.keySet().iterator(); while (e.hasNext()) { Integer origIndex = (Integer)e.next(); Integer subsetIndex = (Integer)glyphs.get(origIndex); writeUShort(currentPos + subsetIndex.intValue() * 4, mtxTab[origIndex.intValue()].getWx()); writeUShort(currentPos + subsetIndex.intValue() * 4 + 2, mtxTab[origIndex.intValue()].getLsb()); } int checksum = getCheckSum(currentPos, hmtxSize); writeULong(hmtxDirOffset, checksum); writeULong(hmtxDirOffset + 4, currentPos); writeULong(hmtxDirOffset + 8, hmtxSize); currentPos += hmtxSize; realSize += hmtxSize; } else { throw new IOException("Can't find hmtx table"); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
public byte[] readFont(FontFileReader in, String name, Map<Integer, Integer> glyphs) throws IOException { //Check if TrueType collection, and that the name exists in the collection if (!checkTTC(in, name)) { throw new IOException("Failed to read font"); } //Copy the Map as we're going to modify it Map<Integer, Integer> subsetGlyphs = new java.util.HashMap<Integer, Integer>(glyphs); output = new byte[in.getFileSize()]; readDirTabs(in); readFontHeader(in); getNumGlyphs(in); readHorizontalHeader(in); readHorizontalMetrics(in); readIndexToLocation(in); scanGlyphs(in, subsetGlyphs); createDirectory(); // Create the TrueType header and directory createHead(in); createHhea(in, subsetGlyphs.size()); // Create the hhea table createHmtx(in, subsetGlyphs); // Create hmtx table createMaxp(in, subsetGlyphs.size()); // copy the maxp table boolean optionalTableFound; optionalTableFound = createCvt(in); // copy the cvt table if (!optionalTableFound) { // cvt is optional (used in TrueType fonts only) log.debug("TrueType: ctv table not present. Skipped."); } optionalTableFound = createFpgm(in); // copy fpgm table if (!optionalTableFound) { // fpgm is optional (used in TrueType fonts only) log.debug("TrueType: fpgm table not present. Skipped."); } optionalTableFound = createPrep(in); // copy prep table if (!optionalTableFound) { // prep is optional (used in TrueType fonts only) log.debug("TrueType: prep table not present. Skipped."); } createLoca(subsetGlyphs.size()); // create empty loca table createGlyf(in, subsetGlyphs); //create glyf table and update loca table pad4(); createCheckSumAdjustment(); byte[] ret = new byte[realSize]; System.arraycopy(output, 0, ret, 0, realSize); return ret; }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private void scanGlyphs(FontFileReader in, Map<Integer, Integer> subsetGlyphs) throws IOException { TTFDirTabEntry glyfTableInfo = (TTFDirTabEntry) dirTabs.get("glyf"); if (glyfTableInfo == null) { throw new IOException("Glyf table could not be found"); } GlyfTable glyfTable = new GlyfTable(in, mtxTab, glyfTableInfo, subsetGlyphs); glyfTable.populateGlyphsWithComposites(); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
private void init(InputStream in) throws java.io.IOException { this.file = IOUtils.toByteArray(in); this.fsize = this.file.length; this.current = 0; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public void seekSet(long offset) throws IOException { if (offset > fsize || offset < 0) { throw new java.io.EOFException("Reached EOF, file size=" + fsize + " offset=" + offset); } current = (int)offset; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public void seekAdd(long add) throws IOException { seekSet(current + add); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public void skip(long add) throws IOException { seekAdd(add); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public byte read() throws IOException { if (current >= fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } final byte ret = file[current++]; return ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final byte readTTFByte() throws IOException { return read(); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final int readTTFUByte() throws IOException { final byte buf = read(); if (buf < 0) { return (int)(256 + buf); } else { return (int)buf; } }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final short readTTFShort() throws IOException { final int ret = (readTTFUByte() << 8) + readTTFUByte(); final short sret = (short)ret; return sret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final int readTTFUShort() throws IOException { final int ret = (readTTFUByte() << 8) + readTTFUByte(); return (int)ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final void writeTTFUShort(long pos, int val) throws IOException { if ((pos + 2) > fsize) { throw new java.io.EOFException("Reached EOF"); } final byte b1 = (byte)((val >> 8) & 0xff); final byte b2 = (byte)(val & 0xff); final int fileIndex = (int) pos; file[fileIndex] = b1; file[fileIndex + 1] = b2; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final short readTTFShort(long pos) throws IOException { final long cp = getCurrentPos(); seekSet(pos); final short ret = readTTFShort(); seekSet(cp); return ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final int readTTFUShort(long pos) throws IOException { long cp = getCurrentPos(); seekSet(pos); int ret = readTTFUShort(); seekSet(cp); return ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final int readTTFLong() throws IOException { long ret = readTTFUByte(); // << 8; ret = (ret << 8) + readTTFUByte(); ret = (ret << 8) + readTTFUByte(); ret = (ret << 8) + readTTFUByte(); return (int)ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final long readTTFULong() throws IOException { long ret = readTTFUByte(); ret = (ret << 8) + readTTFUByte(); ret = (ret << 8) + readTTFUByte(); ret = (ret << 8) + readTTFUByte(); return ret; }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final String readTTFString() throws IOException { int i = current; while (file[i++] != 0) { if (i > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } } byte[] tmp = new byte[i - current]; System.arraycopy(file, current, tmp, 0, i - current); return new String(tmp, "ISO-8859-1"); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final String readTTFString(int len) throws IOException { if ((len + current) > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } byte[] tmp = new byte[len]; System.arraycopy(file, current, tmp, 0, len); current += len; final String encoding; if ((tmp.length > 0) && (tmp[0] == 0)) { encoding = "UTF-16BE"; } else { encoding = "ISO-8859-1"; } return new String(tmp, encoding); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public final String readTTFString(int len, int encodingID) throws IOException { if ((len + current) > fsize) { throw new java.io.EOFException("Reached EOF, file size=" + fsize); } byte[] tmp = new byte[len]; System.arraycopy(file, current, tmp, 0, len); current += len; final String encoding; encoding = "UTF-16BE"; //Use this for all known encoding IDs for now return new String(tmp, encoding); }
// in src/java/org/apache/fop/fonts/truetype/FontFileReader.java
public byte[] getBytes(int offset, int length) throws IOException { if ((offset + length) > fsize) { throw new java.io.IOException("Reached EOF"); } byte[] ret = new byte[length]; System.arraycopy(file, offset, ret, 0, length); return ret; }
// in src/java/org/apache/fop/fonts/truetype/TTFFontLoader.java
Override protected void read() throws IOException { read(this.subFontName); }
// in src/java/org/apache/fop/fonts/truetype/TTFFontLoader.java
private void read(String ttcFontName) throws IOException { InputStream in = openFontUri(resolver, this.fontFileURI); try { TTFFile ttf = new TTFFile(useKerning, useAdvanced); FontFileReader reader = new FontFileReader(in); boolean supported = ttf.readFont(reader, ttcFontName); if (!supported) { throw new IOException("TrueType font is not supported: " + fontFileURI); } buildFont(ttf, ttcFontName); loaded = true; } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/render/print/PrintRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); try { printerJob.print(); } catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); } clearViewportList(); }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); if (endNumber == -1) { // was not set on command line endNumber = getNumberOfPages(); } }
// in src/java/org/apache/fop/render/pdf/ImageRenderedAdapter.java
public void outputContents(OutputStream out) throws IOException { long start = System.currentTimeMillis(); encodingHelper.encode(out); long duration = System.currentTimeMillis() - start; if (log.isDebugEnabled()) { log.debug("Image encoding took " + duration + "ms"); } }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addsRGBColorSpace() throws IOException { if (disableSRGBColorSpace) { if (this.pdfAMode != PDFAMode.DISABLED || this.pdfXMode != PDFXMode.DISABLED || this.outputProfileURI != null) { throw new IllegalStateException("It is not possible to disable the sRGB color" + " space if PDF/A or PDF/X functionality is enabled or an" + " output profile is set!"); } } else { if (this.sRGBColorSpace != null) { return; } //Map sRGB as default RGB profile for DeviceRGB this.sRGBColorSpace = PDFICCBasedColorSpace.setupsRGBAsDefaultRGBColorSpace(pdfDoc); } }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addDefaultOutputProfile() throws IOException { if (this.outputProfile != null) { return; } ICC_Profile profile; InputStream in = null; if (this.outputProfileURI != null) { this.outputProfile = pdfDoc.getFactory().makePDFICCStream(); Source src = getUserAgent().resolveURI(this.outputProfileURI); if (src == null) { throw new IOException("Output profile not found: " + this.outputProfileURI); } if (src instanceof StreamSource) { in = ((StreamSource)src).getInputStream(); } else { in = new URL(src.getSystemId()).openStream(); } try { profile = ColorProfileUtil.getICC_Profile(in); } finally { IOUtils.closeQuietly(in); } this.outputProfile.setColorSpace(profile, null); } else { //Fall back to sRGB profile outputProfile = sRGBColorSpace.getICCStream(); } }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addPDFA1OutputIntent() throws IOException { addDefaultOutputProfile(); String desc = ColorProfileUtil.getICCProfileDescription(this.outputProfile.getICCProfile()); PDFOutputIntent outputIntent = pdfDoc.getFactory().makeOutputIntent(); outputIntent.setSubtype(PDFOutputIntent.GTS_PDFA1); outputIntent.setDestOutputProfile(this.outputProfile); outputIntent.setOutputConditionIdentifier(desc); outputIntent.setInfo(outputIntent.getOutputConditionIdentifier()); pdfDoc.getRoot().addOutputIntent(outputIntent); }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addPDFXOutputIntent() throws IOException { addDefaultOutputProfile(); String desc = ColorProfileUtil.getICCProfileDescription(this.outputProfile.getICCProfile()); int deviceClass = this.outputProfile.getICCProfile().getProfileClass(); if (deviceClass != ICC_Profile.CLASS_OUTPUT) { throw new PDFConformanceException(pdfDoc.getProfile().getPDFXMode() + " requires that" + " the DestOutputProfile be an Output Device Profile. " + desc + " does not match that requirement."); } PDFOutputIntent outputIntent = pdfDoc.getFactory().makeOutputIntent(); outputIntent.setSubtype(PDFOutputIntent.GTS_PDFX); outputIntent.setDestOutputProfile(this.outputProfile); outputIntent.setOutputConditionIdentifier(desc); outputIntent.setInfo(outputIntent.getOutputConditionIdentifier()); pdfDoc.getRoot().addOutputIntent(outputIntent); }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
public PDFDocument setupPDFDocument(OutputStream out) throws IOException { if (this.pdfDoc != null) { throw new IllegalStateException("PDFDocument already set up"); } String producer = userAgent.getProducer() != null ? userAgent.getProducer() : ""; if (maxPDFVersion == null) { this.pdfDoc = new PDFDocument(producer); } else { VersionController controller = VersionController.getFixedVersionController(maxPDFVersion); this.pdfDoc = new PDFDocument(producer, controller); } updateInfo(); updatePDFProfiles(); pdfDoc.setFilterMap(filterMap); pdfDoc.outputHeader(out); //Setup encryption if necessary PDFEncryptionManager.setupPDFEncryption(encryptionParams, pdfDoc); addsRGBColorSpace(); if (this.outputProfileURI != null) { addDefaultOutputProfile(); } if (pdfXMode != PDFXMode.DISABLED) { log.debug(pdfXMode + " is active."); log.warn("Note: " + pdfXMode + " support is work-in-progress and not fully implemented, yet!"); addPDFXOutputIntent(); } if (pdfAMode.isPDFA1LevelB()) { log.debug("PDF/A is active. Conformance Level: " + pdfAMode); addPDFA1OutputIntent(); } this.pdfDoc.enableAccessibility(userAgent.isAccessibilityEnabled()); return this.pdfDoc; }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
public void addEmbeddedFile(PDFEmbeddedFileExtensionAttachment embeddedFile) throws IOException { this.pdfDoc.getProfile().verifyEmbeddedFilesAllowed(); PDFNames names = this.pdfDoc.getRoot().getNames(); if (names == null) { //Add Names if not already present names = this.pdfDoc.getFactory().makeNames(); this.pdfDoc.getRoot().setNames(names); } //Create embedded file PDFEmbeddedFile file = new PDFEmbeddedFile(); this.pdfDoc.registerObject(file); Source src = getUserAgent().resolveURI(embeddedFile.getSrc()); InputStream in = ImageUtil.getInputStream(src); if (in == null) { throw new FileNotFoundException(embeddedFile.getSrc()); } try { OutputStream out = file.getBufferOutputStream(); IOUtils.copyLarge(in, out); } finally { IOUtils.closeQuietly(in); } PDFDictionary dict = new PDFDictionary(); dict.put("F", file); String filename = PDFText.toPDFString(embeddedFile.getFilename(), '_'); PDFFileSpec fileSpec = new PDFFileSpec(filename); fileSpec.setEmbeddedFile(dict); if (embeddedFile.getDesc() != null) { fileSpec.setDescription(embeddedFile.getDesc()); } this.pdfDoc.registerObject(fileSpec); //Make sure there is an EmbeddedFiles in the Names dictionary PDFEmbeddedFiles embeddedFiles = names.getEmbeddedFiles(); if (embeddedFiles == null) { embeddedFiles = new PDFEmbeddedFiles(); this.pdfDoc.assignObjectNumber(embeddedFiles); this.pdfDoc.addTrailerObject(embeddedFiles); names.setEmbeddedFiles(embeddedFiles); } //Add to EmbeddedFiles in the Names dictionary PDFArray nameArray = embeddedFiles.getNames(); if (nameArray == null) { nameArray = new PDFArray(); embeddedFiles.setNames(nameArray); } String name = PDFText.toPDFString(filename); nameArray.add(name); nameArray.add(new PDFReference(fileSpec)); }
// in src/java/org/apache/fop/render/pdf/PDFContentGenerator.java
public void flushPDFDoc() throws IOException { this.document.output(this.outputStream); }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerSVG.java
public void handleImage(RenderingContext context, // CSOK: MethodLength Image image, Rectangle pos) throws IOException { PDFRenderingContext pdfContext = (PDFRenderingContext)context; PDFContentGenerator generator = pdfContext.getGenerator(); ImageXMLDOM imageSVG = (ImageXMLDOM)image; FOUserAgent userAgent = context.getUserAgent(); final float deviceResolution = userAgent.getTargetResolution(); if (log.isDebugEnabled()) { log.debug("Generating SVG at " + deviceResolution + "dpi."); } final float uaResolution = userAgent.getSourceResolution(); SVGUserAgent ua = new SVGUserAgent(userAgent, new AffineTransform()); GVTBuilder builder = new GVTBuilder(); //Controls whether text painted by Batik is generated using text or path operations boolean strokeText = false; //TODO connect with configuration elsewhere. BridgeContext ctx = new PDFBridgeContext(ua, (strokeText ? null : pdfContext.getFontInfo()), userAgent.getFactory().getImageManager(), userAgent.getImageSessionContext(), new AffineTransform()); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(imageSVG.getDocument()); GraphicsNode root; try { root = builder.build(ctx, clonedDoc); builder = null; } catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; } // get the 'width' and 'height' attributes of the SVG document float w = image.getSize().getWidthMpt(); float h = image.getSize().getHeightMpt(); float sx = pos.width / w; float sy = pos.height / h; //Scaling and translation for the bounding box of the image AffineTransform scaling = new AffineTransform( sx, 0, 0, sy, pos.x / 1000f, pos.y / 1000f); double sourceScale = UnitConv.IN2PT / uaResolution; scaling.scale(sourceScale, sourceScale); //Scale for higher resolution on-the-fly images from Batik AffineTransform resolutionScaling = new AffineTransform(); double targetScale = uaResolution / deviceResolution; resolutionScaling.scale(targetScale, targetScale); resolutionScaling.scale(1.0 / sx, 1.0 / sy); //Transformation matrix that establishes the local coordinate system for the SVG graphic //in relation to the current coordinate system AffineTransform imageTransform = new AffineTransform(); imageTransform.concatenate(scaling); imageTransform.concatenate(resolutionScaling); if (log.isTraceEnabled()) { log.trace("nat size: " + w + "/" + h); log.trace("req size: " + pos.width + "/" + pos.height); log.trace("source res: " + uaResolution + ", targetRes: " + deviceResolution + " --> target scaling: " + targetScale); log.trace(image.getSize()); log.trace("sx: " + sx + ", sy: " + sy); log.trace("scaling: " + scaling); log.trace("resolution scaling: " + resolutionScaling); log.trace("image transform: " + resolutionScaling); } /* * Clip to the svg area. * Note: To have the svg overlay (under) a text area then use * an fo:block-container */ if (log.isTraceEnabled()) { generator.comment("SVG setup"); } generator.saveGraphicsState(); if (context.getUserAgent().isAccessibilityEnabled()) { MarkedContentInfo mci = pdfContext.getMarkedContentInfo(); generator.beginMarkedContentSequence(mci.tag, mci.mcid); } generator.updateColor(Color.black, false, null); generator.updateColor(Color.black, true, null); if (!scaling.isIdentity()) { if (log.isTraceEnabled()) { generator.comment("viewbox"); } generator.add(CTMHelper.toPDFString(scaling, false) + " cm\n"); } //SVGSVGElement svg = ((SVGDocument)doc).getRootElement(); PDFGraphics2D graphics = new PDFGraphics2D(true, pdfContext.getFontInfo(), generator.getDocument(), generator.getResourceContext(), pdfContext.getPage().referencePDF(), "", 0); graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); if (!resolutionScaling.isIdentity()) { if (log.isTraceEnabled()) { generator.comment("resolution scaling for " + uaResolution + " -> " + deviceResolution); } generator.add( CTMHelper.toPDFString(resolutionScaling, false) + " cm\n"); graphics.scale( 1.0 / resolutionScaling.getScaleX(), 1.0 / resolutionScaling.getScaleY()); } if (log.isTraceEnabled()) { generator.comment("SVG start"); } //Save state and update coordinate system for the SVG image generator.getState().save(); generator.getState().concatenate(imageTransform); //Now that we have the complete transformation matrix for the image, we can update the //transformation matrix for the AElementBridge. PDFAElementBridge aBridge = (PDFAElementBridge)ctx.getBridge( SVGDOMImplementation.SVG_NAMESPACE_URI, SVGConstants.SVG_A_TAG); aBridge.getCurrentTransform().setTransform(generator.getState().getTransform()); graphics.setPaintingState(generator.getState()); graphics.setOutputStream(generator.getOutputStream()); try { root.paint(graphics); ctx.dispose(); generator.add(graphics.getString()); } catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); } generator.getState().restore(); if (context.getUserAgent().isAccessibilityEnabled()) { generator.restoreGraphicsStateAccess(); } else { generator.restoreGraphicsState(); } if (log.isTraceEnabled()) { generator.comment("SVG end"); } }
// in src/java/org/apache/fop/render/pdf/AbstractPDFImageHandler.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { assert context instanceof PDFRenderingContext; PDFRenderingContext pdfContext = (PDFRenderingContext)context; PDFContentGenerator generator = pdfContext.getGenerator(); PDFImage pdfimage = createPDFImage(image, image.getInfo().getOriginalURI()); PDFXObject xobj = generator.getDocument().addImage( generator.getResourceContext(), pdfimage); float x = (float)pos.getX() / 1000f; float y = (float)pos.getY() / 1000f; float w = (float)pos.getWidth() / 1000f; float h = (float)pos.getHeight() / 1000f; if (context.getUserAgent().isAccessibilityEnabled()) { MarkedContentInfo mci = pdfContext.getMarkedContentInfo(); generator.placeImage(x, y, w, h, xobj, mci.tag, mci.mcid); } else { generator.placeImage(x, y, w, h, xobj); } }
// in src/java/org/apache/fop/render/pdf/ImageRawCCITTFaxAdapter.java
public void outputContents(OutputStream out) throws IOException { getImage().writeTo(out); }
// in src/java/org/apache/fop/render/pdf/PDFImageHandlerGraphics2D.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PDFRenderingContext pdfContext = (PDFRenderingContext)context; PDFContentGenerator generator = pdfContext.getGenerator(); ImageGraphics2D imageG2D = (ImageGraphics2D)image; float fwidth = pos.width / 1000f; float fheight = pos.height / 1000f; float fx = pos.x / 1000f; float fy = pos.y / 1000f; // get the 'width' and 'height' attributes of the SVG document Dimension dim = image.getInfo().getSize().getDimensionMpt(); float imw = (float)dim.getWidth() / 1000f; float imh = (float)dim.getHeight() / 1000f; float sx = fwidth / imw; float sy = fheight / imh; generator.comment("G2D start"); boolean accessibilityEnabled = context.getUserAgent().isAccessibilityEnabled(); if (accessibilityEnabled) { MarkedContentInfo mci = pdfContext.getMarkedContentInfo(); generator.saveGraphicsState(mci.tag, mci.mcid); } else { generator.saveGraphicsState(); } generator.updateColor(Color.black, false, null); generator.updateColor(Color.black, true, null); //TODO Clip to the image area. // transform so that the coordinates (0,0) is from the top left // and positive is down and to the right. (0,0) is where the // viewBox puts it. generator.add(sx + " 0 0 " + sy + " " + fx + " " + fy + " cm\n"); final boolean textAsShapes = false; PDFGraphics2D graphics = new PDFGraphics2D(textAsShapes, pdfContext.getFontInfo(), generator.getDocument(), generator.getResourceContext(), pdfContext.getPage().referencePDF(), "", 0.0f); graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); AffineTransform transform = new AffineTransform(); transform.translate(fx, fy); generator.getState().concatenate(transform); graphics.setPaintingState(generator.getState()); graphics.setOutputStream(generator.getOutputStream()); Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, imw, imh); imageG2D.getGraphics2DImagePainter().paint(graphics, area); generator.add(graphics.getString()); if (accessibilityEnabled) { generator.restoreGraphicsStateAccess(); } else { generator.restoreGraphicsState(); } generator.comment("G2D end"); }
// in src/java/org/apache/fop/render/pdf/ImageRawJPEGAdapter.java
public void outputContents(OutputStream out) throws IOException { InputStream in = getImage().createInputStream(); in = ImageUtil.decorateMarkSupported(in); try { JPEGFile jpeg = new JPEGFile(in); DataInput din = jpeg.getDataInput(); //Copy the whole JPEG file except: // - the ICC profile //TODO Thumbnails could safely be skipped, too. //TODO Metadata (XMP, IPTC, EXIF) could safely be skipped, too. while (true) { int reclen; int segID = jpeg.readMarkerSegment(); switch (segID) { case JPEGConstants.SOI: out.write(0xFF); out.write(segID); break; case JPEGConstants.EOI: case JPEGConstants.SOS: out.write(0xFF); out.write(segID); IOUtils.copy(in, out); //Just copy the rest! return; /* case JPEGConstants.APP1: //Metadata case JPEGConstants.APPD: jpeg.skipCurrentMarkerSegment(); break;*/ case JPEGConstants.APP2: //ICC (see ICC1V42.pdf) boolean skipICCProfile = false; in.mark(16); try { reclen = jpeg.readSegmentLength(); // Check for ICC profile byte[] iccString = new byte[11]; din.readFully(iccString); din.skipBytes(1); //string terminator (null byte) if ("ICC_PROFILE".equals(new String(iccString, "US-ASCII"))) { skipICCProfile = (this.image.getICCProfile() != null); } } finally { in.reset(); } if (skipICCProfile) { //ICC profile is skipped as it is already embedded as a PDF object jpeg.skipCurrentMarkerSegment(); break; } default: out.write(0xFF); out.write(segID); reclen = jpeg.readSegmentLength(); //write short out.write((reclen >>> 8) & 0xFF); out.write((reclen >>> 0) & 0xFF); int left = reclen - 2; byte[] buf = new byte[2048]; while (left > 0) { int part = Math.min(buf.length, left); din.readFully(buf, 0, part); out.write(buf, 0, part); left -= part; } } } } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { if (this.handler == null) { SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); try { TransformerHandler transformerHandler = factory.newTransformerHandler(); setContentHandler(transformerHandler); StreamResult res = new StreamResult(outputStream); transformerHandler.setResult(res); } catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); } this.out = outputStream; } try { handler.startDocument(); } catch (SAXException saxe) { handleSAXException(saxe); } }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
public void stopRenderer() throws IOException { try { handler.endDocument(); } catch (SAXException saxe) { handleSAXException(saxe); } if (this.out != null) { this.out.flush(); } }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
Override public void startRenderer(OutputStream outputStream) throws IOException { log.debug("Rendering areas to Area Tree XML"); if (this.handler == null) { SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); try { TransformerHandler transformerHandler = factory.newTransformerHandler(); this.handler = transformerHandler; StreamResult res = new StreamResult(outputStream); transformerHandler.setResult(res); } catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); } this.out = outputStream; } try { handler.startDocument(); } catch (SAXException saxe) { handleSAXException(saxe); } if (userAgent.getProducer() != null) { comment("Produced by " + userAgent.getProducer()); } atts.clear(); addAttribute("version", VERSION); startElement("areaTree", atts); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
Override public void stopRenderer() throws IOException { endPageSequence(); endElement("areaTree"); try { handler.endDocument(); } catch (SAXException saxe) { handleSAXException(saxe); } if (this.out != null) { this.out.flush(); } log.debug("Written out Area Tree XML"); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
Override public void renderPage(PageViewport page) throws IOException, FOPException { atts.clear(); addAttribute("bounds", page.getViewArea()); addAttribute("key", page.getKey()); addAttribute("nr", page.getPageNumber()); addAttribute("formatted-nr", page.getPageNumberString()); if (page.getSimplePageMasterName() != null) { addAttribute("simple-page-master-name", page.getSimplePageMasterName()); } if (page.isBlank()) { addAttribute("blank", "true"); } transferForeignObjects(page); startElement("pageViewport", atts); startElement("page"); handlePageExtensionAttachments(page); super.renderPage(page); endElement("page"); endElement("pageViewport"); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImageUsingImageHandler(ImageInfo info, Rectangle rect) throws ImageException, IOException { ImageManager manager = getFopFactory().getImageManager(); ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry(); //Load and convert the image to a supported format RenderingContext context = createRenderingContext(); Map hints = createDefaultImageProcessingHints(sessionContext); context.putHints(hints); ImageFlavor[] flavors = imageHandlerRegistry.getSupportedFlavors(context); org.apache.xmlgraphics.image.loader.Image img = manager.getImage( info, flavors, hints, sessionContext); try { drawImage(img, rect, context); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageWritingError(this, ioe); } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImage(Image image, Rectangle rect, RenderingContext context) throws IOException, ImageException { drawImage(image, rect, context, false, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImage(Image image, Rectangle rect, RenderingContext context, boolean convert, Map additionalHints) throws IOException, ImageException { ImageManager manager = getFopFactory().getImageManager(); ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry(); Image effImage; context.putHints(additionalHints); if (convert) { Map hints = createDefaultImageProcessingHints(getUserAgent().getImageSessionContext()); if (additionalHints != null) { hints.putAll(additionalHints); } effImage = manager.convertImage(image, imageHandlerRegistry.getSupportedFlavors(context), hints); } else { effImage = image; } //First check for a dynamically registered handler ImageHandler handler = imageHandlerRegistry.getHandler(context, effImage); if (handler == null) { throw new UnsupportedOperationException( "No ImageHandler available for image: " + effImage.getInfo() + " (" + effImage.getClass().getName() + ")"); } if (log.isTraceEnabled()) { log.trace("Using ImageHandler: " + handler.getClass().getName()); } handler.handleImage(context, effImage, rect); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
private void handleIFExceptionWithIOException(IFException ife) throws IOException { if (ife.getCause() instanceof IOException) { throw (IOException)ife.getCause(); } else { handleIFException(ife); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { try { if (outputStream != null) { StreamResult result = new StreamResult(outputStream); if (getUserAgent().getOutputFile() != null) { result.setSystemId( getUserAgent().getOutputFile().toURI().toURL().toExternalForm()); } if (this.documentHandler == null) { this.documentHandler = createDefaultDocumentHandler(); } this.documentHandler.setResult(result); } super.startRenderer(null); if (log.isDebugEnabled()) { log.debug("Rendering areas via IF document handler (" + this.documentHandler.getClass().getName() + ")..."); } documentHandler.startDocument(); documentHandler.startDocumentHeader(); } catch (IFException e) { handleIFExceptionWithIOException(e); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
public void stopRenderer() throws IOException { try { if (this.inPageSequence) { documentHandler.endPageSequence(); this.inPageSequence = false; } documentHandler.startDocumentTrailer(); //Wrap up document navigation if (hasDocumentNavigation()) { finishOpenGoTos(); Iterator iter = this.deferredDestinations.iterator(); while (iter.hasNext()) { NamedDestination dest = (NamedDestination)iter.next(); iter.remove(); getDocumentNavigationHandler().renderNamedDestination(dest); } if (this.bookmarkTree != null) { getDocumentNavigationHandler().renderBookmarkTree(this.bookmarkTree); } } documentHandler.endDocumentTrailer(); documentHandler.endDocument(); } catch (IFException e) { handleIFExceptionWithIOException(e); } pageIndices.clear(); idPositions.clear(); actionSet.clear(); super.stopRenderer(); log.debug("Rendering finished."); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
public void renderPage(PageViewport page) throws IOException, FOPException { if (log.isTraceEnabled()) { log.trace("renderPage() " + page); } try { pageIndices.put(page.getKey(), new Integer(page.getPageIndex())); Rectangle viewArea = page.getViewArea(); Dimension dim = new Dimension(viewArea.width, viewArea.height); establishForeignAttributes(page.getForeignAttributes()); documentHandler.startPage(page.getPageIndex(), page.getPageNumberString(), page.getSimplePageMasterName(), dim); resetForeignAttributes(); documentHandler.startPageHeader(); //Add page attachments to page header processExtensionAttachments(page); documentHandler.endPageHeader(); this.painter = documentHandler.startPageContent(); super.renderPage(page); this.painter = null; documentHandler.endPageContent(); documentHandler.startPageTrailer(); if (hasDocumentNavigation()) { Iterator iter = this.deferredLinks.iterator(); while (iter.hasNext()) { Link link = (Link)iter.next(); iter.remove(); getDocumentNavigationHandler().renderLink(link); } } documentHandler.endPageTrailer(); establishForeignAttributes(page.getForeignAttributes()); documentHandler.endPage(); resetForeignAttributes(); } catch (IFException e) { handleIFException(e); } }
// in src/java/org/apache/fop/render/intermediate/BorderPainter.java
public void drawBorders(Rectangle borderRect, // CSOK: MethodLength BorderProps bpsTop, BorderProps bpsBottom, BorderProps bpsLeft, BorderProps bpsRight) throws IOException { int startx = borderRect.x; int starty = borderRect.y; int width = borderRect.width; int height = borderRect.height; boolean[] b = new boolean[] { (bpsTop != null), (bpsRight != null), (bpsBottom != null), (bpsLeft != null)}; if (!b[0] && !b[1] && !b[2] && !b[3]) { return; } int[] bw = new int[] { (b[0] ? bpsTop.width : 0), (b[1] ? bpsRight.width : 0), (b[2] ? bpsBottom.width : 0), (b[3] ? bpsLeft.width : 0)}; int[] clipw = new int[] { BorderProps.getClippedWidth(bpsTop), BorderProps.getClippedWidth(bpsRight), BorderProps.getClippedWidth(bpsBottom), BorderProps.getClippedWidth(bpsLeft)}; starty += clipw[0]; height -= clipw[0]; height -= clipw[2]; startx += clipw[3]; width -= clipw[3]; width -= clipw[1]; boolean[] slant = new boolean[] { (b[3] && b[0]), (b[0] && b[1]), (b[1] && b[2]), (b[2] && b[3])}; if (bpsTop != null) { int sx1 = startx; int sx2 = (slant[0] ? sx1 + bw[3] - clipw[3] : sx1); int ex1 = startx + width; int ex2 = (slant[1] ? ex1 - bw[1] + clipw[1] : ex1); int outery = starty - clipw[0]; int clipy = outery + clipw[0]; int innery = outery + bw[0]; saveGraphicsState(); moveTo(sx1, clipy); int sx1a = sx1; int ex1a = ex1; if (bpsTop.mode == BorderProps.COLLAPSE_OUTER) { if (bpsLeft != null && bpsLeft.mode == BorderProps.COLLAPSE_OUTER) { sx1a -= clipw[3]; } if (bpsRight != null && bpsRight.mode == BorderProps.COLLAPSE_OUTER) { ex1a += clipw[1]; } lineTo(sx1a, outery); lineTo(ex1a, outery); } lineTo(ex1, clipy); lineTo(ex2, innery); lineTo(sx2, innery); closePath(); clip(); drawBorderLine(sx1a, outery, ex1a, innery, true, true, bpsTop.style, bpsTop.color); restoreGraphicsState(); } if (bpsRight != null) { int sy1 = starty; int sy2 = (slant[1] ? sy1 + bw[0] - clipw[0] : sy1); int ey1 = starty + height; int ey2 = (slant[2] ? ey1 - bw[2] + clipw[2] : ey1); int outerx = startx + width + clipw[1]; int clipx = outerx - clipw[1]; int innerx = outerx - bw[1]; saveGraphicsState(); moveTo(clipx, sy1); int sy1a = sy1; int ey1a = ey1; if (bpsRight.mode == BorderProps.COLLAPSE_OUTER) { if (bpsTop != null && bpsTop.mode == BorderProps.COLLAPSE_OUTER) { sy1a -= clipw[0]; } if (bpsBottom != null && bpsBottom.mode == BorderProps.COLLAPSE_OUTER) { ey1a += clipw[2]; } lineTo(outerx, sy1a); lineTo(outerx, ey1a); } lineTo(clipx, ey1); lineTo(innerx, ey2); lineTo(innerx, sy2); closePath(); clip(); drawBorderLine(innerx, sy1a, outerx, ey1a, false, false, bpsRight.style, bpsRight.color); restoreGraphicsState(); } if (bpsBottom != null) { int sx1 = startx; int sx2 = (slant[3] ? sx1 + bw[3] - clipw[3] : sx1); int ex1 = startx + width; int ex2 = (slant[2] ? ex1 - bw[1] + clipw[1] : ex1); int outery = starty + height + clipw[2]; int clipy = outery - clipw[2]; int innery = outery - bw[2]; saveGraphicsState(); moveTo(ex1, clipy); int sx1a = sx1; int ex1a = ex1; if (bpsBottom.mode == BorderProps.COLLAPSE_OUTER) { if (bpsLeft != null && bpsLeft.mode == BorderProps.COLLAPSE_OUTER) { sx1a -= clipw[3]; } if (bpsRight != null && bpsRight.mode == BorderProps.COLLAPSE_OUTER) { ex1a += clipw[1]; } lineTo(ex1a, outery); lineTo(sx1a, outery); } lineTo(sx1, clipy); lineTo(sx2, innery); lineTo(ex2, innery); closePath(); clip(); drawBorderLine(sx1a, innery, ex1a, outery, true, false, bpsBottom.style, bpsBottom.color); restoreGraphicsState(); } if (bpsLeft != null) { int sy1 = starty; int sy2 = (slant[0] ? sy1 + bw[0] - clipw[0] : sy1); int ey1 = sy1 + height; int ey2 = (slant[3] ? ey1 - bw[2] + clipw[2] : ey1); int outerx = startx - clipw[3]; int clipx = outerx + clipw[3]; int innerx = outerx + bw[3]; saveGraphicsState(); moveTo(clipx, ey1); int sy1a = sy1; int ey1a = ey1; if (bpsLeft.mode == BorderProps.COLLAPSE_OUTER) { if (bpsTop != null && bpsTop.mode == BorderProps.COLLAPSE_OUTER) { sy1a -= clipw[0]; } if (bpsBottom != null && bpsBottom.mode == BorderProps.COLLAPSE_OUTER) { ey1a += clipw[2]; } lineTo(outerx, ey1a); lineTo(outerx, sy1a); } lineTo(clipx, sy1); lineTo(innerx, sy2); lineTo(innerx, ey2); closePath(); clip(); drawBorderLine(outerx, sy1a, innerx, ey1a, false, true, bpsLeft.style, bpsLeft.color); restoreGraphicsState(); } }
// in src/java/org/apache/fop/render/AbstractGenericSVGHandler.java
protected void renderSVGDocument(final RendererContext rendererContext, final Document doc) throws IOException { updateRendererContext(rendererContext); //Prepare FOUserAgent userAgent = rendererContext.getUserAgent(); SVGUserAgent svgUserAgent = new SVGUserAgent(userAgent, new AffineTransform()); //Create Batik BridgeContext final BridgeContext bridgeContext = new BridgeContext(svgUserAgent); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(doc); //Build the GVT tree final GraphicsNode root = buildGraphicsNode(userAgent, bridgeContext, clonedDoc); // Create Graphics2DImagePainter final RendererContextWrapper wrappedContext = RendererContext.wrapRendererContext( rendererContext); Dimension imageSize = getImageSize(wrappedContext); final Graphics2DImagePainter painter = createGraphics2DImagePainter( root, bridgeContext, imageSize); //Let the painter paint the SVG on the Graphics2D instance Graphics2DAdapter g2dAdapter = rendererContext.getRenderer().getGraphics2DAdapter(); //Paint the image final int x = wrappedContext.getCurrentXPosition(); final int y = wrappedContext.getCurrentYPosition(); final int width = wrappedContext.getWidth(); final int height = wrappedContext.getHeight(); g2dAdapter.paintImage(painter, rendererContext, x, y, width, height); }
// in src/java/org/apache/fop/render/txt/TXTRenderer.java
public void renderPage(PageViewport page) throws IOException, FOPException { if (firstPage) { firstPage = false; } else { currentStream.add(pageEnding); } Rectangle2D bounds = page.getViewArea(); double width = bounds.getWidth(); double height = bounds.getHeight(); pageWidth = Helper.ceilPosition((int) width, CHAR_WIDTH); pageHeight = Helper.ceilPosition((int) height, CHAR_HEIGHT + 2 * LINE_LEADING); // init buffers charData = new StringBuffer[pageHeight]; decoData = new StringBuffer[pageHeight]; for (int i = 0; i < pageHeight; i++) { charData[i] = new StringBuffer(); decoData[i] = new StringBuffer(); } bm = new BorderManager(pageWidth, pageHeight, currentState); super.renderPage(page); flushBorderToBuffer(); flushBuffer(); }
// in src/java/org/apache/fop/render/txt/TXTRenderer.java
public void startRenderer(OutputStream os) throws IOException { log.info("Rendering areas to TEXT."); this.outputStream = os; currentStream = new TXTStream(os); currentStream.setEncoding(this.encoding); firstPage = true; }
// in src/java/org/apache/fop/render/txt/TXTRenderer.java
public void stopRenderer() throws IOException { log.info("writing out TEXT"); outputStream.flush(); super.stopRenderer(); }
// in src/java/org/apache/fop/render/AbstractRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { if (userAgent == null) { throw new IllegalStateException("FOUserAgent has not been set on Renderer"); } }
// in src/java/org/apache/fop/render/AbstractRenderer.java
public void stopRenderer() throws IOException { }
// in src/java/org/apache/fop/render/AbstractRenderer.java
public void renderPage(PageViewport page) throws IOException, FOPException { this.currentPageViewport = page; try { Page p = page.getPage(); renderPageAreas(p); } finally { this.currentPageViewport = null; } }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
private void selectPageFormat(long pagewidth, long pageheight) throws IOException { //Only set the page format if it changes (otherwise duplex printing won't work) if ((pagewidth != this.pageWidth) || (pageheight != this.pageHeight)) { this.pageWidth = pagewidth; this.pageHeight = pageheight; this.currentPageDefinition = PCLPageDefinition.getPageDefinition( pagewidth, pageheight, 1000); if (this.currentPageDefinition == null) { this.currentPageDefinition = PCLPageDefinition.getDefaultPageDefinition(); log.warn("Paper type could not be determined. Falling back to: " + this.currentPageDefinition.getName()); } if (log.isDebugEnabled()) { log.debug("page size: " + currentPageDefinition.getPhysicalPageSize()); log.debug("logical page: " + currentPageDefinition.getLogicalPageRect()); } if (this.currentPageDefinition.isLandscapeFormat()) { gen.writeCommand("&l1O"); //Landscape Orientation } else { gen.writeCommand("&l0O"); //Portrait Orientation } gen.selectPageSize(this.currentPageDefinition.getSelector()); gen.clearHorizontalMargins(); gen.setTopMargin(0); } }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PCLRenderingContext pclContext = (PCLRenderingContext)context; ImageGraphics2D imageG2D = (ImageGraphics2D)image; Dimension imageDim = imageG2D.getSize().getDimensionMpt(); PCLGenerator gen = pclContext.getPCLGenerator(); Point2D transPoint = pclContext.transformedPoint(pos.x, pos.y); gen.setCursorPos(transPoint.getX(), transPoint.getY()); boolean painted = false; ByteArrayOutputStream baout = new ByteArrayOutputStream(); PCLGenerator tempGen = new PCLGenerator(baout, gen.getMaximumBitmapResolution()); tempGen.setDitheringQuality(gen.getDitheringQuality()); try { GraphicContext ctx = (GraphicContext)pclContext.getGraphicContext().clone(); AffineTransform prepareHPGL2 = new AffineTransform(); prepareHPGL2.scale(0.001, 0.001); ctx.setTransform(prepareHPGL2); PCLGraphics2D graphics = new PCLGraphics2D(tempGen); graphics.setGraphicContext(ctx); graphics.setClippingDisabled(false /*pclContext.isClippingDisabled()*/); Rectangle2D area = new Rectangle2D.Double( 0.0, 0.0, imageDim.getWidth(), imageDim.getHeight()); imageG2D.getGraphics2DImagePainter().paint(graphics, area); //If we arrive here, the graphic is natively paintable, so write the graphic gen.writeCommand("*c" + gen.formatDouble4(pos.width / 100f) + "x" + gen.formatDouble4(pos.height / 100f) + "Y"); gen.writeCommand("*c0T"); gen.enterHPGL2Mode(false); gen.writeText("\nIN;"); gen.writeText("SP1;"); //One Plotter unit is 0.025mm! double scale = imageDim.getWidth() / UnitConv.mm2pt(imageDim.getWidth() * 0.025); gen.writeText("SC0," + gen.formatDouble4(scale) + ",0,-" + gen.formatDouble4(scale) + ",2;"); gen.writeText("IR0,100,0,100;"); gen.writeText("PU;PA0,0;\n"); baout.writeTo(gen.getOutputStream()); //Buffer is written to output stream gen.writeText("\n"); gen.enterPCLMode(false); painted = true; } catch (UnsupportedOperationException uoe) { log.debug( "Cannot paint graphic natively. Falling back to bitmap painting. Reason: " + uoe.getMessage()); } if (!painted) { //Fallback solution: Paint to a BufferedImage FOUserAgent ua = context.getUserAgent(); ImageManager imageManager = ua.getFactory().getImageManager(); ImageRendered imgRend; try { imgRend = (ImageRendered)imageManager.convertImage( imageG2D, new ImageFlavor[] {ImageFlavor.RENDERED_IMAGE}/*, hints*/); } catch (ImageException e) { throw new IOException( "Image conversion error while converting the image to a bitmap" + " as a fallback measure: " + e.getMessage()); } gen.paintBitmap(imgRend.getRenderedImage(), new Dimension(pos.width, pos.height), pclContext.isSourceTransparencyEnabled()); } }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
protected void applyStroke(Stroke stroke) throws IOException { if (stroke instanceof BasicStroke) { BasicStroke bs = (BasicStroke)stroke; float[] da = bs.getDashArray(); if (da != null) { gen.writeText("UL1,"); int len = Math.min(20, da.length); float patternLen = 0.0f; for (int idx = 0; idx < len; idx++) { patternLen += da[idx]; } if (len == 1) { patternLen *= 2; } for (int idx = 0; idx < len; idx++) { float perc = da[idx] * 100 / patternLen; gen.writeText(gen.formatDouble2(perc)); if (idx < da.length - 1) { gen.writeText(","); } } if (len == 1) { gen.writeText("," + gen.formatDouble2(da[0] * 100 / patternLen )); } gen.writeText(";"); /* TODO Dash phase NYI float offset = bs.getDashPhase(); gen.writeln(gen.formatDouble4(offset) + " setdash"); */ Point2D ptLen = new Point2D.Double(patternLen, 0); //interpret as absolute length getTransform().deltaTransform(ptLen, ptLen); double transLen = UnitConv.pt2mm(ptLen.distance(0, 0)); gen.writeText("LT1," + gen.formatDouble4(transLen) + ",1;"); } else { gen.writeText("LT;"); } gen.writeText("LA1"); //line cap int ec = bs.getEndCap(); switch (ec) { case BasicStroke.CAP_BUTT: gen.writeText(",1"); break; case BasicStroke.CAP_ROUND: gen.writeText(",4"); break; case BasicStroke.CAP_SQUARE: gen.writeText(",2"); break; default: System.err.println("Unsupported line cap: " + ec); } gen.writeText(",2"); //line join int lj = bs.getLineJoin(); switch (lj) { case BasicStroke.JOIN_MITER: gen.writeText(",1"); break; case BasicStroke.JOIN_ROUND: gen.writeText(",4"); break; case BasicStroke.JOIN_BEVEL: gen.writeText(",5"); break; default: System.err.println("Unsupported line join: " + lj); } float ml = bs.getMiterLimit(); gen.writeText(",3" + gen.formatDouble4(ml)); float lw = bs.getLineWidth(); Point2D ptSrc = new Point2D.Double(lw, 0); //Pen widths are set as absolute metric values (WU0;) Point2D ptDest = getTransform().deltaTransform(ptSrc, null); double transDist = UnitConv.pt2mm(ptDest.distance(0, 0)); //System.out.println("--" + ptDest.distance(0, 0) + " " + transDist); gen.writeText(";PW" + gen.formatDouble4(transDist) + ";"); } else { handleUnsupportedFeature("Unsupported Stroke: " + stroke.getClass().getName()); } }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
protected void applyPaint(Paint paint) throws IOException { if (paint instanceof Color) { Color col = (Color)paint; int shade = gen.convertToPCLShade(col); gen.writeText("TR0;FT10," + shade + ";"); } else { handleUnsupportedFeature("Unsupported Paint: " + paint.getClass().getName()); } }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
private void writeClip(Shape imclip) throws IOException { if (clippingDisabled) { return; } if (imclip == null) { //gen.writeText("IW;"); } else { handleUnsupportedFeature("Clipping is not supported. Shape: " + imclip); /* This is an attempt to clip using the "InputWindow" (IW) but this only allows to * clip a rectangular area. Force falling back to bitmap mode for now. Rectangle2D bounds = imclip.getBounds2D(); Point2D p1 = new Point2D.Double(bounds.getX(), bounds.getY()); Point2D p2 = new Point2D.Double( bounds.getX() + bounds.getWidth(), bounds.getY() + bounds.getHeight()); getTransform().transform(p1, p1); getTransform().transform(p2, p2); gen.writeText("IW" + gen.formatDouble4(p1.getX()) + "," + gen.formatDouble4(p2.getY()) + "," + gen.formatDouble4(p2.getX()) + "," + gen.formatDouble4(p1.getY()) + ";"); */ } }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
public void processPathIteratorStroke(PathIterator iter) throws IOException { gen.writeText("\n"); double[] vals = new double[6]; boolean penDown = false; double x = 0; double y = 0; StringBuffer sb = new StringBuffer(256); penUp(sb); while (!iter.isDone()) { int type = iter.currentSegment(vals); if (type == PathIterator.SEG_CLOSE) { gen.writeText("PM;"); gen.writeText(sb.toString()); gen.writeText("PM2;EP;"); sb.setLength(0); iter.next(); continue; } else if (type == PathIterator.SEG_MOVETO) { gen.writeText(sb.toString()); sb.setLength(0); if (penDown) { penUp(sb); penDown = false; } } else { if (!penDown) { penDown(sb); penDown = true; } } switch (type) { case PathIterator.SEG_CLOSE: break; case PathIterator.SEG_MOVETO: x = vals[0]; y = vals[1]; plotAbsolute(x, y, sb); gen.writeText(sb.toString()); sb.setLength(0); break; case PathIterator.SEG_LINETO: x = vals[0]; y = vals[1]; plotAbsolute(x, y, sb); break; case PathIterator.SEG_CUBICTO: x = vals[4]; y = vals[5]; bezierAbsolute(vals[0], vals[1], vals[2], vals[3], x, y, sb); break; case PathIterator.SEG_QUADTO: double originX = x; double originY = y; x = vals[2]; y = vals[3]; quadraticBezierAbsolute(originX, originY, vals[0], vals[1], x, y, sb); break; default: break; } iter.next(); } sb.append("\n"); gen.writeText(sb.toString()); }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
public void processPathIteratorFill(PathIterator iter) throws IOException { gen.writeText("\n"); double[] vals = new double[6]; boolean penDown = false; double x = 0; double y = 0; boolean pendingPM0 = true; StringBuffer sb = new StringBuffer(256); penUp(sb); while (!iter.isDone()) { int type = iter.currentSegment(vals); if (type == PathIterator.SEG_CLOSE) { sb.append("PM1;"); iter.next(); continue; } else if (type == PathIterator.SEG_MOVETO) { if (penDown) { penUp(sb); penDown = false; } } else { if (!penDown) { penDown(sb); penDown = true; } } switch (type) { case PathIterator.SEG_MOVETO: x = vals[0]; y = vals[1]; plotAbsolute(x, y, sb); break; case PathIterator.SEG_LINETO: x = vals[0]; y = vals[1]; plotAbsolute(x, y, sb); break; case PathIterator.SEG_CUBICTO: x = vals[4]; y = vals[5]; bezierAbsolute(vals[0], vals[1], vals[2], vals[3], x, y, sb); break; case PathIterator.SEG_QUADTO: double originX = x; double originY = y; x = vals[2]; y = vals[3]; quadraticBezierAbsolute(originX, originY, vals[0], vals[1], x, y, sb); break; default: throw new IllegalStateException("Must not get here"); } if (pendingPM0) { pendingPM0 = false; sb.append("PM;"); } iter.next(); } sb.append("PM2;"); fillPolygon(iter.getWindingRule(), sb); sb.append("\n"); gen.writeText(sb.toString()); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
private void drawTextNative(int x, int y, int letterSpacing, int wordSpacing, int[][] dp, String text, FontTriplet triplet) throws IOException { Color textColor = state.getTextColor(); if (textColor != null) { gen.setTransparencyMode(true, false); gen.selectGrayscale(textColor); } gen.setTransparencyMode(true, true); setCursorPos(x, y); float fontSize = state.getFontSize() / 1000f; Font font = parent.getFontInfo().getFontInstance(triplet, state.getFontSize()); int l = text.length(); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); StringBuffer sb = new StringBuffer(Math.max(16, l)); if (dx != null && dxl > 0 && dx[0] != 0) { sb.append("\u001B&a+").append(gen.formatDouble2(dx[0] / 100.0)).append('H'); } for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); char ch; float glyphAdjust = 0; if (font.hasChar(orgChar)) { ch = font.mapChar(orgChar); } else { if (CharUtilities.isFixedWidthSpace(orgChar)) { //Fixed width space are rendered as spaces so copy/paste works in a reader ch = font.mapChar(CharUtilities.SPACE); int spaceDiff = font.getCharWidth(ch) - font.getCharWidth(orgChar); glyphAdjust = -(10 * spaceDiff / fontSize); } else { ch = font.mapChar(orgChar); } } sb.append(ch); if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust += wordSpacing; } glyphAdjust += letterSpacing; if (dx != null && i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { sb.append("\u001B&a+").append(gen.formatDouble2(glyphAdjust / 100.0)).append('H'); } } gen.getOutputStream().write(sb.toString().getBytes(gen.getTextEncoding())); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
private void concatenateTransformationMatrix(AffineTransform transform) throws IOException { if (!transform.isIdentity()) { graphicContext.transform(transform); changePrintDirection(); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
private void changePrintDirection() throws IOException { AffineTransform at = graphicContext.getTransform(); int newDir; newDir = PCLRenderingUtil.determinePrintDirection(at); if (newDir != this.currentPrintDirection) { this.currentPrintDirection = newDir; gen.changePrintDirection(this.currentPrintDirection); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
void setCursorPos(int x, int y) throws IOException { Point2D transPoint = transformedPoint(x, y); gen.setCursorPos(transPoint.getX(), transPoint.getY()); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void writeCommand(String cmd) throws IOException { out.write(27); //ESC out.write(cmd.getBytes(US_ASCII)); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void writeText(String s) throws IOException { out.write(s.getBytes(ISO_8859_1)); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void universalEndOfLanguage() throws IOException { writeCommand("%-12345X"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void resetPrinter() throws IOException { writeCommand("E"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void separateJobs() throws IOException { writeCommand("&l1T"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void formFeed() throws IOException { out.write(12); //=OC ("FF", Form feed) }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setUnitOfMeasure(int value) throws IOException { writeCommand("&u" + value + "D"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setRasterGraphicsResolution(int value) throws IOException { writeCommand("*t" + value + "R"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void selectPageSize(int selector) throws IOException { writeCommand("&l" + selector + "A"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void selectPaperSource(int selector) throws IOException { writeCommand("&l" + selector + "H"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void selectOutputBin(int selector) throws IOException { writeCommand("&l" + selector + "G"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void selectDuplexMode(int selector) throws IOException { writeCommand("&l" + selector + "S"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void clearHorizontalMargins() throws IOException { writeCommand("9"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setTopMargin(int numberOfLines) throws IOException { writeCommand("&l" + numberOfLines + "E"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setTextLength(int numberOfLines) throws IOException { writeCommand("&l" + numberOfLines + "F"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setVMI(double value) throws IOException { writeCommand("&l" + formatDouble4(value) + "C"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setCursorPos(double x, double y) throws IOException { if (x < 0) { //A negative x value will result in a relative movement so go to "0" first. //But this will most probably have no effect anyway since you can't paint to the left //of the logical page writeCommand("&a0h" + formatDouble2(x / 100) + "h" + formatDouble2(y / 100) + "V"); } else { writeCommand("&a" + formatDouble2(x / 100) + "h" + formatDouble2(y / 100) + "V"); } }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void pushCursorPos() throws IOException { writeCommand("&f0S"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void popCursorPos() throws IOException { writeCommand("&f1S"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void changePrintDirection(int rotate) throws IOException { writeCommand("&a" + rotate + "P"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void enterHPGL2Mode(boolean restorePreviousHPGL2Cursor) throws IOException { if (restorePreviousHPGL2Cursor) { writeCommand("%0B"); } else { writeCommand("%1B"); } }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void enterPCLMode(boolean restorePreviousPCLCursor) throws IOException { if (restorePreviousPCLCursor) { writeCommand("%0A"); } else { writeCommand("%1A"); } }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
protected void fillRect(int w, int h, Color col) throws IOException { if ((w == 0) || (h == 0)) { return; } if (h < 0) { h *= -1; } else { //y += h; } setPatternTransparencyMode(false); if (usePCLShades || Color.black.equals(col) || Color.white.equals(col)) { writeCommand("*c" + formatDouble4(w / 100.0) + "h" + formatDouble4(h / 100.0) + "V"); int lineshade = convertToPCLShade(col); writeCommand("*c" + lineshade + "G"); writeCommand("*c2P"); //Shaded fill } else { defineGrayscalePattern(col, 32, DitherUtil.DITHER_MATRIX_4X4); writeCommand("*c" + formatDouble4(w / 100.0) + "h" + formatDouble4(h / 100.0) + "V"); writeCommand("*c32G"); writeCommand("*c4P"); //User-defined pattern } // Reset pattern transparency mode. setPatternTransparencyMode(true); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void defineGrayscalePattern(Color col, int patternID, int ditherMatrixSize) throws IOException { ByteArrayOutputStream baout = new ByteArrayOutputStream(); DataOutputStream data = new DataOutputStream(baout); data.writeByte(0); //Format data.writeByte(0); //Continuation data.writeByte(1); //Pixel Encoding data.writeByte(0); //Reserved data.writeShort(8); //Width in Pixels data.writeShort(8); //Height in Pixels //data.writeShort(600); //X Resolution (didn't manage to get that to work) //data.writeShort(600); //Y Resolution int gray255 = convertToGray(col.getRed(), col.getGreen(), col.getBlue()); byte[] pattern; if (ditherMatrixSize == 8) { pattern = DitherUtil.getBayerDither(DitherUtil.DITHER_MATRIX_8X8, gray255, false); } else { //Since a 4x4 pattern did not work, the 4x4 pattern is applied 4 times to an //8x8 pattern. Maybe this could be changed to use an 8x8 bayer dither pattern //instead of the 4x4 one. pattern = DitherUtil.getBayerDither(DitherUtil.DITHER_MATRIX_4X4, gray255, true); } data.write(pattern); if ((baout.size() % 2) > 0) { baout.write(0); } writeCommand("*c" + patternID + "G"); writeCommand("*c" + baout.size() + "W"); baout.writeTo(this.out); writeCommand("*c4Q"); //temporary pattern }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setSourceTransparencyMode(boolean transparent) throws IOException { setTransparencyMode(transparent, currentPatternTransparency); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setPatternTransparencyMode(boolean transparent) throws IOException { setTransparencyMode(currentSourceTransparency, transparent); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void setTransparencyMode(boolean source, boolean pattern) throws IOException { if (source != currentSourceTransparency && pattern != currentPatternTransparency) { writeCommand("*v" + (source ? '0' : '1') + "n" + (pattern ? '0' : '1') + "O"); } else if (source != currentSourceTransparency) { writeCommand("*v" + (source ? '0' : '1') + "N"); } else if (pattern != currentPatternTransparency) { writeCommand("*v" + (pattern ? '0' : '1') + "O"); } this.currentSourceTransparency = source; this.currentPatternTransparency = pattern; }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void selectGrayscale(Color col) throws IOException { if (Color.black.equals(col)) { selectCurrentPattern(0, 0); //black } else if (Color.white.equals(col)) { selectCurrentPattern(0, 1); //white } else { if (usePCLShades) { selectCurrentPattern(convertToPCLShade(col), 2); } else { defineGrayscalePattern(col, 32, DitherUtil.DITHER_MATRIX_4X4); selectCurrentPattern(32, 4); } } }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void selectCurrentPattern(int patternID, int pattern) throws IOException { if (pattern > 1) { writeCommand("*c" + patternID + "G"); } writeCommand("*v" + pattern + "T"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void paintBitmap(RenderedImage img, Dimension targetDim, boolean sourceTransparency) throws IOException { double targetHResolution = img.getWidth() / UnitConv.mpt2in(targetDim.width); double targetVResolution = img.getHeight() / UnitConv.mpt2in(targetDim.height); double targetResolution = Math.max(targetHResolution, targetVResolution); int resolution = (int)Math.round(targetResolution); int effResolution = calculatePCLResolution(resolution, true); Dimension orgDim = new Dimension(img.getWidth(), img.getHeight()); Dimension effDim; if (targetResolution == effResolution) { effDim = orgDim; //avoid scaling side-effects } else { effDim = new Dimension( (int)Math.ceil(UnitConv.mpt2px(targetDim.width, effResolution)), (int)Math.ceil(UnitConv.mpt2px(targetDim.height, effResolution))); } boolean scaled = !orgDim.equals(effDim); //ImageWriterUtil.saveAsPNG(img, new java.io.File("D:/text-0-org.png")); boolean monochrome = isMonochromeImage(img); if (!monochrome) { //Transparency mask disabled. Doesn't work reliably final boolean transparencyDisabled = true; RenderedImage mask = (transparencyDisabled ? null : getMask(img, effDim)); if (mask != null) { pushCursorPos(); selectCurrentPattern(0, 1); //Solid white setTransparencyMode(true, true); paintMonochromeBitmap(mask, effResolution); popCursorPos(); } RenderedImage red = BitmapImageUtil.convertToMonochrome( img, effDim, this.ditheringQuality); selectCurrentPattern(0, 0); //Solid black setTransparencyMode(sourceTransparency || mask != null, true); paintMonochromeBitmap(red, effResolution); } else { RenderedImage effImg = img; if (scaled) { effImg = BitmapImageUtil.convertToMonochrome(img, effDim); } setSourceTransparencyMode(sourceTransparency); selectCurrentPattern(0, 0); //Solid black paintMonochromeBitmap(effImg, effResolution); } }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void paintMonochromeBitmap(RenderedImage img, int resolution) throws IOException { if (!isValidPCLResolution(resolution)) { throw new IllegalArgumentException("Invalid PCL resolution: " + resolution); } boolean monochrome = isMonochromeImage(img); if (!monochrome) { throw new IllegalArgumentException("img must be a monochrome image"); } setRasterGraphicsResolution(resolution); writeCommand("*r0f" + img.getHeight() + "t" + img.getWidth() + "s1A"); Raster raster = img.getData(); Encoder encoder = new Encoder(img); // Transfer graphics data int imgw = img.getWidth(); IndexColorModel cm = (IndexColorModel)img.getColorModel(); if (cm.getTransferType() == DataBuffer.TYPE_BYTE) { DataBufferByte dataBuffer = (DataBufferByte)raster.getDataBuffer(); MultiPixelPackedSampleModel packedSampleModel = new MultiPixelPackedSampleModel( DataBuffer.TYPE_BYTE, img.getWidth(), img.getHeight(), 1); if (img.getSampleModel().equals(packedSampleModel) && dataBuffer.getNumBanks() == 1) { //Optimized packed encoding byte[] buf = dataBuffer.getData(); int scanlineStride = packedSampleModel.getScanlineStride(); int idx = 0; int c0 = toGray(cm.getRGB(0)); int c1 = toGray(cm.getRGB(1)); boolean zeroIsWhite = c0 > c1; for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { for (int x = 0, maxx = scanlineStride; x < maxx; x++) { if (zeroIsWhite) { encoder.add8Bits(buf[idx]); } else { encoder.add8Bits((byte)~buf[idx]); } idx++; } encoder.endLine(); } } else { //Optimized non-packed encoding for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { byte[] line = (byte[])raster.getDataElements(0, y, imgw, 1, null); for (int x = 0, maxx = imgw; x < maxx; x++) { encoder.addBit(line[x] == 0); } encoder.endLine(); } } } else { //Safe but slow fallback for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { for (int x = 0, maxx = imgw; x < maxx; x++) { int sample = raster.getSample(x, y, 0); encoder.addBit(sample == 0); } encoder.endLine(); } } // End raster graphics writeCommand("*rB"); }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void endLine() throws IOException { if (zeroRow && PCLGenerator.this.currentSourceTransparency) { writeCommand("*b1Y"); } else if (rlewidth < bytewidth) { writeCommand("*b1m" + rlewidth + "W"); out.write(rle, 0, rlewidth); } else { writeCommand("*b0m" + bytewidth + "W"); out.write(uncompressed); } lastcount = -1; rlewidth = 0; ib = 0; x = 0; zeroRow = true; }
// in src/java/org/apache/fop/render/pcl/HardcodedFonts.java
public static boolean setFont(PCLGenerator gen, String name, int size, String text) throws IOException { byte[] encoded = text.getBytes("ISO-8859-1"); for (int i = 0, c = encoded.length; i < c; i++) { if (encoded[i] == 0x3F && text.charAt(i) != '?') { return false; } } return selectFont(gen, name, size); }
// in src/java/org/apache/fop/render/pcl/HardcodedFonts.java
private static boolean selectFont(PCLGenerator gen, String name, int size) throws IOException { int fontcode = 0; if (name.length() > 1 && name.charAt(0) == 'F') { try { fontcode = Integer.parseInt(name.substring(1)); } catch (Exception e) { LOG.error(e); } } //Note "(ON" selects ISO 8859-1 symbol set as used by PCLGenerator String formattedSize = gen.formatDouble2(size / 1000.0); switch (fontcode) { case 1: // F1 = Helvetica // gen.writeCommand("(8U"); // gen.writeCommand("(s1p" + formattedSize + "v0s0b24580T"); // Arial is more common among PCL5 printers than Helvetica - so use Arial gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v0s0b16602T"); break; case 2: // F2 = Helvetica Oblique gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v1s0b16602T"); break; case 3: // F3 = Helvetica Bold gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v0s3b16602T"); break; case 4: // F4 = Helvetica Bold Oblique gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v1s3b16602T"); break; case 5: // F5 = Times Roman // gen.writeCommand("(8U"); // gen.writeCommand("(s1p" + formattedSize + "v0s0b25093T"); // Times New is more common among PCL5 printers than Times - so use Times New gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v0s0b16901T"); break; case 6: // F6 = Times Italic gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v1s0b16901T"); break; case 7: // F7 = Times Bold gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v0s3b16901T"); break; case 8: // F8 = Times Bold Italic gen.writeCommand("(0N"); gen.writeCommand("(s1p" + formattedSize + "v1s3b16901T"); break; case 9: // F9 = Courier gen.writeCommand("(0N"); gen.writeCommand("(s0p" + gen.formatDouble2(120.01f / (size / 1000.00f)) + "h0s0b4099T"); break; case 10: // F10 = Courier Oblique gen.writeCommand("(0N"); gen.writeCommand("(s0p" + gen.formatDouble2(120.01f / (size / 1000.00f)) + "h1s0b4099T"); break; case 11: // F11 = Courier Bold gen.writeCommand("(0N"); gen.writeCommand("(s0p" + gen.formatDouble2(120.01f / (size / 1000.00f)) + "h0s3b4099T"); break; case 12: // F12 = Courier Bold Oblique gen.writeCommand("(0N"); gen.writeCommand("(s0p" + gen.formatDouble2(120.01f / (size / 1000.00f)) + "h1s3b4099T"); break; case 13: // F13 = Symbol return false; //gen.writeCommand("(19M"); //gen.writeCommand("(s1p" + formattedSize + "v0s0b16686T"); // ECMA Latin 1 Symbol Set in Times Roman??? // gen.writeCommand("(9U"); // gen.writeCommand("(s1p" + formattedSize + "v0s0b25093T"); //break; case 14: // F14 = Zapf Dingbats return false; //gen.writeCommand("(14L"); //gen.writeCommand("(s1p" + formattedSize + "v0s0b45101T"); //break; default: //gen.writeCommand("(0N"); //gen.writeCommand("(s" + formattedSize + "V"); return false; } return true; }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerRenderedImage.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PCLRenderingContext pclContext = (PCLRenderingContext)context; ImageRendered imageRend = (ImageRendered)image; PCLGenerator gen = pclContext.getPCLGenerator(); RenderedImage ri = imageRend.getRenderedImage(); Point2D transPoint = pclContext.transformedPoint(pos.x, pos.y); gen.setCursorPos(transPoint.getX(), transPoint.getY()); gen.paintBitmap(ri, new Dimension(pos.width, pos.height), pclContext.isSourceTransparencyEnabled()); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public RtfTableCell newTableCell(int cellWidth) throws IOException { highestCell++; cell = new RtfTableCell(this, writer, cellWidth, highestCell); return cell; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public RtfTableCell newTableCell(int cellWidth, RtfAttributes attrs) throws IOException { highestCell++; cell = new RtfTableCell(this, writer, cellWidth, attrs, highestCell); return cell; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public RtfTableCell newTableCellMergedVertically(int cellWidth, RtfAttributes attrs) throws IOException { highestCell++; cell = new RtfTableCell (this, writer, cellWidth, attrs, highestCell); cell.setVMerge(RtfTableCell.MERGE_WITH_PREVIOUS); return cell; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public RtfTableCell newTableCellMergedHorizontally (int cellWidth, RtfAttributes attrs) throws IOException, FOPException { highestCell++; // Added by Normand Masse // Inherit attributes from base cell for merge RtfAttributes wAttributes = null; if (attrs != null) { try { wAttributes = (RtfAttributes)attrs.clone(); } catch (CloneNotSupportedException e) { throw new FOPException(e); } } cell = new RtfTableCell(this, writer, cellWidth, wAttributes, highestCell); cell.setHMerge(RtfTableCell.MERGE_WITH_PREVIOUS); return cell; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
protected void writeRtfPrefix() throws IOException { newLine(); writeGroupMark(true); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
protected void writeRtfContent() throws IOException { if (getTable().isNestedTable()) { //nested table writeControlWord("intbl"); //itap is the depth (level) of the current nested table writeControlWord("itap" + getTable().getNestedTableDepth()); } else { //normal (not nested) table writeRowAndCellsDefintions(); } // now children can write themselves, we have the correct RTF prefix code super.writeRtfContent(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
public void writeRowAndCellsDefintions() throws IOException { // render the row and cells definitions writeControlWord("trowd"); if (!getTable().isNestedTable()) { writeControlWord("itap0"); } //check for keep-together if (attrib != null && attrib.isSet(ITableAttributes.ROW_KEEP_TOGETHER)) { writeControlWord(ROW_KEEP_TOGETHER); } writePaddingAttributes(); final RtfTable parentTable = (RtfTable) parent; adjustBorderProperties(parentTable); writeAttributes(attrib, new String[]{ITableAttributes.ATTR_HEADER}); writeAttributes(attrib, ITableAttributes.ROW_BORDER); writeAttributes(attrib, ITableAttributes.CELL_BORDER); writeAttributes(attrib, IBorderAttributes.BORDERS); if (attrib.isSet(ITableAttributes.ROW_HEIGHT)) { writeOneAttribute( ITableAttributes.ROW_HEIGHT, attrib.getValue(ITableAttributes.ROW_HEIGHT)); } // write X positions of our cells int xPos = 0; final Object leftIndent = attrib.getValue(ITableAttributes.ATTR_ROW_LEFT_INDENT); if (leftIndent != null) { xPos = ((Integer)leftIndent).intValue(); } RtfAttributes tableBorderAttributes = getTable().getBorderAttributes(); int index = 0; for (Iterator it = getChildren().iterator(); it.hasNext();) { final RtfElement e = (RtfElement)it.next(); if (e instanceof RtfTableCell) { RtfTableCell rtfcell = (RtfTableCell)e; // Adjust the cell's display attributes so the table's/row's borders // are drawn properly. if (tableBorderAttributes != null) { // get border attributes from table if (index == 0) { String border = ITableAttributes.CELL_BORDER_LEFT; if (!rtfcell.getRtfAttributes().isSet(border)) { rtfcell.getRtfAttributes().set(border, (RtfAttributes) tableBorderAttributes.getValue(border)); } } if (index == this.getChildCount() - 1) { String border = ITableAttributes.CELL_BORDER_RIGHT; if (!rtfcell.getRtfAttributes().isSet(border)) { rtfcell.getRtfAttributes().set(border, (RtfAttributes) tableBorderAttributes.getValue(border)); } } if (isFirstRow()) { String border = ITableAttributes.CELL_BORDER_TOP; if (!rtfcell.getRtfAttributes().isSet(border)) { rtfcell.getRtfAttributes().set(border, (RtfAttributes) tableBorderAttributes.getValue(border)); } } if ((parentTable != null) && (parentTable.isHighestRow(id))) { String border = ITableAttributes.CELL_BORDER_BOTTOM; if (!rtfcell.getRtfAttributes().isSet(border)) { rtfcell.getRtfAttributes().set(border, (RtfAttributes) tableBorderAttributes.getValue(border)); } } } // get border attributes from row if (index == 0) { if (!rtfcell.getRtfAttributes().isSet(ITableAttributes.CELL_BORDER_LEFT)) { rtfcell.getRtfAttributes().set(ITableAttributes.CELL_BORDER_LEFT, (String) attrib.getValue(ITableAttributes.ROW_BORDER_LEFT)); } } if (index == this.getChildCount() - 1) { if (!rtfcell.getRtfAttributes().isSet(ITableAttributes.CELL_BORDER_RIGHT)) { rtfcell.getRtfAttributes().set(ITableAttributes.CELL_BORDER_RIGHT, (String) attrib.getValue(ITableAttributes.ROW_BORDER_RIGHT)); } } if (isFirstRow()) { if (!rtfcell.getRtfAttributes().isSet(ITableAttributes.CELL_BORDER_TOP)) { rtfcell.getRtfAttributes().set(ITableAttributes.CELL_BORDER_TOP, (String) attrib.getValue(ITableAttributes.ROW_BORDER_TOP)); } } if ((parentTable != null) && (parentTable.isHighestRow(id))) { if (!rtfcell.getRtfAttributes().isSet(ITableAttributes.CELL_BORDER_BOTTOM)) { rtfcell.getRtfAttributes().set(ITableAttributes.CELL_BORDER_BOTTOM, (String) attrib.getValue(ITableAttributes.ROW_BORDER_BOTTOM)); } } // write cell's definition xPos = rtfcell.writeCellDef(xPos); } index++; // Added by Boris POUDEROUS on 2002/07/02 } newLine(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
protected void writeRtfSuffix() throws IOException { if (getTable().isNestedTable()) { //nested table writeGroupMark(true); writeStarControlWord("nesttableprops"); writeRowAndCellsDefintions(); writeControlWordNS("nestrow"); writeGroupMark(false); writeGroupMark(true); writeControlWord("nonesttables"); writeControlWord("par"); writeGroupMark(false); } else { writeControlWord("row"); } writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableRow.java
private void writePaddingAttributes() throws IOException { // Row padding attributes generated in the converter package // use RTF 1.6 definitions - try to compute a reasonable RTF 1.5 value // out of them if present // how to do vertical padding with RTF 1.5? if (attrib != null && !attrib.isSet(ATTR_RTF_15_TRGAPH)) { int gaph = -1; try { // set (RTF 1.5) gaph to the average of the (RTF 1.6) left and right padding values final Integer leftPadStr = (Integer)attrib.getValue(ATTR_ROW_PADDING_LEFT); if (leftPadStr != null) { gaph = leftPadStr.intValue(); } final Integer rightPadStr = (Integer)attrib.getValue(ATTR_ROW_PADDING_RIGHT); if (rightPadStr != null) { gaph = (gaph + rightPadStr.intValue()) / 2; } } catch (Exception e) { final String msg = "RtfTableRow.writePaddingAttributes: " + e.toString(); // getRtfFile().getLog().logWarning(msg); } if (gaph >= 0) { attrib.set(ATTR_RTF_15_TRGAPH, gaph); } } // write all padding attributes writeAttributes(attrib, ATTRIB_ROW_PADDING); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfPageNumber.java
protected void writeRtfContent() throws IOException { /* writeGroupMark(true); writeControlWord(RTF_FIELD); writeGroupMark(true); writeAttributes(attrib, RtfText.ATTR_NAMES); // Added by Boris Poudérous writeStarControlWord(RTF_FIELD_PAGE); writeGroupMark(false); writeGroupMark(true); writeControlWord(RTF_FIELD_RESULT); writeGroupMark(false); writeGroupMark(false); */ writeGroupMark(true); writeAttributes(attrib, RtfText.ATTR_NAMES); writeControlWord("chpgn"); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfHeader startHeader() throws IOException, RtfStructureException { if (header != null) { throw new RtfStructureException("startHeader called more than once"); } header = new RtfHeader(this, writer); listTableContainer = new RtfContainer(this, writer); return header; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfListTable startListTable(RtfAttributes attr) throws IOException { listNum++; if (listTable != null) { return listTable; } else { listTable = new RtfListTable(this, writer, new Integer(listNum), attr); listTableContainer.addChild(listTable); } return listTable; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfPageArea startPageArea() throws IOException, RtfStructureException { if (pageArea != null) { throw new RtfStructureException("startPageArea called more than once"); } // create an empty header if there was none if (header == null) { startHeader(); } header.close(); pageArea = new RtfPageArea(this, writer); addChild(pageArea); return pageArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfPageArea getPageArea() throws IOException, RtfStructureException { if (pageArea == null) { return startPageArea(); } return pageArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfDocumentArea startDocumentArea() throws IOException, RtfStructureException { if (docArea != null) { throw new RtfStructureException("startDocumentArea called more than once"); } // create an empty header if there was none if (header == null) { startHeader(); } header.close(); docArea = new RtfDocumentArea(this, writer); addChild(docArea); return docArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfDocumentArea getDocumentArea() throws IOException, RtfStructureException { if (docArea == null) { return startDocumentArea(); } return docArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
protected void writeRtfPrefix() throws IOException { writeGroupMark(true); writeControlWord("rtf1"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
protected void writeRtfSuffix() throws IOException { writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public synchronized void flush() throws IOException { writeRtf(); writer.flush(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfText.java
public void writeRtfContent() throws IOException { writeChars: { //these lines were added by Boris Pouderous if (attr != null) { writeAttributes(attr, new String[] {RtfText.SPACE_BEFORE}); writeAttributes(attr, new String[] {RtfText.SPACE_AFTER}); } if (isTab()) { writeControlWord("tab"); } else if (isNewLine()) { break writeChars; } else if (isBold(true)) { writeControlWord("b"); } else if (isBold(false)) { writeControlWord("b0"); // TODO not optimal, consecutive RtfText with same attributes // could be written without group marks } else { writeGroupMark(true); if (attr != null && mustWriteAttributes()) { writeAttributes(attr, RtfText.ATTR_NAMES); } RtfStringConverter.getInstance().writeRtfString(writer, text); writeGroupMark(false); } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public RtfParagraph newParagraph() throws IOException { closeAll(); para = new RtfParagraph(this, writer); return para; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public RtfParagraph newParagraph(RtfAttributes attrs) throws IOException { closeAll(); para = new RtfParagraph(this, writer, attrs); return para; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public RtfExternalGraphic newImage() throws IOException { closeAll(); externalGraphic = new RtfExternalGraphic(this, writer); return externalGraphic; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
private void closeCurrentParagraph() throws IOException { if (para != null) { para.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
private void closeCurrentExternalGraphic() throws IOException { if (externalGraphic != null) { externalGraphic.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
private void closeCurrentTable() throws IOException { if (table != null) { table.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
protected void writeRtfPrefix() throws IOException { writeGroupMark(true); writeMyAttributes(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
protected void writeRtfSuffix() throws IOException { writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public void closeAll() throws IOException { closeCurrentParagraph(); closeCurrentExternalGraphic(); closeCurrentTable(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public RtfTable newTable(RtfAttributes attrs, ITableColumnsInfo tc) throws IOException { closeAll(); table = new RtfTable(this, writer, attrs, tc); return table; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public RtfTable newTable(ITableColumnsInfo tc) throws IOException { closeAll(); table = new RtfTable(this, writer, tc); return table; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfterBeforeBase.java
public RtfTextrun getTextrun() throws IOException { return RtfTextrun.getTextrun(this, writer, null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyle.java
public void writeListPrefix(RtfListItem item) throws IOException { }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyle.java
public void writeParagraphPrefix(RtfElement element) throws IOException { }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyle.java
public void writeLevelGroup(RtfElement element) throws IOException { }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfExternalGraphic newImage() throws IOException { closeAll(); externalGraphic = new RtfExternalGraphic(this, writer); return externalGraphic; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfParagraph newParagraph(RtfAttributes attrs) throws IOException { closeAll(); paragraph = new RtfParagraph(this, writer, attrs); return paragraph; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfParagraph newParagraph() throws IOException { return newParagraph(null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfParagraphKeepTogether newParagraphKeepTogether() throws IOException { return new RtfParagraphKeepTogether(this, writer); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfTable newTable(ITableColumnsInfo tc) throws IOException { closeAll(); table = new RtfTable(this, writer, tc); return table; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfTable newTable(RtfAttributes attrs, ITableColumnsInfo tc) throws IOException { closeAll(); table = new RtfTable(this, writer, attrs, tc); return table; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfList newList(RtfAttributes attrs) throws IOException { closeAll(); list = new RtfList(this, writer, attrs); return list; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfBefore newBefore(RtfAttributes attrs) throws IOException { closeAll(); before = new RtfBefore(this, writer, attrs); return before; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfAfter newAfter(RtfAttributes attrs) throws IOException { closeAll(); after = new RtfAfter(this, writer, attrs); return after; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfJforCmd newJforCmd(RtfAttributes attrs) throws IOException { jforCmd = new RtfJforCmd(this, writer, attrs); return jforCmd; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
protected void writeRtfPrefix() throws IOException { writeAttributes(attrib, RtfPage.PAGE_ATTR); newLine(); writeControlWord("sectd"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
protected void writeRtfSuffix() throws IOException { // write suffix /sect only if this section is not last section (see bug #51484) List siblings = parent.getChildren(); if ( ( siblings.indexOf ( this ) + 1 ) < siblings.size() ) { writeControlWord("sect"); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
private void closeCurrentTable() throws IOException { if (table != null) { table.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
private void closeCurrentParagraph() throws IOException { if (paragraph != null) { paragraph.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
private void closeCurrentList() throws IOException { if (list != null) { list.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
private void closeCurrentExternalGraphic() throws IOException { if (externalGraphic != null) { externalGraphic.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
private void closeCurrentBefore() throws IOException { if (before != null) { before.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
private void closeAll() throws IOException { closeCurrentTable(); closeCurrentParagraph(); closeCurrentList(); closeCurrentExternalGraphic(); closeCurrentBefore(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfSection.java
public RtfTextrun getTextrun() throws IOException { return RtfTextrun.getTextrun(this, writer, null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfLeader.java
protected void writeRtfContent() throws IOException { int thickness = LEADER_STANDARD_WIDTH; String tablead = null; String tabwidth = null; for (Iterator it = attrs.nameIterator(); it.hasNext();) { final String name = (String)it.next(); if (attrs.isSet(name)) { if (name.equals(LEADER_TABLEAD)) { tablead = attrs.getValue(LEADER_TABLEAD).toString(); } else if (name.equals(LEADER_WIDTH)) { tabwidth = attrs.getValue(LEADER_WIDTH).toString(); } } } if (attrs.getValue(LEADER_RULE_THICKNESS) != null) { thickness += Integer.parseInt(attrs.getValue(LEADER_RULE_THICKNESS).toString()) / 1000 * 2; attrs.unset(LEADER_RULE_THICKNESS); } //Remove private attributes attrs.unset(LEADER_WIDTH); attrs.unset(LEADER_TABLEAD); // If leader is 100% we use a tabulator, because its more // comfortable, specially for the table of content if (attrs.getValue(LEADER_USETAB) != null) { attrs.unset(LEADER_USETAB); writeControlWord(LEADER_TAB_RIGHT); if (tablead != null) { writeControlWord(tablead); } writeControlWord(LEADER_TAB_WIDTH + tabwidth); writeGroupMark(true); writeControlWord(LEADER_IGNORE_STYLE); writeAttributes(attrs, null); writeControlWord(LEADER_EXPAND); writeControlWord(LEADER_TAB_VALUE); writeGroupMark(false); } else { // Using white spaces with different underline formats writeControlWord(LEADER_IGNORE_STYLE); writeControlWord(LEADER_ZERO_WIDTH); writeGroupMark(true); writeControlWord(LEADER_RULE_THICKNESS + thickness); writeControlWord(LEADER_UP); super.writeAttributes(attrs, null); if (tablead != null) { writeControlWord(tablead); } // Calculation for the necessary amount of white spaces // Depending on font-size 15 -> 1cm = 7,5 spaces // TODO for rule-thickness this has to be done better for (double d = (Integer.parseInt(tabwidth) / 560) * 7.5; d >= 1; d--) { RtfStringConverter.getInstance().writeRtfString(writer, " "); } writeGroupMark(false); writeControlWord(LEADER_ZERO_WIDTH); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfContainer.java
protected void writeRtfContent() throws IOException { for (Iterator it = children.iterator(); it.hasNext();) { final RtfElement e = (RtfElement)it.next(); e.writeRtf(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfContainer.java
void dump(Writer w, int indent) throws IOException { super.dump(w, indent); for (Iterator it = children.iterator(); it.hasNext();) { final RtfElement e = (RtfElement)it.next(); e.dump(w, indent + 1); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFontTable.java
protected void writeRtfContent() throws IOException { RtfFontManager.getInstance ().writeFonts ((RtfHeader)parent); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleBullet.java
public void writeListPrefix(RtfListItem item) throws IOException { // bulleted list item.writeControlWord("pnlvlblt"); item.writeControlWord("ilvl0"); item.writeOneAttribute(RtfListTable.LIST_NUMBER, new Integer(item.getNumber())); item.writeOneAttribute("pnindent", item.getParentList().attrib.getValue(RtfListTable.LIST_INDENT)); item.writeControlWord("pnf1"); item.writeGroupMark(true); item.writeControlWord("pndec"); item.writeOneAttribute(RtfListTable.LIST_FONT_TYPE, "2"); item.writeControlWord("pntxtb"); item.writeControlWord("'b7"); item.writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleBullet.java
public void writeParagraphPrefix(RtfElement element) throws IOException { element.writeGroupMark(true); element.writeControlWord("pntext"); element.writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleBullet.java
public void writeLevelGroup(RtfElement element) throws IOException { element.attrib.set(RtfListTable.LIST_NUMBER_TYPE, 23); element.writeGroupMark(true); element.writeOneAttributeNS(RtfListTable.LIST_TEXT_FORM, "\\'01\\'b7"); element.writeGroupMark(false); element.writeGroupMark(true); element.writeOneAttributeNS(RtfListTable.LIST_NUM_POSITION, null); element.writeGroupMark(false); element.attrib.set(RtfListTable.LIST_FONT_TYPE, 2); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfAfter.java
protected void writeMyAttributes() throws IOException { writeAttributes(attrib, FOOTER_ATTR); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfDocumentArea.java
public RtfSection newSection() throws IOException { if (currentSection != null) { currentSection.close(); } currentSection = new RtfSection(this, writer); return currentSection; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFontManager.java
public void writeFonts (RtfHeader header) throws IOException { if (fontTable == null || fontTable.size () == 0) { return; } header.newLine(); header.writeGroupMark(true); header.writeControlWord("fonttbl"); int len = fontTable.size (); for (int i = 0; i < len; i++) { header.writeGroupMark(true); header.newLine(); header.write("\\f" + i); header.write(" " + (String) fontTable.elementAt (i)); header.write(";"); header.writeGroupMark(false); } header.newLine(); header.writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
protected void writeRtfContent() throws IOException { writeGroupMark(true); writeAttributes(getRtfAttributes(), null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
protected void writeRtfContent() throws IOException { writeGroupMark(false); boolean bHasTableCellParent = this.getParentOfClass(RtfTableCell.class) != null; //Unknown behavior when a table starts a new section, //Word may crash if (breakType != BREAK_NONE) { if (!bHasTableCellParent) { writeControlWord("sect"); /* The following modifiers don't seem to appear in the right place */ switch (breakType) { case BREAK_EVEN_PAGE: writeControlWord("sbkeven"); break; case BREAK_ODD_PAGE: writeControlWord("sbkodd"); break; case BREAK_COLUMN: writeControlWord("sbkcol"); break; default: writeControlWord("sbkpage"); } } else { log.warn("Cannot create break-after for a paragraph inside a table."); } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
private void addOpenGroupMark(RtfAttributes attrs) throws IOException { RtfOpenGroupMark r = new RtfOpenGroupMark(this, writer, attrs); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
private void addCloseGroupMark(int breakType) throws IOException { RtfCloseGroupMark r = new RtfCloseGroupMark(this, writer, breakType); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
private void addCloseGroupMark() throws IOException { RtfCloseGroupMark r = new RtfCloseGroupMark(this, writer, BREAK_NONE); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void pushBlockAttributes(RtfAttributes attrs) throws IOException { rtfSpaceManager.stopUpdatingSpaceBefore(); RtfSpaceSplitter splitter = rtfSpaceManager.pushRtfSpaceSplitter(attrs); addOpenGroupMark(splitter.getCommonAttributes()); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void popBlockAttributes(int breakType) throws IOException { rtfSpaceManager.popRtfSpaceSplitter(); rtfSpaceManager.stopUpdatingSpaceBefore(); addCloseGroupMark(breakType); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void pushInlineAttributes(RtfAttributes attrs) throws IOException { rtfSpaceManager.pushInlineAttributes(attrs); addOpenGroupMark(attrs); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void addPageNumberCitation(String refId) throws IOException { RtfPageNumberCitation r = new RtfPageNumberCitation(this, writer, refId); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void popInlineAttributes() throws IOException { rtfSpaceManager.popInlineAttributes(); addCloseGroupMark(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void addString(String s) throws IOException { if (s.equals("")) { return; } RtfAttributes attrs = rtfSpaceManager.getLastInlineAttribute(); //add RtfSpaceSplitter to inherit accumulated space rtfSpaceManager.pushRtfSpaceSplitter(attrs); rtfSpaceManager.setCandidate(attrs); // create a string and add it as a child new RtfString(this, writer, s); rtfSpaceManager.popRtfSpaceSplitter(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public RtfFootnote addFootnote() throws IOException { return new RtfFootnote(this, writer); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public RtfParagraphBreak addParagraphBreak() throws IOException { // get copy of children list List children = getChildren(); Stack tmp = new Stack(); RtfParagraphBreak par = null; // delete all previous CloseGroupMark int deletedCloseGroupCount = 0; ListIterator lit = children.listIterator(children.size()); while (lit.hasPrevious() && (lit.previous() instanceof RtfCloseGroupMark)) { tmp.push(Integer.valueOf(((RtfCloseGroupMark)lit.next()).getBreakType())); lit.remove(); deletedCloseGroupCount++; } if (children.size() != 0) { // add paragraph break and restore all deleted close group marks setChildren(children); par = new RtfParagraphBreak(this, writer); for (int i = 0; i < deletedCloseGroupCount; i++) { addCloseGroupMark(((Integer)tmp.pop()).intValue()); } } return par; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void addLeader(RtfAttributes attrs) throws IOException { new RtfLeader(this, writer, attrs); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void addPageNumber(RtfAttributes attr) throws IOException { RtfPageNumber r = new RtfPageNumber(this, writer, attr); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public RtfHyperLink addHyperlink(RtfAttributes attr) throws IOException { return new RtfHyperLink(this, writer, attr); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public void addBookmark(String id) throws IOException { if (id != "") { // if id is not empty, add boormark new RtfBookmark(this, writer, id); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public RtfExternalGraphic newImage() throws IOException { return new RtfExternalGraphic(this, writer); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
public static RtfTextrun getTextrun(RtfContainer container, Writer writer, RtfAttributes attrs) throws IOException { List list = container.getChildren(); if (list.size() == 0) { //add a new RtfTextrun RtfTextrun textrun = new RtfTextrun(container, writer, attrs); list.add(textrun); return textrun; } Object obj = list.get(list.size() - 1); if (obj instanceof RtfTextrun) { //if the last child is a RtfTextrun, return it return (RtfTextrun) obj; } //add a new RtfTextrun as the last child RtfTextrun textrun = new RtfTextrun(container, writer, attrs); list.add(textrun); return textrun; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTextrun.java
protected void writeRtfContent() throws IOException { /** *TODO: The textrun's children are iterated twice: * 1. To determine the last RtfParagraphBreak * 2. To write the children * Maybe this can be done more efficient. */ boolean bHasTableCellParent = this.getParentOfClass(RtfTableCell.class) != null; RtfAttributes attrBlockLevel = new RtfAttributes(); //determine, if this RtfTextrun is the last child of its parent boolean bLast = false; for (Iterator it = parent.getChildren().iterator(); it.hasNext();) { if (it.next() == this) { bLast = !it.hasNext(); break; } } //get last RtfParagraphBreak, which is not followed by any visible child RtfParagraphBreak lastParagraphBreak = null; if (bLast) { RtfElement aBefore = null; for (Iterator it = getChildren().iterator(); it.hasNext();) { final RtfElement e = (RtfElement)it.next(); if (e instanceof RtfParagraphBreak) { //If the element before was a paragraph break or a bookmark //they will be hidden and are therefore not considered as visible if (!(aBefore instanceof RtfParagraphBreak) && !(aBefore instanceof RtfBookmark)) { lastParagraphBreak = (RtfParagraphBreak)e; } } else { if (!(e instanceof RtfOpenGroupMark) && !(e instanceof RtfCloseGroupMark) && e.isEmpty()) { lastParagraphBreak = null; } } aBefore = e; } } //may contain for example \intbl writeAttributes(attrib, null); if (rtfListItem != null) { rtfListItem.getRtfListStyle().writeParagraphPrefix(this); } //write all children boolean bPrevPar = false; boolean bBookmark = false; boolean bFirst = true; for (Iterator it = getChildren().iterator(); it.hasNext();) { final RtfElement e = (RtfElement)it.next(); final boolean bRtfParagraphBreak = (e instanceof RtfParagraphBreak); if (bHasTableCellParent) { attrBlockLevel.set(e.getRtfAttributes()); } /** * -Write RtfParagraphBreak only, if the previous visible child * was't also a RtfParagraphBreak. * -Write RtfParagraphBreak only, if it is not the first visible * child. * -If the RtfTextrun is the last child of its parent, write a * RtfParagraphBreak only, if it is not the last child. * -If the RtfParagraphBreak can not be hidden (e.g. a table cell requires it) * it is also written */ boolean bHide = false; bHide = bRtfParagraphBreak; bHide = bHide && (bPrevPar || bFirst || (bSuppressLastPar && bLast && lastParagraphBreak != null && e == lastParagraphBreak) || bBookmark) && ((RtfParagraphBreak)e).canHide(); if (!bHide) { newLine(); e.writeRtf(); if (rtfListItem != null && e instanceof RtfParagraphBreak) { rtfListItem.getRtfListStyle().writeParagraphPrefix(this); } } if (e instanceof RtfParagraphBreak) { bPrevPar = true; } else if (e instanceof RtfBookmark) { bBookmark = true; } else if (e instanceof RtfCloseGroupMark) { //do nothing } else if (e instanceof RtfOpenGroupMark) { //do nothing } else { bPrevPar = bPrevPar && e.isEmpty(); bFirst = bFirst && e.isEmpty(); bBookmark = false; } } //for (Iterator it = ...) // if (bHasTableCellParent) { writeAttributes(attrBlockLevel, null); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfLineBreak.java
protected void writeRtfContent() throws IOException { writeControlWord("line"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleText.java
public void writeListPrefix(RtfListItem item) throws IOException { // bulleted list item.writeControlWord("pnlvlblt"); item.writeControlWord("ilvl0"); item.writeOneAttribute(RtfListTable.LIST_NUMBER, new Integer(item.getNumber())); item.writeOneAttribute("pnindent", item.getParentList().attrib.getValue(RtfListTable.LIST_INDENT)); item.writeControlWord("pnf1"); item.writeGroupMark(true); //item.writeControlWord("pndec"); item.writeOneAttribute(RtfListTable.LIST_FONT_TYPE, "2"); item.writeControlWord("pntxtb"); RtfStringConverter.getInstance().writeRtfString(item.writer, text); item.writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleText.java
public void writeParagraphPrefix(RtfElement element) throws IOException { element.writeGroupMark(true); element.writeControlWord("pntext"); element.writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleText.java
public void writeLevelGroup(RtfElement element) throws IOException { element.attrib.set(RtfListTable.LIST_NUMBER_TYPE, 23); element.writeGroupMark(true); String sCount; if (text.length() < 10) { sCount = "0" + String.valueOf(text.length()); } else { sCount = String.valueOf(Integer.toHexString(text.length())); if (sCount.length() == 1) { sCount = "0" + sCount; } } element.writeOneAttributeNS( RtfListTable.LIST_TEXT_FORM, "\\'" + sCount + RtfStringConverter.getInstance().escape(text)); element.writeGroupMark(false); element.writeGroupMark(true); element.writeOneAttributeNS(RtfListTable.LIST_NUM_POSITION, null); element.writeGroupMark(false); element.attrib.set(RtfListTable.LIST_FONT_TYPE, 2); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTemplate.java
public void setTemplateFilePath(String templateFilePath) throws IOException { // no validity checks here - leave this to the RTF client if (templateFilePath == null) { this.templateFilePath = null; } else { this.templateFilePath = templateFilePath.trim(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTemplate.java
public void writeTemplate (RtfHeader header) throws IOException { if (templateFilePath == null || templateFilePath.length() == 0) { return; } header.writeGroupMark (true); header.writeControlWord ("template"); header.writeRtfString(this.templateFilePath); header.writeGroupMark (false); header.writeGroupMark (true); header.writeControlWord ("linkstyles"); header.writeGroupMark (false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleNumber.java
public void writeListPrefix(RtfListItem item) throws IOException { item.writeControlWord("pnlvlbody"); item.writeControlWord("ilvl0"); item.writeOneAttribute(RtfListTable.LIST_NUMBER, "0"); item.writeControlWord("pndec"); item.writeOneAttribute("pnstart", new Integer(1)); item.writeOneAttribute("pnindent", item.attrib.getValue(RtfListTable.LIST_INDENT)); item.writeControlWord("pntxta."); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleNumber.java
public void writeParagraphPrefix(RtfElement element) throws IOException { element.writeGroupMark(true); element.writeControlWord("pntext"); element.writeControlWord("f" + RtfFontManager.getInstance().getFontNumber("Symbol")); element.writeControlWord("'b7"); element.writeControlWord("tab"); element.writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListStyleNumber.java
public void writeLevelGroup(RtfElement element) throws IOException { element.writeOneAttributeNS( RtfListTable.LIST_START_AT, new Integer(1)); element.attrib.set(RtfListTable.LIST_NUMBER_TYPE, 0); element.writeGroupMark(true); element.writeOneAttributeNS( RtfListTable.LIST_TEXT_FORM, "\\'03\\\'00. ;"); element.writeGroupMark(false); element.writeGroupMark(true); element.writeOneAttributeNS( RtfListTable.LIST_NUM_POSITION, "\\'01;"); element.writeGroupMark(false); element.writeOneAttribute(RtfListTable.LIST_FONT_TYPE, new Integer(0)); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExtraRowSet.java
RtfTableCell createExtraCell(int rowIndex, int xOffset, int cellWidth, RtfAttributes parentCellAttributes) throws IOException { final RtfTableCell c = new RtfTableCell(null, writer, cellWidth, parentCellAttributes, DEFAULT_IDNUM); cells.add(new PositionedCell(c, rowIndex, xOffset)); return c; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExtraRowSet.java
protected void writeRtfContent() throws IOException { // sort cells by rowIndex and xOffset Collections.sort(cells); // process all extra cells by rendering them into extra rows List rowCells = null; int rowIndex = -1; for (Iterator it = cells.iterator(); it.hasNext();) { final PositionedCell pc = (PositionedCell)it.next(); if (pc.rowIndex != rowIndex) { // starting a new row, render previous one if (rowCells != null) { writeRow(rowCells); } rowIndex = pc.rowIndex; rowCells = new LinkedList(); } rowCells.add(pc); } // render last row if (rowCells != null) { writeRow(rowCells); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExtraRowSet.java
private void writeRow(List cells) throws IOException { if (allCellsEmpty(cells)) { return; } final RtfTableRow row = new RtfTableRow(null, writer, DEFAULT_IDNUM); int cellIndex = 0; // Get the context of the table that holds the nested table ITableColumnsInfo parentITableColumnsInfo = getParentITableColumnsInfo(); parentITableColumnsInfo.selectFirstColumn(); // X offset of the current empty cell to add float xOffset = 0; float xOffsetOfLastPositionedCell = 0; for (Iterator it = cells.iterator(); it.hasNext();) { final PositionedCell pc = (PositionedCell)it.next(); // if first cell is not at offset 0, add placeholder cell // TODO should be merged with the cell that is above it if (cellIndex == 0 && pc.xOffset > 0) { /** * Added by Boris Poudérous */ // Add empty cells merged vertically with the cells above and with the same widths // (BEFORE the cell that contains the nested table) for (int i = 0; (xOffset < pc.xOffset) && (i < parentITableColumnsInfo.getNumberOfColumns()); i++) { // Get the width of the cell above xOffset += parentITableColumnsInfo.getColumnWidth(); // Create the empty cell merged vertically row.newTableCellMergedVertically((int)parentITableColumnsInfo.getColumnWidth(), pc.cell.attrib); // Select next column in order to have its width parentITableColumnsInfo.selectNextColumn(); } } row.addChild(pc.cell); // Line added by Boris Poudérous xOffsetOfLastPositionedCell = pc.xOffset + pc.cell.getCellWidth(); cellIndex++; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
protected void writeRtfPrefix() throws IOException { super.writeRtfPrefix(); getRtfListStyle().writeParagraphPrefix(this); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
public RtfTextrun getTextrun() throws IOException { return this; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
public void addString(String s) throws IOException { final String label = s.trim(); if (label.length() > 0 && Character.isDigit(label.charAt(0))) { rtfListItem.setRtfListStyle(new RtfListStyleNumber()); } else { rtfListItem.setRtfListStyle(new RtfListStyleText(label)); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
public RtfParagraph newParagraph(RtfAttributes attrs) throws IOException { if (paragraph != null) { paragraph.close(); } paragraph = new RtfListItemParagraph(this, attrs); return paragraph; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
public RtfParagraph newParagraph() throws IOException { return newParagraph(null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
public RtfTextrun getTextrun() throws IOException { RtfTextrun textrun = RtfTextrun.getTextrun(this, writer, null); textrun.setRtfListItem(this); return textrun; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
public RtfList newList(RtfAttributes attrs) throws IOException { RtfList list = new RtfList(this, writer, attrs); return list; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
protected void writeRtfPrefix() throws IOException { // pard causes word97 (and sometimes 2000 too) to crash if the list is nested in a table if (!parentList.getHasTableParent()) { writeControlWord("pard"); } writeOneAttribute(RtfText.LEFT_INDENT_FIRST, "360"); //attrib.getValue(RtfListTable.LIST_INDENT)); writeOneAttribute(RtfText.LEFT_INDENT_BODY, attrib.getValue(RtfText.LEFT_INDENT_BODY)); // group for list setup info writeGroupMark(true); writeStarControlWord("pn"); //Modified by Chris Scott //fixes second line indentation getRtfListStyle().writeListPrefix(this); writeGroupMark(false); writeOneAttribute(RtfListTable.LIST_NUMBER, new Integer(number)); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListItem.java
protected void writeRtfSuffix() throws IOException { super.writeRtfSuffix(); /* reset paragraph defaults to make sure list ends * but pard causes word97 (and sometimes 2000 too) to crash if the list * is nested in a table */ if (!parentList.getHasTableParent()) { writeControlWord("pard"); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfPage.java
protected void writeRtfContent() throws IOException { writeAttributes(attrib, PAGE_ATTR); if (attrib != null) { Object widthRaw = attrib.getValue(PAGE_WIDTH); Object heightRaw = attrib.getValue(PAGE_HEIGHT); if ((widthRaw instanceof Integer) && (heightRaw instanceof Integer) && ((Integer) widthRaw).intValue() > ((Integer) heightRaw).intValue()) { writeControlWord(LANDSCAPE); } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHeader.java
protected void writeRtfContent() throws IOException { writeControlWord(charset); writeUserProperties(); RtfColorTable.getInstance().writeColors(this); super.writeRtfContent(); RtfTemplate.getInstance().writeTemplate(this); RtfStyleSheetTable.getInstance().writeStyleSheet(this); writeFootnoteProperties(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHeader.java
private void writeUserProperties() throws IOException { if (userProperties.size() > 0) { writeGroupMark(true); writeStarControlWord("userprops"); for (Iterator it = userProperties.entrySet().iterator(); it.hasNext();) { final Map.Entry entry = (Map.Entry)it.next(); writeGroupMark(true); writeControlWord("propname"); RtfStringConverter.getInstance().writeRtfString(writer, entry.getKey().toString()); writeGroupMark(false); writeControlWord("proptype30"); writeGroupMark(true); writeControlWord("staticval"); RtfStringConverter.getInstance().writeRtfString(writer, entry.getValue().toString()); writeGroupMark(false); } writeGroupMark(false); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHeader.java
void write(String toWrite) throws IOException { writer.write(toWrite); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHeader.java
void writeRtfString(String toWrite) throws IOException { RtfStringConverter.getInstance().writeRtfString(writer, toWrite); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHeader.java
private void writeFootnoteProperties() throws IOException { newLine(); writeControlWord("fet0"); //footnotes, not endnotes writeControlWord("ftnbj"); //place footnotes at the end of the //page (should be the default, but //Word 2000 thinks otherwise) }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
protected void writeRtfContent() throws IOException { try { writeRtfContentWithException(); } catch (ExternalGraphicException ie) { writeExceptionInRtf(ie); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
protected void writeRtfContentWithException() throws IOException { if (writer == null) { return; } if (url == null && imagedata == null) { throw new ExternalGraphicException( "No image data is available (neither URL, nor in-memory)"); } String linkToRoot = System.getProperty("jfor_link_to_root"); if (url != null && linkToRoot != null) { writer.write("{\\field {\\* \\fldinst { INCLUDEPICTURE \""); writer.write(linkToRoot); File urlFile = new File(url.getFile()); writer.write(urlFile.getName()); writer.write("\" \\\\* MERGEFORMAT \\\\d }}}"); return; } // getRtfFile ().getLog ().logInfo ("Writing image '" + url + "'."); if (imagedata == null) { try { final InputStream in = url.openStream(); try { imagedata = IOUtils.toByteArray(url.openStream()); } finally { IOUtils.closeQuietly(in); } } catch (Exception e) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + url + "' (" + e + ")"); } } if (imagedata == null) { return; } // Determine image file format String file = (url != null ? url.getFile() : "<unknown>"); imageformat = FormatBase.determineFormat(imagedata); if (imageformat != null) { imageformat = imageformat.convert(imageformat, imagedata); } if (imageformat == null || imageformat.getType() == ImageConstants.I_NOT_SUPPORTED || "".equals(imageformat.getRtfTag())) { throw new ExternalGraphicException("The tag <fo:external-graphic> " + "does not support " + file.substring(file.lastIndexOf(".") + 1) + " - image type."); } // Writes the beginning of the rtf image writeGroupMark(true); writeStarControlWord("shppict"); writeGroupMark(true); writeControlWord("pict"); StringBuffer buf = new StringBuffer(imagedata.length * 3); writeControlWord(imageformat.getRtfTag()); computeImageSize(); writeSizeInfo(); writeAttributes(getRtfAttributes(), null); for (int i = 0; i < imagedata.length; i++) { int iData = imagedata [i]; // Make positive byte if (iData < 0) { iData += 256; } if (iData < 16) { // Set leading zero and append buf.append('0'); } buf.append(Integer.toHexString(iData)); } int len = buf.length(); char[] chars = new char[len]; buf.getChars(0, len, chars, 0); writer.write(chars); // Writes the end of RTF image writeGroupMark(false); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
private void writeSizeInfo () throws IOException { // Set image size if (width != -1) { writeControlWord("picw" + width); } if (height != -1) { writeControlWord("pich" + height); } if (widthDesired != -1) { if (perCentW) { writeControlWord("picscalex" + widthDesired); } else { //writeControlWord("picscalex" + widthDesired * 100 / width); writeControlWord("picwgoal" + widthDesired); } } else if (scaleUniform && heightDesired != -1) { if (perCentH) { writeControlWord("picscalex" + heightDesired); } else { writeControlWord("picscalex" + heightDesired * 100 / height); } } if (heightDesired != -1) { if (perCentH) { writeControlWord("picscaley" + heightDesired); } else { //writeControlWord("picscaley" + heightDesired * 100 / height); writeControlWord("pichgoal" + heightDesired); } } else if (scaleUniform && widthDesired != -1) { if (perCentW) { writeControlWord("picscaley" + widthDesired); } else { writeControlWord("picscaley" + widthDesired * 100 / width); } } if (this.cropValues[0] != 0) { writeOneAttribute("piccropl", new Integer(this.cropValues[0])); } if (this.cropValues[1] != 0) { writeOneAttribute("piccropt", new Integer(this.cropValues[1])); } if (this.cropValues[2] != 0) { writeOneAttribute("piccropr", new Integer(this.cropValues[2])); } if (this.cropValues[3] != 0) { writeOneAttribute("piccropb", new Integer(this.cropValues[3])); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
public void setImageData(byte[] data) throws IOException { this.imagedata = data; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
public void setURL(String urlString) throws IOException { URL tmpUrl = null; try { tmpUrl = new URL (urlString); } catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } } this.url = tmpUrl; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfGenerator.java
protected void writeRtfContent() throws IOException { newLine(); writeGroupMark(true); writeStarControlWord("generator"); writer.write("Apache XML Graphics RTF Library"); writer.write(";"); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListTable.java
public void writeRtfContent() throws IOException { newLine(); if (lists != null) { //write '\listtable' writeGroupMark(true); writeStarControlWordNS(LIST_TABLE); newLine(); for (Iterator it = lists.iterator(); it.hasNext();) { final RtfList list = (RtfList)it.next(); writeListTableEntry(list); newLine(); } writeGroupMark(false); newLine(); //write '\listoveridetable' writeGroupMark(true); writeStarControlWordNS(LIST_OVR_TABLE); int z = 1; newLine(); for (Iterator it = styles.iterator(); it.hasNext();) { final RtfListStyle style = (RtfListStyle)it.next(); writeGroupMark(true); writeStarControlWordNS(LIST_OVR); writeGroupMark(true); writeOneAttributeNS(LIST_ID, style.getRtfList().getListId().toString()); writeOneAttributeNS(LIST_OVR_COUNT, new Integer(0)); writeOneAttributeNS(LIST_NUMBER, new Integer(z++)); writeGroupMark(false); writeGroupMark(false); newLine(); } writeGroupMark(false); newLine(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfListTable.java
private void writeListTableEntry(RtfList list) throws IOException { //write list-specific attributes writeGroupMark(true); writeControlWordNS(LIST); writeOneAttributeNS(LIST_TEMPLATE_ID, list.getListTemplateId().toString()); writeOneAttributeNS(LIST, attrib.getValue(LIST)); // write level-specific attributes writeGroupMark(true); writeControlWordNS(LIST_LEVEL); writeOneAttributeNS(LIST_JUSTIFICATION, attrib.getValue(LIST_JUSTIFICATION)); writeOneAttributeNS(LIST_FOLLOWING_CHAR, attrib.getValue(LIST_FOLLOWING_CHAR)); writeOneAttributeNS(LIST_SPACE, new Integer(0)); writeOneAttributeNS(LIST_INDENT, attrib.getValue(LIST_INDENT)); RtfListItem item = (RtfListItem)list.getChildren().get(0); if (item != null) { item.getRtfListStyle().writeLevelGroup(this); } writeGroupMark(false); writeGroupMark(true); writeControlWordNS(LIST_NAME); writeGroupMark(false); writeOneAttributeNS(LIST_ID, list.getListId().toString()); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFootnote.java
public RtfTextrun getTextrun() throws IOException { if (bBody) { RtfTextrun textrun = RtfTextrun.getTextrun(body, writer, null); textrun.setSuppressLastPar(true); return textrun; } else { return textrunInline; } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFootnote.java
protected void writeRtfContent() throws IOException { textrunInline.writeRtfContent(); writeGroupMark(true); writeControlWord("footnote"); writeControlWord("ftnalt"); body.writeRtfContent(); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFootnote.java
public RtfList newList(RtfAttributes attrs) throws IOException { if (list != null) { list.close(); } list = new RtfList(body, writer, attrs); return list; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
public final void close() throws IOException { closed = true; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
public final void writeRtf() throws IOException { if (!written) { written = true; if (okToWriteRtf()) { writeRtfPrefix(); writeRtfContent(); writeRtfSuffix(); } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
public void newLine() throws IOException { writer.write("\n"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected final void writeControlWord(String word) throws IOException { writer.write('\\'); writer.write(word); writer.write(' '); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected final void writeStarControlWord(String word) throws IOException { writer.write("\\*\\"); writer.write(word); writer.write(' '); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected final void writeStarControlWordNS(String word) throws IOException { writer.write("\\*\\"); writer.write(word); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected final void writeControlWordNS(String word) throws IOException { writer.write('\\'); writer.write(word); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected void writeRtfPrefix() throws IOException { }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected void writeRtfSuffix() throws IOException { }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected final void writeGroupMark(boolean isStart) throws IOException { writer.write(isStart ? "{" : "}"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected void writeAttributes(RtfAttributes attr, String [] nameList) throws IOException { if (attr == null) { return; } if (nameList != null) { // process only given attribute names for (int i = 0; i < nameList.length; i++) { final String name = nameList[i]; if (attr.isSet(name)) { writeOneAttribute(name, attr.getValue(name)); } } } else { // process all defined attributes for (Iterator it = attr.nameIterator(); it.hasNext();) { final String name = (String)it.next(); if (attr.isSet(name)) { writeOneAttribute(name, attr.getValue(name)); } } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected void writeOneAttribute(String name, Object value) throws IOException { String cw = name; if (value instanceof Integer) { // attribute has integer value, must write control word + value cw += value; } else if (value instanceof String) { cw += value; } else if (value instanceof RtfAttributes) { writeControlWord(cw); writeAttributes((RtfAttributes) value, null); return; } writeControlWord(cw); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected void writeOneAttributeNS(String name, Object value) throws IOException { String cw = name; if (value instanceof Integer) { // attribute has integer value, must write control word + value cw += value; } else if (value instanceof String) { cw += value; } else if (value instanceof RtfAttributes) { writeControlWord(cw); writeAttributes((RtfAttributes) value, null); return; } writeControlWordNS(cw); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
void dump(Writer w, int indent) throws IOException { for (int i = 0; i < indent; i++) { w.write(' '); } w.write(this.toString()); w.write('\n'); w.flush(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfElement.java
protected void writeExceptionInRtf(Exception ie) throws IOException { writeGroupMark(true); writeControlWord("par"); // make the exception message stand out so that the problem is visible writeControlWord("fs48"); // RtfStringConverter.getInstance().writeRtfString(m_writer, // JForVersionInfo.getShortVersionInfo() + ": "); RtfStringConverter.getInstance().writeRtfString(writer, ie.getClass().getName()); writeControlWord("fs20"); RtfStringConverter.getInstance().writeRtfString(writer, " " + ie.toString()); writeControlWord("par"); writeGroupMark(false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfStyleSheetTable.java
public void writeStyleSheet (RtfHeader header) throws IOException { if (styles == null || styles.size () == 0) { return; } header.writeGroupMark (true); header.writeControlWord ("stylesheet"); int number = nameTable.size (); for (int i = 0; i < number; i++) { String name = (String) nameTable.elementAt (i); header.writeGroupMark (true); header.writeControlWord ("*\\" + this.getRtfStyleReference (name)); Object o = attrTable.get (name); if (o != null) { header.writeAttributes ((RtfAttributes) o, RtfText.ATTR_NAMES); header.writeAttributes ((RtfAttributes) o, RtfText.ALIGNMENT); } header.write (name + ";"); header.writeGroupMark (false); } header.writeGroupMark (false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmark.java
public void writeRtfPrefix () throws IOException { startBookmark (); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmark.java
public void writeRtfContent () throws IOException { // this.getRtfFile ().getLog ().logInfo ("Write bookmark '" + bookmark + "'."); // No content to write }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmark.java
public void writeRtfSuffix () throws IOException { endBookmark (); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmark.java
private void startBookmark () throws IOException { // {\*\bkmkstart test} writeRtfBookmark ("bkmkstart"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmark.java
private void endBookmark () throws IOException { // {\*\bkmkend test} writeRtfBookmark ("bkmkend"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmark.java
private void writeRtfBookmark (String tag) throws IOException { if (bookmark == null) { return; } this.writeGroupMark (true); //changed. Now using writeStarControlWord this.writeStarControlWord (tag); writer.write (bookmark); this.writeGroupMark (false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraphKeepTogether.java
protected void writeRtfContent() throws IOException { //First reet paragraph properties // create a new one with keepn if (status == STATUS_OPEN_PARAGRAPH) { writeControlWord("pard"); writeControlWord("par"); writeControlWord("keepn"); writeGroupMark(true); status = STATUS_NULL; } if (status == STATUS_CLOSE_PARAGRAPH) { writeGroupMark(false); status = STATUS_NULL; } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfColorTable.java
public void writeColors (RtfHeader header) throws IOException { if (colorTable == null || colorTable.size () == 0) { return; } header.newLine(); header.writeGroupMark (true); //Don't use writeControlWord, because it appends a blank, //which may confuse Wordpad. //This also implicitly writes the first color (=index 0), which //is reserved for auto-colored. header.write ("\\colortbl;"); int len = colorTable.size (); for (int i = 0; i < len; i++) { int identifier = ((Integer) colorTable.get (i)).intValue (); header.newLine(); header.write ("\\red" + determineColorLevel (identifier, RED)); header.write ("\\green" + determineColorLevel (identifier, GREEN)); header.write ("\\blue" + determineColorLevel (identifier, BLUE) + ";"); } header.newLine(); header.writeGroupMark (false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfString.java
protected void writeRtfContent() throws IOException { RtfStringConverter.getInstance().writeRtfString(writer, text); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfPageNumberCitation.java
protected void writeRtfContent() throws IOException { // If we have a valid ID if (isValid()) { // Build page reference field String pageRef = RTF_FIELD_PAGEREF_MODEL; final int insertionIndex = pageRef.indexOf("}"); pageRef = pageRef.substring(0, insertionIndex) + "\"" + id + "\"" + " " + pageRef.substring(insertionIndex, pageRef.length()); id = null; // Write RTF content writeGroupMark(true); writeControlWord(RTF_FIELD); writeGroupMark(true); writeAttributes(attrib, RtfText.ATTR_NAMES); // Added by Boris Poudérous writeStarControlWord(pageRef); writeGroupMark(false); writeGroupMark(true); writeControlWord(RTF_FIELD_RESULT + '#'); //To see where the page-number would be writeGroupMark(false); writeGroupMark(false); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfList.java
public RtfListItem newListItem() throws IOException { if (item != null) { item.close(); } item = new RtfListItem(this, writer); return item; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfStringConverter.java
public void writeRtfString(Writer w, String str) throws IOException { if (str == null) { return; } w.write(escape(str)); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBookmarkContainerImpl.java
public RtfBookmark newBookmark (String bookmark) throws IOException { if (mBookmark != null) { mBookmark.close (); } mBookmark = new RtfBookmark (this, writer, bookmark); return mBookmark; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfBefore.java
protected void writeMyAttributes() throws IOException { writeAttributes(attrib, HEADER_ATTR); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
protected void writeRtfPrefix() throws IOException { //Reset paragraph properties if needed if (resetProperties) { writeControlWord("pard"); } /* * Original comment said "do not write text attributes here, they are * handled by RtfText." However, the text attributes appear to be * relevant to paragraphs as well. */ writeAttributes(attrib, RtfText.ATTR_NAMES); writeAttributes(attrib, PARA_ATTRIBUTES); // Added by Normand Masse // Write alignment attributes after \intbl for cells if (attrib.isSet("intbl") && mustWriteAttributes()) { writeAttributes(attrib, RtfText.ALIGNMENT); } //Set keepn if needed (Keep paragraph with the next paragraph) if (keepn) { writeControlWord("keepn"); } // start a group for this paragraph and write our own attributes if needed if (mustWriteGroupMark()) { writeGroupMark(true); } if (mustWriteAttributes()) { // writeAttributes(m_attrib, new String [] {"cs"}); // Added by Normand Masse // If \intbl then attributes have already been written (see higher in method) if (!attrib.isSet("intbl")) { writeAttributes(attrib, RtfText.ALIGNMENT); } //this line added by Chris Scott, Westinghouse writeAttributes(attrib, RtfText.BORDER); writeAttributes(attrib, RtfText.INDENT); writeAttributes(attrib, RtfText.TABS); if (writeForBreak) { writeControlWord("pard\\par"); } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
protected void writeRtfSuffix() throws IOException { // sometimes the end of paragraph mark must be suppressed in table cells boolean writeMark = true; if (parent instanceof RtfTableCell) { writeMark = ((RtfTableCell)parent).paragraphNeedsPar(this); } if (writeMark) { writeControlWord("par"); } if (mustWriteGroupMark()) { writeGroupMark(false); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfText newText(String str) throws IOException { return newText(str, null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfText newText(String str, RtfAttributes attr) throws IOException { closeAll(); text = new RtfText(this, writer, str, attr); return text; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public void newPageBreak() throws IOException { writeForBreak = true; new RtfPageBreak(this, writer); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public void newLineBreak() throws IOException { new RtfLineBreak(this, writer); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfPageNumber newPageNumber()throws IOException { pageNumber = new RtfPageNumber(this, writer); return pageNumber; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfPageNumberCitation newPageNumberCitation(String id) throws IOException { pageNumberCitation = new RtfPageNumberCitation(this, writer, id); return pageNumberCitation; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfHyperLink newHyperLink(String str, RtfAttributes attr) throws IOException { hyperlink = new RtfHyperLink(this, writer, str, attr); return hyperlink; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
public RtfExternalGraphic newImage() throws IOException { closeAll(); externalGraphic = new RtfExternalGraphic(this, writer); return externalGraphic; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
private void closeCurrentText() throws IOException { if (text != null) { text.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
private void closeCurrentHyperLink() throws IOException { if (hyperlink != null) { hyperlink.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraph.java
private void closeAll() throws IOException { closeCurrentText(); closeCurrentHyperLink(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfParagraphBreak.java
protected void writeRtfContent() throws IOException { if (controlWord != null ) { writeControlWord(controlWord); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfPageBreak.java
protected void writeRtfContent() throws IOException { writeControlWord("page"); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfParagraph newParagraph(RtfAttributes attrs) throws IOException { closeAll(); // in tables, RtfParagraph must have the intbl attribute if (attrs == null) { attrs = new RtfAttributes(); } attrs.set("intbl"); paragraph = new RtfParagraph(this, writer, attrs); if (paragraph.attrib.isSet("qc")) { setCenter = true; attrs.set("qc"); } else if (paragraph.attrib.isSet("qr")) { setRight = true; attrs.set("qr"); } else { attrs.set("ql"); } attrs.set("intbl"); //lines modified by Chris Scott, Westinghouse return paragraph; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfExternalGraphic newImage() throws IOException { closeAll(); externalGraphic = new RtfExternalGraphic(this, writer); return externalGraphic; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfParagraph newParagraph() throws IOException { return newParagraph(null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfList newList(RtfAttributes attrib) throws IOException { closeAll(); list = new RtfList(this, writer, attrib); return list; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfTable newTable(ITableColumnsInfo tc) throws IOException { closeAll(); table = new RtfTable(this, writer, tc); return table; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfTable newTable(RtfAttributes attrs, ITableColumnsInfo tc) throws IOException { closeAll(); table = new RtfTable(this, writer, attrs, tc); // Added tc Boris Poudérous 07/22/2002 return table; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
int writeCellDef(int offset) throws IOException { /* * Don't write \clmgf or \clmrg. Instead add the widths * of all spanned columns and create a single wider cell, * because \clmgf and \clmrg won't work in last row of a * table (Word2000 seems to do the same). * Cause of this, dont't write horizontally merged cells. * They just exist as placeholders in TableContext class, * and are never written to RTF file. */ // horizontal cell merge codes if (hMerge == MERGE_WITH_PREVIOUS) { return offset; } newLine(); this.widthOffset = offset; // vertical cell merge codes if (vMerge == MERGE_START) { writeControlWord("clvmgf"); } else if (vMerge == MERGE_WITH_PREVIOUS) { writeControlWord("clvmrg"); } /** * Added by Boris POUDEROUS on 2002/06/26 */ // Cell background color processing : writeAttributes (attrib, ITableAttributes.CELL_COLOR); /** - end - */ writeAttributes (attrib, ITableAttributes.ATTRIB_CELL_PADDING); writeAttributes (attrib, ITableAttributes.CELL_BORDER); writeAttributes (attrib, IBorderAttributes.BORDERS); // determine cell width int iCurrentWidth = this.cellWidth; if (attrib.getValue("number-columns-spanned") != null) { // Get the number of columns spanned int nbMergedCells = ((Integer)attrib.getValue("number-columns-spanned")).intValue(); RtfTable tab = getRow().getTable(); // Get the context of the current table in order to get the width of each column ITableColumnsInfo tableColumnsInfo = tab.getITableColumnsInfo(); tableColumnsInfo.selectFirstColumn(); // Reach the column index in table context corresponding to the current column cell // id is the index of the current cell (it begins at 1) // getColumnIndex() is the index of the current column in table context (it begins at 0) // => so we must withdraw 1 when comparing these two variables. while ((this.id - 1) != tableColumnsInfo.getColumnIndex()) { tableColumnsInfo.selectNextColumn(); } // We withdraw one cell because the first cell is already created // (it's the current cell) ! int i = nbMergedCells - 1; while (i > 0) { tableColumnsInfo.selectNextColumn(); iCurrentWidth += (int)tableColumnsInfo.getColumnWidth(); i--; } } final int xPos = offset + iCurrentWidth; //these lines added by Chris Scott, Westinghouse //some attributes need to be written before opening block if (setCenter) { writeControlWord("trqc"); } else if (setRight) { writeControlWord("trqr"); } else { writeControlWord("trql"); } writeAttributes (attrib, ITableAttributes.CELL_VERT_ALIGN); writeControlWord("cellx" + xPos); return xPos; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
protected void writeRtfContent() throws IOException { // Never write horizontally merged cells. if (hMerge == MERGE_WITH_PREVIOUS) { return; } super.writeRtfContent(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
protected void writeRtfPrefix() throws IOException { // Never write horizontally merged cells. if (hMerge == MERGE_WITH_PREVIOUS) { return; } super.writeRtfPrefix(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
protected void writeRtfSuffix() throws IOException { // Never write horizontally merged cells. if (hMerge == MERGE_WITH_PREVIOUS) { return; } if (getRow().getTable().isNestedTable()) { //nested table if (lastBreak == null) { writeControlWordNS("nestcell"); } writeGroupMark(true); writeControlWord("nonesttables"); writeControlWord("par"); writeGroupMark(false); } else { // word97 hangs if cell does not contain at least one "par" control word // TODO this is what causes the extra spaces in nested table of test // 004-spacing-in-tables.fo, // but if is not here we generate invalid RTF for word97 if (setCenter) { writeControlWord("qc"); } else if (setRight) { writeControlWord("qr"); } else { RtfElement lastChild = null; if (getChildren().size() > 0) { lastChild = (RtfElement) getChildren().get(getChildren().size() - 1); } if (lastChild != null && lastChild instanceof RtfTextrun) { //Don't write \ql in order to allow for example a right aligned paragraph //in a not right aligned table-cell to write its \qr. } else { writeControlWord("ql"); } } if (!containsText()) { writeControlWord("intbl"); //R.Marra this create useless paragraph //Seem working into Word97 with the "intbl" only //writeControlWord("par"); } if (lastBreak == null) { writeControlWord("cell"); } } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
private void closeCurrentParagraph() throws IOException { if (paragraph != null) { paragraph.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
private void closeCurrentList() throws IOException { if (list != null) { list.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
private void closeCurrentTable() throws IOException { if (table != null) { table.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
private void closeCurrentExternalGraphic() throws IOException { if (externalGraphic != null) { externalGraphic.close(); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
private void closeAll() throws IOException { closeCurrentTable(); closeCurrentParagraph(); closeCurrentList(); closeCurrentExternalGraphic(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTableCell.java
public RtfTextrun getTextrun() throws IOException { RtfAttributes attrs = new RtfAttributes(); if (!getRow().getTable().isNestedTable()) { attrs.set("intbl"); } RtfTextrun textrun = RtfTextrun.getTextrun(this, writer, attrs); //Suppress the very last \par, because the closing \cell applies the //paragraph attributes. textrun.setSuppressLastPar(true); return textrun; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public void writeRtfPrefix () throws IOException { super.writeGroupMark (true); super.writeControlWord ("field"); super.writeGroupMark (true); super.writeStarControlWord ("fldinst"); writer.write ("HYPERLINK \"" + url + "\" "); super.writeGroupMark (false); super.writeGroupMark (true); super.writeControlWord ("fldrslt"); // start a group for this paragraph and write our own attributes if needed if (attrib != null && attrib.isSet ("cs")) { writeGroupMark (true); writeAttributes(attrib, new String [] {"cs"}); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public void writeRtfSuffix () throws IOException { if (attrib != null && attrib.isSet ("cs")) { writeGroupMark (false); } super.writeGroupMark (false); super.writeGroupMark (false); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public RtfText newText (String str) throws IOException { return newText (str, null); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public RtfText newText (String str, RtfAttributes attr) throws IOException { closeAll (); mText = new RtfText (this, writer, str, attr); return mText; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public void newLineBreak () throws IOException { new RtfLineBreak (this, writer); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
private void closeCurrentText () throws IOException { if (mText != null) { mText.close (); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
private void closeAll () throws IOException { closeCurrentText(); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfHyperLink.java
public RtfTextrun getTextrun() throws IOException { RtfTextrun textrun = RtfTextrun.getTextrun(this, writer, null); return textrun; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfPageArea.java
public RtfPage newPage(RtfAttributes attr) throws IOException { if (currentPage != null) { currentPage.close(); } currentPage = new RtfPage(this, writer, attr); return currentPage; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
public RtfTableRow newTableRow() throws IOException { if (row != null) { row.close(); } highestRow++; row = new RtfTableRow(this, writer, attrib, highestRow); return row; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
public RtfTableRow newTableRow(RtfAttributes attrs) throws IOException, FOPException { RtfAttributes attr = null; if (attrib != null) { try { attr = (RtfAttributes) attrib.clone (); } catch (CloneNotSupportedException e) { throw new FOPException(e); } attr.set (attrs); } else { attr = attrs; } if (row != null) { row.close(); } highestRow++; row = new RtfTableRow(this, writer, attr, highestRow); return row; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
protected void writeRtfPrefix() throws IOException { if (isNestedTable()) { writeControlWordNS("pard"); } writeGroupMark(true); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfTable.java
protected void writeRtfSuffix() throws IOException { writeGroupMark(false); if (isNestedTable()) { getRow().writeRowAndCellsDefintions(); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
private void putGraphic(AbstractGraphics abstractGraphic, ImageInfo info) throws IOException { try { FOUserAgent userAgent = abstractGraphic.getUserAgent(); ImageManager manager = userAgent.getFactory().getImageManager(); ImageSessionContext sessionContext = userAgent.getImageSessionContext(); Map hints = ImageUtil.getDefaultHints(sessionContext); Image image = manager.getImage(info, FLAVORS, hints, sessionContext); putGraphic(abstractGraphic, image); } catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
private void putGraphic(AbstractGraphics abstractGraphic, Image image) throws IOException { byte[] rawData = null; final ImageInfo info = image.getInfo(); if (image instanceof ImageRawStream) { ImageRawStream rawImage = (ImageRawStream)image; InputStream in = rawImage.createInputStream(); try { rawData = IOUtils.toByteArray(in); } finally { IOUtils.closeQuietly(in); } } if (rawData == null) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageWritingError(this, null); return; } //Set up percentage calculations this.percentManager.setDimension(abstractGraphic); PercentBaseContext pContext = new PercentBaseContext() { public int getBaseLength(int lengthBase, FObj fobj) { switch (lengthBase) { case LengthBase.IMAGE_INTRINSIC_WIDTH: return info.getSize().getWidthMpt(); case LengthBase.IMAGE_INTRINSIC_HEIGHT: return info.getSize().getHeightMpt(); default: return percentManager.getBaseLength(lengthBase, fobj); } } }; ImageLayout layout = new ImageLayout(abstractGraphic, pContext, image.getInfo().getSize().getDimensionMpt()); final IRtfTextrunContainer c = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); final RtfExternalGraphic rtfGraphic = c.getTextrun().newImage(); //set URL if (info.getOriginalURI() != null) { rtfGraphic.setURL(info.getOriginalURI()); } rtfGraphic.setImageData(rawData); FoUnitsConverter converter = FoUnitsConverter.getInstance(); Dimension viewport = layout.getViewportSize(); Rectangle placement = layout.getPlacement(); int cropLeft = Math.round(converter.convertMptToTwips(-placement.x)); int cropTop = Math.round(converter.convertMptToTwips(-placement.y)); int cropRight = Math.round(converter.convertMptToTwips( -1 * (viewport.width - placement.x - placement.width))); int cropBottom = Math.round(converter.convertMptToTwips( -1 * (viewport.height - placement.y - placement.height))); rtfGraphic.setCropping(cropLeft, cropTop, cropRight, cropBottom); int width = Math.round(converter.convertMptToTwips(viewport.width)); int height = Math.round(converter.convertMptToTwips(viewport.height)); width += cropLeft + cropRight; height += cropTop + cropBottom; rtfGraphic.setWidthTwips(width); rtfGraphic.setHeightTwips(height); //TODO: make this configurable: // int compression = m_context.m_options.getRtfExternalGraphicCompressionRate (); int compression = 0; if (compression != 0) { if (!rtfGraphic.setCompressionRate(compression)) { log.warn("The compression rate " + compression + " is invalid. The value has to be between 1 and 100 %."); } } }
// in src/java/org/apache/fop/render/bitmap/PNGRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { log.info("rendering areas to PNG"); multiFileUtil = new MultiFileRenderingUtil(PNG_FILE_EXTENSION, getUserAgent().getOutputFile()); this.firstOutputStream = outputStream; }
// in src/java/org/apache/fop/render/bitmap/PNGRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); for (int i = 0; i < pageViewportList.size(); i++) { OutputStream os = getCurrentOutputStream(i); if (os == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.stoppingAfterFirstPageNoFilename(this); break; } try { // Do the rendering: get the image for this page PageViewport pv = (PageViewport)pageViewportList.get(i); RenderedImage image = (RenderedImage)getPageImage(pv); // Encode this image if (log.isDebugEnabled()) { log.debug("Encoding page " + (i + 1)); } writeImage(os, image); } finally { //Only close self-created OutputStreams if (os != firstOutputStream) { IOUtils.closeQuietly(os); } } } }
// in src/java/org/apache/fop/render/bitmap/PNGRenderer.java
private void writeImage(OutputStream os, RenderedImage image) throws IOException { ImageWriterParams params = new ImageWriterParams(); params.setResolution(Math.round(userAgent.getTargetResolution())); // Encode PNG image ImageWriter writer = ImageWriterRegistry.getInstance().getWriterFor(getMimeType()); if (writer == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noImageWriterFound(this, getMimeType()); } if (log.isDebugEnabled()) { log.debug("Writing image using " + writer.getClass().getName()); } writer.writeImage(image, os, params); }
// in src/java/org/apache/fop/render/bitmap/PNGRenderer.java
protected OutputStream getCurrentOutputStream(int pageNumber) throws IOException { if (pageNumber == 0) { return firstOutputStream; } else { return multiFileUtil.createOutputStream(pageNumber); } }
// in src/java/org/apache/fop/render/bitmap/MultiFileRenderingUtil.java
public OutputStream createOutputStream(int pageNumber) throws IOException { if (filePrefix == null) { return null; } else { File f = new File(outputDir, filePrefix + (pageNumber + 1) + "." + fileExtension); OutputStream os = new BufferedOutputStream(new FileOutputStream(f)); return os; } }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { this.outputStream = outputStream; super.startRenderer(outputStream); }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); log.debug("Starting TIFF encoding ..."); // Creates lazy iterator over generated page images Iterator pageImagesItr = new LazyPageImagesIterator(getNumberOfPages(), log); // Creates writer ImageWriter writer = ImageWriterRegistry.getInstance().getWriterFor(getMimeType()); if (writer == null) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noImageWriterFound(this, getMimeType()); } if (writer.supportsMultiImageWriter()) { MultiImageWriter multiWriter = writer.createMultiImageWriter(outputStream); try { // Write all pages/images while (pageImagesItr.hasNext()) { RenderedImage img = (RenderedImage) pageImagesItr.next(); multiWriter.writeImage(img, writerParams); } } finally { multiWriter.close(); } } else { RenderedImage renderedImage = null; if (pageImagesItr.hasNext()) { renderedImage = (RenderedImage) pageImagesItr.next(); } writer.writeImage(renderedImage, outputStream, writerParams); if (pageImagesItr.hasNext()) { BitmapRendererEventProducer eventProducer = BitmapRendererEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.stoppingAfterFirstPageNoFilename(this); } } // Cleaning outputStream.flush(); clearViewportList(); log.debug("TIFF encoding done."); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
private AFPFont fontFromType(String type, String codepage, String encoding, ResourceAccessor accessor, Configuration afpFontCfg) throws ConfigurationException, IOException { if ("raster".equalsIgnoreCase(type)) { String name = afpFontCfg.getAttribute("name", "Unknown"); // Create a new font object RasterFont font = new RasterFont(name); Configuration[] rasters = afpFontCfg.getChildren("afp-raster-font"); if (rasters.length == 0) { eventProducer.fontConfigMissing(this, "<afp-raster-font...", afpFontCfg.getLocation()); return null; } for (int j = 0; j < rasters.length; j++) { Configuration rasterCfg = rasters[j]; String characterset = rasterCfg.getAttribute("characterset"); if (characterset == null) { eventProducer.fontConfigMissing(this, "characterset attribute", afpFontCfg.getLocation()); return null; } float size = rasterCfg.getAttributeAsFloat("size"); int sizeMpt = (int) (size * 1000); String base14 = rasterCfg.getAttribute("base14-font", null); if (base14 != null) { try { Class<? extends Typeface> clazz = Class.forName( "org.apache.fop.fonts.base14." + base14).asSubclass(Typeface.class); try { Typeface tf = clazz.newInstance(); font.addCharacterSet(sizeMpt, CharacterSetBuilder.getSingleByteInstance() .build(characterset, codepage, encoding, tf, eventProducer)); } catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); } } catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); } } else { font.addCharacterSet(sizeMpt, CharacterSetBuilder.getSingleByteInstance() .buildSBCS(characterset, codepage, encoding, accessor, eventProducer)); } } return font; } else if ("outline".equalsIgnoreCase(type)) { String characterset = afpFontCfg.getAttribute("characterset"); if (characterset == null) { eventProducer.fontConfigMissing(this, "characterset attribute", afpFontCfg.getLocation()); return null; } String name = afpFontCfg.getAttribute("name", characterset); CharacterSet characterSet = null; String base14 = afpFontCfg.getAttribute("base14-font", null); if (base14 != null) { try { Class<? extends Typeface> clazz = Class.forName("org.apache.fop.fonts.base14." + base14).asSubclass(Typeface.class); try { Typeface tf = clazz.newInstance(); characterSet = CharacterSetBuilder.getSingleByteInstance() .build(characterset, codepage, encoding, tf, eventProducer); } catch (Exception ie) { String msg = "The base 14 font class " + clazz.getName() + " could not be instantiated"; log.error(msg); } } catch (ClassNotFoundException cnfe) { String msg = "The base 14 font class for " + characterset + " could not be found"; log.error(msg); } } else { characterSet = CharacterSetBuilder.getSingleByteInstance().buildSBCS( characterset, codepage, encoding, accessor, eventProducer); } // Return new font object return new OutlineFont(name, characterSet); } else if ("CIDKeyed".equalsIgnoreCase(type)) { String characterset = afpFontCfg.getAttribute("characterset"); if (characterset == null) { eventProducer.fontConfigMissing(this, "characterset attribute", afpFontCfg.getLocation()); return null; } String name = afpFontCfg.getAttribute("name", characterset); CharacterSet characterSet = null; CharacterSetType charsetType = afpFontCfg.getAttributeAsBoolean("ebcdic-dbcs", false) ? CharacterSetType.DOUBLE_BYTE_LINE_DATA : CharacterSetType.DOUBLE_BYTE; characterSet = CharacterSetBuilder.getDoubleByteInstance().buildDBCS(characterset, codepage, encoding, charsetType, accessor, eventProducer); // Create a new font object DoubleByteFont font = new DoubleByteFont(name, characterSet); return font; } else { log.error("No or incorrect type attribute: " + type); } return null; }
// in src/java/org/apache/fop/render/afp/AFPSVGHandler.java
protected void renderSVGDocument(final RendererContext rendererContext, final Document doc) throws IOException { AFPRendererContext afpRendererContext = (AFPRendererContext)rendererContext; AFPInfo afpInfo = afpRendererContext.getInfo(); this.paintAsBitmap = afpInfo.paintAsBitmap(); FOUserAgent userAgent = rendererContext.getUserAgent(); // fallback paint as bitmap String uri = getDocumentURI(doc); if (paintAsBitmap) { try { super.renderSVGDocument(rendererContext, doc); } catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, uri); } return; } // Create a new AFPGraphics2D final boolean textAsShapes = afpInfo.strokeText(); AFPGraphics2D g2d = afpInfo.createGraphics2D(textAsShapes); AFPPaintingState paintingState = g2d.getPaintingState(); paintingState.setImageUri(uri); // Create an AFPBridgeContext BridgeContext bridgeContext = createBridgeContext(userAgent, g2d); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(doc); // Build the SVG DOM and provide the painter with it GraphicsNode root = buildGraphicsNode(userAgent, bridgeContext, clonedDoc); // Create Graphics2DImagePainter final RendererContextWrapper wrappedContext = RendererContext.wrapRendererContext(rendererContext); Dimension imageSize = getImageSize(wrappedContext); Graphics2DImagePainter painter = createGraphics2DImagePainter(bridgeContext, root, imageSize); // Create AFPObjectAreaInfo RendererContextWrapper rctx = RendererContext.wrapRendererContext(rendererContext); int x = rctx.getCurrentXPosition(); int y = rctx.getCurrentYPosition(); int width = afpInfo.getWidth(); int height = afpInfo.getHeight(); int resolution = afpInfo.getResolution(); paintingState.save(); // save AFPObjectAreaInfo objectAreaInfo = createObjectAreaInfo(paintingState, x, y, width, height, resolution); // Create AFPGraphicsObjectInfo AFPResourceInfo resourceInfo = afpInfo.getResourceInfo(); AFPGraphicsObjectInfo graphicsObjectInfo = createGraphicsObjectInfo( paintingState, painter, userAgent, resourceInfo, g2d); graphicsObjectInfo.setObjectAreaInfo(objectAreaInfo); // Create the GOCA GraphicsObject in the DataStream AFPResourceManager resourceManager = afpInfo.getResourceManager(); resourceManager.createObject(graphicsObjectInfo); paintingState.restore(); // resume }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void clip() throws IOException { //not supported by AFP }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void closePath() throws IOException { //used for clipping only, so not implemented }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void moveTo(int x, int y) throws IOException { //used for clipping only, so not implemented }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void lineTo(int x, int y) throws IOException { //used for clipping only, so not implemented }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void saveGraphicsState() throws IOException { //used for clipping only, so not implemented }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void restoreGraphicsState() throws IOException { //used for clipping only, so not implemented }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override protected void drawBorderLine( // CSOK: ParameterNumber int x1, int y1, int x2, int y2, boolean horz, boolean startOrBefore, int style, Color color) throws IOException { BorderPaintingInfo borderPaintInfo = new BorderPaintingInfo( toPoints(x1), toPoints(y1), toPoints(x2), toPoints(y2), horz, style, color); delegate.paint(borderPaintInfo); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IOException { if (start.y != end.y) { //TODO Support arbitrary lines if necessary throw new UnsupportedOperationException( "Can only deal with horizontal lines right now"); } //Simply delegates to drawBorderLine() as AFP line painting is not very sophisticated. int halfWidth = width / 2; drawBorderLine(start.x, start.y - halfWidth, end.x, start.y + halfWidth, true, true, style.getEnumValue(), color); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void drawText( // CSOK: MethodLength int x, int y, final int letterSpacing, final int wordSpacing, final int[][] dp, final String text) throws IFException { final int fontSize = this.state.getFontSize(); getPaintingState().setFontSize(fontSize); FontTriplet triplet = new FontTriplet( state.getFontFamily(), state.getFontStyle(), state.getFontWeight()); //TODO Ignored: state.getFontVariant() String fontKey = getFontInfo().getInternalFontKey(triplet); if (fontKey == null) { triplet = new FontTriplet("any", Font.STYLE_NORMAL, Font.WEIGHT_NORMAL); fontKey = getFontInfo().getInternalFontKey(triplet); } // register font as necessary Map<String, Typeface> fontMetricMap = documentHandler.getFontInfo().getFonts(); final AFPFont afpFont = (AFPFont)fontMetricMap.get(fontKey); final Font font = getFontInfo().getFontInstance(triplet, fontSize); AFPPageFonts pageFonts = getPaintingState().getPageFonts(); AFPFontAttributes fontAttributes = pageFonts.registerFont(fontKey, afpFont, fontSize); final int fontReference = fontAttributes.getFontReference(); final int[] coords = unitConv.mpts2units(new float[] {x, y} ); final CharacterSet charSet = afpFont.getCharacterSet(fontSize); if (afpFont.isEmbeddable()) { try { documentHandler.getResourceManager().embedFont(afpFont, charSet); } catch (IOException ioe) { throw new IFException("Error while embedding font resources", ioe); } } AbstractPageObject page = getDataStream().getCurrentPage(); PresentationTextObject pto = page.getPresentationTextObject(); try { pto.createControlSequences(new PtocaProducer() { public void produce(PtocaBuilder builder) throws IOException { Point p = getPaintingState().getPoint(coords[X], coords[Y]); builder.setTextOrientation(getPaintingState().getRotation()); builder.absoluteMoveBaseline(p.y); builder.absoluteMoveInline(p.x); builder.setExtendedTextColor(state.getTextColor()); builder.setCodedFont((byte)fontReference); int l = text.length(); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); StringBuffer sb = new StringBuffer(); if (dxl > 0 && dx[0] != 0) { int dxu = Math.round(unitConv.mpt2units(dx[0])); builder.relativeMoveInline(-dxu); } //Following are two variants for glyph placement. //SVI does not seem to be implemented in the same way everywhere, so //a fallback alternative is preserved here. final boolean usePTOCAWordSpacing = true; if (usePTOCAWordSpacing) { int interCharacterAdjustment = 0; if (letterSpacing != 0) { interCharacterAdjustment = Math.round(unitConv.mpt2units( letterSpacing)); } builder.setInterCharacterAdjustment(interCharacterAdjustment); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + letterSpacing)); int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement; if (wordSpacing != 0) { varSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + wordSpacing + letterSpacing)); } builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement); boolean fixedSpaceMode = false; for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( fixedSpaceCharacterIncrement); fixedSpaceMode = true; sb.append(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { if (fixedSpaceMode) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( varSpaceCharacterIncrement); fixedSpaceMode = false; } char ch; if (orgChar == CharUtilities.NBSPACE) { ch = ' '; //converted to normal space to allow word spacing } else { ch = orgChar; } sb.append(ch); } if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } else { for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { sb.append(CharUtilities.SPACE); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { sb.append(orgChar); } if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust += wordSpacing; } glyphAdjust += letterSpacing; if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } flushText(builder, sb, charSet); } private void flushText(PtocaBuilder builder, StringBuffer sb, final CharacterSet charSet) throws IOException { if (sb.length() > 0) { builder.addTransparentData(charSet.encodeChars(sb)); sb.setLength(0); } } }); } catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void produce(PtocaBuilder builder) throws IOException { Point p = getPaintingState().getPoint(coords[X], coords[Y]); builder.setTextOrientation(getPaintingState().getRotation()); builder.absoluteMoveBaseline(p.y); builder.absoluteMoveInline(p.x); builder.setExtendedTextColor(state.getTextColor()); builder.setCodedFont((byte)fontReference); int l = text.length(); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); StringBuffer sb = new StringBuffer(); if (dxl > 0 && dx[0] != 0) { int dxu = Math.round(unitConv.mpt2units(dx[0])); builder.relativeMoveInline(-dxu); } //Following are two variants for glyph placement. //SVI does not seem to be implemented in the same way everywhere, so //a fallback alternative is preserved here. final boolean usePTOCAWordSpacing = true; if (usePTOCAWordSpacing) { int interCharacterAdjustment = 0; if (letterSpacing != 0) { interCharacterAdjustment = Math.round(unitConv.mpt2units( letterSpacing)); } builder.setInterCharacterAdjustment(interCharacterAdjustment); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + letterSpacing)); int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement; if (wordSpacing != 0) { varSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + wordSpacing + letterSpacing)); } builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement); boolean fixedSpaceMode = false; for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( fixedSpaceCharacterIncrement); fixedSpaceMode = true; sb.append(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { if (fixedSpaceMode) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( varSpaceCharacterIncrement); fixedSpaceMode = false; } char ch; if (orgChar == CharUtilities.NBSPACE) { ch = ' '; //converted to normal space to allow word spacing } else { ch = orgChar; } sb.append(ch); } if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } else { for (int i = 0; i < l; i++) { char orgChar = text.charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { sb.append(CharUtilities.SPACE); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { sb.append(orgChar); } if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust += wordSpacing; } glyphAdjust += letterSpacing; if (i < dxl - 1) { glyphAdjust += dx[i + 1]; } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } } flushText(builder, sb, charSet); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
private void flushText(PtocaBuilder builder, StringBuffer sb, final CharacterSet charSet) throws IOException { if (sb.length() > 0) { builder.addTransparentData(charSet.encodeChars(sb)); sb.setLength(0); } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
protected void saveGraphicsState() throws IOException { getPaintingState().save(); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
protected void restoreGraphicsState() throws IOException { getPaintingState().restore(); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { AFPRenderingContext afpContext = (AFPRenderingContext)context; AFPImageObjectInfo imageObjectInfo = (AFPImageObjectInfo)createDataObjectInfo(); AFPPaintingState paintingState = afpContext.getPaintingState(); // set resource information setResourceInformation(imageObjectInfo, image.getInfo().getOriginalURI(), afpContext.getForeignAttributes()); setDefaultResourceLevel(imageObjectInfo, afpContext.getResourceManager()); // Positioning imageObjectInfo.setObjectAreaInfo(createObjectAreaInfo(paintingState, pos)); Dimension targetSize = pos.getSize(); // Image content ImageRendered imageRend = (ImageRendered)image; RenderedImageEncoder encoder = new RenderedImageEncoder(imageRend, targetSize); encoder.prepareEncoding(imageObjectInfo, paintingState); boolean included = afpContext.getResourceManager().tryIncludeObject(imageObjectInfo); if (!included) { long start = System.currentTimeMillis(); //encode only if the same image has not been encoded, yet encoder.encodeImage(imageObjectInfo, paintingState); if (log.isDebugEnabled()) { long duration = System.currentTimeMillis() - start; log.debug("Image encoding took " + duration + "ms."); } // Create image afpContext.getResourceManager().createObject(imageObjectInfo); } }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
private AFPDataObjectInfo encodeImage (AFPImageObjectInfo imageObjectInfo, AFPPaintingState paintingState) throws IOException { RenderedImage renderedImage = imageRendered.getRenderedImage(); FunctionSet functionSet = useFS10 ? FunctionSet.FS10 : FunctionSet.FS11; if (usePageSegments) { assert resampledDim != null; //Resize, optionally resample and convert image imageObjectInfo.setCreatePageSegment(true); float ditheringQuality = paintingState.getDitheringQuality(); if (this.resample) { if (log.isDebugEnabled()) { log.debug("Resample from " + intrinsicSize.getDimensionPx() + " to " + resampledDim); } renderedImage = BitmapImageUtil.convertToMonochrome(renderedImage, resampledDim, ditheringQuality); } else if (ditheringQuality >= 0.5f) { renderedImage = BitmapImageUtil.convertToMonochrome(renderedImage, intrinsicSize.getDimensionPx(), ditheringQuality); } } //TODO To reduce AFP file size, investigate using a compression scheme. //Currently, all image data is uncompressed. ColorModel cm = renderedImage.getColorModel(); if (log.isTraceEnabled()) { log.trace("ColorModel: " + cm); } int pixelSize = cm.getPixelSize(); if (cm.hasAlpha()) { pixelSize -= 8; } byte[] imageData = null; ByteArrayOutputStream baos = new ByteArrayOutputStream(); boolean allowDirectEncoding = true; if (allowDirectEncoding && (pixelSize <= maxPixelSize)) { //Attempt to encode without resampling the image ImageEncodingHelper helper = new ImageEncodingHelper(renderedImage, pixelSize == 32); ColorModel encodedColorModel = helper.getEncodedColorModel(); boolean directEncode = true; if (helper.getEncodedColorModel().getPixelSize() > maxPixelSize) { directEncode = false; //pixel size needs to be reduced } if (BitmapImageUtil.getColorIndexSize(renderedImage) > 2) { directEncode = false; //Lookup tables are not implemented, yet } if (useFS10 && BitmapImageUtil.isMonochromeImage(renderedImage) && BitmapImageUtil.isZeroBlack(renderedImage)) { directEncode = false; //need a special method to invert the bit-stream since setting the //subtractive mode in AFP alone doesn't seem to do the trick. if (encodeInvertedBilevel(helper, imageObjectInfo, baos)) { imageData = baos.toByteArray(); } } if (directEncode) { log.debug("Encoding image directly..."); imageObjectInfo.setBitsPerPixel(encodedColorModel.getPixelSize()); if (pixelSize == 32) { functionSet = FunctionSet.FS45; //IOCA FS45 required for CMYK } //Lossy or loss-less? if (!paintingState.canEmbedJpeg() && paintingState.getBitmapEncodingQuality() < 1.0f) { try { if (log.isDebugEnabled()) { log.debug("Encoding using baseline DCT (JPEG, q=" + paintingState.getBitmapEncodingQuality() + ")..."); } encodeToBaselineDCT(renderedImage, paintingState.getBitmapEncodingQuality(), paintingState.getResolution(), baos); imageObjectInfo.setCompression(ImageContent.COMPID_JPEG); } catch (IOException ioe) { //Some JPEG codecs cannot encode CMYK helper.encode(baos); } } else { helper.encode(baos); } imageData = baos.toByteArray(); } } if (imageData == null) { log.debug("Encoding image via RGB..."); imageData = encodeViaRGB(renderedImage, imageObjectInfo, paintingState, baos); } // Should image be FS45? if (paintingState.getFS45()) { functionSet = FunctionSet.FS45; } //Wrapping 300+ resolution FS11 IOCA in a page segment is apparently necessary(?) imageObjectInfo.setCreatePageSegment( (functionSet.equals(FunctionSet.FS11) || functionSet.equals(FunctionSet.FS45)) && paintingState.getWrapPSeg() ); imageObjectInfo.setMimeType(functionSet.getMimeType()); imageObjectInfo.setData(imageData); return imageObjectInfo; }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
private byte[] encodeViaRGB(RenderedImage renderedImage, AFPImageObjectInfo imageObjectInfo, AFPPaintingState paintingState, ByteArrayOutputStream baos) throws IOException { byte[] imageData; //Convert image to 24bit RGB ImageEncodingHelper.encodeRenderedImageAsRGB(renderedImage, baos); imageData = baos.toByteArray(); imageObjectInfo.setBitsPerPixel(24); boolean colorImages = paintingState.isColorImages(); imageObjectInfo.setColor(colorImages); // convert to grayscale if (!colorImages) { log.debug("Converting RGB image to grayscale..."); baos.reset(); int bitsPerPixel = paintingState.getBitsPerPixel(); imageObjectInfo.setBitsPerPixel(bitsPerPixel); //TODO this should be done off the RenderedImage to avoid buffering the //intermediate 24bit image ImageEncodingHelper.encodeRGBAsGrayScale( imageData, renderedImage.getWidth(), renderedImage.getHeight(), bitsPerPixel, baos); imageData = baos.toByteArray(); if (bitsPerPixel == 1) { imageObjectInfo.setSubtractive(true); } } return imageData; }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
private boolean encodeInvertedBilevel(ImageEncodingHelper helper, AFPImageObjectInfo imageObjectInfo, OutputStream out) throws IOException { RenderedImage renderedImage = helper.getImage(); if (!BitmapImageUtil.isMonochromeImage(renderedImage)) { throw new IllegalStateException("This method only supports binary images!"); } int tiles = renderedImage.getNumXTiles() * renderedImage.getNumYTiles(); if (tiles > 1) { return false; } SampleModel sampleModel = renderedImage.getSampleModel(); SampleModel expectedSampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, renderedImage.getWidth(), renderedImage.getHeight(), 1); if (!expectedSampleModel.equals(sampleModel)) { return false; //Pixels are not packed } imageObjectInfo.setBitsPerPixel(1); Raster raster = renderedImage.getTile(0, 0); DataBuffer buffer = raster.getDataBuffer(); if (buffer instanceof DataBufferByte) { DataBufferByte byteBuffer = (DataBufferByte)buffer; log.debug("Encoding image as inverted bi-level..."); byte[] rawData = byteBuffer.getData(); int remaining = rawData.length; int pos = 0; byte[] data = new byte[4096]; while (remaining > 0) { int size = Math.min(remaining, data.length); for (int i = 0; i < size; i++) { data[i] = (byte)~rawData[pos]; //invert bits pos++; } out.write(data, 0, size); remaining -= size; } return true; } return false; }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
private void encodeToBaselineDCT(RenderedImage image, float quality, int resolution, OutputStream out) throws IOException { ImageWriter writer = ImageWriterRegistry.getInstance().getWriterFor("image/jpeg"); ImageWriterParams params = new ImageWriterParams(); params.setJPEGQuality(quality, true); params.setResolution(resolution); writer.writeImage(image, out, params); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRawCCITTFax.java
Override public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { log.debug("Embedding undecoded CCITT data as data container..."); super.handleImage(context, image, pos); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerGraphics2D.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { AFPRenderingContext afpContext = (AFPRenderingContext)context; AFPGraphicsObjectInfo graphicsObjectInfo = (AFPGraphicsObjectInfo)createDataObjectInfo(); // set resource information setResourceInformation(graphicsObjectInfo, image.getInfo().getOriginalURI(), afpContext.getForeignAttributes()); // Positioning graphicsObjectInfo.setObjectAreaInfo( createObjectAreaInfo(afpContext.getPaintingState(), pos)); setDefaultResourceLevel(graphicsObjectInfo, afpContext.getResourceManager()); AFPPaintingState paintingState = afpContext.getPaintingState(); paintingState.save(); // save AffineTransform placement = new AffineTransform(); placement.translate(pos.x, pos.y); paintingState.concatenate(placement); // Image content ImageGraphics2D imageG2D = (ImageGraphics2D)image; final boolean textAsShapes = paintingState.isStrokeGOCAText(); AFPGraphics2D g2d = new AFPGraphics2D( textAsShapes, afpContext.getPaintingState(), afpContext.getResourceManager(), graphicsObjectInfo.getResourceInfo(), (textAsShapes ? null : afpContext.getFontInfo())); g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); graphicsObjectInfo.setGraphics2D(g2d); graphicsObjectInfo.setPainter(imageG2D.getGraphics2DImagePainter()); // Create image afpContext.getResourceManager().createObject(graphicsObjectInfo); paintingState.restore(); // resume }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRawStream.java
Override public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { if (log.isDebugEnabled()) { log.debug("Embedding undecoded image data (" + image.getInfo().getMimeType() + ") as data container..."); } super.handleImage(context, image, pos); }
// in src/java/org/apache/fop/render/afp/AbstractAFPImageHandlerRawStream.java
private void updateDataObjectInfo(AFPDataObjectInfo dataObjectInfo, ImageRawStream rawStream, AFPResourceManager resourceManager) throws IOException { dataObjectInfo.setMimeType(rawStream.getFlavor().getMimeType()); AFPResourceInfo resourceInfo = dataObjectInfo.getResourceInfo(); if (!resourceInfo.levelChanged()) { resourceInfo.setLevel(resourceManager.getResourceLevelDefaults() .getDefaultResourceLevel(ResourceObject.TYPE_IMAGE)); } InputStream inputStream = rawStream.createInputStream(); try { dataObjectInfo.setData(IOUtils.toByteArray(inputStream)); } finally { IOUtils.closeQuietly(inputStream); } int dataHeight = rawStream.getSize().getHeightPx(); dataObjectInfo.setDataHeight(dataHeight); int dataWidth = rawStream.getSize().getWidthPx(); dataObjectInfo.setDataWidth(dataWidth); ImageSize imageSize = rawStream.getSize(); dataObjectInfo.setDataHeightRes((int) (imageSize.getDpiHorizontal() * 10)); dataObjectInfo.setDataWidthRes((int) (imageSize.getDpiVertical() * 10)); }
// in src/java/org/apache/fop/render/afp/AbstractAFPImageHandlerRawStream.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { AFPRenderingContext afpContext = (AFPRenderingContext)context; AFPDataObjectInfo dataObjectInfo = createDataObjectInfo(); // set resource information setResourceInformation(dataObjectInfo, image.getInfo().getOriginalURI(), afpContext.getForeignAttributes()); // Positioning dataObjectInfo.setObjectAreaInfo(createObjectAreaInfo(afpContext.getPaintingState(), pos)); // set object area info //AFPObjectAreaInfo objectAreaInfo = dataObjectInfo.getObjectAreaInfo(); AFPPaintingState paintingState = afpContext.getPaintingState(); int resolution = paintingState.getResolution(); AFPObjectAreaInfo objectAreaInfo = dataObjectInfo.getObjectAreaInfo(); objectAreaInfo.setResolution(resolution); // Image content ImageRawStream imageStream = (ImageRawStream)image; updateDataObjectInfo(dataObjectInfo, imageStream, afpContext.getResourceManager()); setAdditionalParameters(dataObjectInfo, imageStream); // Create image afpContext.getResourceManager().createObject(dataObjectInfo); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRawJPEG.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { AFPRenderingContext afpContext = (AFPRenderingContext)context; AFPImageObjectInfo imageObjectInfo = (AFPImageObjectInfo)createDataObjectInfo(); AFPPaintingState paintingState = afpContext.getPaintingState(); // set resource information setResourceInformation(imageObjectInfo, image.getInfo().getOriginalURI(), afpContext.getForeignAttributes()); setDefaultResourceLevel(imageObjectInfo, afpContext.getResourceManager()); // Positioning imageObjectInfo.setObjectAreaInfo(createObjectAreaInfo(paintingState, pos)); updateIntrinsicSize(imageObjectInfo, paintingState, image.getSize()); // Image content ImageRawJPEG jpeg = (ImageRawJPEG)image; imageObjectInfo.setCompression(ImageContent.COMPID_JPEG); ColorSpace cs = jpeg.getColorSpace(); switch (cs.getType()) { case ColorSpace.TYPE_GRAY: imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS11); imageObjectInfo.setColor(false); imageObjectInfo.setBitsPerPixel(8); break; case ColorSpace.TYPE_RGB: imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS11); imageObjectInfo.setColor(true); imageObjectInfo.setBitsPerPixel(24); break; case ColorSpace.TYPE_CMYK: imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS45); imageObjectInfo.setColor(true); imageObjectInfo.setBitsPerPixel(32); break; default: throw new IllegalStateException( "Color space of JPEG image not supported: " + cs); } boolean included = afpContext.getResourceManager().tryIncludeObject(imageObjectInfo); if (!included) { log.debug("Embedding undecoded JPEG as IOCA image..."); InputStream inputStream = jpeg.createInputStream(); try { imageObjectInfo.setData(IOUtils.toByteArray(inputStream)); } finally { IOUtils.closeQuietly(inputStream); } // Create image afpContext.getResourceManager().createObject(imageObjectInfo); } }
// in src/java/org/apache/fop/render/afp/AFPGraphics2DAdapter.java
public void paintImage(Graphics2DImagePainter painter, RendererContext rendererContext, int x, int y, int width, int height) throws IOException { AFPRendererContext afpRendererContext = (AFPRendererContext)rendererContext; AFPInfo afpInfo = afpRendererContext.getInfo(); final boolean textAsShapes = false; AFPGraphics2D g2d = afpInfo.createGraphics2D(textAsShapes); paintingState.save(); //Fallback solution: Paint to a BufferedImage if (afpInfo.paintAsBitmap()) { // paint image RendererContextWrapper rendererContextWrapper = RendererContext.wrapRendererContext(rendererContext); float targetResolution = rendererContext.getUserAgent().getTargetResolution(); int resolution = Math.round(targetResolution); boolean colorImages = afpInfo.isColorSupported(); BufferedImage bufferedImage = paintToBufferedImage( painter, rendererContextWrapper, resolution, !colorImages, false); // draw image AffineTransform at = paintingState.getData().getTransform(); at.translate(x, y); g2d.drawImage(bufferedImage, at, null); } else { AFPGraphicsObjectInfo graphicsObjectInfo = new AFPGraphicsObjectInfo(); graphicsObjectInfo.setPainter(painter); graphicsObjectInfo.setGraphics2D(g2d); // get the 'width' and 'height' attributes of the SVG document Dimension imageSize = painter.getImageSize(); float imw = (float)imageSize.getWidth() / 1000f; float imh = (float)imageSize.getHeight() / 1000f; Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, imw, imh); graphicsObjectInfo.setArea(area); AFPResourceManager resourceManager = afpInfo.getResourceManager(); resourceManager.createObject(graphicsObjectInfo); } paintingState.restore(); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerSVG.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { AFPRenderingContext afpContext = (AFPRenderingContext)context; ImageXMLDOM imageSVG = (ImageXMLDOM)image; FOUserAgent userAgent = afpContext.getUserAgent(); AFPGraphicsObjectInfo graphicsObjectInfo = (AFPGraphicsObjectInfo)createDataObjectInfo(); AFPResourceInfo resourceInfo = graphicsObjectInfo.getResourceInfo(); setDefaultToInlineResourceLevel(graphicsObjectInfo); // Create a new AFPGraphics2D AFPPaintingState paintingState = afpContext.getPaintingState(); final boolean textAsShapes = paintingState.isStrokeGOCAText(); AFPGraphics2D g2d = new AFPGraphics2D( textAsShapes, afpContext.getPaintingState(), afpContext.getResourceManager(), resourceInfo, (textAsShapes ? null : afpContext.getFontInfo())); g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); paintingState.setImageUri(image.getInfo().getOriginalURI()); // Create an AFPBridgeContext BridgeContext bridgeContext = AFPSVGHandler.createBridgeContext(userAgent, g2d); // Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) // to it. Document clonedDoc = BatikUtil.cloneSVGDocument(imageSVG.getDocument()); // Build the SVG DOM and provide the painter with it GraphicsNode root; try { GVTBuilder builder = new GVTBuilder(); root = builder.build(bridgeContext, clonedDoc); } catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; } // Image positioning AFPObjectAreaInfo objectAreaInfo = AFPImageHandler.createObjectAreaInfo(paintingState, pos); graphicsObjectInfo.setObjectAreaInfo(objectAreaInfo); paintingState.save(); // save AffineTransform placement = new AffineTransform(); placement.translate(pos.x, pos.y); paintingState.concatenate(placement); //Set up painter and target graphicsObjectInfo.setGraphics2D(g2d); // Create Graphics2DImagePainter Dimension imageSize = image.getSize().getDimensionMpt(); Graphics2DImagePainter painter = new Graphics2DImagePainterImpl( root, bridgeContext, imageSize); graphicsObjectInfo.setPainter(painter); // Create the GOCA GraphicsObject in the DataStream AFPResourceManager resourceManager = afpContext.getResourceManager(); resourceManager.createObject(graphicsObjectInfo); paintingState.restore(); // resume }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public void renderPage(PageViewport pageViewport) throws IOException, FOPException { super.renderPage(pageViewport); if (statusListener != null) { statusListener.notifyPageRendered(); } }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public void stopRenderer() throws IOException { super.stopRenderer(); if (statusListener != null) { statusListener.notifyRendererStopped(); // Refreshes view of page } }
// in src/java/org/apache/fop/render/AbstractGraphics2DAdapter.java
public void paintImage(Graphics2DImagePainter painter, RendererContext context, int x, int y, int width, int height) throws IOException { //TODO Deprecated method to be removed once Barcode4J 2.1 is released. paintImage((org.apache.xmlgraphics.java2d.Graphics2DImagePainter)painter, context, x, y, width, height); }
// in src/java/org/apache/fop/render/ps/PSRenderingUtil.java
public static void writeSetupCodeList(PSGenerator gen, List setupCodeList, String type) throws IOException { if (setupCodeList != null) { Iterator i = setupCodeList.iterator(); while (i.hasNext()) { PSSetupCode setupCode = (PSSetupCode)i.next(); gen.commentln("%FOPBegin" + type + ": (" + (setupCode.getName() != null ? setupCode.getName() : "") + ")"); LineNumberReader reader = new LineNumberReader( new java.io.StringReader(setupCode.getContent())); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { gen.writeln(line.trim()); } } gen.commentln("%FOPEnd" + type); i.remove(); } } }
// in src/java/org/apache/fop/render/ps/PSRenderingUtil.java
public static void writeEnclosedExtensionAttachments(PSGenerator gen, Collection attachmentCollection) throws IOException { Iterator iter = attachmentCollection.iterator(); while (iter.hasNext()) { PSExtensionAttachment attachment = (PSExtensionAttachment)iter.next(); if (attachment != null) { writeEnclosedExtensionAttachment(gen, attachment); } iter.remove(); } }
// in src/java/org/apache/fop/render/ps/PSRenderingUtil.java
public static void writeEnclosedExtensionAttachment(PSGenerator gen, PSExtensionAttachment attachment) throws IOException { if (attachment instanceof PSCommentBefore) { gen.commentln("%" + attachment.getContent()); } else if (attachment instanceof PSCommentAfter) { gen.commentln("%" + attachment.getContent()); } else { String info = ""; if (attachment instanceof PSSetupCode) { PSSetupCode setupCodeAttach = (PSSetupCode)attachment; String name = setupCodeAttach.getName(); if (name != null) { info += ": (" + name + ")"; } } String type = attachment.getType(); gen.commentln("%FOPBegin" + type + info); LineNumberReader reader = new LineNumberReader( new java.io.StringReader(attachment.getContent())); String line; while ((line = reader.readLine()) != null) { line = line.trim(); if (line.length() > 0) { gen.writeln(line); } } gen.commentln("%FOPEnd" + type); } }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
public static Map writeFontDict(PSGenerator gen, FontInfo fontInfo) throws IOException { return writeFontDict(gen, fontInfo, fontInfo.getFonts(), true); }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
public static Map writeFontDict(PSGenerator gen, FontInfo fontInfo, Map<String, Typeface> fonts) throws IOException { return writeFontDict(gen, fontInfo, fonts, false); }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
private static Map writeFontDict(PSGenerator gen, FontInfo fontInfo, Map<String, Typeface> fonts, boolean encodeAllCharacters) throws IOException { gen.commentln("%FOPBeginFontDict"); Map fontResources = new java.util.HashMap(); for (String key : fonts.keySet()) { Typeface tf = getTypeFace(fontInfo, fonts, key); PSResource fontRes = new PSResource(PSResource.TYPE_FONT, tf.getFontName()); fontResources.put(key, fontRes); embedFont(gen, tf, fontRes); if (tf instanceof SingleByteFont) { SingleByteFont sbf = (SingleByteFont)tf; if (encodeAllCharacters) { sbf.encodeAllUnencodedCharacters(); } for (int i = 0, c = sbf.getAdditionalEncodingCount(); i < c; i++) { SingleByteEncoding encoding = sbf.getAdditionalEncoding(i); defineEncoding(gen, encoding); String postFix = "_" + (i + 1); PSResource derivedFontRes = defineDerivedFont(gen, tf.getFontName(), tf.getFontName() + postFix, encoding.getName()); fontResources.put(key + postFix, derivedFontRes); } } } gen.commentln("%FOPEndFontDict"); reencodeFonts(gen, fonts); return fontResources; }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
private static void reencodeFonts(PSGenerator gen, Map<String, Typeface> fonts) throws IOException { ResourceTracker tracker = gen.getResourceTracker(); if (!tracker.isResourceSupplied(WINANSI_ENCODING_RESOURCE)) { //Only out Base 14 fonts still use that defineWinAnsiEncoding(gen); } gen.commentln("%FOPBeginFontReencode"); //Rewrite font encodings for (String key : fonts.keySet()) { Typeface tf = fonts.get(key); if (tf instanceof LazyFont) { tf = ((LazyFont)tf).getRealFont(); if (tf == null) { continue; } } if (null == tf.getEncodingName()) { //ignore (ZapfDingbats and Symbol used to run through here, kept for safety reasons) } else if ("SymbolEncoding".equals(tf.getEncodingName())) { //ignore (no encoding redefinition) } else if ("ZapfDingbatsEncoding".equals(tf.getEncodingName())) { //ignore (no encoding redefinition) } else { if (tf instanceof Base14Font) { //Our Base 14 fonts don't use the default encoding redefineFontEncoding(gen, tf.getFontName(), tf.getEncodingName()); } else if (tf instanceof SingleByteFont) { SingleByteFont sbf = (SingleByteFont)tf; if (!sbf.isUsingNativeEncoding()) { //Font has been configured to use an encoding other than the default one redefineFontEncoding(gen, tf.getFontName(), tf.getEncodingName()); } } } } gen.commentln("%FOPEndFontReencode"); }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
public static void embedFont(PSGenerator gen, Typeface tf, PSResource fontRes) throws IOException { boolean embeddedFont = false; if (FontType.TYPE1 == tf.getFontType()) { if (tf instanceof CustomFont) { CustomFont cf = (CustomFont)tf; if (isEmbeddable(cf)) { InputStream in = getInputStreamOnFont(gen, cf); if (in != null) { gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, fontRes); embedType1Font(gen, in); gen.writeDSCComment(DSCConstants.END_RESOURCE); gen.getResourceTracker().registerSuppliedResource(fontRes); embeddedFont = true; } else { gen.commentln("%WARNING: Could not embed font: " + cf.getFontName()); log.warn("Font " + cf.getFontName() + " is marked as supplied in the" + " PostScript file but could not be embedded!"); } } } } if (!embeddedFont) { gen.writeDSCComment(DSCConstants.INCLUDE_RESOURCE, fontRes); } }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
private static InputStream getInputStreamOnFont(PSGenerator gen, CustomFont font) throws IOException { if (isEmbeddable(font)) { Source source = font.getEmbedFileSource(); if (source == null && font.getEmbedResourceName() != null) { source = new StreamSource(PSFontUtils.class .getResourceAsStream(font.getEmbedResourceName())); } if (source == null) { return null; } InputStream in = null; if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null && source.getSystemId() != null) { try { in = new java.net.URL(source.getSystemId()).openStream(); } catch (MalformedURLException e) { new FileNotFoundException( "File not found. URL could not be resolved: " + e.getMessage()); } } if (in == null) { return null; } //Make sure the InputStream is decorated with a BufferedInputStream if (!(in instanceof java.io.BufferedInputStream)) { in = new java.io.BufferedInputStream(in); } return in; } else { return null; } }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
public static PSResource defineEncoding(PSGenerator gen, SingleByteEncoding encoding) throws IOException { PSResource res = new PSResource(PSResource.TYPE_ENCODING, encoding.getName()); gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, res); gen.writeln("/" + encoding.getName() + " ["); String[] charNames = encoding.getCharNameMap(); for (int i = 0; i < 256; i++) { if (i > 0) { if ((i % 5) == 0) { gen.newLine(); } else { gen.write(" "); } } String glyphname = null; if (i < charNames.length) { glyphname = charNames[i]; } if (glyphname == null || "".equals(glyphname)) { glyphname = Glyphs.NOTDEF; } gen.write("/"); gen.write(glyphname); } gen.newLine(); gen.writeln("] def"); gen.writeDSCComment(DSCConstants.END_RESOURCE); gen.getResourceTracker().registerSuppliedResource(res); return res; }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
public static PSResource defineDerivedFont (PSGenerator gen, String baseFontName, String fontName, String encoding) throws IOException { PSResource res = new PSResource(PSResource.TYPE_FONT, fontName); gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, res); gen.commentln("%XGCDependencies: font " + baseFontName); gen.commentln("%XGC+ encoding " + encoding); gen.writeln("/" + baseFontName + " findfont"); gen.writeln("dup length dict begin"); gen.writeln(" {1 index /FID ne {def} {pop pop} ifelse} forall"); gen.writeln(" /Encoding " + encoding + " def"); gen.writeln(" currentdict"); gen.writeln("end"); gen.writeln("/" + fontName + " exch definefont pop"); gen.writeDSCComment(DSCConstants.END_RESOURCE); gen.getResourceTracker().registerSuppliedResource(res); return res; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerRawJPEG.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRawJPEG jpeg = (ImageRawJPEG)image; float x = (float)pos.getX() / 1000f; float y = (float)pos.getY() / 1000f; float w = (float)pos.getWidth() / 1000f; float h = (float)pos.getHeight() / 1000f; Rectangle2D targetRect = new Rectangle2D.Float( x, y, w, h); ImageInfo info = image.getInfo(); ImageEncoder encoder = new ImageEncoderJPEG(jpeg); PSImageUtils.writeImage(encoder, info.getSize().getDimensionPx(), info.getOriginalURI(), targetRect, jpeg.getColorSpace(), 8, jpeg.isInverted(), gen); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerRawJPEG.java
public void generateForm(RenderingContext context, Image image, PSImageFormResource form) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRawJPEG jpeg = (ImageRawJPEG)image; ImageInfo info = image.getInfo(); String imageDescription = info.getMimeType() + " " + info.getOriginalURI(); ImageEncoder encoder = new ImageEncoderJPEG(jpeg); FormGenerator formGen = new ImageFormGenerator( form.getName(), imageDescription, info.getSize().getDimensionPt(), info.getSize().getDimensionPx(), encoder, jpeg.getColorSpace(), jpeg.isInverted()); formGen.generate(gen); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
public void process(InputStream in, OutputStream out, int pageCount, Rectangle2D documentBoundingBox) throws DSCException, IOException { DSCParser parser = new DSCParser(in); PSGenerator gen = new PSGenerator(out); parser.addListener(new DefaultNestedDocumentHandler(gen)); parser.addListener(new IncludeResourceListener(gen)); //Skip DSC header DSCHeaderComment header = DSCTools.checkAndSkipDSC30Header(parser); header.generate(gen); parser.setFilter(new DSCFilter() { private final Set filtered = new java.util.HashSet(); { //We rewrite those as part of the processing filtered.add(DSCConstants.PAGES); filtered.add(DSCConstants.BBOX); filtered.add(DSCConstants.HIRES_BBOX); filtered.add(DSCConstants.DOCUMENT_NEEDED_RESOURCES); filtered.add(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES); } public boolean accept(DSCEvent event) { if (event.isDSCComment()) { //Filter %%Pages which we add manually from a parameter return !(filtered.contains(event.asDSCComment().getName())); } else { return true; } } }); //Get PostScript language level (may be missing) while (true) { DSCEvent event = parser.nextEvent(); if (event == null) { reportInvalidDSC(); } if (DSCTools.headerCommentsEndHere(event)) { //Set number of pages DSCCommentPages pages = new DSCCommentPages(pageCount); pages.generate(gen); new DSCCommentBoundingBox(documentBoundingBox).generate(gen); new DSCCommentHiResBoundingBox(documentBoundingBox).generate(gen); PSFontUtils.determineSuppliedFonts(resTracker, fontInfo, fontInfo.getUsedFonts()); registerSuppliedForms(resTracker, globalFormResources); //Supplied Resources DSCCommentDocumentSuppliedResources supplied = new DSCCommentDocumentSuppliedResources( resTracker.getDocumentSuppliedResources()); supplied.generate(gen); //Needed Resources DSCCommentDocumentNeededResources needed = new DSCCommentDocumentNeededResources( resTracker.getDocumentNeededResources()); needed.generate(gen); //Write original comment that ends the header comments event.generate(gen); break; } if (event.isDSCComment()) { DSCComment comment = event.asDSCComment(); if (DSCConstants.LANGUAGE_LEVEL.equals(comment.getName())) { DSCCommentLanguageLevel level = (DSCCommentLanguageLevel)comment; gen.setPSLevel(level.getLanguageLevel()); } } event.generate(gen); } //Skip to the FOPFontSetup PostScriptComment fontSetupPlaceholder = parser.nextPSComment("FOPFontSetup", gen); if (fontSetupPlaceholder == null) { throw new DSCException("Didn't find %FOPFontSetup comment in stream"); } PSFontUtils.writeFontDict(gen, fontInfo, fontInfo.getUsedFonts()); generateForms(globalFormResources, gen); //Skip the prolog and to the first page DSCComment pageOrTrailer = parser.nextDSCComment(DSCConstants.PAGE, gen); if (pageOrTrailer == null) { throw new DSCException("Page expected, but none found"); } //Process individual pages (and skip as necessary) while (true) { DSCCommentPage page = (DSCCommentPage)pageOrTrailer; page.generate(gen); pageOrTrailer = DSCTools.nextPageOrTrailer(parser, gen); if (pageOrTrailer == null) { reportInvalidDSC(); } else if (!DSCConstants.PAGE.equals(pageOrTrailer.getName())) { pageOrTrailer.generate(gen); break; } } //Write the rest while (parser.hasNext()) { DSCEvent event = parser.nextEvent(); event.generate(gen); } gen.flush(); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private static void registerSuppliedForms(ResourceTracker resTracker, Map formResources) throws IOException { if (formResources == null) { return; } Iterator iter = formResources.values().iterator(); while (iter.hasNext()) { PSImageFormResource form = (PSImageFormResource)iter.next(); resTracker.registerSuppliedResource(form); } }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private void generateForms(Map formResources, PSGenerator gen) throws IOException { if (formResources == null) { return; } Iterator iter = formResources.values().iterator(); while (iter.hasNext()) { PSImageFormResource form = (PSImageFormResource)iter.next(); generateFormForImage(gen, form); } }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private void generateFormForImage(PSGenerator gen, PSImageFormResource form) throws IOException { final String uri = form.getImageURI(); ImageManager manager = userAgent.getFactory().getImageManager(); ImageInfo info = null; try { ImageSessionContext sessionContext = userAgent.getImageSessionContext(); info = manager.getImageInfo(uri, sessionContext); //Create a rendering context for form creation PSRenderingContext formContext = new PSRenderingContext( userAgent, gen, fontInfo, true); ImageFlavor[] flavors; ImageHandlerRegistry imageHandlerRegistry = userAgent.getFactory().getImageHandlerRegistry(); flavors = imageHandlerRegistry.getSupportedFlavors(formContext); Map hints = ImageUtil.getDefaultHints(sessionContext); org.apache.xmlgraphics.image.loader.Image img = manager.getImage( info, flavors, hints, sessionContext); ImageHandler basicHandler = imageHandlerRegistry.getHandler(formContext, img); if (basicHandler == null) { throw new UnsupportedOperationException( "No ImageHandler available for image: " + img.getInfo() + " (" + img.getClass().getName() + ")"); } if (!(basicHandler instanceof PSImageHandler)) { throw new IllegalStateException( "ImageHandler implementation doesn't behave properly." + " It should have returned false in isCompatible(). Class: " + basicHandler.getClass().getName()); } PSImageHandler handler = (PSImageHandler)basicHandler; if (log.isTraceEnabled()) { log.trace("Using ImageHandler: " + handler.getClass().getName()); } handler.generateForm(formContext, img, form); } catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.imageError(resTracker, (info != null ? info.toString() : uri), ie, null); } }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private static FormGenerator createMissingForm(String formName, final Dimension2D dimensions) { FormGenerator formGen = new FormGenerator(formName, null, dimensions) { protected void generatePaintProc(PSGenerator gen) throws IOException { gen.writeln("0 setgray"); gen.writeln("0 setlinewidth"); String w = gen.formatDouble(dimensions.getWidth()); String h = gen.formatDouble(dimensions.getHeight()); gen.writeln(w + " " + h + " scale"); gen.writeln("0 0 1 1 rectstroke"); gen.writeln("newpath"); gen.writeln("0 0 moveto"); gen.writeln("1 1 lineto"); gen.writeln("stroke"); gen.writeln("newpath"); gen.writeln("0 1 moveto"); gen.writeln("1 0 lineto"); gen.writeln("stroke"); } }; return formGen; }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
protected void generatePaintProc(PSGenerator gen) throws IOException { gen.writeln("0 setgray"); gen.writeln("0 setlinewidth"); String w = gen.formatDouble(dimensions.getWidth()); String h = gen.formatDouble(dimensions.getHeight()); gen.writeln(w + " " + h + " scale"); gen.writeln("0 0 1 1 rectstroke"); gen.writeln("newpath"); gen.writeln("0 0 moveto"); gen.writeln("1 1 lineto"); gen.writeln("stroke"); gen.writeln("newpath"); gen.writeln("0 1 moveto"); gen.writeln("1 0 lineto"); gen.writeln("stroke"); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
public void processEvent(DSCEvent event, DSCParser parser) throws IOException, DSCException { if (event.isDSCComment() && event instanceof DSCCommentIncludeResource) { DSCCommentIncludeResource include = (DSCCommentIncludeResource)event; PSResource res = include.getResource(); if (res.getType().equals(PSResource.TYPE_FORM)) { if (inlineFormResources.containsValue(res)) { PSImageFormResource form = (PSImageFormResource) inlineFormResources.get(res); //Create an inline form //Wrap in save/restore pair to release memory gen.writeln("save"); generateFormForImage(gen, form); boolean execformFound = false; DSCEvent next = parser.nextEvent(); if (next.isLine()) { PostScriptLine line = next.asLine(); if (line.getLine().endsWith(" execform")) { line.generate(gen); execformFound = true; } } if (!execformFound) { throw new IOException( "Expected a PostScript line in the form: <form> execform"); } gen.writeln("restore"); } else { //Do nothing } parser.next(); } } }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageGraphics2D imageG2D = (ImageGraphics2D)image; Graphics2DImagePainter painter = imageG2D.getGraphics2DImagePainter(); float fx = (float)pos.getX() / 1000f; float fy = (float)pos.getY() / 1000f; float fwidth = (float)pos.getWidth() / 1000f; float fheight = (float)pos.getHeight() / 1000f; // get the 'width' and 'height' attributes of the SVG document Dimension dim = painter.getImageSize(); float imw = (float)dim.getWidth() / 1000f; float imh = (float)dim.getHeight() / 1000f; float sx = fwidth / (float)imw; float sy = fheight / (float)imh; gen.commentln("%FOPBeginGraphics2D"); gen.saveGraphicsState(); final boolean clip = false; if (clip) { // Clip to the image area. gen.writeln("newpath"); gen.defineRect(fx, fy, fwidth, fheight); gen.writeln("clip"); } // transform so that the coordinates (0,0) is from the top left // and positive is down and to the right. (0,0) is where the // viewBox puts it. gen.concatMatrix(sx, 0, 0, sy, fx, fy); final boolean textAsShapes = false; PSGraphics2D graphics = new PSGraphics2D(textAsShapes, gen); graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); AffineTransform transform = new AffineTransform(); // scale to viewbox transform.translate(fx, fy); gen.getCurrentState().concatMatrix(transform); Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, imw, imh); painter.paint(graphics, area); gen.restoreGraphicsState(); gen.commentln("%FOPEndGraphics2D"); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
public void generateForm(RenderingContext context, Image image, final PSImageFormResource form) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); final ImageGraphics2D imageG2D = (ImageGraphics2D)image; ImageInfo info = image.getInfo(); FormGenerator formGen = buildFormGenerator(gen.getPSLevel(), form, info, imageG2D); formGen.generate(gen); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
private FormGenerator buildFormGenerator(int psLanguageLevel, final PSImageFormResource form, final ImageInfo info, final ImageGraphics2D imageG2D) { String imageDescription = info.getMimeType() + " " + info.getOriginalURI(); final Dimension2D dimensionsPt = info.getSize().getDimensionPt(); final Dimension2D dimensionsMpt = info.getSize().getDimensionMpt(); FormGenerator formGen; if (psLanguageLevel <= 2) { formGen = new EPSFormGenerator(form.getName(), imageDescription, dimensionsPt) { @Override void doGeneratePaintProc(PSGenerator gen) throws IOException { paintImageG2D(imageG2D, dimensionsMpt, gen); } }; } else { formGen = new EPSFormGenerator(form.getName(), imageDescription, dimensionsPt) { @Override protected void generateAdditionalDataStream(PSGenerator gen) throws IOException { gen.writeln("/" + form.getName() + ":Data currentfile <<"); gen.writeln(" /Filter /SubFileDecode"); gen.writeln(" /DecodeParms << /EODCount 0 /EODString (%FOPEndOfData) >>"); gen.writeln(">> /ReusableStreamDecode filter"); paintImageG2D(imageG2D, dimensionsMpt, gen); gen.writeln("%FOPEndOfData"); gen.writeln("def"); } @Override void doGeneratePaintProc(PSGenerator gen) throws IOException { gen.writeln(form.getName() + ":Data 0 setfileposition"); gen.writeln(form.getName() + ":Data cvx exec"); } }; } return formGen; }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
Override void doGeneratePaintProc(PSGenerator gen) throws IOException { paintImageG2D(imageG2D, dimensionsMpt, gen); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
Override protected void generateAdditionalDataStream(PSGenerator gen) throws IOException { gen.writeln("/" + form.getName() + ":Data currentfile <<"); gen.writeln(" /Filter /SubFileDecode"); gen.writeln(" /DecodeParms << /EODCount 0 /EODString (%FOPEndOfData) >>"); gen.writeln(">> /ReusableStreamDecode filter"); paintImageG2D(imageG2D, dimensionsMpt, gen); gen.writeln("%FOPEndOfData"); gen.writeln("def"); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
Override void doGeneratePaintProc(PSGenerator gen) throws IOException { gen.writeln(form.getName() + ":Data 0 setfileposition"); gen.writeln(form.getName() + ":Data cvx exec"); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
protected void paintImageG2D(final ImageGraphics2D imageG2D, Dimension2D dimensionsMpt, PSGenerator gen) throws IOException { PSGraphics2DAdapter adapter = new PSGraphics2DAdapter(gen, false); adapter.paintImage(imageG2D.getGraphics2DImagePainter(), null, 0, 0, (int) Math.round(dimensionsMpt.getWidth()), (int) Math.round(dimensionsMpt.getHeight())); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerGraphics2D.java
Override protected final void generatePaintProc(PSGenerator gen) throws IOException { gen.getResourceTracker().notifyResourceUsageOnPage( PSProcSets.EPS_PROCSET); gen.writeln("BeginEPSF"); doGeneratePaintProc(gen); gen.writeln("EndEPSF"); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
private void writeHeader() throws IOException { //PostScript Header gen.writeln(DSCConstants.PS_ADOBE_30); gen.writeDSCComment(DSCConstants.CREATOR, new String[] {getUserAgent().getProducer()}); gen.writeDSCComment(DSCConstants.CREATION_DATE, new Object[] {new java.util.Date()}); gen.writeDSCComment(DSCConstants.LANGUAGE_LEVEL, new Integer(gen.getPSLevel())); gen.writeDSCComment(DSCConstants.PAGES, new Object[] {DSCConstants.ATEND}); gen.writeDSCComment(DSCConstants.BBOX, DSCConstants.ATEND); gen.writeDSCComment(DSCConstants.HIRES_BBOX, DSCConstants.ATEND); gen.writeDSCComment(DSCConstants.DOCUMENT_SUPPLIED_RESOURCES, new Object[] {DSCConstants.ATEND}); writeExtensions(COMMENT_DOCUMENT_HEADER); gen.writeDSCComment(DSCConstants.END_COMMENTS); //Defaults gen.writeDSCComment(DSCConstants.BEGIN_DEFAULTS); gen.writeDSCComment(DSCConstants.END_DEFAULTS); //Prolog and Setup written right before the first page-sequence, see startPageSequence() //Do this only once, as soon as we have all the content for the Setup section! //Prolog gen.writeDSCComment(DSCConstants.BEGIN_PROLOG); PSProcSets.writeStdProcSet(gen); PSProcSets.writeEPSProcSet(gen); FOPProcSet.INSTANCE.writeTo(gen); gen.writeDSCComment(DSCConstants.END_PROLOG); //Setup gen.writeDSCComment(DSCConstants.BEGIN_SETUP); PSRenderingUtil.writeSetupCodeList(gen, setupCodeList, "SetupCode"); if (!psUtil.isOptimizeResources()) { this.fontResources.addAll(PSFontUtils.writeFontDict(gen, fontInfo)); } else { gen.commentln("%FOPFontSetup"); //Place-holder, will be replaced in the second pass } gen.writeDSCComment(DSCConstants.END_SETUP); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
private void rewritePostScriptFile() throws IOException { log.debug("Processing PostScript resources..."); long startTime = System.currentTimeMillis(); ResourceTracker resTracker = gen.getResourceTracker(); InputStream in = new java.io.FileInputStream(this.tempFile); in = new java.io.BufferedInputStream(in); try { try { ResourceHandler handler = new ResourceHandler(getUserAgent(), this.fontInfo, resTracker, this.formResources); handler.process(in, this.outputStream, this.currentPageNumber, this.documentBoundingBox); this.outputStream.flush(); } catch (DSCException e) { throw new RuntimeException(e.getMessage()); } } finally { IOUtils.closeQuietly(in); if (!this.tempFile.delete()) { this.tempFile.deleteOnExit(); log.warn("Could not delete temporary file: " + this.tempFile); } } if (log.isDebugEnabled()) { long duration = System.currentTimeMillis() - startTime; log.debug("Resource Processing complete in " + duration + " ms."); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
private void writeExtensions(int which) throws IOException { Collection extensions = comments[which]; if (extensions != null) { PSRenderingUtil.writeEnclosedExtensionAttachments(gen, extensions); extensions.clear(); } }
// in src/java/org/apache/fop/render/ps/PSImageHandlerRawCCITTFax.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRawCCITTFax ccitt = (ImageRawCCITTFax)image; float x = (float)pos.getX() / 1000f; float y = (float)pos.getY() / 1000f; float w = (float)pos.getWidth() / 1000f; float h = (float)pos.getHeight() / 1000f; Rectangle2D targetRect = new Rectangle2D.Float( x, y, w, h); ImageInfo info = image.getInfo(); ImageEncoder encoder = new ImageEncoderCCITTFax(ccitt); PSImageUtils.writeImage(encoder, info.getSize().getDimensionPx(), info.getOriginalURI(), targetRect, ccitt.getColorSpace(), 1, false, gen); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerRawCCITTFax.java
public void generateForm(RenderingContext context, Image image, PSImageFormResource form) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRawCCITTFax ccitt = (ImageRawCCITTFax)image; ImageInfo info = image.getInfo(); String imageDescription = info.getMimeType() + " " + info.getOriginalURI(); ImageEncoder encoder = new ImageEncoderCCITTFax(ccitt); FormGenerator formGen = new ImageFormGenerator( form.getName(), imageDescription, info.getSize().getDimensionPt(), info.getSize().getDimensionPx(), encoder, ccitt.getColorSpace(), 1, false); formGen.generate(gen); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerSVG.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageXMLDOM imageSVG = (ImageXMLDOM)image; //Controls whether text painted by Batik is generated using text or path operations boolean strokeText = false; //TODO Configure text stroking SVGUserAgent ua = new SVGUserAgent(context.getUserAgent(), new AffineTransform()); PSGraphics2D graphics = new PSGraphics2D(strokeText, gen); graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); BridgeContext ctx = new PSBridgeContext(ua, (strokeText ? null : psContext.getFontInfo()), context.getUserAgent().getFactory().getImageManager(), context.getUserAgent().getImageSessionContext()); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(imageSVG.getDocument()); GraphicsNode root; try { GVTBuilder builder = new GVTBuilder(); root = builder.build(ctx, clonedDoc); } catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgNotBuilt(this, e, image.getInfo().getOriginalURI()); return; } // get the 'width' and 'height' attributes of the SVG document float w = (float)ctx.getDocumentSize().getWidth() * 1000f; float h = (float)ctx.getDocumentSize().getHeight() * 1000f; float sx = pos.width / w; float sy = pos.height / h; ctx = null; gen.commentln("%FOPBeginSVG"); gen.saveGraphicsState(); final boolean clip = false; if (clip) { /* * Clip to the svg area. * Note: To have the svg overlay (under) a text area then use * an fo:block-container */ gen.writeln("newpath"); gen.defineRect(pos.getMinX() / 1000f, pos.getMinY() / 1000f, pos.width / 1000f, pos.height / 1000f); gen.writeln("clip"); } // transform so that the coordinates (0,0) is from the top left // and positive is down and to the right. (0,0) is where the // viewBox puts it. gen.concatMatrix(sx, 0, 0, sy, pos.getMinX() / 1000f, pos.getMinY() / 1000f); AffineTransform transform = new AffineTransform(); // scale to viewbox transform.translate(pos.getMinX(), pos.getMinY()); gen.getCurrentState().concatMatrix(transform); try { root.paint(graphics); } catch (Exception e) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, e, image.getInfo().getOriginalURI()); } gen.restoreGraphicsState(); gen.commentln("%FOPEndSVG"); }
// in src/java/org/apache/fop/render/ps/FOPProcSet.java
public void writeTo(PSGenerator gen) throws IOException { gen.writeDSCComment(DSCConstants.BEGIN_RESOURCE, new Object[] {TYPE_PROCSET, getName(), Float.toString(getVersion()), Integer.toString(getRevision())}); gen.writeDSCComment(DSCConstants.VERSION, new Object[] {Float.toString(getVersion()), Integer.toString(getRevision())}); gen.writeDSCComment(DSCConstants.COPYRIGHT, "Copyright 2009 " + "The Apache Software Foundation. " + "License terms: http://www.apache.org/licenses/LICENSE-2.0"); gen.writeDSCComment(DSCConstants.TITLE, "Basic set of procedures used by Apache FOP"); gen.writeln("/TJ { % Similar but not equal to PDF's TJ operator"); gen.writeln(" {"); gen.writeln(" dup type /stringtype eq"); gen.writeln(" { show }"); //normal text show gen.writeln(" { neg 1000 div 0 rmoveto }"); //negative X movement gen.writeln(" ifelse"); gen.writeln(" } forall"); gen.writeln("} bd"); gen.writeln("/ATJ { % As TJ but adds letter-spacing"); gen.writeln(" /ATJls exch def"); gen.writeln(" {"); gen.writeln(" dup type /stringtype eq"); gen.writeln(" { ATJls 0 3 2 roll ashow }"); //normal text show gen.writeln(" { neg 1000 div 0 rmoveto }"); //negative X movement gen.writeln(" ifelse"); gen.writeln(" } forall"); gen.writeln("} bd"); gen.writeDSCComment(DSCConstants.END_RESOURCE); gen.getResourceTracker().registerSuppliedResource(this); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerEPS.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRawEPS eps = (ImageRawEPS)image; float x = (float)pos.getX() / 1000f; float y = (float)pos.getY() / 1000f; float w = (float)pos.getWidth() / 1000f; float h = (float)pos.getHeight() / 1000f; ImageInfo info = image.getInfo(); Rectangle2D bbox = eps.getBoundingBox(); if (bbox == null) { bbox = new Rectangle2D.Double(); bbox.setFrame(new Point2D.Double(), info.getSize().getDimensionPt()); } InputStream in = eps.createInputStream(); try { String resourceName = info.getOriginalURI(); if (resourceName == null) { resourceName = "inline image"; } PSImageUtils.renderEPS(in, resourceName, new Rectangle2D.Float(x, y, w, h), bbox, gen); } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/render/ps/ImageEncoderJPEG.java
public void writeTo(OutputStream out) throws IOException { jpeg.writeTo(out); }
// in src/java/org/apache/fop/render/ps/ImageEncoderCCITTFax.java
public void writeTo(OutputStream out) throws IOException { ccitt.writeTo(out); }
// in src/java/org/apache/fop/render/ps/PSGraphics2DAdapter.java
public void paintImage(Graphics2DImagePainter painter, RendererContext context, int x, int y, int width, int height) throws IOException { float fwidth = width / 1000f; float fheight = height / 1000f; float fx = x / 1000f; float fy = y / 1000f; // get the 'width' and 'height' attributes of the SVG document Dimension dim = painter.getImageSize(); float imw = (float)dim.getWidth() / 1000f; float imh = (float)dim.getHeight() / 1000f; boolean paintAsBitmap = false; if (context != null) { Map foreign = (Map)context.getProperty(RendererContextConstants.FOREIGN_ATTRIBUTES); paintAsBitmap = (foreign != null && ImageHandlerUtil.isConversionModeBitmap(foreign)); } float sx = paintAsBitmap ? 1.0f : (fwidth / (float)imw); float sy = paintAsBitmap ? 1.0f : (fheight / (float)imh); gen.commentln("%FOPBeginGraphics2D"); gen.saveGraphicsState(); if (clip) { // Clip to the image area. gen.writeln("newpath"); gen.defineRect(fx, fy, fwidth, fheight); gen.writeln("clip"); } // transform so that the coordinates (0,0) is from the top left // and positive is down and to the right. (0,0) is where the // viewBox puts it. gen.concatMatrix(sx, 0, 0, sy, fx, fy); final boolean textAsShapes = false; PSGraphics2D graphics = new PSGraphics2D(textAsShapes, gen); graphics.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext()); AffineTransform transform = new AffineTransform(); // scale to viewbox transform.translate(fx, fy); gen.getCurrentState().concatMatrix(transform); if (paintAsBitmap) { //Fallback solution: Paint to a BufferedImage int resolution = (int)Math.round(context.getUserAgent().getTargetResolution()); RendererContextWrapper ctx = RendererContext.wrapRendererContext(context); BufferedImage bi = paintToBufferedImage(painter, ctx, resolution, false, false); float scale = PDFFactory.DEFAULT_PDF_RESOLUTION / context.getUserAgent().getTargetResolution(); graphics.drawImage(bi, new AffineTransform(scale, 0, 0, scale, 0, 0), null); } else { Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, imw, imh); painter.paint(graphics, area); } gen.restoreGraphicsState(); gen.commentln("%FOPEndGraphics2D"); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
protected void drawImageUsingImageHandler(ImageInfo info, Rectangle rect) throws ImageException, IOException { if (!getPSUtil().isOptimizeResources() || PSImageUtils.isImageInlined(info, (PSRenderingContext)createRenderingContext())) { super.drawImageUsingImageHandler(info, rect); } else { if (log.isDebugEnabled()) { log.debug("Image " + info + " is embedded as a form later"); } //Don't load image at this time, just put a form placeholder in the stream PSResource form = documentHandler.getFormForImage(info.getOriginalURI()); PSImageUtils.drawForm(form, info, rect, getGenerator()); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
protected void saveGraphicsState() throws IOException { endTextObject(); getGenerator().saveGraphicsState(); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
protected void restoreGraphicsState() throws IOException { endTextObject(); getGenerator().restoreGraphicsState(); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
protected void beginTextObject() throws IOException { if (!inTextMode) { PSGenerator generator = getGenerator(); generator.saveGraphicsState(); generator.writeln("BT"); inTextMode = true; } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
protected void endTextObject() throws IOException { if (inTextMode) { inTextMode = false; PSGenerator generator = getGenerator(); generator.writeln("ET"); generator.restoreGraphicsState(); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
private void writeText( // CSOK: ParameterNumber String text, int start, int len, int letterSpacing, int wordSpacing, int[][] dp, Font font, Typeface tf) throws IOException { PSGenerator generator = getGenerator(); int end = start + len; int initialSize = len; initialSize += initialSize / 2; boolean hasLetterSpacing = (letterSpacing != 0); boolean needTJ = false; int lineStart = 0; StringBuffer accText = new StringBuffer(initialSize); StringBuffer sb = new StringBuffer(initialSize); int[] dx = IFUtil.convertDPToDX ( dp ); int dxl = (dx != null ? dx.length : 0); for (int i = start; i < end; i++) { char orgChar = text.charAt(i); char ch; int cw; int glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { //Fixed width space are rendered as spaces so copy/paste works in a reader ch = font.mapChar(CharUtilities.SPACE); cw = font.getCharWidth(orgChar); glyphAdjust = font.getCharWidth(ch) - cw; } else { if ((wordSpacing != 0) && CharUtilities.isAdjustableSpace(orgChar)) { glyphAdjust -= wordSpacing; } ch = font.mapChar(orgChar); cw = font.getCharWidth(orgChar); } if (dx != null && i < dxl - 1) { glyphAdjust -= dx[i + 1]; } char codepoint = (char)(ch % 256); PSGenerator.escapeChar(codepoint, accText); //add character to accumulated text if (glyphAdjust != 0) { needTJ = true; if (sb.length() == 0) { sb.append('['); //Need to start TJ } if (accText.length() > 0) { if ((sb.length() - lineStart + accText.length()) > 200) { sb.append(PSGenerator.LF); lineStart = sb.length(); } sb.append('('); sb.append(accText); sb.append(") "); accText.setLength(0); //reset accumulated text } sb.append(Integer.toString(glyphAdjust)).append(' '); } } if (needTJ) { if (accText.length() > 0) { sb.append('('); sb.append(accText); sb.append(')'); } if (hasLetterSpacing) { sb.append("] " + formatMptAsPt(generator, letterSpacing) + " ATJ"); } else { sb.append("] TJ"); } } else { sb.append('(').append(accText).append(")"); if (hasLetterSpacing) { StringBuffer spb = new StringBuffer(); spb.append(formatMptAsPt(generator, letterSpacing)) .append(" 0 "); sb.insert(0, spb.toString()); sb.append(" " + generator.mapCommand("ashow")); } else { sb.append(" " + generator.mapCommand("show")); } } generator.writeln(sb.toString()); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
private void useFont(String key, int size) throws IOException { PSResource res = this.documentHandler.getPSResourceForFontKey(key); PSGenerator generator = getGenerator(); generator.useFont("/" + res.getName(), size / 1000f); generator.getResourceTracker().notifyResourceUsageOnPage(res); }
// in src/java/org/apache/fop/render/ps/PSImageUtils.java
public static void drawForm(PSResource form, ImageInfo info, Rectangle rect, PSGenerator generator) throws IOException { Rectangle2D targetRect = new Rectangle2D.Double( rect.getMinX() / 1000.0, rect.getMinY() / 1000.0, rect.getWidth() / 1000.0, rect.getHeight() / 1000.0); generator.saveGraphicsState(); translateAndScale(generator, info.getSize().getDimensionPt(), targetRect); //The following %%IncludeResource marker is needed later by ResourceHandler! generator.writeDSCComment(DSCConstants.INCLUDE_RESOURCE, form); generator.getResourceTracker().notifyResourceUsageOnPage(form); generator.writeln(form.getName() + " execform"); generator.restoreGraphicsState(); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerRenderedImage.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRendered imageRend = (ImageRendered)image; float x = (float)pos.getX() / 1000f; float y = (float)pos.getY() / 1000f; float w = (float)pos.getWidth() / 1000f; float h = (float)pos.getHeight() / 1000f; RenderedImage ri = imageRend.getRenderedImage(); PSImageUtils.renderBitmapImage(ri, x, y, w, h, gen); }
// in src/java/org/apache/fop/render/ps/PSImageHandlerRenderedImage.java
public void generateForm(RenderingContext context, Image image, PSImageFormResource form) throws IOException { PSRenderingContext psContext = (PSRenderingContext)context; PSGenerator gen = psContext.getGenerator(); ImageRendered imageRend = (ImageRendered)image; ImageInfo info = image.getInfo(); String imageDescription = info.getMimeType() + " " + info.getOriginalURI(); RenderedImage ri = imageRend.getRenderedImage(); FormGenerator formGen = new ImageFormGenerator( form.getName(), imageDescription, info.getSize().getDimensionPt(), ri, false); formGen.generate(gen); }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
protected void paintTextRun(TextRun textRun, Graphics2D g2d) throws IOException { AttributedCharacterIterator runaci = textRun.getACI(); runaci.first(); TextPaintInfo tpi = (TextPaintInfo)runaci.getAttribute(PAINT_INFO); if (tpi == null || !tpi.visible) { return; } if ((tpi != null) && (tpi.composite != null)) { g2d.setComposite(tpi.composite); } //------------------------------------ TextSpanLayout layout = textRun.getLayout(); logTextRun(runaci, layout); CharSequence chars = collectCharacters(runaci); runaci.first(); //Reset ACI final PSGraphics2D ps = (PSGraphics2D)g2d; final PSGenerator gen = ps.getPSGenerator(); ps.preparePainting(); if (DEBUG) { log.debug("Text: " + chars); gen.commentln("%Text: " + chars); } GeneralPath debugShapes = null; if (DEBUG) { debugShapes = new GeneralPath(); } TextUtil textUtil = new TextUtil(gen); textUtil.setupFonts(runaci); if (!textUtil.hasFonts()) { //Draw using Java2D when no native fonts are available textRun.getLayout().draw(g2d); return; } gen.saveGraphicsState(); gen.concatMatrix(g2d.getTransform()); Shape imclip = g2d.getClip(); clip(ps, imclip); gen.writeln("BT"); //beginTextObject() AffineTransform localTransform = new AffineTransform(); Point2D prevPos = null; GVTGlyphVector gv = layout.getGlyphVector(); PSTextRun psRun = new PSTextRun(); //Used to split a text run into smaller runs for (int index = 0, c = gv.getNumGlyphs(); index < c; index++) { char ch = chars.charAt(index); boolean visibleChar = gv.isGlyphVisible(index) || (CharUtilities.isAnySpace(ch) && !CharUtilities.isZeroWidthSpace(ch)); logCharacter(ch, layout, index, visibleChar); if (!visibleChar) { continue; } Point2D glyphPos = gv.getGlyphPosition(index); AffineTransform glyphTransform = gv.getGlyphTransform(index); if (log.isTraceEnabled()) { log.trace("pos " + glyphPos + ", transform " + glyphTransform); } if (DEBUG) { Shape sh = gv.getGlyphLogicalBounds(index); if (sh == null) { sh = new Ellipse2D.Double(glyphPos.getX(), glyphPos.getY(), 2, 2); } debugShapes.append(sh, false); } //Exact position of the glyph localTransform.setToIdentity(); localTransform.translate(glyphPos.getX(), glyphPos.getY()); if (glyphTransform != null) { localTransform.concatenate(glyphTransform); } localTransform.scale(1, -1); boolean flushCurrentRun = false; //Try to optimize by combining characters using the same font and on the same line. if (glyphTransform != null) { //Happens for text-on-a-path flushCurrentRun = true; } if (psRun.getRunLength() >= 128) { //Don't let a run get too long flushCurrentRun = true; } //Note the position of the glyph relative to the previous one Point2D relPos; if (prevPos == null) { relPos = new Point2D.Double(0, 0); } else { relPos = new Point2D.Double( glyphPos.getX() - prevPos.getX(), glyphPos.getY() - prevPos.getY()); } if (psRun.vertChanges == 0 && psRun.getHorizRunLength() > 2 && relPos.getY() != 0) { //new line flushCurrentRun = true; } //Select the actual character to paint char paintChar = (CharUtilities.isAnySpace(ch) ? ' ' : ch); //Select (sub)font for character Font f = textUtil.selectFontForChar(paintChar); char mapped = f.mapChar(ch); boolean fontChanging = textUtil.isFontChanging(f, mapped); if (fontChanging) { flushCurrentRun = true; } if (flushCurrentRun) { //Paint the current run and reset for the next run psRun.paint(ps, textUtil, tpi); psRun.reset(); } //Track current run psRun.addCharacter(paintChar, relPos); psRun.noteStartingTransformation(localTransform); //Change font if necessary if (fontChanging) { textUtil.setCurrentFont(f, mapped); } //Update last position prevPos = glyphPos; } psRun.paint(ps, textUtil, tpi); gen.writeln("ET"); //endTextObject() gen.restoreGraphicsState(); if (DEBUG) { //Paint debug shapes g2d.setStroke(new BasicStroke(0)); g2d.setColor(Color.LIGHT_GRAY); g2d.draw(debugShapes); } }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
private void applyColor(Paint paint, final PSGenerator gen) throws IOException { if (paint == null) { return; } else if (paint instanceof Color) { Color col = (Color)paint; gen.useColor(col); } else { log.warn("Paint not supported: " + paint.toString()); } }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
private void clip(PSGraphics2D ps, Shape shape) throws IOException { if (shape == null) { return; } ps.getPSGenerator().writeln("newpath"); PathIterator iter = shape.getPathIterator(IDENTITY_TRANSFORM); ps.processPathIterator(iter); ps.getPSGenerator().writeln("clip"); }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
public void writeTextMatrix(AffineTransform transform) throws IOException { double[] matrix = new double[6]; transform.getMatrix(matrix); gen.writeln(gen.formatDouble5(matrix[0]) + " " + gen.formatDouble5(matrix[1]) + " " + gen.formatDouble5(matrix[2]) + " " + gen.formatDouble5(matrix[3]) + " " + gen.formatDouble5(matrix[4]) + " " + gen.formatDouble5(matrix[5]) + " Tm"); }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
public void selectFont(Font f, char mapped) throws IOException { int encoding = mapped / 256; String postfix = (encoding == 0 ? null : Integer.toString(encoding)); PSResource res = getResourceForFont(f, postfix); gen.useFont("/" + res.getName(), f.getFontSize() / 1000f); gen.getResourceTracker().notifyResourceUsageOnPage(res); }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
public void paint(PSGraphics2D g2d, TextUtil textUtil, TextPaintInfo tpi) throws IOException { if (getRunLength() > 0) { if (log.isDebugEnabled()) { log.debug("Text run: " + currentChars); } textUtil.writeTextMatrix(this.textTransform); if (isXShow()) { log.debug("Horizontal text: xshow"); paintXYShow(g2d, textUtil, tpi.fillPaint, true, false); } else if (isYShow()) { log.debug("Vertical text: yshow"); paintXYShow(g2d, textUtil, tpi.fillPaint, false, true); } else { log.debug("Arbitrary text: xyshow"); paintXYShow(g2d, textUtil, tpi.fillPaint, true, true); } boolean stroke = (tpi.strokePaint != null) && (tpi.strokeStroke != null); if (stroke) { log.debug("Stroked glyph outlines"); paintStrokedGlyphs(g2d, textUtil, tpi.strokePaint, tpi.strokeStroke); } } }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
private void paintXYShow(PSGraphics2D g2d, TextUtil textUtil, Paint paint, boolean x, boolean y) throws IOException { PSGenerator gen = textUtil.gen; char firstChar = this.currentChars.charAt(0); //Font only has to be setup up before the first character Font f = textUtil.selectFontForChar(firstChar); char mapped = f.mapChar(firstChar); textUtil.selectFont(f, mapped); textUtil.setCurrentFont(f, mapped); applyColor(paint, gen); StringBuffer sb = new StringBuffer(); sb.append('('); for (int i = 0, c = this.currentChars.length(); i < c; i++) { char ch = this.currentChars.charAt(i); mapped = f.mapChar(ch); char codepoint = (char) (mapped % 256); PSGenerator.escapeChar(codepoint, sb); } sb.append(')'); if (x || y) { sb.append("\n["); int idx = 0; Iterator iter = this.relativePositions.iterator(); while (iter.hasNext()) { Point2D pt = (Point2D)iter.next(); if (idx > 0) { if (x) { sb.append(format(gen, pt.getX())); } if (y) { if (x) { sb.append(' '); } sb.append(format(gen, -pt.getY())); } if (idx % 8 == 0) { sb.append('\n'); } else { sb.append(' '); } } idx++; } if (x) { sb.append('0'); } if (y) { if (x) { sb.append(' '); } sb.append('0'); } sb.append(']'); } sb.append(' '); if (x) { sb.append('x'); } if (y) { sb.append('y'); } sb.append("show"); // --> xshow, yshow or xyshow gen.writeln(sb.toString()); }
// in src/java/org/apache/fop/render/ps/PSTextPainter.java
private void paintStrokedGlyphs(PSGraphics2D g2d, TextUtil textUtil, Paint strokePaint, Stroke stroke) throws IOException { PSGenerator gen = textUtil.gen; applyColor(strokePaint, gen); PSGraphics2D.applyStroke(stroke, gen); Font f = null; Iterator iter = this.relativePositions.iterator(); iter.next(); Point2D pos = new Point2D.Double(0, 0); gen.writeln("0 0 M"); for (int i = 0, c = this.currentChars.length(); i < c; i++) { char ch = this.currentChars.charAt(0); if (i == 0) { //Font only has to be setup up before the first character f = textUtil.selectFontForChar(ch); } char mapped = f.mapChar(ch); if (i == 0) { textUtil.selectFont(f, mapped); textUtil.setCurrentFont(f, mapped); } mapped = f.mapChar(this.currentChars.charAt(i)); //add glyph outlines to current path char codepoint = (char)(mapped % 256); gen.write("(" + codepoint + ")"); gen.writeln(" false charpath"); if (iter.hasNext()) { //Position for the next character Point2D pt = (Point2D)iter.next(); pos.setLocation(pos.getX() + pt.getX(), pos.getY() - pt.getY()); gen.writeln(gen.formatDouble5(pos.getX()) + " " + gen.formatDouble5(pos.getY()) + " M"); } } gen.writeln("stroke"); //paints all accumulated glyph outlines }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void drawBorderLine( // CSOK: ParameterNumber int x1, int y1, int x2, int y2, boolean horz, boolean startOrBefore, int style, Color col) throws IOException { drawBorderLine(generator, toPoints(x1), toPoints(y1), toPoints(x2), toPoints(y2), horz, startOrBefore, style, col); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
private static void drawLine(PSGenerator gen, float startx, float starty, float endx, float endy) throws IOException { gen.writeln(gen.formatDouble(startx) + " " + gen.formatDouble(starty) + " " + gen.mapCommand("moveto") + " " + gen.formatDouble(endx) + " " + gen.formatDouble(endy) + " " + gen.mapCommand("lineto") + " " + gen.mapCommand("stroke") + " " + gen.mapCommand("newpath")); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
public static void drawBorderLine( // CSOK: ParameterNumber PSGenerator gen, float x1, float y1, float x2, float y2, boolean horz, // CSOK: JavadocMethod boolean startOrBefore, int style, Color col) // CSOK: JavadocMethod throws IOException { // CSOK: JavadocMethod float w = x2 - x1; float h = y2 - y1; if ((w < 0) || (h < 0)) { log.error("Negative extent received. Border won't be painted."); return; } switch (style) { case Constants.EN_DASHED: gen.useColor(col); if (horz) { float unit = Math.abs(2 * h); int rep = (int)(w / unit); if (rep % 2 == 0) { rep++; } unit = w / rep; gen.useDash("[" + unit + "] 0"); gen.useLineCap(0); gen.useLineWidth(h); float ym = y1 + (h / 2); drawLine(gen, x1, ym, x2, ym); } else { float unit = Math.abs(2 * w); int rep = (int)(h / unit); if (rep % 2 == 0) { rep++; } unit = h / rep; gen.useDash("[" + unit + "] 0"); gen.useLineCap(0); gen.useLineWidth(w); float xm = x1 + (w / 2); drawLine(gen, xm, y1, xm, y2); } break; case Constants.EN_DOTTED: gen.useColor(col); gen.useLineCap(1); //Rounded! if (horz) { float unit = Math.abs(2 * h); int rep = (int)(w / unit); if (rep % 2 == 0) { rep++; } unit = w / rep; gen.useDash("[0 " + unit + "] 0"); gen.useLineWidth(h); float ym = y1 + (h / 2); drawLine(gen, x1, ym, x2, ym); } else { float unit = Math.abs(2 * w); int rep = (int)(h / unit); if (rep % 2 == 0) { rep++; } unit = h / rep; gen.useDash("[0 " + unit + "] 0"); gen.useLineWidth(w); float xm = x1 + (w / 2); drawLine(gen, xm, y1, xm, y2); } break; case Constants.EN_DOUBLE: gen.useColor(col); gen.useDash(null); if (horz) { float h3 = h / 3; gen.useLineWidth(h3); float ym1 = y1 + (h3 / 2); float ym2 = ym1 + h3 + h3; drawLine(gen, x1, ym1, x2, ym1); drawLine(gen, x1, ym2, x2, ym2); } else { float w3 = w / 3; gen.useLineWidth(w3); float xm1 = x1 + (w3 / 2); float xm2 = xm1 + w3 + w3; drawLine(gen, xm1, y1, xm1, y2); drawLine(gen, xm2, y1, xm2, y2); } break; case Constants.EN_GROOVE: case Constants.EN_RIDGE: float colFactor = (style == Constants.EN_GROOVE ? 0.4f : -0.4f); gen.useDash(null); if (horz) { Color uppercol = ColorUtil.lightenColor(col, -colFactor); Color lowercol = ColorUtil.lightenColor(col, colFactor); float h3 = h / 3; gen.useLineWidth(h3); float ym1 = y1 + (h3 / 2); gen.useColor(uppercol); drawLine(gen, x1, ym1, x2, ym1); gen.useColor(col); drawLine(gen, x1, ym1 + h3, x2, ym1 + h3); gen.useColor(lowercol); drawLine(gen, x1, ym1 + h3 + h3, x2, ym1 + h3 + h3); } else { Color leftcol = ColorUtil.lightenColor(col, -colFactor); Color rightcol = ColorUtil.lightenColor(col, colFactor); float w3 = w / 3; gen.useLineWidth(w3); float xm1 = x1 + (w3 / 2); gen.useColor(leftcol); drawLine(gen, xm1, y1, xm1, y2); gen.useColor(col); drawLine(gen, xm1 + w3, y1, xm1 + w3, y2); gen.useColor(rightcol); drawLine(gen, xm1 + w3 + w3, y1, xm1 + w3 + w3, y2); } break; case Constants.EN_INSET: case Constants.EN_OUTSET: colFactor = (style == Constants.EN_OUTSET ? 0.4f : -0.4f); gen.useDash(null); if (horz) { Color c = ColorUtil.lightenColor(col, (startOrBefore ? 1 : -1) * colFactor); gen.useLineWidth(h); float ym1 = y1 + (h / 2); gen.useColor(c); drawLine(gen, x1, ym1, x2, ym1); } else { Color c = ColorUtil.lightenColor(col, (startOrBefore ? 1 : -1) * colFactor); gen.useLineWidth(w); float xm1 = x1 + (w / 2); gen.useColor(c); drawLine(gen, xm1, y1, xm1, y2); } break; case Constants.EN_HIDDEN: break; default: gen.useColor(col); gen.useDash(null); gen.useLineCap(0); if (horz) { gen.useLineWidth(h); float ym = y1 + (h / 2); drawLine(gen, x1, ym, x2, ym); } else { gen.useLineWidth(w); float xm = x1 + (w / 2); drawLine(gen, xm, y1, xm, y2); } } }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IOException { if (start.y != end.y) { //TODO Support arbitrary lines if necessary throw new UnsupportedOperationException( "Can only deal with horizontal lines right now"); } saveGraphicsState(); int half = width / 2; int starty = start.y - half; //Rectangle boundingRect = new Rectangle(start.x, start.y - half, end.x - start.x, width); switch (style.getEnumValue()) { case Constants.EN_SOLID: case Constants.EN_DASHED: case Constants.EN_DOUBLE: drawBorderLine(start.x, starty, end.x, starty + width, true, true, style.getEnumValue(), color); break; case Constants.EN_DOTTED: clipRect(start.x, starty, end.x - start.x, width); //This displaces the dots to the right by half a dot's width //TODO There's room for improvement here generator.concatMatrix(1, 0, 0, 1, toPoints(half), 0); drawBorderLine(start.x, starty, end.x, starty + width, true, true, style.getEnumValue(), color); break; case Constants.EN_GROOVE: case Constants.EN_RIDGE: generator.useColor(ColorUtil.lightenColor(color, 0.6f)); moveTo(start.x, starty); lineTo(end.x, starty); lineTo(end.x, starty + 2 * half); lineTo(start.x, starty + 2 * half); closePath(); generator.write(" " + generator.mapCommand("fill")); generator.writeln(" " + generator.mapCommand("newpath")); generator.useColor(color); if (style == RuleStyle.GROOVE) { moveTo(start.x, starty); lineTo(end.x, starty); lineTo(end.x, starty + half); lineTo(start.x + half, starty + half); lineTo(start.x, starty + 2 * half); } else { moveTo(end.x, starty); lineTo(end.x, starty + 2 * half); lineTo(start.x, starty + 2 * half); lineTo(start.x, starty + half); lineTo(end.x - half, starty + half); } closePath(); generator.write(" " + generator.mapCommand("fill")); generator.writeln(" " + generator.mapCommand("newpath")); break; default: throw new UnsupportedOperationException("rule style not supported"); } restoreGraphicsState(); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void moveTo(int x, int y) throws IOException { generator.writeln(generator.formatDouble(toPoints(x)) + " " + generator.formatDouble(toPoints(y)) + " " + generator.mapCommand("moveto")); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void lineTo(int x, int y) throws IOException { generator.writeln(generator.formatDouble(toPoints(x)) + " " + generator.formatDouble(toPoints(y)) + " " + generator.mapCommand("lineto")); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void closePath() throws IOException { generator.writeln("cp"); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
private void clipRect(int x, int y, int width, int height) throws IOException { generator.defineRect(toPoints(x), toPoints(y), toPoints(width), toPoints(height)); clip(); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void clip() throws IOException { generator.writeln(generator.mapCommand("clip") + " " + generator.mapCommand("newpath")); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void saveGraphicsState() throws IOException { generator.saveGraphicsState(); }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
protected void restoreGraphicsState() throws IOException { generator.restoreGraphicsState(); }
// in src/java/org/apache/fop/render/ps/NativeTextHandler.java
public void writeSetup() throws IOException { if (fontInfo != null) { PSFontUtils.writeFontDict(getPSGenerator(), fontInfo); } }
// in src/java/org/apache/fop/render/ps/NativeTextHandler.java
public void writePageSetup() throws IOException { //nop }
// in src/java/org/apache/fop/render/ps/NativeTextHandler.java
public void drawString(String text, float x, float y) throws IOException { // TODO Remove me after removing the deprecated method in TextHandler. throw new UnsupportedOperationException("Deprecated method!"); }
// in src/java/org/apache/fop/render/ps/NativeTextHandler.java
public void drawString(Graphics2D g, String s, float x, float y) throws IOException { PSGraphics2D g2d = (PSGraphics2D)g; g2d.preparePainting(); if (this.overrideFont == null) { java.awt.Font awtFont = g2d.getFont(); this.font = createFont(awtFont); } else { this.font = this.overrideFont; this.overrideFont = null; } //Color and Font state g2d.establishColor(g2d.getColor()); establishCurrentFont(); PSGenerator gen = getPSGenerator(); gen.saveGraphicsState(); //Clip Shape imclip = g2d.getClip(); g2d.writeClip(imclip); //Prepare correct transformation AffineTransform trans = g2d.getTransform(); gen.concatMatrix(trans); gen.writeln(gen.formatDouble(x) + " " + gen.formatDouble(y) + " moveto "); gen.writeln("1 -1 scale"); StringBuffer sb = new StringBuffer("("); escapeText(s, sb); sb.append(") t "); gen.writeln(sb.toString()); gen.restoreGraphicsState(); }
// in src/java/org/apache/fop/render/ps/NativeTextHandler.java
private void establishCurrentFont() throws IOException { if ((currentFontName != this.font.getFontName()) || (currentFontSize != this.font.getFontSize())) { PSGenerator gen = getPSGenerator(); gen.writeln("/" + this.font.getFontTriplet().getName() + " " + gen.formatDouble(font.getFontSize() / 1000f) + " F"); currentFontName = this.font.getFontName(); currentFontSize = this.font.getFontSize(); } }
// in src/java/org/apache/fop/render/java2d/Java2DImageHandlerRenderedImage.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { Java2DRenderingContext java2dContext = (Java2DRenderingContext)context; ImageInfo info = image.getInfo(); ImageRendered imageRend = (ImageRendered)image; Graphics2D g2d = java2dContext.getGraphics2D(); AffineTransform at = new AffineTransform(); at.translate(pos.x, pos.y); //scaling based on layout instructions double sx = pos.getWidth() / (double)info.getSize().getWidthMpt(); double sy = pos.getHeight() / (double)info.getSize().getHeightMpt(); //scaling because of image resolution //float sourceResolution = java2dContext.getUserAgent().getSourceResolution(); //source resolution seems to be a bad idea, not sure why float sourceResolution = GraphicsConstants.DEFAULT_DPI; sourceResolution *= 1000; //we're working in the millipoint area sx *= sourceResolution / info.getSize().getDpiHorizontal(); sy *= sourceResolution / info.getSize().getDpiVertical(); at.scale(sx, sy); RenderedImage rend = imageRend.getRenderedImage(); if (imageRend.getTransparentColor() != null && !rend.getColorModel().hasAlpha()) { int transCol = imageRend.getTransparentColor().getRGB(); BufferedImage bufImage = makeTransparentImage(rend); WritableRaster alphaRaster = bufImage.getAlphaRaster(); //TODO Masked images: Does anyone know a more efficient method to do this? final int[] transparent = new int[] {0x00}; for (int y = 0, maxy = bufImage.getHeight(); y < maxy; y++) { for (int x = 0, maxx = bufImage.getWidth(); x < maxx; x++) { int col = bufImage.getRGB(x, y); if (col == transCol) { //Mask out all pixels that match the transparent color alphaRaster.setPixel(x, y, transparent); } } } g2d.drawRenderedImage(bufImage, at); } else { g2d.drawRenderedImage(rend, at); } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
private void concatenateTransformationMatrix(AffineTransform transform) throws IOException { g2dState.transform(transform); }
// in src/java/org/apache/fop/render/java2d/Java2DImageHandlerGraphics2D.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { Java2DRenderingContext java2dContext = (Java2DRenderingContext)context; ImageInfo info = image.getInfo(); ImageGraphics2D imageG2D = (ImageGraphics2D)image; Dimension dim = info.getSize().getDimensionMpt(); Graphics2D g2d = (Graphics2D)java2dContext.getGraphics2D().create(); g2d.translate(pos.x, pos.y); double sx = pos.width / dim.getWidth(); double sy = pos.height / dim.getHeight(); g2d.scale(sx, sy); Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, dim.getWidth(), dim.getHeight()); imageG2D.getGraphics2DImagePainter().paint(g2d, area); g2d.dispose(); }
// in src/java/org/apache/fop/render/java2d/Java2DGraphics2DAdapter.java
public void paintImage(Graphics2DImagePainter painter, RendererContext context, int x, int y, int width, int height) throws IOException { float fwidth = width / 1000f; float fheight = height / 1000f; float fx = x / 1000f; float fy = y / 1000f; // get the 'width' and 'height' attributes of the SVG document Dimension dim = painter.getImageSize(); float imw = (float)dim.getWidth() / 1000f; float imh = (float)dim.getHeight() / 1000f; float sx = fwidth / (float)imw; float sy = fheight / (float)imh; Java2DRenderer renderer = (Java2DRenderer)context.getRenderer(); Java2DGraphicsState state = renderer.state; //Create copy and paint on that Graphics2D g2d = (Graphics2D)state.getGraph().create(); g2d.setColor(Color.black); g2d.setBackground(Color.black); //TODO Clip to the image area. // transform so that the coordinates (0,0) is from the top left // and positive is down and to the right. (0,0) is where the // viewBox puts it. g2d.translate(fx, fy); AffineTransform at = AffineTransform.getScaleInstance(sx, sy); if (!at.isIdentity()) { g2d.transform(at); } Rectangle2D area = new Rectangle2D.Double(0.0, 0.0, imw, imh); painter.paint(g2d, area); g2d.dispose(); }
// in src/java/org/apache/fop/render/java2d/CustomFontMetricsMapper.java
private void initialize(final Source source) throws FontFormatException, IOException { int type = Font.TRUETYPE_FONT; if (FontType.TYPE1.equals(typeface.getFontType())) { type = TYPE1_FONT; //Font.TYPE1_FONT; only available in Java 1.5 } InputStream is = null; if (source instanceof StreamSource) { is = ((StreamSource) source).getInputStream(); } else if (source.getSystemId() != null) { is = new java.net.URL(source.getSystemId()).openStream(); } else { throw new IllegalArgumentException("No font source provided."); } this.font = Font.createFont(type, is); is.close(); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public void startRenderer(OutputStream out) throws IOException { super.startRenderer(out); // do nothing by default }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public void stopRenderer() throws IOException { log.debug("Java2DRenderer stopped"); renderingDone = true; int numberOfPages = currentPageNumber; // TODO set all vars to null for gc if (numberOfPages == 0) { new FOPException("No page could be rendered"); } }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public void renderPage(PageViewport pageViewport) throws IOException, FOPException { try { rememberPage((PageViewport)pageViewport.clone()); } catch (CloneNotSupportedException e) { throw new FOPException(e); } //The clone() call is necessary as we store the page for later. Otherwise, the //RenderPagesModel calls PageViewport.clear() to release memory as early as possible. currentPageNumber++; }
// in src/java/org/apache/fop/afp/apps/FontPatternExtractor.java
public void extract(File file, File targetDir) throws IOException { InputStream in = new java.io.FileInputStream(file); try { MODCAParser parser = new MODCAParser(in); ByteArrayOutputStream baout = new ByteArrayOutputStream(); UnparsedStructuredField strucField; while ((strucField = parser.readNextStructuredField()) != null) { if (strucField.getSfTypeID() == 0xD3EE89) { byte[] sfData = strucField.getData(); println(strucField.toString()); HexDump.dump(sfData, 0, printStream, 0); baout.write(sfData); } } ByteArrayInputStream bin = new ByteArrayInputStream(baout.toByteArray()); DataInputStream din = new DataInputStream(bin); long len = din.readInt() & 0xFFFFFFFFL; println("Length: " + len); din.skip(4); //checksum int tidLen = din.readUnsignedShort() - 2; byte[] tid = new byte[tidLen]; din.readFully(tid); String filename = new String(tid, "ISO-8859-1"); int asciiCount1 = countUSAsciiCharacters(filename); String filenameEBCDIC = new String(tid, "Cp1146"); int asciiCount2 = countUSAsciiCharacters(filenameEBCDIC); println("TID: " + filename + " " + filenameEBCDIC); if (asciiCount2 > asciiCount1) { //Haven't found an indicator if the name is encoded in EBCDIC or not //so we use a trick. filename = filenameEBCDIC; } if (!filename.toLowerCase().endsWith(".pfb")) { filename = filename + ".pfb"; } println("Output filename: " + filename); File out = new File(targetDir, filename); OutputStream fout = new java.io.FileOutputStream(out); try { IOUtils.copyLarge(din, fout); } finally { IOUtils.closeQuietly(fout); } } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/afp/ptoca/TextDataInfoProducer.java
public void produce(PtocaBuilder builder) throws IOException { builder.setTextOrientation(textDataInfo.getRotation()); builder.absoluteMoveBaseline(textDataInfo.getY()); builder.absoluteMoveInline(textDataInfo.getX()); builder.setVariableSpaceCharacterIncrement( textDataInfo.getVariableSpaceCharacterIncrement()); builder.setInterCharacterAdjustment( textDataInfo.getInterCharacterAdjustment()); builder.setExtendedTextColor(textDataInfo.getColor()); builder.setCodedFont((byte)textDataInfo.getFontReference()); // Add transparent data String textString = textDataInfo.getString(); String encoding = textDataInfo.getEncoding(); builder.addTransparentData(CharactersetEncoder.encodeSBCS(textString, encoding)); }
// in src/java/org/apache/fop/afp/ptoca/TransparentDataControlSequence.java
void writeTo(OutputStream outStream) throws IOException { encodedChars.writeTo(outStream, offset, length); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
private void commit(byte functionType) throws IOException { int length = baout.size() + 2; assert length < 256; OutputStream out = getOutputStreamForControlSequence(length); out.write(length); out.write(functionType); baout.writeTo(out); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void writeIntroducer() throws IOException { OutputStream out = getOutputStreamForControlSequence(ESCAPE.length); out.write(ESCAPE); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void setCodedFont(byte font) throws IOException { // Avoid unnecessary specification of the font if (currentFont == font) { return; } else { currentFont = font; } newControlSequence(); writeBytes(font); commit(chained(SCFL)); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void absoluteMoveInline(int coordinate) throws IOException { if (coordinate == this.currentX) { return; } newControlSequence(); writeShort(coordinate); commit(chained(AMI)); currentX = coordinate; }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void relativeMoveInline(int increment) throws IOException { newControlSequence(); writeShort(increment); commit(chained(RMI)); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void absoluteMoveBaseline(int coordinate) throws IOException { if (coordinate == this.currentY) { return; } newControlSequence(); writeShort(coordinate); commit(chained(AMB)); currentY = coordinate; currentX = -1; }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void addTransparentData(EncodedChars encodedChars) throws IOException { for (TransparentData trn : new TransparentDataControlSequence(encodedChars)) { newControlSequence(); trn.writeTo(baout); commit(chained(TRN)); } }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void drawBaxisRule(int length, int width) throws IOException { newControlSequence(); writeShort(length); // Rule length writeShort(width); // Rule width writeBytes(0); // Rule width fraction is always null. enough? commit(chained(DBR)); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void drawIaxisRule(int length, int width) throws IOException { newControlSequence(); writeShort(length); // Rule length writeShort(width); // Rule width writeBytes(0); // Rule width fraction is always null. enough? commit(chained(DIR)); }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void setTextOrientation(int orientation) throws IOException { if (orientation == this.currentOrientation) { return; } newControlSequence(); AxisOrientation.getRightHandedAxisOrientationFor(orientation).writeTo(baout); commit(chained(STO)); this.currentOrientation = orientation; currentX = -1; currentY = -1; }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void setExtendedTextColor(Color col) throws IOException { if (ColorUtil.isSameColor(col, currentColor)) { return; } if (col instanceof ColorWithAlternatives) { ColorWithAlternatives cwa = (ColorWithAlternatives)col; Color alt = cwa.getFirstAlternativeOfType(ColorSpace.TYPE_CMYK); if (alt != null) { col = alt; } } ColorSpace cs = col.getColorSpace(); newControlSequence(); if (col.getColorSpace().getType() == ColorSpace.TYPE_CMYK) { // Color space - 0x04 = CMYK, all else are reserved and must be zero writeBytes(0x00, 0x04, 0x00, 0x00, 0x00, 0x00); writeBytes(8, 8, 8, 8); // Number of bits in component 1, 2, 3 & 4 respectively float[] comps = col.getColorComponents(null); assert comps.length == 4; for (int i = 0; i < 4; i++) { int component = Math.round(comps[i] * 255); writeBytes(component); } } else if (cs instanceof CIELabColorSpace) { // Color space - 0x08 = CIELAB, all else are reserved and must be zero writeBytes(0x00, 0x08, 0x00, 0x00, 0x00, 0x00); writeBytes(8, 8, 8, 0); // Number of bits in component 1,2,3 & 4 //Sadly, 16 bit components don't seem to work float[] colorComponents = col.getColorComponents(null); int l = Math.round(colorComponents[0] * 255f); int a = Math.round(colorComponents[1] * 255f) - 128; int b = Math.round(colorComponents[2] * 255f) - 128; writeBytes(l, a, b); // l*, a* and b* } else { // Color space - 0x01 = RGB, all else are reserved and must be zero writeBytes(0x00, 0x01, 0x00, 0x00, 0x00, 0x00); writeBytes(8, 8, 8, 0); // Number of bits in component 1, 2, 3 & 4 respectively writeBytes(col.getRed(), col.getGreen(), col.getBlue()); // RGB intensity } commit(chained(SEC)); this.currentColor = col; }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void setVariableSpaceCharacterIncrement(int incr) throws IOException { if (incr == this.currentVariableSpaceCharacterIncrement) { return; } assert incr >= 0 && incr < (1 << 16); newControlSequence(); writeShort(Math.abs(incr)); //Increment commit(chained(SVI)); this.currentVariableSpaceCharacterIncrement = incr; }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void setInterCharacterAdjustment(int incr) throws IOException { if (incr == this.currentInterCharacterAdjustment) { return; } assert incr >= Short.MIN_VALUE && incr <= Short.MAX_VALUE; newControlSequence(); writeShort(Math.abs(incr)); //Increment writeBytes(incr >= 0 ? 0 : 1); // Direction commit(chained(SIA)); this.currentInterCharacterAdjustment = incr; }
// in src/java/org/apache/fop/afp/ptoca/PtocaBuilder.java
public void endChainedControlSequence() throws IOException { newControlSequence(); commit(NOP); }
// in src/java/org/apache/fop/afp/ptoca/LineDataInfoProducer.java
public void produce(PtocaBuilder builder) throws IOException { builder.setTextOrientation(lineDataInfo.getRotation()); int x1 = ensurePositive(lineDataInfo.getX1()); int y1 = ensurePositive(lineDataInfo.getY1()); builder.absoluteMoveBaseline(y1); builder.absoluteMoveInline(x1); builder.setExtendedTextColor(lineDataInfo.getColor()); int x2 = ensurePositive(lineDataInfo.getX2()); int y2 = ensurePositive(lineDataInfo.getY2()); int thickness = lineDataInfo.getThickness(); if (y1 == y2) { builder.drawIaxisRule(x2 - x1, thickness); } else if (x1 == x2) { builder.drawBaxisRule(y2 - y1, thickness); } else { LOG.error("Invalid axis rule: unable to draw line"); return; } }
// in src/java/org/apache/fop/afp/DataStream.java
public void endDocument() throws IOException { if (complete) { String msg = "Invalid state - document already ended."; LOG.warn("endDocument():: " + msg); throw new IllegalStateException(msg); } if (currentPageObject != null) { // End the current page if necessary endPage(); } if (currentPageGroup != null) { // End the current page group if necessary endPageGroup(); } // Write out document if (document != null) { document.endDocument(); document.writeToStream(this.outputStream); } this.outputStream.flush(); this.complete = true; this.document = null; this.outputStream = null; }
// in src/java/org/apache/fop/afp/DataStream.java
public void endOverlay() throws IOException { if (currentOverlay != null) { currentOverlay.endPage(); currentOverlay = null; currentPage = currentPageObject; } }
// in src/java/org/apache/fop/afp/DataStream.java
public void endPage() throws IOException { if (currentPageObject != null) { currentPageObject.endPage(); if (currentPageGroup != null) { currentPageGroup.addPage(currentPageObject); currentPageGroup.writeToStream(this.outputStream); } else { document.addPage(currentPageObject); document.writeToStream(this.outputStream); } currentPageObject = null; currentPage = null; } }
// in src/java/org/apache/fop/afp/DataStream.java
public void createText(final AFPTextDataInfo textDataInfo, final int letterSpacing, final int wordSpacing, final Font font, final CharacterSet charSet) throws UnsupportedEncodingException { int rotation = paintingState.getRotation(); if (rotation != 0) { textDataInfo.setRotation(rotation); Point p = getPoint(textDataInfo.getX(), textDataInfo.getY()); textDataInfo.setX(p.x); textDataInfo.setY(p.y); } // use PtocaProducer to create PTX records PtocaProducer producer = new PtocaProducer() { public void produce(PtocaBuilder builder) throws IOException { builder.setTextOrientation(textDataInfo.getRotation()); builder.absoluteMoveBaseline(textDataInfo.getY()); builder.absoluteMoveInline(textDataInfo.getX()); builder.setExtendedTextColor(textDataInfo.getColor()); builder.setCodedFont((byte)textDataInfo.getFontReference()); int l = textDataInfo.getString().length(); StringBuffer sb = new StringBuffer(); int interCharacterAdjustment = 0; AFPUnitConverter unitConv = paintingState.getUnitConverter(); if (letterSpacing != 0) { interCharacterAdjustment = Math.round(unitConv.mpt2units(letterSpacing)); } builder.setInterCharacterAdjustment(interCharacterAdjustment); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int spacing = spaceWidth + letterSpacing; int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units(spacing)); int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement; if (wordSpacing != 0) { varSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + wordSpacing + letterSpacing)); } builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement); boolean fixedSpaceMode = false; for (int i = 0; i < l; i++) { char orgChar = textDataInfo.getString().charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( fixedSpaceCharacterIncrement); fixedSpaceMode = true; sb.append(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { if (fixedSpaceMode) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( varSpaceCharacterIncrement); fixedSpaceMode = false; } char ch; if (orgChar == CharUtilities.NBSPACE) { ch = ' '; //converted to normal space to allow word spacing } else { ch = orgChar; } sb.append(ch); } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } flushText(builder, sb, charSet); } private void flushText(PtocaBuilder builder, StringBuffer sb, final CharacterSet charSet) throws IOException { if (sb.length() > 0) { builder.addTransparentData(charSet.encodeChars(sb)); sb.setLength(0); } } }; currentPage.createText(producer); }
// in src/java/org/apache/fop/afp/DataStream.java
public void produce(PtocaBuilder builder) throws IOException { builder.setTextOrientation(textDataInfo.getRotation()); builder.absoluteMoveBaseline(textDataInfo.getY()); builder.absoluteMoveInline(textDataInfo.getX()); builder.setExtendedTextColor(textDataInfo.getColor()); builder.setCodedFont((byte)textDataInfo.getFontReference()); int l = textDataInfo.getString().length(); StringBuffer sb = new StringBuffer(); int interCharacterAdjustment = 0; AFPUnitConverter unitConv = paintingState.getUnitConverter(); if (letterSpacing != 0) { interCharacterAdjustment = Math.round(unitConv.mpt2units(letterSpacing)); } builder.setInterCharacterAdjustment(interCharacterAdjustment); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int spacing = spaceWidth + letterSpacing; int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units(spacing)); int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement; if (wordSpacing != 0) { varSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + wordSpacing + letterSpacing)); } builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement); boolean fixedSpaceMode = false; for (int i = 0; i < l; i++) { char orgChar = textDataInfo.getString().charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( fixedSpaceCharacterIncrement); fixedSpaceMode = true; sb.append(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { if (fixedSpaceMode) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( varSpaceCharacterIncrement); fixedSpaceMode = false; } char ch; if (orgChar == CharUtilities.NBSPACE) { ch = ' '; //converted to normal space to allow word spacing } else { ch = orgChar; } sb.append(ch); } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } flushText(builder, sb, charSet); }
// in src/java/org/apache/fop/afp/DataStream.java
private void flushText(PtocaBuilder builder, StringBuffer sb, final CharacterSet charSet) throws IOException { if (sb.length() > 0) { builder.addTransparentData(charSet.encodeChars(sb)); sb.setLength(0); } }
// in src/java/org/apache/fop/afp/DataStream.java
public void startDocument() throws IOException { this.document = factory.createDocument(); document.writeToStream(this.outputStream); }
// in src/java/org/apache/fop/afp/DataStream.java
public void startPageGroup() throws IOException { endPageGroup(); this.currentPageGroup = factory.createPageGroup(tleSequence); }
// in src/java/org/apache/fop/afp/DataStream.java
public void endPageGroup() throws IOException { if (currentPageGroup != null) { currentPageGroup.endPageGroup(); tleSequence = currentPageGroup.getTleSequence(); document.addPageGroup(currentPageGroup); currentPageGroup = null; } document.writeToStream(outputStream); //Flush objects }
// in src/java/org/apache/fop/afp/AFPDitheredRectanglePainter.java
public void paint(PaintingInfo paintInfo) throws IOException { RectanglePaintingInfo rectanglePaintInfo = (RectanglePaintingInfo)paintInfo; if (rectanglePaintInfo.getWidth() <= 0 || rectanglePaintInfo.getHeight() <= 0) { return; } int ditherMatrix = DitherUtil.DITHER_MATRIX_8X8; Dimension ditherSize = new Dimension(ditherMatrix, ditherMatrix); //Prepare an FS10 bi-level image AFPImageObjectInfo imageObjectInfo = new AFPImageObjectInfo(); imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS10); //imageObjectInfo.setCreatePageSegment(true); imageObjectInfo.getResourceInfo().setLevel(new AFPResourceLevel(AFPResourceLevel.INLINE)); imageObjectInfo.getResourceInfo().setImageDimension(ditherSize); imageObjectInfo.setBitsPerPixel(1); imageObjectInfo.setColor(false); //Note: the following may not be supported by older implementations imageObjectInfo.setMappingOption(MappingOptionTriplet.REPLICATE_AND_TRIM); //Dither image size int resolution = paintingState.getResolution(); ImageSize ditherBitmapSize = new ImageSize( ditherSize.width, ditherSize.height, resolution); imageObjectInfo.setDataHeightRes((int)Math.round( ditherBitmapSize.getDpiHorizontal() * 10)); imageObjectInfo.setDataWidthRes((int)Math.round( ditherBitmapSize.getDpiVertical() * 10)); imageObjectInfo.setDataWidth(ditherSize.width); imageObjectInfo.setDataHeight(ditherSize.height); //Create dither image Color col = paintingState.getColor(); byte[] dither = DitherUtil.getBayerDither(ditherMatrix, col, false); imageObjectInfo.setData(dither); //Positioning int rotation = paintingState.getRotation(); AffineTransform at = paintingState.getData().getTransform(); Point2D origin = at.transform(new Point2D.Float( rectanglePaintInfo.getX() * 1000, rectanglePaintInfo.getY() * 1000), null); AFPUnitConverter unitConv = paintingState.getUnitConverter(); float width = unitConv.pt2units(rectanglePaintInfo.getWidth()); float height = unitConv.pt2units(rectanglePaintInfo.getHeight()); AFPObjectAreaInfo objectAreaInfo = new AFPObjectAreaInfo( (int) Math.round(origin.getX()), (int) Math.round(origin.getY()), Math.round(width), Math.round(height), resolution, rotation); imageObjectInfo.setObjectAreaInfo(objectAreaInfo); //Create rectangle resourceManager.createObject(imageObjectInfo); }
// in src/java/org/apache/fop/afp/parser/MODCAParser.java
public UnparsedStructuredField readNextStructuredField() throws IOException { //Find the SF delimiter do { //Exhausted streams and so no next SF // - null return represents this case // TODO should this happen? if (din.available() == 0) { return null; } } while (din.readByte() != CARRIAGE_CONTROL_CHAR); //Read introducer as byte array to preserve any data not parsed below byte[] introducerData = new byte[INTRODUCER_LENGTH]; //Length of introducer din.readFully(introducerData); Introducer introducer = new Introducer(introducerData); int dataLength = introducer.getLength() - INTRODUCER_LENGTH; //Handle optional extension byte[] extData = null; if (introducer.isExtensionPresent()) { short extLength = 0; extLength = (short)((din.readByte()) & 0xFF); if (extLength > 0) { extData = new byte[extLength - 1]; din.readFully(extData); dataLength -= extLength; } } //Read payload byte[] data = new byte[dataLength]; din.readFully(data); UnparsedStructuredField sf = new UnparsedStructuredField(introducer, data, extData); if (LOG.isTraceEnabled()) { LOG.trace(sf); } return sf; }
// in src/java/org/apache/fop/afp/parser/UnparsedStructuredField.java
public void writeTo(OutputStream out) throws IOException { out.write(introducer.introducerData); if (isSfiExtensionPresent()) { out.write(this.extData.length + 1); out.write(this.extData); } out.write(this.data); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetCharacterSet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GSCS order code BinaryUtils.convert(fontReference)[0] }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsFullArc.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); // integer portion of multiplier data[6] = BinaryUtils.convert(mh, 1)[0]; // fractional portion of multiplier data[7] = BinaryUtils.convert(mhr, 1)[0]; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsCharacterString.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); byte[] strData = getStringAsBytes(); System.arraycopy(strData, 0, data, 6, strData.length); os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetFractionalLineWidth.java
public void writeToStream(OutputStream os) throws IOException { int integral = (int) multiplier; int fractional = (int) ((multiplier - (float) integral) * 256); byte[] data = new byte[] { getOrderCode(), // GSLW order code 0x02, // two bytes next (byte) integral, // integral line with (byte) fractional // and fractional }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetLineType.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GSLW order code type // line type }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetPatternSymbol.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GSPT order code pattern }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/AbstractGraphicsCoord.java
public void writeToStream(OutputStream os) throws IOException { os.write(getData()); }
// in src/java/org/apache/fop/afp/goca/GraphicsData.java
Override public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[9]; copySF(data, SF_CLASS, Type.DATA, Category.GRAPHICS); int dataLength = getDataLength(); byte[] len = BinaryUtils.convert(dataLength, 2); data[1] = len[0]; // Length byte 1 data[2] = len[1]; // Length byte 2 if (this.segmentedData) { data[6] |= 32; //Data is segmented } os.write(data); writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetLineWidth.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GSLW order code (byte) multiplier // MH (line-width) }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetProcessColor.java
public void writeToStream(OutputStream os) throws IOException { float[] colorComponents = color.getColorComponents(null); // COLSPCE byte colspace; ColorSpace cs = color.getColorSpace(); int colSpaceType = cs.getType(); ByteArrayOutputStream baout = new ByteArrayOutputStream(); byte[] colsizes; if (colSpaceType == ColorSpace.TYPE_CMYK) { colspace = CMYK; colsizes = new byte[] {0x08, 0x08, 0x08, 0x08}; for (int i = 0; i < colorComponents.length; i++) { baout.write(Math.round(colorComponents[i] * 255)); } } else if (colSpaceType == ColorSpace.TYPE_RGB) { colspace = RGB; colsizes = new byte[] {0x08, 0x08, 0x08, 0x00}; for (int i = 0; i < colorComponents.length; i++) { baout.write(Math.round(colorComponents[i] * 255)); } } else if (cs instanceof CIELabColorSpace) { colspace = CIELAB; colsizes = new byte[] {0x08, 0x08, 0x08, 0x00}; DataOutput dout = new java.io.DataOutputStream(baout); //According to GOCA, I'd expect the multiplicator below to be 255f, not 100f //But only IBM AFP Workbench seems to support Lab colors and it requires "c * 100f" int l = Math.round(colorComponents[0] * 100f); int a = Math.round(colorComponents[1] * 255f) - 128; int b = Math.round(colorComponents[2] * 255f) - 128; dout.writeByte(l); dout.writeByte(a); dout.writeByte(b); } else { throw new IllegalStateException(); } int len = getDataLength(); byte[] data = new byte[12]; data[0] = getOrderCode(); // GSPCOL order code data[1] = (byte) (len - 2); // LEN data[2] = 0x00; // reserved; must be zero data[3] = colspace; // COLSPCE data[4] = 0x00; // reserved; must be zero data[5] = 0x00; // reserved; must be zero data[6] = 0x00; // reserved; must be zero data[7] = 0x00; // reserved; must be zero data[8] = colsizes[0]; // COLSIZE(S) data[9] = colsizes[1]; data[10] = colsizes[2]; data[11] = colsizes[3]; os.write(data); baout.writeTo(os); }
// in src/java/org/apache/fop/afp/goca/GraphicsImage.java
public void writeToStream(OutputStream os) throws IOException { byte[] xcoord = BinaryUtils.convert(x, 2); byte[] ycoord = BinaryUtils.convert(y, 2); byte[] w = BinaryUtils.convert(width, 2); byte[] h = BinaryUtils.convert(height, 2); byte[] startData = new byte[] { getOrderCode(), // GBIMG order code (byte) 0x0A, // LENGTH xcoord[0], xcoord[1], ycoord[0], ycoord[1], 0x00, // FORMAT 0x00, // RES w[0], // WIDTH w[1], // h[0], // HEIGHT h[1] // }; os.write(startData); byte[] dataHeader = new byte[] { (byte) 0x92 // GIMD }; final int lengthOffset = 1; writeChunksToStream(imageData, dataHeader, lengthOffset, MAX_DATA_LEN, os); byte[] endData = new byte[] { (byte) 0x93, // GEIMG order code 0x00 // LENGTH }; os.write(endData); }
// in src/java/org/apache/fop/afp/goca/GraphicsBox.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = (byte)0x20; // CONTROL draw control flags data[3] = 0x00; // reserved os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsAreaEnd.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GEAR order code 0x00, // LENGTH }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsChainedSegment.java
Override public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[14]; data[0] = getOrderCode(); // BEGIN_SEGMENT data[1] = 0x0C; // Length of following parameters // segment name byte[] nameBytes = getNameBytes(); System.arraycopy(nameBytes, 0, data, 2, NAME_LENGTH); data[6] = 0x00; // FLAG1 (ignored) //FLAG2 data[7] |= this.appended ? APPEND_TO_EXISING : APPEND_NEW_SEGMENT; if (this.prologPresent) { data[7] |= PROLOG; } int dataLength = super.getDataLength(); byte[] len = BinaryUtils.convert(dataLength, 2); data[8] = len[0]; // SEGL data[9] = len[1]; // P/S NAME (predecessor name) if (predecessorNameBytes != null) { System.arraycopy(predecessorNameBytes, 0, data, 10, NAME_LENGTH); } os.write(data); writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/goca/GraphicsLine.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsAreaBegin.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GBAR order code (byte)(RES1 + (drawBoundary ? BOUNDARY : NO_BOUNDARY)) }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/AbstractGraphicsDrawingOrderContainer.java
protected void writeStart(OutputStream os) throws IOException { setStarted(true); }
// in src/java/org/apache/fop/afp/goca/AbstractGraphicsDrawingOrderContainer.java
protected void writeContent(OutputStream os) throws IOException { writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/goca/GraphicsEndProlog.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { getOrderCode(), // GEPROL order code 0x00, // Reserved }; os.write(data); }
// in src/java/org/apache/fop/afp/goca/GraphicsSetMix.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { 0x0C, // GSMX order code mode // MODE (mix mode value) }; os.write(data); }
// in src/java/org/apache/fop/afp/fonts/CharactersetEncoder.java
public void writeTo(OutputStream out, int offset, int length) throws IOException { if (offset < 0 || length < 0 || offset + length > bytes.length) { throw new IllegalArgumentException(); } out.write(bytes, this.offset + offset, length); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected InputStream openInputStream(ResourceAccessor accessor, String filename, AFPEventProducer eventProducer) throws IOException { URI uri; try { uri = new URI(filename.trim()); } catch (URISyntaxException e) { throw new FileNotFoundException("Invalid filename: " + filename + " (" + e.getMessage() + ")"); } if (LOG.isDebugEnabled()) { LOG.debug("Opening " + uri); } InputStream inputStream = accessor.createInputStream(uri); return inputStream; }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
public CharacterSet buildSBCS(String characterSetName, String codePageName, String encoding, ResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException { return processFont(characterSetName, codePageName, encoding, CharacterSetType.SINGLE_BYTE, accessor, eventProducer); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
public CharacterSet buildDBCS(String characterSetName, String codePageName, String encoding, CharacterSetType charsetType, ResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException { return processFont(characterSetName, codePageName, encoding, charsetType, accessor, eventProducer); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
public CharacterSet build(String characterSetName, String codePageName, String encoding, Typeface typeface, AFPEventProducer eventProducer) throws IOException { return new FopCharacterSet(codePageName, encoding, characterSetName, typeface, eventProducer); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
private CharacterSet processFont(String characterSetName, String codePageName, String encoding, CharacterSetType charsetType, ResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException { // check for cached version of the characterset String descriptor = characterSetName + "_" + encoding + "_" + codePageName; CharacterSet characterSet = (CharacterSet) characterSetsCache.get(descriptor); if (characterSet != null) { return characterSet; } // characterset not in the cache, so recreating characterSet = new CharacterSet(codePageName, encoding, charsetType, characterSetName, accessor, eventProducer); InputStream inputStream = null; try { /** * Get the code page which contains the character mapping * information to map the unicode character id to the graphic * chracter global identifier. */ Map<String, String> codePage; synchronized (codePagesCache) { codePage = codePagesCache.get(codePageName); if (codePage == null) { codePage = loadCodePage(codePageName, encoding, accessor, eventProducer); codePagesCache.put(codePageName, codePage); } } inputStream = openInputStream(accessor, characterSetName, eventProducer); StructuredFieldReader structuredFieldReader = new StructuredFieldReader(inputStream); // Process D3A689 Font Descriptor FontDescriptor fontDescriptor = processFontDescriptor(structuredFieldReader); characterSet.setNominalVerticalSize(fontDescriptor.getNominalFontSizeInMillipoints()); // Process D3A789 Font Control FontControl fontControl = processFontControl(structuredFieldReader); if (fontControl != null) { //process D3AE89 Font Orientation CharacterSetOrientation[] characterSetOrientations = processFontOrientation(structuredFieldReader); double metricNormalizationFactor; if (fontControl.isRelative()) { metricNormalizationFactor = 1; } else { int dpi = fontControl.getDpi(); metricNormalizationFactor = 1000.0d * 72000.0d / fontDescriptor.getNominalFontSizeInMillipoints() / dpi; } //process D3AC89 Font Position processFontPosition(structuredFieldReader, characterSetOrientations, metricNormalizationFactor); //process D38C89 Font Index (per orientation) for (int i = 0; i < characterSetOrientations.length; i++) { processFontIndex(structuredFieldReader, characterSetOrientations[i], codePage, metricNormalizationFactor); characterSet.addCharacterSetOrientation(characterSetOrientations[i]); } } else { throw new IOException("Missing D3AE89 Font Control structured field."); } } finally { closeInputStream(inputStream); } characterSetsCache.put(descriptor, characterSet); return characterSet; }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected Map<String, String> loadCodePage(String codePage, String encoding, ResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException { // Create the HashMap to store code page information Map<String, String> codePages = new HashMap<String, String>(); InputStream inputStream = null; try { inputStream = openInputStream(accessor, codePage.trim(), eventProducer); StructuredFieldReader structuredFieldReader = new StructuredFieldReader(inputStream); byte[] data = structuredFieldReader.getNext(CHARACTER_TABLE_SF); int position = 0; byte[] gcgiBytes = new byte[8]; byte[] charBytes = new byte[1]; // Read data, ignoring bytes 0 - 2 for (int index = 3; index < data.length; index++) { if (position < 8) { // Build the graphic character global identifier key gcgiBytes[position] = data[index]; position++; } else if (position == 9) { position = 0; // Set the character charBytes[0] = data[index]; String gcgiString = new String(gcgiBytes, AFPConstants.EBCIDIC_ENCODING); //Use the 8-bit char index to find the Unicode character using the Java encoding //given in the configuration. If the code page and the Java encoding don't //match, a wrong Unicode character will be associated with the AFP GCGID. //Idea: we could use IBM's GCGID to Unicode map and build code pages ourselves. String charString = new String(charBytes, encoding); codePages.put(gcgiString, charString); } else { position++; } } } catch (FileNotFoundException e) { eventProducer.codePageNotFound(this, e); } finally { closeInputStream(inputStream); } return codePages; }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected static FontDescriptor processFontDescriptor( StructuredFieldReader structuredFieldReader) throws IOException { byte[] fndData = structuredFieldReader.getNext(FONT_DESCRIPTOR_SF); return new FontDescriptor(fndData); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected FontControl processFontControl(StructuredFieldReader structuredFieldReader) throws IOException { byte[] fncData = structuredFieldReader.getNext(FONT_CONTROL_SF); FontControl fontControl = null; if (fncData != null) { fontControl = new FontControl(); if (fncData[7] == (byte) 0x02) { fontControl.setRelative(true); } int metricResolution = getUBIN(fncData, 9); if (metricResolution == 1000) { //Special case: 1000 units per em (rather than dpi) fontControl.setUnitsPerEm(1000); } else { fontControl.setDpi(metricResolution / 10); } } return fontControl; }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected CharacterSetOrientation[] processFontOrientation( StructuredFieldReader structuredFieldReader) throws IOException { byte[] data = structuredFieldReader.getNext(FONT_ORIENTATION_SF); int position = 0; byte[] fnoData = new byte[26]; List<CharacterSetOrientation> orientations = new ArrayList<CharacterSetOrientation>(); // Read data, ignoring bytes 0 - 2 for (int index = 3; index < data.length; index++) { // Build the font orientation record fnoData[position] = data[index]; position++; if (position == 26) { position = 0; int orientation = determineOrientation(fnoData[2]); // Space Increment int space = ((fnoData[8] & 0xFF ) << 8) + (fnoData[9] & 0xFF); // Em-Space Increment int em = ((fnoData[14] & 0xFF ) << 8) + (fnoData[15] & 0xFF); CharacterSetOrientation cso = new CharacterSetOrientation(orientation); cso.setSpaceIncrement(space); cso.setEmSpaceIncrement(em); orientations.add(cso); } } return orientations.toArray(EMPTY_CSO_ARRAY); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected void processFontPosition(StructuredFieldReader structuredFieldReader, CharacterSetOrientation[] characterSetOrientations, double metricNormalizationFactor) throws IOException { byte[] data = structuredFieldReader.getNext(FONT_POSITION_SF); int position = 0; byte[] fpData = new byte[26]; int characterSetOrientationIndex = 0; // Read data, ignoring bytes 0 - 2 for (int index = 3; index < data.length; index++) { if (position < 22) { // Build the font orientation record fpData[position] = data[index]; if (position == 9) { CharacterSetOrientation characterSetOrientation = characterSetOrientations[characterSetOrientationIndex]; int xHeight = getSBIN(fpData, 2); int capHeight = getSBIN(fpData, 4); int ascHeight = getSBIN(fpData, 6); int dscHeight = getSBIN(fpData, 8); dscHeight = dscHeight * -1; characterSetOrientation.setXHeight( (int)Math.round(xHeight * metricNormalizationFactor)); characterSetOrientation.setCapHeight( (int)Math.round(capHeight * metricNormalizationFactor)); characterSetOrientation.setAscender( (int)Math.round(ascHeight * metricNormalizationFactor)); characterSetOrientation.setDescender( (int)Math.round(dscHeight * metricNormalizationFactor)); } } else if (position == 22) { position = 0; characterSetOrientationIndex++; fpData[position] = data[index]; } position++; } }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected void processFontIndex(StructuredFieldReader structuredFieldReader, CharacterSetOrientation cso, Map<String, String> codepage, double metricNormalizationFactor) throws IOException { byte[] data = structuredFieldReader.getNext(FONT_INDEX_SF); int position = 0; byte[] gcgid = new byte[8]; byte[] fiData = new byte[20]; char lowest = 255; char highest = 0; String firstABCMismatch = null; // Read data, ignoring bytes 0 - 2 for (int index = 3; index < data.length; index++) { if (position < 8) { gcgid[position] = data[index]; position++; } else if (position < 27) { fiData[position - 8] = data[index]; position++; } else if (position == 27) { fiData[position - 8] = data[index]; position = 0; String gcgiString = new String(gcgid, AFPConstants.EBCIDIC_ENCODING); String idx = codepage.get(gcgiString); if (idx != null) { char cidx = idx.charAt(0); int width = getUBIN(fiData, 0); int a = getSBIN(fiData, 10); int b = getUBIN(fiData, 12); int c = getSBIN(fiData, 14); int abc = a + b + c; int diff = Math.abs(abc - width); if (diff != 0 && width != 0) { double diffPercent = 100 * diff / (double)width; if (diffPercent > 2) { if (LOG.isTraceEnabled()) { LOG.trace(gcgiString + ": " + a + " + " + b + " + " + c + " = " + (a + b + c) + " but found: " + width); } if (firstABCMismatch == null) { firstABCMismatch = gcgiString; } } } if (cidx < lowest) { lowest = cidx; } if (cidx > highest) { highest = cidx; } int normalizedWidth = (int)Math.round(width * metricNormalizationFactor); cso.setWidth(cidx, normalizedWidth); } } } cso.setFirstChar(lowest); cso.setLastChar(highest); if (LOG.isDebugEnabled() && firstABCMismatch != null) { //Debug level because it usually is no problem. LOG.debug("Font has metrics inconsitencies where A+B+C doesn't equal the" + " character increment. The first such character found: " + firstABCMismatch); } }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
protected Map<String, String> loadCodePage(String codePage, String encoding, ResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException { // Create the HashMap to store code page information Map<String, String> codePages = new HashMap<String, String>(); InputStream inputStream = null; try { inputStream = openInputStream(accessor, codePage.trim(), eventProducer); StructuredFieldReader structuredFieldReader = new StructuredFieldReader(inputStream); byte[] data; while ((data = structuredFieldReader.getNext(CHARACTER_TABLE_SF)) != null) { int position = 0; byte[] gcgiBytes = new byte[8]; byte[] charBytes = new byte[2]; // Read data, ignoring bytes 0 - 2 for (int index = 3; index < data.length; index++) { if (position < 8) { // Build the graphic character global identifier key gcgiBytes[position] = data[index]; position++; } else if (position == 9) { // Set the character charBytes[0] = data[index]; position++; } else if (position == 10) { position = 0; // Set the character charBytes[1] = data[index]; String gcgiString = new String(gcgiBytes, AFPConstants.EBCIDIC_ENCODING); String charString = new String(charBytes, encoding); codePages.put(gcgiString, charString); } else { position++; } } } } catch (FileNotFoundException e) { eventProducer.codePageNotFound(this, e); } finally { closeInputStream(inputStream); } return codePages; }
// in src/java/org/apache/fop/afp/AFPStreamer.java
public DataStream createDataStream(AFPPaintingState paintingState) throws IOException { this.tempFile = File.createTempFile(AFPDATASTREAM_TEMP_FILE_PREFIX, null); this.documentFile = new RandomAccessFile(tempFile, "rw"); this.documentOutputStream = new BufferedOutputStream( new FileOutputStream(documentFile.getFD())); this.dataStream = factory.createDataStream(paintingState, documentOutputStream); return dataStream; }
// in src/java/org/apache/fop/afp/AFPStreamer.java
public void close() throws IOException { Iterator it = pathResourceGroupMap.values().iterator(); while (it.hasNext()) { StreamedResourceGroup resourceGroup = (StreamedResourceGroup)it.next(); resourceGroup.close(); } // close any open print-file resource group if (printFileResourceGroup != null) { printFileResourceGroup.close(); } // write out document writeToStream(outputStream); outputStream.close(); if (documentOutputStream != null) { documentOutputStream.close(); } if (documentFile != null) { documentFile.close(); } // delete temporary file tempFile.delete(); }
// in src/java/org/apache/fop/afp/AFPStreamer.java
public void writeToStream(OutputStream os) throws IOException { // long start = System.currentTimeMillis(); int len = (int)documentFile.length(); int numChunks = len / BUFFER_SIZE; int remainingChunkSize = len % BUFFER_SIZE; byte[] buffer; documentFile.seek(0); if (numChunks > 0) { buffer = new byte[BUFFER_SIZE]; for (int i = 0; i < numChunks; i++) { documentFile.read(buffer, 0, BUFFER_SIZE); os.write(buffer, 0, BUFFER_SIZE); } } else { buffer = new byte[remainingChunkSize]; } if (remainingChunkSize > 0) { documentFile.read(buffer, 0, remainingChunkSize); os.write(buffer, 0, remainingChunkSize); } os.flush(); // long end = System.currentTimeMillis(); // log.debug("writing time " + (end - start) + "ms"); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public DataStream createDataStream(AFPPaintingState paintingState, OutputStream outputStream) throws IOException { this.dataStream = streamer.createDataStream(paintingState); streamer.setOutputStream(outputStream); return this.dataStream; }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void writeToStream() throws IOException { streamer.close(); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public boolean tryIncludeObject(AFPDataObjectInfo dataObjectInfo) throws IOException { AFPResourceInfo resourceInfo = dataObjectInfo.getResourceInfo(); updateResourceInfoUri(resourceInfo); String objectName = includeNameMap.get(resourceInfo); if (objectName != null) { // an existing data resource so reference it by adding an include to the current page includeObject(dataObjectInfo, objectName); return true; } objectName = pageSegmentMap.get(resourceInfo); if (objectName != null) { // an existing data resource so reference it by adding an include to the current page includePageSegment(dataObjectInfo, objectName); return true; } return false; }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void createObject(AFPDataObjectInfo dataObjectInfo) throws IOException { if (tryIncludeObject(dataObjectInfo)) { //Object has already been produced and is available by inclusion, so return early. return; } AbstractNamedAFPObject namedObj = null; AFPResourceInfo resourceInfo = dataObjectInfo.getResourceInfo(); boolean useInclude = true; Registry.ObjectType objectType = null; // new resource so create if (dataObjectInfo instanceof AFPImageObjectInfo) { AFPImageObjectInfo imageObjectInfo = (AFPImageObjectInfo)dataObjectInfo; namedObj = dataObjectFactory.createImage(imageObjectInfo); } else if (dataObjectInfo instanceof AFPGraphicsObjectInfo) { AFPGraphicsObjectInfo graphicsObjectInfo = (AFPGraphicsObjectInfo)dataObjectInfo; namedObj = dataObjectFactory.createGraphic(graphicsObjectInfo); } else { // natively embedded data object namedObj = dataObjectFactory.createObjectContainer(dataObjectInfo); objectType = dataObjectInfo.getObjectType(); useInclude = objectType != null && objectType.isIncludable(); } AFPResourceLevel resourceLevel = resourceInfo.getLevel(); ResourceGroup resourceGroup = streamer.getResourceGroup(resourceLevel); useInclude &= resourceGroup != null; if (useInclude) { boolean usePageSegment = dataObjectInfo.isCreatePageSegment(); // if it is to reside within a resource group at print-file or external level if (resourceLevel.isPrintFile() || resourceLevel.isExternal()) { if (usePageSegment) { String pageSegmentName = "S10" + namedObj.getName().substring(3); namedObj.setName(pageSegmentName); PageSegment seg = new PageSegment(pageSegmentName); seg.addObject(namedObj); namedObj = seg; } // wrap newly created data object in a resource object namedObj = dataObjectFactory.createResource(namedObj, resourceInfo, objectType); } // add data object into its resource group destination resourceGroup.addObject(namedObj); // create the include object String objectName = namedObj.getName(); if (usePageSegment) { includePageSegment(dataObjectInfo, objectName); pageSegmentMap.put(resourceInfo, objectName); } else { includeObject(dataObjectInfo, objectName); // record mapping of resource info to data object resource name includeNameMap.put(resourceInfo, objectName); } } else { // not to be included so inline data object directly into the current page dataStream.getCurrentPage().addObject(namedObj); } }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void embedFont(AFPFont afpFont, CharacterSet charSet) throws IOException { if (afpFont.isEmbeddable()) { //Embed fonts (char sets and code pages) if (charSet.getResourceAccessor() != null) { ResourceAccessor accessor = charSet.getResourceAccessor(); createIncludedResource( charSet.getName(), accessor, ResourceObject.TYPE_FONT_CHARACTER_SET); createIncludedResource( charSet.getCodePage(), accessor, ResourceObject.TYPE_CODE_PAGE); } } }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void createIncludedResource(String resourceName, ResourceAccessor accessor, byte resourceObjectType) throws IOException { URI uri; try { uri = new URI(resourceName.trim()); } catch (URISyntaxException e) { throw new IOException("Could not create URI from resource name: " + resourceName + " (" + e.getMessage() + ")"); } createIncludedResource(resourceName, uri, accessor, resourceObjectType); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void createIncludedResource(String resourceName, URI uri, ResourceAccessor accessor, byte resourceObjectType) throws IOException { AFPResourceLevel resourceLevel = new AFPResourceLevel(AFPResourceLevel.PRINT_FILE); AFPResourceInfo resourceInfo = new AFPResourceInfo(); resourceInfo.setLevel(resourceLevel); resourceInfo.setName(resourceName); resourceInfo.setUri(uri.toASCIIString()); String objectName = includeNameMap.get(resourceInfo); if (objectName == null) { if (log.isDebugEnabled()) { log.debug("Adding included resource: " + resourceName); } IncludedResourceObject resourceContent = new IncludedResourceObject( resourceName, accessor, uri); ResourceObject resourceObject = factory.createResource(resourceName); resourceObject.setDataObject(resourceContent); resourceObject.setType(resourceObjectType); ResourceGroup resourceGroup = streamer.getResourceGroup(resourceLevel); resourceGroup.addObject(resourceObject); // record mapping of resource info to data object resource name includeNameMap.put(resourceInfo, resourceName); } else { //skip, already created } }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
public void createIncludedResourceFromExternal(final String resourceName, final URI uri, final ResourceAccessor accessor) throws IOException { AFPResourceLevel resourceLevel = new AFPResourceLevel(AFPResourceLevel.PRINT_FILE); AFPResourceInfo resourceInfo = new AFPResourceInfo(); resourceInfo.setLevel(resourceLevel); resourceInfo.setName(resourceName); resourceInfo.setUri(uri.toASCIIString()); String resource = includeNameMap.get(resourceInfo); if (resource == null) { ResourceGroup resourceGroup = streamer.getResourceGroup(resourceLevel); //resourceObject delegates write commands to copyNamedResource() //The included resource may already be wrapped in a resource object AbstractNamedAFPObject resourceObject = new AbstractNamedAFPObject(null) { @Override protected void writeContent(OutputStream os) throws IOException { InputStream inputStream = null; try { inputStream = accessor.createInputStream(uri); BufferedInputStream bin = new BufferedInputStream(inputStream); AFPResourceUtil.copyNamedResource(resourceName, bin, os); } finally { IOUtils.closeQuietly(inputStream); } } //bypass super.writeStart @Override protected void writeStart(OutputStream os) throws IOException { } //bypass super.writeEnd @Override protected void writeEnd(OutputStream os) throws IOException { } }; resourceGroup.addObject(resourceObject); includeNameMap.put(resourceInfo, resourceName); } }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
Override protected void writeContent(OutputStream os) throws IOException { InputStream inputStream = null; try { inputStream = accessor.createInputStream(uri); BufferedInputStream bin = new BufferedInputStream(inputStream); AFPResourceUtil.copyNamedResource(resourceName, bin, os); } finally { IOUtils.closeQuietly(inputStream); } }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
Override protected void writeStart(OutputStream os) throws IOException { }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
Override protected void writeEnd(OutputStream os) throws IOException { }
// in src/java/org/apache/fop/afp/modca/MapImageObject.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[11]; copySF(data, Type.MAP, Category.IMAGE); int tripletLen = getTripletDataLength(); byte[] len = BinaryUtils.convert(10 + tripletLen, 2); data[1] = len[0]; data[2] = len[1]; len = BinaryUtils.convert(2 + tripletLen, 2); data[9] = len[0]; data[10] = len[1]; os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/MapPageSegment.java
public void writeToStream(OutputStream os) throws IOException { int count = getPageSegments().size(); byte groupLength = 0x0C; int groupsLength = count * groupLength; byte[] data = new byte[groupsLength + 12 + 1]; data[0] = 0x5A; // Set the total record length byte[] rl1 = BinaryUtils.convert(data.length - 1, 2); //Ignore the // first byte in // the length data[1] = rl1[0]; data[2] = rl1[1]; // Structured field ID for a MPS data[3] = (byte) 0xD3; data[4] = Type.MIGRATION; data[5] = Category.PAGE_SEGMENT; data[6] = 0x00; // Flags data[7] = 0x00; // Reserved data[8] = 0x00; // Reserved data[9] = groupLength; data[10] = 0x00; // Reserved data[11] = 0x00; // Reserved data[12] = 0x00; // Reserved int pos = 13; Iterator iter = this.pageSegments.iterator(); while (iter.hasNext()) { pos += 4; String name = (String)iter.next(); try { byte[] nameBytes = name.getBytes(AFPConstants.EBCIDIC_ENCODING); System.arraycopy(nameBytes, 0, data, pos, nameBytes.length); } catch (UnsupportedEncodingException usee) { LOG.error("UnsupportedEncodingException translating the name " + name); } pos += 8; } os.write(data); }
// in src/java/org/apache/fop/afp/modca/InvokeMediumMap.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.MAP, Category.MEDIUM_MAP); // Set the total record length byte[] len = BinaryUtils.convert(16, 2); //Ignore first byte data[1] = len[0]; data[2] = len[1]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/StreamedResourceGroup.java
public void addObject(AbstractNamedAFPObject namedObject) throws IOException { if (!started) { writeStart(os); started = true; } try { namedObject.writeToStream(os); } finally { os.flush(); } }
// in src/java/org/apache/fop/afp/modca/StreamedResourceGroup.java
public void close() throws IOException { writeEnd(os); complete = true; }
// in src/java/org/apache/fop/afp/modca/GraphicsObject.java
Override protected void writeStart(OutputStream os) throws IOException { super.writeStart(os); byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.GRAPHICS); os.write(data); }
// in src/java/org/apache/fop/afp/modca/GraphicsObject.java
Override protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/modca/GraphicsObject.java
Override protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.GRAPHICS); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PreprocessPresentationObject.java
public void writeStart(OutputStream os) throws IOException { super.writeStart(os); byte[] data = new byte[9]; copySF(data, Type.PROCESS, Category.DATA_RESOURCE); byte[] l = BinaryUtils.convert(19 + getTripletDataLength(), 2); data[1] = l[0]; // Length byte 1 data[2] = l[1]; // Length byte 1 os.write(data); }
// in src/java/org/apache/fop/afp/modca/PreprocessPresentationObject.java
public void writeContent(OutputStream os) throws IOException { byte[] data = new byte[12]; byte[] l = BinaryUtils.convert(12 + getTripletDataLength(), 2); data[0] = l[0]; // RGLength data[1] = l[1]; // RGLength data[2] = objType; // ObjType data[3] = 0x00; // Reserved data[4] = 0x00; // Reserved data[5] = objOrent; // ObjOrent if (objXOffset > 0) { byte[] xOff = BinaryUtils.convert(objYOffset, 3); data[6] = xOff[0]; // XocaOset (not specified) data[7] = xOff[1]; // XocaOset data[8] = xOff[2]; // XocaOset } else { data[6] = (byte)0xFF; // XocaOset (not specified) data[7] = (byte)0xFF; // XocaOset data[8] = (byte)0xFF; // XocaOset } if (objYOffset > 0) { byte[] yOff = BinaryUtils.convert(objYOffset, 3); data[9] = yOff[0]; // YocaOset (not specified) data[10] = yOff[1]; // YocaOset data[11] = yOff[2]; // YocaOset } else { data[9] = (byte)0xFF; // YocaOset (not specified) data[10] = (byte)0xFF; // YocaOset data[11] = (byte)0xFF; // YocaOset } os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/ResourceObject.java
protected void writeStart(OutputStream os) throws IOException { super.writeStart(os); byte[] data = new byte[19]; copySF(data, Type.BEGIN, Category.NAME_RESOURCE); // Set the total record length int tripletDataLength = getTripletDataLength(); byte[] len = BinaryUtils.convert(18 + tripletDataLength, 2); data[1] = len[0]; // Length byte 1 data[2] = len[1]; // Length byte 2 // Set reserved bits data[17] = 0x00; // Reserved data[18] = 0x00; // Reserved os.write(data); // Write triplets writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/ResourceObject.java
protected void writeContent(OutputStream os) throws IOException { if (namedObject != null) { namedObject.writeToStream(os); } }
// in src/java/org/apache/fop/afp/modca/ResourceObject.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.NAME_RESOURCE); os.write(data); }
// in src/java/org/apache/fop/afp/modca/IMImageObject.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); if (imageOutputControl != null) { imageOutputControl.writeToStream(os); } if (imageInputDescriptor != null) { imageInputDescriptor.writeToStream(os); } if (imageCellPosition != null) { imageCellPosition.writeToStream(os); } if (imageRasterData != null) { imageRasterData.writeToStream(os); } }
// in src/java/org/apache/fop/afp/modca/IMImageObject.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.IM_IMAGE); os.write(data); }
// in src/java/org/apache/fop/afp/modca/IMImageObject.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.IM_IMAGE); os.write(data); }
// in src/java/org/apache/fop/afp/modca/IncludePageSegment.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[23]; //(9 +14) copySF(data, Type.INCLUDE, Category.PAGE_SEGMENT); // Set the total record length byte[] len = BinaryUtils.convert(22, 2); //Ignore first byte data[1] = len[0]; data[2] = len[1]; byte[] xPos = BinaryUtils.convert(x, 3); data[17] = xPos[0]; // x coordinate data[18] = xPos[1]; data[19] = xPos[2]; byte[] yPos = BinaryUtils.convert(y, 3); data[20] = yPos[0]; // y coordinate data[21] = yPos[1]; data[22] = yPos[2]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/MapContainerData.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[11]; copySF(data, Type.MAP, Category.OBJECT_CONTAINER); int tripletLen = getTripletDataLength(); byte[] len = BinaryUtils.convert(10 + tripletLen, 2); data[1] = len[0]; data[2] = len[1]; len = BinaryUtils.convert(2 + tripletLen, 2); data[9] = len[0]; data[10] = len[1]; os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/TagLogicalElement.java
public void writeToStream(OutputStream os) throws IOException { setFullyQualifiedName( FullyQualifiedNameTriplet.TYPE_ATTRIBUTE_GID, FullyQualifiedNameTriplet.FORMAT_CHARSTR, name); setAttributeValue(value); setAttributeQualifier(tleID, 1); byte[] data = new byte[SF_HEADER_LENGTH]; copySF(data, Type.ATTRIBUTE, Category.PROCESS_ELEMENT); int tripletDataLength = getTripletDataLength(); byte[] l = BinaryUtils.convert(data.length + tripletDataLength - 1, 2); data[1] = l[0]; data[2] = l[1]; os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/PresentationEnvironmentControl.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[11]; copySF(data, Type.CONTROL, Category.DOCUMENT); int tripletDataLen = getTripletDataLength(); byte[] len = BinaryUtils.convert(10 + tripletDataLen); data[1] = len[0]; data[2] = len[1]; data[9] = 0x00; // Reserved; must be zero data[10] = 0x00; // Reserved; must be zero os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/ResourceGroup.java
public void addObject(AbstractNamedAFPObject namedObject) throws IOException { resourceSet.add(namedObject); }
// in src/java/org/apache/fop/afp/modca/ResourceGroup.java
public void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.RESOURCE_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ResourceGroup.java
public void writeContent(OutputStream os) throws IOException { Iterator it = resourceSet.iterator(); while (it.hasNext()) { Object object = it.next(); if (object instanceof Streamable) { Streamable streamableObject = (Streamable)object; streamableObject.writeToStream(os); } } }
// in src/java/org/apache/fop/afp/modca/ResourceGroup.java
public void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.RESOURCE_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.PRESENTATION_TEXT); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
protected void writeContent(OutputStream os) throws IOException { writeObjects(this.presentationTextDataList, os); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.PRESENTATION_TEXT); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ObjectEnvironmentGroup.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.OBJECT_ENVIRONMENT_GROUP); int tripletDataLength = getTripletDataLength(); int sfLen = data.length + tripletDataLength - 1; byte[] len = BinaryUtils.convert(sfLen, 2); data[1] = len[0]; data[2] = len[1]; os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/ObjectEnvironmentGroup.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); if (presentationEnvironmentControl != null) { presentationEnvironmentControl.writeToStream(os); } if (objectAreaDescriptor != null) { objectAreaDescriptor.writeToStream(os); } if (objectAreaPosition != null) { objectAreaPosition.writeToStream(os); } if (mapImageObject != null) { mapImageObject.writeToStream(os); } if (mapContainerData != null) { mapContainerData.writeToStream(os); } if (mapDataResource != null) { mapDataResource.writeToStream(os); } if (dataDescriptor != null) { dataDescriptor.writeToStream(os); } }
// in src/java/org/apache/fop/afp/modca/ObjectEnvironmentGroup.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.OBJECT_ENVIRONMENT_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/IncludeObject.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[36]; super.copySF(data, Type.INCLUDE, Category.DATA_RESOURCE); // Set the total record length int tripletDataLength = getTripletDataLength(); byte[] len = BinaryUtils.convert(35 + tripletDataLength, 2); //Ignore first byte data[1] = len[0]; data[2] = len[1]; data[17] = 0x00; // reserved data[18] = objectType; writeOsetTo(data, 19, xoaOset); writeOsetTo(data, 22, yoaOset); oaOrent.writeTo(data, 25); writeOsetTo(data, 29, xocaOset); writeOsetTo(data, 32, yocaOset); // RefCSys (Reference coordinate system) data[35] = 0x01; // Page or overlay coordinate system // Write structured field data os.write(data); // Write triplet for FQN internal/external object reference writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/ImageObject.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.IMAGE); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ImageObject.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); if (imageSegment != null) { final byte[] dataHeader = new byte[9]; copySF(dataHeader, SF_CLASS, Type.DATA, Category.IMAGE); final int lengthOffset = 1; // TODO save memory! ByteArrayOutputStream baos = new ByteArrayOutputStream(); imageSegment.writeToStream(baos); byte[] data = baos.toByteArray(); writeChunksToStream(data, dataHeader, lengthOffset, MAX_DATA_LEN, os); } }
// in src/java/org/apache/fop/afp/modca/ImageObject.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.IMAGE); os.write(data); }
// in src/java/org/apache/fop/afp/modca/GraphicsDataDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] headerData = new byte[9]; copySF(headerData, Type.DESCRIPTOR, Category.GRAPHICS); byte[] drawingOrderSubsetData = getDrawingOrderSubset(); byte[] windowSpecificationData = getWindowSpecification(); byte[] len = BinaryUtils.convert(headerData.length + drawingOrderSubsetData.length + windowSpecificationData.length - 1, 2); headerData[1] = len[0]; headerData[2] = len[1]; os.write(headerData); os.write(drawingOrderSubsetData); os.write(windowSpecificationData); }
// in src/java/org/apache/fop/afp/modca/ObjectAreaDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[9]; copySF(data, Type.DESCRIPTOR, Category.OBJECT_AREA); addTriplet(new DescriptorPositionTriplet(OBJECT_AREA_POSITION_ID)); addTriplet(new MeasurementUnitsTriplet(widthRes, heightRes)); addTriplet(new ObjectAreaSizeTriplet(width, height)); /* not allowed in Presentation Interchange Set 1 addTriplet(new PresentationSpaceResetMixingTriplet( PresentationSpaceResetMixingTriplet.NOT_RESET)); */ int tripletDataLength = getTripletDataLength(); byte[] len = BinaryUtils.convert(data.length + tripletDataLength - 1, 2); data[1] = len[0]; // Length data[2] = len[1]; os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/ImageDataDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[22]; copySF(data, Type.DESCRIPTOR, Category.IMAGE); // SF length byte[] len = BinaryUtils.convert(data.length - 1, 2); data[1] = len[0]; data[2] = len[1]; byte[] x = BinaryUtils.convert(widthRes, 2); data[10] = x[0]; data[11] = x[1]; byte[] y = BinaryUtils.convert(heightRes, 2); data[12] = y[0]; data[13] = y[1]; byte[] w = BinaryUtils.convert(width, 2); data[14] = w[0]; data[15] = w[1]; byte[] h = BinaryUtils.convert(height, 2); data[16] = h[0]; data[17] = h[1]; //IOCA Function Set Field data[18] = (byte)0xF7; // ID = Set IOCA Function Set data[19] = 0x02; // Length data[20] = 0x01; // Category = Function set identifier data[21] = functionSet; os.write(data); }
// in src/java/org/apache/fop/afp/modca/ResourceEnvironmentGroup.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.RESOURCE_ENVIROMENT_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ResourceEnvironmentGroup.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.RESOURCE_ENVIROMENT_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ResourceEnvironmentGroup.java
protected void writeContent(OutputStream os) throws IOException { writeObjects(mapDataResources, os); writeObjects(mapPageOverlays, os); writeObjects(preProcessPresentationObjects, os); }
// in src/java/org/apache/fop/afp/modca/AbstractResourceEnvironmentGroupContainer.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); if (resourceEnvironmentGroup != null) { resourceEnvironmentGroup.writeToStream(os); } }
// in src/java/org/apache/fop/afp/modca/AxisOrientation.java
public void writeTo(OutputStream stream) throws IOException { byte[] data = new byte[4]; writeTo(data, 0); stream.write(data); }
// in src/java/org/apache/fop/afp/modca/Document.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.DOCUMENT); os.write(data); }
// in src/java/org/apache/fop/afp/modca/Document.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.DOCUMENT); os.write(data); }
// in src/java/org/apache/fop/afp/modca/AbstractResourceGroupContainer.java
Override public void writeToStream(OutputStream os) throws IOException { if (!started) { writeStart(os); started = true; } writeContent(os); if (complete) { writeEnd(os); } }
// in src/java/org/apache/fop/afp/modca/AbstractResourceGroupContainer.java
Override protected void writeObjects(Collection/*<AbstractAFPObject>*/ objects, OutputStream os) throws IOException { writeObjects(objects, os, false); }
// in src/java/org/apache/fop/afp/modca/AbstractResourceGroupContainer.java
protected void writeObjects(Collection/*<AbstractAFPObject>*/ objects, OutputStream os, boolean forceWrite) throws IOException { if (objects != null && objects.size() > 0) { Iterator it = objects.iterator(); while (it.hasNext()) { AbstractAFPObject ao = (AbstractAFPObject)it.next(); if (forceWrite || canWrite(ao)) { ao.writeToStream(os); it.remove(); } else { break; } } } }
// in src/java/org/apache/fop/afp/modca/ContainerDataDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[21]; copySF(data, Type.DESCRIPTOR, Category.OBJECT_CONTAINER); // SF length byte[] len = BinaryUtils.convert(data.length - 1, 2); data[1] = len[0]; data[2] = len[1]; // XocBase = 10 inches data[9] = 0x00; // YocBase = 10 inches data[10] = 0x00; // XocUnits byte[] xdpi = BinaryUtils.convert(widthRes * 10, 2); data[11] = xdpi[0]; data[12] = xdpi[1]; // YocUnits byte[] ydpi = BinaryUtils.convert(heightRes * 10, 2); data[13] = ydpi[0]; data[14] = ydpi[1]; // XocSize byte[] xsize = BinaryUtils.convert(width, 3); data[15] = xsize[0]; data[16] = xsize[1]; data[17] = xsize[2]; // YocSize byte[] ysize = BinaryUtils.convert(height, 3); data[18] = ysize[0]; data[19] = ysize[1]; data[20] = ysize[2]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/AbstractDataObject.java
protected void writeStart(OutputStream os) throws IOException { setStarted(true); }
// in src/java/org/apache/fop/afp/modca/AbstractDataObject.java
protected void writeContent(OutputStream os) throws IOException { writeTriplets(os); if (objectEnvironmentGroup != null) { objectEnvironmentGroup.writeToStream(os); } }
// in src/java/org/apache/fop/afp/modca/PresentationTextDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[23]; copySF(data, Type.MIGRATION, Category.PRESENTATION_TEXT); data[1] = 0x00; // length data[2] = 0x16; data[9] = 0x00; data[10] = 0x00; byte[] xdpi = BinaryUtils.convert(widthRes * 10, 2); data[11] = xdpi[0]; // xdpi data[12] = xdpi[1]; byte[] ydpi = BinaryUtils.convert(heightRes * 10, 2); data[13] = ydpi[0]; // ydpi data[14] = ydpi[1]; byte[] x = BinaryUtils.convert(width, 3); data[15] = x[0]; data[16] = x[1]; data[17] = x[2]; byte[] y = BinaryUtils.convert(height, 3); data[18] = y[0]; data[19] = y[1]; data[20] = y[2]; data[21] = 0x00; data[22] = 0x00; os.write(data); }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
public void writeContent(OutputStream os) throws IOException { super.writeTriplets(os); writeObjects(mapCodedFonts, os); writeObjects(mapDataResources, os); writeObjects(mapPageOverlays, os); writeObjects(mapPageSegments, os); if (pageDescriptor != null) { pageDescriptor.writeToStream(os); } if (objectAreaDescriptor != null && objectAreaPosition != null) { objectAreaDescriptor.writeToStream(os); objectAreaPosition.writeToStream(os); } if (presentationTextDataDescriptor != null) { presentationTextDataDescriptor.writeToStream(os); } }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.ACTIVE_ENVIRONMENT_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.ACTIVE_ENVIRONMENT_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/Overlay.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.OVERLAY); os.write(data); }
// in src/java/org/apache/fop/afp/modca/Overlay.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); getActiveEnvironmentGroup().writeToStream(os); writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/modca/Overlay.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.OVERLAY); os.write(data); }
// in src/java/org/apache/fop/afp/modca/IncludePageOverlay.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[25]; //(9 +16) copySF(data, Type.INCLUDE, Category.PAGE_OVERLAY); // Set the total record length byte[] len = BinaryUtils.convert(24, 2); //Ignore first byte data[1] = len[0]; data[2] = len[1]; byte[] xPos = BinaryUtils.convert(x, 3); data[17] = xPos[0]; // x coordinate data[18] = xPos[1]; data[19] = xPos[2]; byte[] yPos = BinaryUtils.convert(y, 3); data[20] = yPos[0]; // y coordinate data[21] = yPos[1]; data[22] = yPos[2]; switch (orientation) { case 90: data[23] = 0x2D; data[24] = 0x00; break; case 180: data[23] = 0x5A; data[24] = 0x00; break; case 270: data[23] = (byte) 0x87; data[24] = 0x00; break; default: data[23] = 0x00; data[24] = 0x00; break; } os.write(data); }
// in src/java/org/apache/fop/afp/modca/IncludedResourceObject.java
public void writeToStream(OutputStream os) throws IOException { InputStream in = resourceAccessor.createInputStream(this.uri); try { AFPResourceUtil.copyResourceFile(in, os); } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/afp/modca/AbstractPageObject.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); writeObjects(this.objects, os); }
// in src/java/org/apache/fop/afp/modca/AbstractTripletStructuredObject.java
protected void writeTriplets(OutputStream os) throws IOException { if (hasTriplets()) { writeObjects(triplets, os); triplets = null; // gc } }
// in src/java/org/apache/fop/afp/modca/PresentationTextData.java
public void writeToStream(OutputStream os) throws IOException { assert getBytesAvailable() >= 0; byte[] data = baos.toByteArray(); byte[] size = BinaryUtils.convert(data.length - 1, 2); data[1] = size[0]; data[2] = size[1]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/NoOperation.java
public void writeToStream(OutputStream os) throws IOException { byte[] contentData = content.getBytes(AFPConstants.EBCIDIC_ENCODING); int contentLen = contentData.length; // packet maximum of 32759 bytes if (contentLen > MAX_DATA_LEN) { contentLen = MAX_DATA_LEN; } byte[] data = new byte[9 + contentLen]; data[0] = 0x5A; // Set the total record length byte[] rl1 = BinaryUtils.convert(8 + contentLen, 2); //Ignore first byte data[1] = rl1[0]; data[2] = rl1[1]; // Structured field ID for a NOP data[3] = (byte) 0xD3; data[4] = (byte) 0xEE; data[5] = (byte) 0xEE; data[6] = 0x00; // Reserved data[7] = 0x00; // Reserved data[8] = 0x00; // Reserved int pos = 9; for (int i = 0; i < contentLen; i++) { data[pos++] = contentData[i]; } os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/MeasurementUnitsTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = TEN_INCHES; // XoaBase data[3] = TEN_INCHES; // YoaBase byte[] xUnits = BinaryUtils.convert(xRes * 10, 2); data[4] = xUnits[0]; // XoaUnits (x units per unit base) data[5] = xUnits[1]; byte[] yUnits = BinaryUtils.convert(yRes * 10, 2); data[6] = yUnits[0]; // YoaUnits (y units per unit base) data[7] = yUnits[1]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/AttributeValueTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = super.getData(); data[2] = 0x00; // Reserved data[3] = 0x00; // Reserved // convert name and value to ebcdic byte[] tleByteValue = null; try { tleByteValue = attVal.getBytes(AFPConstants.EBCIDIC_ENCODING); } catch (UnsupportedEncodingException usee) { tleByteValue = attVal.getBytes(); throw new IllegalArgumentException(attVal + " encoding failed"); } System.arraycopy(tleByteValue, 0, data, 4, tleByteValue.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/ObjectAreaSizeTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = type; // SizeType byte[] xOASize = BinaryUtils.convert(x, 3); data[3] = xOASize[0]; // XoaSize - Object area extent for X axis data[4] = xOASize[1]; data[5] = xOASize[2]; byte[] yOASize = BinaryUtils.convert(y, 3); data[6] = yOASize[0]; // YoaSize - Object area extent for Y axis data[7] = yOASize[1]; data[8] = yOASize[2]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/CommentTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); byte[] strData = commentString.getBytes(AFPConstants.EBCIDIC_ENCODING); System.arraycopy(strData, 0, data, 2, strData.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/DescriptorPositionTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = oapId; os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/ResourceObjectTypeTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = objectType; os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/ObjectByteExtentTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); byte[] extData = BinaryUtils.convert(byteExt, 4); System.arraycopy(extData, 0, data, 2, extData.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/ObjectClassificationTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = 0x00; // reserved (must be zero) data[3] = objectClass; // ObjClass data[4] = 0x00; // reserved (must be zero) data[5] = 0x00; // reserved (must be zero) // StrucFlgs - Information on the structure of the object container byte[] structureFlagsBytes = getStructureFlagsAsBytes(dataInContainer, containerHasOEG, dataInOCD); data[6] = structureFlagsBytes[0]; data[7] = structureFlagsBytes[1]; byte[] objectIdBytes = objectType.getOID(); // RegObjId - MOD:CA-registered ASN.1 OID for object type (8-23) System.arraycopy(objectIdBytes, 0, data, 8, objectIdBytes.length); // ObjTpName - name of object type (24-55) byte[] objectTypeNameBytes; objectTypeNameBytes = StringUtils.rpad(objectType.getName(), ' ', OBJECT_TYPE_NAME_LEN).getBytes( AFPConstants.EBCIDIC_ENCODING); System.arraycopy(objectTypeNameBytes, 0, data, 24, objectTypeNameBytes.length); // ObjLev - release level or version number of object type (56-63) byte[] objectLevelBytes; objectLevelBytes = StringUtils.rpad(objectLevel, ' ', OBJECT_LEVEL_LEN).getBytes( AFPConstants.EBCIDIC_ENCODING); System.arraycopy(objectLevelBytes, 0, data, 56, objectLevelBytes.length); // CompName - name of company or organization that owns object definition (64-95) byte[] companyNameBytes; companyNameBytes = StringUtils.rpad(companyName, ' ', COMPANY_NAME_LEN).getBytes( AFPConstants.EBCIDIC_ENCODING); System.arraycopy(companyNameBytes, 0, data, 64, companyNameBytes.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/PresentationSpaceMixingRulesTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); System.arraycopy(rules, 0, data, 2, rules.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/MappingOptionTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = mapValue; os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/PresentationSpaceResetMixingTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = backgroundMixFlag; os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/AttributeQualifierTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); byte[] id = BinaryUtils.convert(seqNumber, 4); System.arraycopy(id, 0, data, 2, id.length); byte[] level = BinaryUtils.convert(levNumber, 4); System.arraycopy(level, 0, data, 6, level.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/ExtendedResourceLocalIdentifierTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = type; byte[] resLID = BinaryUtils.convert(localId, 4); // 4 bytes System.arraycopy(resLID, 0, data, 3, resLID.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/FullyQualifiedNameTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = type; data[3] = format; // FQName byte[] fqNameBytes; String encoding = AFPConstants.EBCIDIC_ENCODING; if (format == FORMAT_URL) { encoding = AFPConstants.US_ASCII_ENCODING; } try { fqNameBytes = fqName.getBytes(encoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( encoding + " encoding failed"); } System.arraycopy(fqNameBytes, 0, data, 4, fqNameBytes.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PageDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[24]; copySF(data, Type.DESCRIPTOR, Category.PAGE); data[2] = 0x17; // XpgBase data[9] = 0x00; // XpgBase = 10 inches // YpgBase data[10] = 0x00; // YpgBase = 10 inches // XpgUnits byte[] xdpi = BinaryUtils.convert(widthRes * 10, 2); data[11] = xdpi[0]; data[12] = xdpi[1]; // YpgUnits byte[] ydpi = BinaryUtils.convert(heightRes * 10, 2); data[13] = ydpi[0]; data[14] = ydpi[1]; // XpgSize byte[] x = BinaryUtils.convert(width, 3); data[15] = x[0]; data[16] = x[1]; data[17] = x[2]; // YpgSize byte[] y = BinaryUtils.convert(height, 3); data[18] = y[0]; data[19] = y[1]; data[20] = y[2]; data[21] = 0x00; // Reserved data[22] = 0x00; // Reserved data[23] = 0x00; // Reserved os.write(data); }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
public void writeToStream(OutputStream os) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); byte[] startData = new byte[9]; copySF(startData, Type.MAP, Category.CODED_FONT); baos.write(startData); Iterator iter = fontList.iterator(); while (iter.hasNext()) { FontDefinition fd = (FontDefinition) iter.next(); // Start of repeating groups (occurs 1 to 254) baos.write(0x00); if (fd.scale == 0) { // Raster Font baos.write(0x22); // Length of 34 } else { // Outline Font baos.write(0x3A); // Length of 58 } // Font Character Set Name Reference baos.write(0x0C); //TODO Relax requirement for 8 chars in the name baos.write(0x02); baos.write((byte) 0x86); baos.write(0x00); baos.write(fd.characterSet); // Font Code Page Name Reference baos.write(0x0C); //TODO Relax requirement for 8 chars in the name baos.write(0x02); baos.write((byte) 0x85); baos.write(0x00); baos.write(fd.codePage); //TODO idea: for CIDKeyed fonts, maybe hint at Unicode encoding with X'50' triplet //to allow font substitution. // Character Rotation baos.write(0x04); baos.write(0x26); baos.write(fd.orientation); baos.write(0x00); // Resource Local Identifier baos.write(0x04); baos.write(0x24); baos.write(0x05); baos.write(fd.fontReferenceKey); if (fd.scale != 0) { // Outline Font (triplet '1F') baos.write(0x14); baos.write(0x1F); baos.write(0x00); baos.write(0x00); baos.write(BinaryUtils.convert(fd.scale, 2)); // Height baos.write(new byte[] {0x00, 0x00}); // Width baos.write(new byte[] {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); baos.write(0x60); // Outline Font (triplet '5D') baos.write(0x04); baos.write(0x5D); baos.write(BinaryUtils.convert(fd.scale, 2)); } } byte[] data = baos.toByteArray(); // Set the total record length byte[] rl1 = BinaryUtils.convert(data.length - 1, 2); data[1] = rl1[0]; data[2] = rl1[1]; os.write(data); }
// in src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); }
// in src/java/org/apache/fop/afp/modca/ObjectContainer.java
protected void writeStart(OutputStream os) throws IOException { byte[] headerData = new byte[17]; copySF(headerData, Type.BEGIN, Category.OBJECT_CONTAINER); // Set the total record length int containerLen = headerData.length + getTripletDataLength() - 1; byte[] len = BinaryUtils.convert(containerLen, 2); headerData[1] = len[0]; // Length byte 1 headerData[2] = len[1]; // Length byte 2 os.write(headerData); }
// in src/java/org/apache/fop/afp/modca/ObjectContainer.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); // write triplets and OEG // write OCDs byte[] dataHeader = new byte[9]; copySF(dataHeader, SF_CLASS, Type.DATA, Category.OBJECT_CONTAINER); final int lengthOffset = 1; if (data != null) { writeChunksToStream(data, dataHeader, lengthOffset, MAX_DATA_LEN, os); } }
// in src/java/org/apache/fop/afp/modca/ObjectContainer.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.OBJECT_CONTAINER); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PageGroup.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.PAGE_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PageGroup.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.PAGE_GROUP); os.write(data); }
// in src/java/org/apache/fop/afp/modca/ObjectAreaPosition.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[33]; copySF(data, Type.POSITION, Category.OBJECT_AREA); byte[] len = BinaryUtils.convert(32, 2); data[1] = len[0]; // Length data[2] = len[1]; data[9] = 0x01; // OAPosID = 1 data[10] = 0x17; // RGLength = 23 byte[] xcoord = BinaryUtils.convert(x, 3); data[11] = xcoord[0]; // XoaOSet data[12] = xcoord[1]; data[13] = xcoord[2]; byte[] ycoord = BinaryUtils.convert(y, 3); data[14] = ycoord[0]; // YoaOSet data[15] = ycoord[1]; data[16] = ycoord[2]; byte xorient = (byte)(rotation / 2); data[17] = xorient; // XoaOrent byte yorient = (byte)(rotation / 2 + 45); data[19] = yorient; // YoaOrent byte[] xoffset = BinaryUtils.convert(xOffset, 3); data[22] = xoffset[0]; // XocaOSet data[23] = xoffset[1]; data[24] = xoffset[2]; byte[] yoffset = BinaryUtils.convert(yOffset, 3); data[25] = yoffset[0]; // YocaOSet data[26] = yoffset[1]; data[27] = yoffset[2]; data[28] = 0x00; // XocaOrent data[29] = 0x00; data[30] = 0x2D; // YocaOrent data[31] = 0x00; data[32] = this.refCSys; // RefCSys os.write(data); }
// in src/java/org/apache/fop/afp/modca/PageSegment.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.PAGE_SEGMENT); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PageSegment.java
protected void writeContent(OutputStream os) throws IOException { super.writeContent(os); writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/modca/PageSegment.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.PAGE_SEGMENT); os.write(data); }
// in src/java/org/apache/fop/afp/modca/AbstractAFPObject.java
protected <S extends Streamable> void writeObjects(Collection<S> objects, OutputStream os) throws IOException { if (objects != null) { Iterator<S> it = objects.iterator(); while (it.hasNext()) { Streamable s = it.next(); s.writeToStream(os); it.remove(); // once written, immediately remove the object } } }
// in src/java/org/apache/fop/afp/modca/AbstractAFPObject.java
protected static void writeChunksToStream(byte[] data, byte[] dataHeader, int lengthOffset, int maxChunkLength, OutputStream os) throws IOException { int dataLength = data.length; int numFullChunks = dataLength / maxChunkLength; int lastChunkLength = dataLength % maxChunkLength; int headerLen = dataHeader.length - lengthOffset; // length field is just before data so do not include in data length if (headerLen == 2) { headerLen = 0; } byte[] len; int off = 0; if (numFullChunks > 0) { // write out full data chunks len = BinaryUtils.convert(headerLen + maxChunkLength, 2); dataHeader[lengthOffset] = len[0]; // Length byte 1 dataHeader[lengthOffset + 1] = len[1]; // Length byte 2 for (int i = 0; i < numFullChunks; i++, off += maxChunkLength) { os.write(dataHeader); os.write(data, off, maxChunkLength); } } if (lastChunkLength > 0) { // write last data chunk len = BinaryUtils.convert(headerLen + lastChunkLength, 2); dataHeader[lengthOffset] = len[0]; // Length byte 1 dataHeader[lengthOffset + 1] = len[1]; // Length byte 2 os.write(dataHeader); os.write(data, off, lastChunkLength); } }
// in src/java/org/apache/fop/afp/modca/AbstractStructuredObject.java
protected void writeStart(OutputStream os) throws IOException { }
// in src/java/org/apache/fop/afp/modca/AbstractStructuredObject.java
protected void writeEnd(OutputStream os) throws IOException { }
// in src/java/org/apache/fop/afp/modca/AbstractStructuredObject.java
protected void writeContent(OutputStream os) throws IOException { }
// in src/java/org/apache/fop/afp/modca/AbstractStructuredObject.java
public void writeToStream(OutputStream os) throws IOException { writeStart(os); writeContent(os); writeEnd(os); }
// in src/java/org/apache/fop/afp/modca/MapPageOverlay.java
public void writeToStream(OutputStream os) throws IOException { int oLayCount = getOverlays().size(); int recordlength = oLayCount * 18; byte[] data = new byte[recordlength + 9]; data[0] = 0x5A; // Set the total record length byte[] rl1 = BinaryUtils.convert(recordlength + 8, 2); //Ignore the // first byte in // the length data[1] = rl1[0]; data[2] = rl1[1]; // Structured field ID for a MPO data[3] = (byte) 0xD3; data[4] = (byte) Type.MAP; data[5] = (byte) Category.PAGE_OVERLAY; data[6] = 0x00; // Reserved data[7] = 0x00; // Reserved data[8] = 0x00; // Reserved int pos = 8; //For each overlay byte olayref = 0x00; for (int i = 0; i < oLayCount; i++) { olayref = (byte) (olayref + 1); data[++pos] = 0x00; data[++pos] = 0x12; //the length of repeating group data[++pos] = 0x0C; //Fully Qualified Name data[++pos] = 0x02; data[++pos] = (byte) 0x84; data[++pos] = 0x00; //now add the name byte[] name = (byte[]) overLays.get(i); for (int j = 0; j < name.length; j++) { data[++pos] = name[j]; } data[++pos] = 0x04; //Resource Local Identifier (RLI) data[++pos] = 0x24; data[++pos] = 0x02; //now add the unique id to the RLI data[++pos] = olayref; } os.write(data); }
// in src/java/org/apache/fop/afp/modca/MapDataResource.java
public void writeToStream(OutputStream os) throws IOException { super.writeStart(os); byte[] data = new byte[11]; copySF(data, Type.MAP, Category.DATA_RESOURCE); int tripletDataLen = getTripletDataLength(); byte[] len = BinaryUtils.convert(10 + tripletDataLen, 2); data[1] = len[0]; data[2] = len[1]; len = BinaryUtils.convert(2 + tripletDataLen, 2); data[9] = len[0]; data[10] = len[1]; os.write(data); writeTriplets(os); }
// in src/java/org/apache/fop/afp/modca/PageObject.java
protected void writeStart(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.BEGIN, Category.PAGE); os.write(data); }
// in src/java/org/apache/fop/afp/modca/PageObject.java
protected void writeContent(OutputStream os) throws IOException { writeTriplets(os); getActiveEnvironmentGroup().writeToStream(os); writeObjects(objects, os); }
// in src/java/org/apache/fop/afp/modca/PageObject.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[17]; copySF(data, Type.END, Category.PAGE); os.write(data); }
// in src/java/org/apache/fop/afp/util/StructuredFieldReader.java
public byte[] getNext(byte[] identifier) throws IOException { byte[] bytes = AFPResourceUtil.getNext(identifier, this.inputStream); if (bytes != null) { //Users of this class expect the field data without length and identifier int srcPos = 2 + identifier.length; byte[] tmp = new byte[bytes.length - srcPos]; System.arraycopy(bytes, srcPos, tmp, 0, tmp.length); bytes = tmp; } return bytes; }
// in src/java/org/apache/fop/afp/util/SimpleResourceAccessor.java
public InputStream createInputStream(URI uri) throws IOException { URI resolved = resolveAgainstBase(uri); URL url = resolved.toURL(); return url.openStream(); }
// in src/java/org/apache/fop/afp/util/DTDEntityResolver.java
public InputSource resolveEntity(String publicId, String systemId) throws IOException { URL resource = null; if ( AFP_DTD_1_2_ID.equals(publicId) ) { resource = getResource( AFP_DTD_1_2_RESOURCE ); } else if ( AFP_DTD_1_1_ID.equals(publicId) ) { resource = getResource( AFP_DTD_1_1_RESOURCE ); } else if ( AFP_DTD_1_0_ID.equals(publicId) ) { throw new FontRuntimeException( "The AFP Installed Font Definition 1.0 DTD is not longer supported" ); } else if (systemId != null && systemId.indexOf("afp-fonts.dtd") >= 0 ) { throw new FontRuntimeException( "The AFP Installed Font Definition DTD must be specified using the public id" ); } else { return null; } InputSource inputSource = new InputSource( resource.openStream() ); inputSource.setPublicId( publicId ); inputSource.setSystemId( systemId ); return inputSource; }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
public static byte[] getNext(byte[] identifier, InputStream inputStream) throws IOException { MODCAParser parser = new MODCAParser(inputStream); while (true) { UnparsedStructuredField field = parser.readNextStructuredField(); if (field == null) { return null; } if (field.getSfClassCode() == identifier[0] && field.getSfTypeCode() == identifier[1] && field.getSfCategoryCode() == identifier[2]) { return field.getCompleteFieldAsBytes(); } } }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
public static void copyResourceFile(final InputStream in, OutputStream out) throws IOException { MODCAParser parser = new MODCAParser(in); while (true) { UnparsedStructuredField field = parser.readNextStructuredField(); if (field == null) { break; } out.write(MODCAParser.CARRIAGE_CONTROL_CHAR); field.writeTo(out); } }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
public static void copyNamedResource(String name, final InputStream in, final OutputStream out) throws IOException { final MODCAParser parser = new MODCAParser(in); Collection<String> resourceNames = new java.util.HashSet<String>(); //Find matching "Begin" field final UnparsedStructuredField fieldBegin; while (true) { final UnparsedStructuredField field = parser.readNextStructuredField(); if (field == null) { throw new IOException("Requested resource '" + name + "' not found. Encountered resource names: " + resourceNames); } if (field.getSfTypeCode() != TYPE_CODE_BEGIN) { //0xA8=Begin continue; //Not a "Begin" field } final String resourceName = getResourceName(field); resourceNames.add(resourceName); if (resourceName.equals(name)) { if (LOG.isDebugEnabled()) { LOG.debug("Start of requested structured field found:\n" + field); } fieldBegin = field; break; //Name doesn't match } } //Decide whether the resource file has to be wrapped in a resource object boolean wrapInResource; if (fieldBegin.getSfCategoryCode() == Category.PAGE_SEGMENT) { //A naked page segment must be wrapped in a resource object wrapInResource = true; } else if (fieldBegin.getSfCategoryCode() == Category.NAME_RESOURCE) { //A resource object can be copied directly wrapInResource = false; } else { throw new IOException("Cannot handle resource: " + fieldBegin); } //Copy structured fields (wrapped or as is) if (wrapInResource) { ResourceObject resourceObject = new ResourceObject(name) { protected void writeContent(OutputStream os) throws IOException { copyNamedStructuredFields(name, fieldBegin, parser, out); } }; resourceObject.setType(ResourceObject.TYPE_PAGE_SEGMENT); resourceObject.writeToStream(out); } else { copyNamedStructuredFields(name, fieldBegin, parser, out); } }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
protected void writeContent(OutputStream os) throws IOException { copyNamedStructuredFields(name, fieldBegin, parser, out); }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
private static void copyNamedStructuredFields(final String name, UnparsedStructuredField fieldBegin, MODCAParser parser, OutputStream out) throws IOException { UnparsedStructuredField field = fieldBegin; while (true) { if (field == null) { throw new IOException("Ending structured field not found for resource " + name); } out.write(MODCAParser.CARRIAGE_CONTROL_CHAR); field.writeTo(out); if (field.getSfTypeCode() == TYPE_CODE_END && fieldBegin.getSfCategoryCode() == field.getSfCategoryCode() && name.equals(getResourceName(field))) { break; } field = parser.readNextStructuredField(); } }
// in src/java/org/apache/fop/afp/util/DefaultFOPResourceAccessor.java
public InputStream createInputStream(URI uri) throws IOException { //Step 1: resolve against local base URI --> URI URI resolved = resolveAgainstBase(uri); //Step 2: resolve against the user agent --> stream String base = (this.categoryBaseURI != null ? this.categoryBaseURI : this.userAgent.getBaseURL()); Source src = userAgent.resolveURI(resolved.toASCIIString(), base); if (src == null) { throw new FileNotFoundException("Resource not found: " + uri.toASCIIString()); } else if (src instanceof StreamSource) { StreamSource ss = (StreamSource)src; InputStream in = ss.getInputStream(); if (in != null) { return in; } if (ss.getReader() != null) { //Don't support reader, retry using system ID below IOUtils.closeQuietly(ss.getReader()); } } URL url = new URL(src.getSystemId()); return url.openStream(); }
// in src/java/org/apache/fop/afp/ioca/ImageInputDescriptor.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[45]; copySF(data, Type.DESCRIPTOR, Category.IM_IMAGE); data[1] = 0x00; // length data[2] = 0x2C; // Constant data. data[9] = 0x00; data[10] = 0x00; data[11] = 0x09; data[12] = 0x60; data[13] = 0x09; data[14] = 0x60; data[15] = 0x00; data[16] = 0x00; data[17] = 0x00; data[18] = 0x00; data[19] = 0x00; data[20] = 0x00; // X Base (Fixed x00) data[21] = 0x00; // Y Base (Fixed x00) data[22] = 0x00; byte[] imagepoints = BinaryUtils.convert(resolution * 10, 2); /** * Specifies the number of image points per unit base for the X axis * of the image. This value is ten times the resolution of the image * in the X direction. */ data[23] = imagepoints[0]; data[24] = imagepoints[1]; /** * Specifies the number of image points per unit base for the Y axis * of the image. This value is ten times the resolution of the image * in the Y direction. */ data[25] = imagepoints[0]; data[26] = imagepoints[1]; /** * Specifies the extent in the X direction, in image points, of an * non-celled (simple) image. */ data[27] = 0x00; data[28] = 0x01; /** * Specifies the extent in the Y direction, in image points, of an * non-celled (simple) image. */ data[29] = 0x00; data[30] = 0x01; // Constant Data data[31] = 0x00; data[32] = 0x00; data[33] = 0x00; data[34] = 0x00; data[35] = 0x2D; data[36] = 0x00; // Default size of image cell in X direction data[37] = 0x00; data[38] = 0x01; // Default size of image cell in Y direction data[39] = 0x00; data[40] = 0x01; // Constant Data data[41] = 0x00; data[42] = 0x01; // Image Color data[43] = (byte)0xFF; data[44] = (byte)0xFF; os.write(data); }
// in src/java/org/apache/fop/afp/ioca/IDEStructureParameter.java
public void writeToStream(OutputStream os) throws IOException { int length = 7 + bitsPerIDE.length; byte flags = 0x00; if (subtractive) { flags |= 1 << 7; } if (grayCoding) { flags |= 1 << 6; } DataOutputStream dout = new DataOutputStream(os); dout.writeByte(0x9B); //ID dout.writeByte(length - 2); //LENGTH dout.writeByte(flags); //FLAGS dout.writeByte(this.colorModel); //FORMAT for (int i = 0; i < 3; i++) { dout.writeByte(0); //RESERVED } dout.write(this.bitsPerIDE); //component sizes }
// in src/java/org/apache/fop/afp/ioca/ImageContent.java
Override protected void writeContent(OutputStream os) throws IOException { if (imageSizeParameter != null) { imageSizeParameter.writeToStream(os); } // TODO convert to triplet/parameter class os.write(getImageEncodingParameter()); os.write(getImageIDESizeParameter()); if (getIDEStructureParameter() != null) { getIDEStructureParameter().writeToStream(os); } boolean useFS10 = (this.ideSize == 1); if (!useFS10) { os.write(getExternalAlgorithmParameter()); } final byte[] dataHeader = new byte[] { (byte)0xFE, // ID (byte)0x92, // ID 0x00, // length 0x00 // length }; final int lengthOffset = 2; // Image Data if (data != null) { writeChunksToStream(data, dataHeader, lengthOffset, MAX_DATA_LEN, os); } }
// in src/java/org/apache/fop/afp/ioca/ImageContent.java
Override protected void writeStart(OutputStream os) throws IOException { final byte[] startData = new byte[] { (byte)0x91, // ID 0x01, // Length (byte)0xff, // Object Type = IOCA Image Object }; os.write(startData); }
// in src/java/org/apache/fop/afp/ioca/ImageContent.java
Override protected void writeEnd(OutputStream os) throws IOException { final byte[] endData = new byte[] { (byte)0x93, // ID 0x00, // Length }; os.write(endData); }
// in src/java/org/apache/fop/afp/ioca/ImageSizeParameter.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[] { (byte)0x94, // ID = Image Size Parameter 0x09, // Length 0x00, // Unit base - 10 Inches 0x00, // HRESOL 0x00, // 0x00, // VRESOL 0x00, // 0x00, // HSIZE 0x00, // 0x00, // VSIZE 0x00, // }; byte[] x = BinaryUtils.convert(hRes, 2); data[3] = x[0]; data[4] = x[1]; byte[] y = BinaryUtils.convert(vRes, 2); data[5] = y[0]; data[6] = y[1]; byte[] w = BinaryUtils.convert(hSize, 2); data[7] = w[0]; data[8] = w[1]; byte[] h = BinaryUtils.convert(vSize, 2); data[9] = h[0]; data[10] = h[1]; os.write(data); }
// in src/java/org/apache/fop/afp/ioca/ImageOutputControl.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[33]; data[0] = 0x5A; data[1] = 0x00; data[2] = 0x20; data[3] = (byte) 0xD3; data[4] = (byte) 0xA7; data[5] = (byte) 0x7B; data[6] = 0x00; data[7] = 0x00; data[8] = 0x00; // XoaOset byte[] x1 = BinaryUtils.convert(xCoord, 3); data[9] = x1[0]; data[10] = x1[1]; data[11] = x1[2]; // YoaOset byte[] x2 = BinaryUtils.convert(yCoord, 3); data[12] = x2[0]; data[13] = x2[1]; data[14] = x2[2]; switch (orientation) { case 0: // 0 and 90 degrees respectively data[15] = 0x00; data[16] = 0x00; data[17] = 0x2D; data[18] = 0x00; break; case 90: // 90 and 180 degrees respectively data[15] = 0x2D; data[16] = 0x00; data[17] = 0x5A; data[18] = 0x00; break; case 180: // 180 and 270 degrees respectively data[15] = 0x5A; data[16] = 0x00; data[17] = (byte) 0x87; data[18] = 0x00; break; case 270: // 270 and 0 degrees respectively data[15] = (byte) 0x87; data[16] = 0x00; data[17] = 0x00; data[18] = 0x00; break; default: // 0 and 90 degrees respectively data[15] = 0x00; data[16] = 0x00; data[17] = 0x2D; data[18] = 0x00; break; } // Constant Data data[19] = 0x00; data[20] = 0x00; data[21] = 0x00; data[22] = 0x00; data[23] = 0x00; data[24] = 0x00; data[25] = 0x00; data[26] = 0x00; if (singlePoint) { data[27] = 0x03; data[28] = (byte) 0xE8; data[29] = 0x03; data[30] = (byte) 0xE8; } else { data[27] = 0x07; data[28] = (byte) 0xD0; data[29] = 0x07; data[30] = (byte) 0xD0; } // Constant Data data[31] = (byte) 0xFF; data[32] = (byte) 0xFF; os.write(data); }
// in src/java/org/apache/fop/afp/ioca/ImageCellPosition.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[21]; copySF(data, Type.POSITION, Category.IM_IMAGE); data[1] = 0x00; // length data[2] = 0x14; /** * Specifies the offset along the Xp direction, in image points, * of this image cell from the IM image object area origin. */ byte[] x1 = BinaryUtils.convert(xOffset, 2); data[9] = x1[0]; data[10] = x1[1]; /** * Specifies the offset along the Yp direction, in image points, * of this image cell from the IM image object area origin. */ byte[] x2 = BinaryUtils.convert(yOffset, 2); data[11] = x2[0]; data[12] = x2[1]; data[13] = xSize[0]; data[14] = xSize[1]; data[15] = ySize[0]; data[16] = ySize[1]; data[17] = xFillSize[0]; data[18] = xFillSize[1]; data[19] = yFillSize[0]; data[20] = yFillSize[1]; os.write(data); }
// in src/java/org/apache/fop/afp/ioca/ImageRasterData.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = new byte[9]; copySF(data, Type.DATA, Category.IM_IMAGE); // The size of the structured field byte[] len = BinaryUtils.convert(rasterData.length + 8, 2); data[1] = len[0]; data[2] = len[1]; os.write(data); os.write(rasterData); }
// in src/java/org/apache/fop/afp/ioca/ImageSegment.java
public void writeContent(OutputStream os) throws IOException { if (imageContent != null) { imageContent.writeToStream(os); } }
// in src/java/org/apache/fop/afp/ioca/ImageSegment.java
protected void writeStart(OutputStream os) throws IOException { //Name disabled, it's optional and not referenced by our code //byte[] nameBytes = getNameBytes(); byte[] data = new byte[] { 0x70, // ID 0x00, // Length /* nameBytes[0], // Name byte 1 nameBytes[1], // Name byte 2 nameBytes[2], // Name byte 3 nameBytes[3], // Name byte 4 */ }; os.write(data); }
// in src/java/org/apache/fop/afp/ioca/ImageSegment.java
protected void writeEnd(OutputStream os) throws IOException { byte[] data = new byte[] { 0x71, // ID 0x00, // Length }; os.write(data); }
// in src/java/org/apache/fop/events/model/EventModel.java
private void writeXMLizable(XMLizable object, File outputFile) throws IOException { //These two approaches do not seem to work in all environments: //Result res = new StreamResult(outputFile); //Result res = new StreamResult(outputFile.toURI().toURL().toExternalForm()); //With an old Xalan version: file:/C:/.... --> file:\C:\..... OutputStream out = new java.io.FileOutputStream(outputFile); out = new java.io.BufferedOutputStream(out); Result res = new StreamResult(out); try { SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler handler = tFactory.newTransformerHandler(); Transformer transformer = handler.getTransformer(); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); handler.setResult(res); handler.startDocument(); object.toSAX(handler); handler.endDocument(); } catch (TransformerConfigurationException e) { throw new IOException(e.getMessage()); } catch (TransformerFactoryConfigurationError e) { throw new IOException(e.getMessage()); } catch (SAXException e) { throw new IOException(e.getMessage()); } finally { IOUtils.closeQuietly(out); } }
// in src/java/org/apache/fop/events/model/EventModel.java
public void saveToXML(File modelFile) throws IOException { writeXMLizable(this, modelFile); }
// in src/java/org/apache/fop/area/PageViewport.java
public void savePage(ObjectOutputStream out) throws IOException { // set the unresolved references so they are serialized page.setUnresolvedReferences(unresolvedIDRefs); out.writeObject(page); page = null; }
// in src/java/org/apache/fop/area/PageViewport.java
public void loadPage(ObjectInputStream in) throws IOException, ClassNotFoundException { page = (Page) in.readObject(); unresolvedIDRefs = page.getUnresolvedReferences(); if (unresolvedIDRefs != null && pendingResolved != null) { for (String id : pendingResolved.keySet()) { resolveIDRef(id, pendingResolved.get(id)); } pendingResolved = null; } }
// in src/java/org/apache/fop/area/inline/InlineViewport.java
private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeBoolean(contentPosition != null); if (contentPosition != null) { out.writeFloat((float) contentPosition.getX()); out.writeFloat((float) contentPosition.getY()); out.writeFloat((float) contentPosition.getWidth()); out.writeFloat((float) contentPosition.getHeight()); } out.writeBoolean(clip); out.writeObject((TreeMap)traits); out.writeObject(content); }
// in src/java/org/apache/fop/area/inline/InlineViewport.java
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { if (in.readBoolean()) { contentPosition = new Rectangle2D.Float(in.readFloat(), in.readFloat(), in.readFloat(), in.readFloat()); } this.clip = in.readBoolean(); this.traits = (TreeMap) in.readObject(); this.content = (Area) in.readObject(); }
// in src/java/org/apache/fop/area/RegionViewport.java
private void writeObject(java.io.ObjectOutputStream out) throws IOException { out.writeFloat((float) viewArea.getX()); out.writeFloat((float) viewArea.getY()); out.writeFloat((float) viewArea.getWidth()); out.writeFloat((float) viewArea.getHeight()); out.writeBoolean(clip); out.writeObject((TreeMap)traits); out.writeObject(regionReference); }
// in src/java/org/apache/fop/area/RegionViewport.java
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { viewArea = new Rectangle2D.Float(in.readFloat(), in.readFloat(), in.readFloat(), in.readFloat()); clip = in.readBoolean(); traits = (TreeMap)in.readObject(); setRegionReference((RegionReference) in.readObject()); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readLangSysTable(String tableTag, long langSysTable, String langSysTag) throws IOException { in.seekSet(langSysTable); if (log.isDebugEnabled()) { log.debug(tableTag + " lang sys table: " + langSysTag ); } // read lookup order (reorder) table offset int lo = in.readTTFUShort(); // read required feature index int rf = in.readTTFUShort(); String rfi; if ( rf != 65535 ) { rfi = "f" + rf; } else { rfi = null; } // read (non-required) feature count int nf = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " lang sys table reorder table: " + lo ); log.debug(tableTag + " lang sys table required feature index: " + rf ); log.debug(tableTag + " lang sys table non-required feature count: " + nf ); } // read (non-required) feature indices int[] fia = new int[nf]; List fl = new java.util.ArrayList(); for ( int i = 0; i < nf; i++ ) { int fi = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " lang sys table non-required feature index: " + fi ); } fia[i] = fi; fl.add ( "f" + fi ); } if ( seLanguages == null ) { seLanguages = new java.util.LinkedHashMap(); } seLanguages.put ( langSysTag, new Object[] { rfi, fl } ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readScriptTable(String tableTag, long scriptTable, String scriptTag) throws IOException { in.seekSet(scriptTable); if (log.isDebugEnabled()) { log.debug(tableTag + " script table: " + scriptTag ); } // read default language system table offset int dl = in.readTTFUShort(); String dt = defaultTag; if ( dl > 0 ) { if (log.isDebugEnabled()) { log.debug(tableTag + " default lang sys tag: " + dt ); log.debug(tableTag + " default lang sys table offset: " + dl ); } } // read language system record count int nl = in.readTTFUShort(); List ll = new java.util.ArrayList(); if ( nl > 0 ) { String[] lta = new String[nl]; int[] loa = new int[nl]; // read language system records for ( int i = 0, n = nl; i < n; i++ ) { String lt = in.readTTFString(4); int lo = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " lang sys tag: " + lt ); log.debug(tableTag + " lang sys table offset: " + lo ); } lta[i] = lt; loa[i] = lo; if ( dl == lo ) { dl = 0; dt = lt; } ll.add ( lt ); } // read non-default language system tables for ( int i = 0, n = nl; i < n; i++ ) { readLangSysTable ( tableTag, scriptTable + loa [ i ], lta [ i ] ); } } // read default language system table (if specified) if ( dl > 0 ) { readLangSysTable ( tableTag, scriptTable + dl, dt ); } else if ( dt != null ) { if (log.isDebugEnabled()) { log.debug(tableTag + " lang sys default: " + dt ); } } seScripts.put ( scriptTag, new Object[] { dt, ll, seLanguages } ); seLanguages = null; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readScriptList(String tableTag, long scriptList) throws IOException { in.seekSet(scriptList); // read script record count int ns = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " script list record count: " + ns ); } if ( ns > 0 ) { String[] sta = new String[ns]; int[] soa = new int[ns]; // read script records for ( int i = 0, n = ns; i < n; i++ ) { String st = in.readTTFString(4); int so = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " script tag: " + st ); log.debug(tableTag + " script table offset: " + so ); } sta[i] = st; soa[i] = so; } // read script tables for ( int i = 0, n = ns; i < n; i++ ) { seLanguages = null; readScriptTable ( tableTag, scriptList + soa [ i ], sta [ i ] ); } } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readFeatureTable(String tableTag, long featureTable, String featureTag, int featureIndex) throws IOException { in.seekSet(featureTable); if (log.isDebugEnabled()) { log.debug(tableTag + " feature table: " + featureTag ); } // read feature params offset int po = in.readTTFUShort(); // read lookup list indices count int nl = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " feature table parameters offset: " + po ); log.debug(tableTag + " feature table lookup list index count: " + nl ); } // read lookup table indices int[] lia = new int[nl]; List lul = new java.util.ArrayList(); for ( int i = 0; i < nl; i++ ) { int li = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " feature table lookup index: " + li ); } lia[i] = li; lul.add ( "lu" + li ); } seFeatures.put ( "f" + featureIndex, new Object[] { featureTag, lul } ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readFeatureList(String tableTag, long featureList) throws IOException { in.seekSet(featureList); // read feature record count int nf = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " feature list record count: " + nf ); } if ( nf > 0 ) { String[] fta = new String[nf]; int[] foa = new int[nf]; // read feature records for ( int i = 0, n = nf; i < n; i++ ) { String ft = in.readTTFString(4); int fo = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " feature tag: " + ft ); log.debug(tableTag + " feature table offset: " + fo ); } fta[i] = ft; foa[i] = fo; } // read feature tables for ( int i = 0, n = nf; i < n; i++ ) { if (log.isDebugEnabled()) { log.debug(tableTag + " feature index: " + i ); } readFeatureTable ( tableTag, featureList + foa [ i ], fta [ i ], i ); } } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphCoverageTable readCoverageTableFormat1(String label, long tableOffset, int coverageFormat) throws IOException { List entries = new java.util.ArrayList(); in.seekSet(tableOffset); // skip over format (already known) in.skip ( 2 ); // read glyph count int ng = in.readTTFUShort(); int[] ga = new int[ng]; for ( int i = 0, n = ng; i < n; i++ ) { int g = in.readTTFUShort(); ga[i] = g; entries.add ( Integer.valueOf(g) ); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(label + " glyphs: " + toString(ga) ); } return GlyphCoverageTable.createCoverageTable ( entries ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphCoverageTable readCoverageTableFormat2(String label, long tableOffset, int coverageFormat) throws IOException { List entries = new java.util.ArrayList(); in.seekSet(tableOffset); // skip over format (already known) in.skip ( 2 ); // read range record count int nr = in.readTTFUShort(); for ( int i = 0, n = nr; i < n; i++ ) { // read range start int s = in.readTTFUShort(); // read range end int e = in.readTTFUShort(); // read range coverage (mapping) index int m = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(label + " range[" + i + "]: [" + s + "," + e + "]: " + m ); } entries.add ( new GlyphCoverageTable.MappingRange ( s, e, m ) ); } return GlyphCoverageTable.createCoverageTable ( entries ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphCoverageTable readCoverageTable(String label, long tableOffset) throws IOException { GlyphCoverageTable gct; long cp = in.getCurrentPos(); in.seekSet(tableOffset); // read coverage table format int cf = in.readTTFUShort(); if ( cf == 1 ) { gct = readCoverageTableFormat1 ( label, tableOffset, cf ); } else if ( cf == 2 ) { gct = readCoverageTableFormat2 ( label, tableOffset, cf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported coverage table format: " + cf ); } in.seekSet ( cp ); return gct; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphClassTable readClassDefTableFormat1(String label, long tableOffset, int classFormat) throws IOException { List entries = new java.util.ArrayList(); in.seekSet(tableOffset); // skip over format (already known) in.skip ( 2 ); // read start glyph int sg = in.readTTFUShort(); entries.add ( Integer.valueOf(sg) ); // read glyph count int ng = in.readTTFUShort(); // read glyph classes int[] ca = new int[ng]; for ( int i = 0, n = ng; i < n; i++ ) { int gc = in.readTTFUShort(); ca[i] = gc; entries.add ( Integer.valueOf(gc) ); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(label + " glyph classes: " + toString(ca) ); } return GlyphClassTable.createClassTable ( entries ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphClassTable readClassDefTableFormat2(String label, long tableOffset, int classFormat) throws IOException { List entries = new java.util.ArrayList(); in.seekSet(tableOffset); // skip over format (already known) in.skip ( 2 ); // read range record count int nr = in.readTTFUShort(); for ( int i = 0, n = nr; i < n; i++ ) { // read range start int s = in.readTTFUShort(); // read range end int e = in.readTTFUShort(); // read range glyph class (mapping) index int m = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(label + " range[" + i + "]: [" + s + "," + e + "]: " + m ); } entries.add ( new GlyphClassTable.MappingRange ( s, e, m ) ); } return GlyphClassTable.createClassTable ( entries ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphClassTable readClassDefTable(String label, long tableOffset) throws IOException { GlyphClassTable gct; long cp = in.getCurrentPos(); in.seekSet(tableOffset); // read class table format int cf = in.readTTFUShort(); if ( cf == 1 ) { gct = readClassDefTableFormat1 ( label, tableOffset, cf ); } else if ( cf == 2 ) { gct = readClassDefTableFormat2 ( label, tableOffset, cf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported class definition table format: " + cf ); } in.seekSet ( cp ); return gct; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readSingleSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read delta glyph int dg = in.readTTFShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " single substitution subtable format: " + subtableFormat + " (delta)" ); log.debug(tableTag + " single substitution coverage table offset: " + co ); log.debug(tableTag + " single substitution delta: " + dg ); } // read coverage table seMapping = readCoverageTable ( tableTag + " single substitution coverage", subtableOffset + co ); seEntries.add ( Integer.valueOf ( dg ) ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readSingleSubTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read glyph count int ng = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " single substitution subtable format: " + subtableFormat + " (mapped)" ); log.debug(tableTag + " single substitution coverage table offset: " + co ); log.debug(tableTag + " single substitution glyph count: " + ng ); } // read coverage table seMapping = readCoverageTable ( tableTag + " single substitution coverage", subtableOffset + co ); // read glyph substitutions int[] gsa = new int[ng]; for ( int i = 0, n = ng; i < n; i++ ) { int gs = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " single substitution glyph[" + i + "]: " + gs ); } gsa[i] = gs; seEntries.add ( Integer.valueOf ( gs ) ); } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readSingleSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readSingleSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readSingleSubTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported single substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readMultipleSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read sequence count int ns = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " multiple substitution subtable format: " + subtableFormat + " (mapped)" ); log.debug(tableTag + " multiple substitution coverage table offset: " + co ); log.debug(tableTag + " multiple substitution sequence count: " + ns ); } // read coverage table seMapping = readCoverageTable ( tableTag + " multiple substitution coverage", subtableOffset + co ); // read sequence table offsets int[] soa = new int[ns]; for ( int i = 0, n = ns; i < n; i++ ) { soa[i] = in.readTTFUShort(); } // read sequence tables int[][] gsa = new int [ ns ] []; for ( int i = 0, n = ns; i < n; i++ ) { int so = soa[i]; int[] ga; if ( so > 0 ) { in.seekSet(subtableOffset + so); // read glyph count int ng = in.readTTFUShort(); ga = new int[ng]; for ( int j = 0; j < ng; j++ ) { ga[j] = in.readTTFUShort(); } } else { ga = null; } if (log.isDebugEnabled()) { log.debug(tableTag + " multiple substitution sequence[" + i + "]: " + toString ( ga ) ); } gsa [ i ] = ga; } seEntries.add ( gsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMultipleSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMultipleSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported multiple substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readAlternateSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read alternate set count int ns = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " alternate substitution subtable format: " + subtableFormat + " (mapped)" ); log.debug(tableTag + " alternate substitution coverage table offset: " + co ); log.debug(tableTag + " alternate substitution alternate set count: " + ns ); } // read coverage table seMapping = readCoverageTable ( tableTag + " alternate substitution coverage", subtableOffset + co ); // read alternate set table offsets int[] soa = new int[ns]; for ( int i = 0, n = ns; i < n; i++ ) { soa[i] = in.readTTFUShort(); } // read alternate set tables for ( int i = 0, n = ns; i < n; i++ ) { int so = soa[i]; in.seekSet(subtableOffset + so); // read glyph count int ng = in.readTTFUShort(); int[] ga = new int[ng]; for ( int j = 0; j < ng; j++ ) { int gs = in.readTTFUShort(); ga[j] = gs; } if (log.isDebugEnabled()) { log.debug(tableTag + " alternate substitution alternate set[" + i + "]: " + toString ( ga ) ); } seEntries.add ( ga ); } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readAlternateSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readAlternateSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported alternate substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readLigatureSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read ligature set count int ns = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " ligature substitution subtable format: " + subtableFormat + " (mapped)" ); log.debug(tableTag + " ligature substitution coverage table offset: " + co ); log.debug(tableTag + " ligature substitution ligature set count: " + ns ); } // read coverage table seMapping = readCoverageTable ( tableTag + " ligature substitution coverage", subtableOffset + co ); // read ligature set table offsets int[] soa = new int[ns]; for ( int i = 0, n = ns; i < n; i++ ) { soa[i] = in.readTTFUShort(); } // read ligature set tables for ( int i = 0, n = ns; i < n; i++ ) { int so = soa[i]; in.seekSet(subtableOffset + so); // read ligature table count int nl = in.readTTFUShort(); int[] loa = new int[nl]; for ( int j = 0; j < nl; j++ ) { loa[j] = in.readTTFUShort(); } List ligs = new java.util.ArrayList(); for ( int j = 0; j < nl; j++ ) { int lo = loa[j]; in.seekSet(subtableOffset + so + lo); // read ligature glyph id int lg = in.readTTFUShort(); // read ligature (input) component count int nc = in.readTTFUShort(); int[] ca = new int [ nc - 1 ]; // read ligature (input) component glyph ids for ( int k = 0; k < nc - 1; k++ ) { ca[k] = in.readTTFUShort(); } if (log.isDebugEnabled()) { log.debug(tableTag + " ligature substitution ligature set[" + i + "]: ligature(" + lg + "), components: " + toString ( ca ) ); } ligs.add ( new GlyphSubstitutionTable.Ligature ( lg, ca ) ); } seEntries.add ( new GlyphSubstitutionTable.LigatureSet ( ligs ) ); } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readLigatureSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readLigatureSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported ligature substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphTable.RuleLookup[] readRuleLookups(int numLookups, String header) throws IOException { GlyphTable.RuleLookup[] la = new GlyphTable.RuleLookup [ numLookups ]; for ( int i = 0, n = numLookups; i < n; i++ ) { int sequenceIndex = in.readTTFUShort(); int lookupIndex = in.readTTFUShort(); la [ i ] = new GlyphTable.RuleLookup ( sequenceIndex, lookupIndex ); // dump info if debugging and header is non-null if ( log.isDebugEnabled() && ( header != null ) ) { log.debug(header + "lookup[" + i + "]: " + la[i]); } } return la; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readContextualSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read rule set count int nrs = in.readTTFUShort(); // read rule set offsets int[] rsoa = new int [ nrs ]; for ( int i = 0; i < nrs; i++ ) { rsoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " contextual substitution format: " + subtableFormat + " (glyphs)" ); log.debug(tableTag + " contextual substitution coverage table offset: " + co ); log.debug(tableTag + " contextual substitution rule set count: " + nrs ); for ( int i = 0; i < nrs; i++ ) { log.debug(tableTag + " contextual substitution rule set offset[" + i + "]: " + rsoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " contextual substitution coverage", subtableOffset + co ); } else { ct = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ nrs ]; String header = null; for ( int i = 0; i < nrs; i++ ) { GlyphTable.RuleSet rs; int rso = rsoa [ i ]; if ( rso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + rso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { GlyphTable.GlyphSequenceRule r; int ro = roa [ j ]; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + rso + ro ); // read glyph count int ng = in.readTTFUShort(); // read rule lookup count int nl = in.readTTFUShort(); // read glyphs int[] glyphs = new int [ ng - 1 ]; for ( int k = 0, nk = glyphs.length; k < nk; k++ ) { glyphs [ k ] = in.readTTFUShort(); } // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual substitution lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.GlyphSequenceRule ( lookups, ng, glyphs ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readContextualSubTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read class def table offset int cdo = in.readTTFUShort(); // read class rule set count int ngc = in.readTTFUShort(); // read class rule set offsets int[] csoa = new int [ ngc ]; for ( int i = 0; i < ngc; i++ ) { csoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " contextual substitution format: " + subtableFormat + " (glyph classes)" ); log.debug(tableTag + " contextual substitution coverage table offset: " + co ); log.debug(tableTag + " contextual substitution class set count: " + ngc ); for ( int i = 0; i < ngc; i++ ) { log.debug(tableTag + " contextual substitution class set offset[" + i + "]: " + csoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " contextual substitution coverage", subtableOffset + co ); } else { ct = null; } // read class definition table GlyphClassTable cdt; if ( cdo > 0 ) { cdt = readClassDefTable ( tableTag + " contextual substitution class definition", subtableOffset + cdo ); } else { cdt = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ ngc ]; String header = null; for ( int i = 0; i < ngc; i++ ) { int cso = csoa [ i ]; GlyphTable.RuleSet rs; if ( cso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + cso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { int ro = roa [ j ]; GlyphTable.ClassSequenceRule r; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + cso + ro ); // read glyph count int ng = in.readTTFUShort(); // read rule lookup count int nl = in.readTTFUShort(); // read classes int[] classes = new int [ ng - 1 ]; for ( int k = 0, nk = classes.length; k < nk; k++ ) { classes [ k ] = in.readTTFUShort(); } // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual substitution lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.ClassSequenceRule ( lookups, ng, classes ); } else { assert ro > 0 : "unexpected null subclass rule offset"; r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( cdt ); seEntries.add ( Integer.valueOf ( ngc ) ); seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readContextualSubTableFormat3(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read glyph (input sequence length) count int ng = in.readTTFUShort(); // read substitution lookup count int nl = in.readTTFUShort(); // read glyph coverage offsets, one per glyph input sequence length count int[] gcoa = new int [ ng ]; for ( int i = 0; i < ng; i++ ) { gcoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " contextual substitution format: " + subtableFormat + " (glyph sets)" ); log.debug(tableTag + " contextual substitution glyph input sequence length count: " + ng ); log.debug(tableTag + " contextual substitution lookup count: " + nl ); for ( int i = 0; i < ng; i++ ) { log.debug(tableTag + " contextual substitution coverage table offset[" + i + "]: " + gcoa[i] ); } } // read coverage tables GlyphCoverageTable[] gca = new GlyphCoverageTable [ ng ]; for ( int i = 0; i < ng; i++ ) { int gco = gcoa [ i ]; GlyphCoverageTable gct; if ( gco > 0 ) { gct = readCoverageTable ( tableTag + " contextual substitution coverage[" + i + "]", subtableOffset + gco ); } else { gct = null; } gca [ i ] = gct; } // read rule lookups String header = null; if (log.isDebugEnabled()) { header = tableTag + " contextual substitution lookups: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); // construct rule, rule set, and rule set array GlyphTable.Rule r = new GlyphTable.CoverageSequenceRule ( lookups, ng, gca ); GlyphTable.RuleSet rs = new GlyphTable.HomogeneousRuleSet ( new GlyphTable.Rule[] {r} ); GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet[] {rs}; // store results assert ( gca != null ) && ( gca.length > 0 ); seMapping = gca[0]; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readContextualSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readContextualSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readContextualSubTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readContextualSubTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported contextual substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readChainedContextualSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read rule set count int nrs = in.readTTFUShort(); // read rule set offsets int[] rsoa = new int [ nrs ]; for ( int i = 0; i < nrs; i++ ) { rsoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " chained contextual substitution format: " + subtableFormat + " (glyphs)" ); log.debug(tableTag + " chained contextual substitution coverage table offset: " + co ); log.debug(tableTag + " chained contextual substitution rule set count: " + nrs ); for ( int i = 0; i < nrs; i++ ) { log.debug(tableTag + " chained contextual substitution rule set offset[" + i + "]: " + rsoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " chained contextual substitution coverage", subtableOffset + co ); } else { ct = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ nrs ]; String header = null; for ( int i = 0; i < nrs; i++ ) { GlyphTable.RuleSet rs; int rso = rsoa [ i ]; if ( rso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + rso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { GlyphTable.ChainedGlyphSequenceRule r; int ro = roa [ j ]; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + rso + ro ); // read backtrack glyph count int nbg = in.readTTFUShort(); // read backtrack glyphs int[] backtrackGlyphs = new int [ nbg ]; for ( int k = 0, nk = backtrackGlyphs.length; k < nk; k++ ) { backtrackGlyphs [ k ] = in.readTTFUShort(); } // read input glyph count int nig = in.readTTFUShort(); // read glyphs int[] glyphs = new int [ nig - 1 ]; for ( int k = 0, nk = glyphs.length; k < nk; k++ ) { glyphs [ k ] = in.readTTFUShort(); } // read lookahead glyph count int nlg = in.readTTFUShort(); // read lookahead glyphs int[] lookaheadGlyphs = new int [ nlg ]; for ( int k = 0, nk = lookaheadGlyphs.length; k < nk; k++ ) { lookaheadGlyphs [ k ] = in.readTTFUShort(); } // read rule lookup count int nl = in.readTTFUShort(); // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual substitution lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.ChainedGlyphSequenceRule ( lookups, nig, glyphs, backtrackGlyphs, lookaheadGlyphs ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readChainedContextualSubTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read backtrack class def table offset int bcdo = in.readTTFUShort(); // read input class def table offset int icdo = in.readTTFUShort(); // read lookahead class def table offset int lcdo = in.readTTFUShort(); // read class set count int ngc = in.readTTFUShort(); // read class set offsets int[] csoa = new int [ ngc ]; for ( int i = 0; i < ngc; i++ ) { csoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " chained contextual substitution format: " + subtableFormat + " (glyph classes)" ); log.debug(tableTag + " chained contextual substitution coverage table offset: " + co ); log.debug(tableTag + " chained contextual substitution class set count: " + ngc ); for ( int i = 0; i < ngc; i++ ) { log.debug(tableTag + " chained contextual substitution class set offset[" + i + "]: " + csoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " chained contextual substitution coverage", subtableOffset + co ); } else { ct = null; } // read backtrack class definition table GlyphClassTable bcdt; if ( bcdo > 0 ) { bcdt = readClassDefTable ( tableTag + " contextual substitution backtrack class definition", subtableOffset + bcdo ); } else { bcdt = null; } // read input class definition table GlyphClassTable icdt; if ( icdo > 0 ) { icdt = readClassDefTable ( tableTag + " contextual substitution input class definition", subtableOffset + icdo ); } else { icdt = null; } // read lookahead class definition table GlyphClassTable lcdt; if ( lcdo > 0 ) { lcdt = readClassDefTable ( tableTag + " contextual substitution lookahead class definition", subtableOffset + lcdo ); } else { lcdt = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ ngc ]; String header = null; for ( int i = 0; i < ngc; i++ ) { int cso = csoa [ i ]; GlyphTable.RuleSet rs; if ( cso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + cso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { int ro = roa [ j ]; GlyphTable.ChainedClassSequenceRule r; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + cso + ro ); // read backtrack glyph class count int nbc = in.readTTFUShort(); // read backtrack glyph classes int[] backtrackClasses = new int [ nbc ]; for ( int k = 0, nk = backtrackClasses.length; k < nk; k++ ) { backtrackClasses [ k ] = in.readTTFUShort(); } // read input glyph class count int nic = in.readTTFUShort(); // read input glyph classes int[] classes = new int [ nic - 1 ]; for ( int k = 0, nk = classes.length; k < nk; k++ ) { classes [ k ] = in.readTTFUShort(); } // read lookahead glyph class count int nlc = in.readTTFUShort(); // read lookahead glyph classes int[] lookaheadClasses = new int [ nlc ]; for ( int k = 0, nk = lookaheadClasses.length; k < nk; k++ ) { lookaheadClasses [ k ] = in.readTTFUShort(); } // read rule lookup count int nl = in.readTTFUShort(); // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual substitution lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.ChainedClassSequenceRule ( lookups, nic, classes, backtrackClasses, lookaheadClasses ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( icdt ); seEntries.add ( bcdt ); seEntries.add ( lcdt ); seEntries.add ( Integer.valueOf ( ngc ) ); seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readChainedContextualSubTableFormat3(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read backtrack glyph count int nbg = in.readTTFUShort(); // read backtrack glyph coverage offsets int[] bgcoa = new int [ nbg ]; for ( int i = 0; i < nbg; i++ ) { bgcoa [ i ] = in.readTTFUShort(); } // read input glyph count int nig = in.readTTFUShort(); // read input glyph coverage offsets int[] igcoa = new int [ nig ]; for ( int i = 0; i < nig; i++ ) { igcoa [ i ] = in.readTTFUShort(); } // read lookahead glyph count int nlg = in.readTTFUShort(); // read lookahead glyph coverage offsets int[] lgcoa = new int [ nlg ]; for ( int i = 0; i < nlg; i++ ) { lgcoa [ i ] = in.readTTFUShort(); } // read substitution lookup count int nl = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " chained contextual substitution format: " + subtableFormat + " (glyph sets)" ); log.debug(tableTag + " chained contextual substitution backtrack glyph count: " + nbg ); for ( int i = 0; i < nbg; i++ ) { log.debug(tableTag + " chained contextual substitution backtrack coverage table offset[" + i + "]: " + bgcoa[i] ); } log.debug(tableTag + " chained contextual substitution input glyph count: " + nig ); for ( int i = 0; i < nig; i++ ) { log.debug(tableTag + " chained contextual substitution input coverage table offset[" + i + "]: " + igcoa[i] ); } log.debug(tableTag + " chained contextual substitution lookahead glyph count: " + nlg ); for ( int i = 0; i < nlg; i++ ) { log.debug(tableTag + " chained contextual substitution lookahead coverage table offset[" + i + "]: " + lgcoa[i] ); } log.debug(tableTag + " chained contextual substitution lookup count: " + nl ); } // read backtrack coverage tables GlyphCoverageTable[] bgca = new GlyphCoverageTable[nbg]; for ( int i = 0; i < nbg; i++ ) { int bgco = bgcoa [ i ]; GlyphCoverageTable bgct; if ( bgco > 0 ) { bgct = readCoverageTable ( tableTag + " chained contextual substitution backtrack coverage[" + i + "]", subtableOffset + bgco ); } else { bgct = null; } bgca[i] = bgct; } // read input coverage tables GlyphCoverageTable[] igca = new GlyphCoverageTable[nig]; for ( int i = 0; i < nig; i++ ) { int igco = igcoa [ i ]; GlyphCoverageTable igct; if ( igco > 0 ) { igct = readCoverageTable ( tableTag + " chained contextual substitution input coverage[" + i + "]", subtableOffset + igco ); } else { igct = null; } igca[i] = igct; } // read lookahead coverage tables GlyphCoverageTable[] lgca = new GlyphCoverageTable[nlg]; for ( int i = 0; i < nlg; i++ ) { int lgco = lgcoa [ i ]; GlyphCoverageTable lgct; if ( lgco > 0 ) { lgct = readCoverageTable ( tableTag + " chained contextual substitution lookahead coverage[" + i + "]", subtableOffset + lgco ); } else { lgct = null; } lgca[i] = lgct; } // read rule lookups String header = null; if (log.isDebugEnabled()) { header = tableTag + " chained contextual substitution lookups: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); // construct rule, rule set, and rule set array GlyphTable.Rule r = new GlyphTable.ChainedCoverageSequenceRule ( lookups, nig, igca, bgca, lgca ); GlyphTable.RuleSet rs = new GlyphTable.HomogeneousRuleSet ( new GlyphTable.Rule[] {r} ); GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet[] {rs}; // store results assert ( igca != null ) && ( igca.length > 0 ); seMapping = igca[0]; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readChainedContextualSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readChainedContextualSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readChainedContextualSubTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readChainedContextualSubTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported chained contextual substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readExtensionSubTableFormat1(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read extension lookup type int lt = in.readTTFUShort(); // read extension offset long eo = in.readTTFULong(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " extension substitution subtable format: " + subtableFormat ); log.debug(tableTag + " extension substitution lookup type: " + lt ); log.debug(tableTag + " extension substitution lookup table offset: " + eo ); } // read referenced subtable from extended offset readGSUBSubtable ( lt, lookupFlags, lookupSequence, subtableSequence, subtableOffset + eo ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readExtensionSubTable(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readExtensionSubTableFormat1 ( lookupType, lookupFlags, lookupSequence, subtableSequence, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported extension substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readReverseChainedSingleSubTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GSUB"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read backtrack glyph count int nbg = in.readTTFUShort(); // read backtrack glyph coverage offsets int[] bgcoa = new int [ nbg ]; for ( int i = 0; i < nbg; i++ ) { bgcoa [ i ] = in.readTTFUShort(); } // read lookahead glyph count int nlg = in.readTTFUShort(); // read backtrack glyph coverage offsets int[] lgcoa = new int [ nlg ]; for ( int i = 0; i < nlg; i++ ) { lgcoa [ i ] = in.readTTFUShort(); } // read substitution (output) glyph count int ng = in.readTTFUShort(); // read substitution (output) glyphs int[] glyphs = new int [ ng ]; for ( int i = 0, n = ng; i < n; i++ ) { glyphs [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " reverse chained contextual substitution format: " + subtableFormat ); log.debug(tableTag + " reverse chained contextual substitution coverage table offset: " + co ); log.debug(tableTag + " reverse chained contextual substitution backtrack glyph count: " + nbg ); for ( int i = 0; i < nbg; i++ ) { log.debug(tableTag + " reverse chained contextual substitution backtrack coverage table offset[" + i + "]: " + bgcoa[i] ); } log.debug(tableTag + " reverse chained contextual substitution lookahead glyph count: " + nlg ); for ( int i = 0; i < nlg; i++ ) { log.debug(tableTag + " reverse chained contextual substitution lookahead coverage table offset[" + i + "]: " + lgcoa[i] ); } log.debug(tableTag + " reverse chained contextual substitution glyphs: " + toString(glyphs) ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " reverse chained contextual substitution coverage", subtableOffset + co ); // read backtrack coverage tables GlyphCoverageTable[] bgca = new GlyphCoverageTable[nbg]; for ( int i = 0; i < nbg; i++ ) { int bgco = bgcoa[i]; GlyphCoverageTable bgct; if ( bgco > 0 ) { bgct = readCoverageTable ( tableTag + " reverse chained contextual substitution backtrack coverage[" + i + "]", subtableOffset + bgco ); } else { bgct = null; } bgca[i] = bgct; } // read lookahead coverage tables GlyphCoverageTable[] lgca = new GlyphCoverageTable[nlg]; for ( int i = 0; i < nlg; i++ ) { int lgco = lgcoa[i]; GlyphCoverageTable lgct; if ( lgco > 0 ) { lgct = readCoverageTable ( tableTag + " reverse chained contextual substitution lookahead coverage[" + i + "]", subtableOffset + lgco ); } else { lgct = null; } lgca[i] = lgct; } // store results seMapping = ct; seEntries.add ( bgca ); seEntries.add ( lgca ); seEntries.add ( glyphs ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readReverseChainedSingleSubTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read substitution subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readReverseChainedSingleSubTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported reverse chained single substitution subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGSUBSubtable(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset) throws IOException { initATSubState(); int subtableFormat = -1; switch ( lookupType ) { case GSUBLookupType.SINGLE: subtableFormat = readSingleSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.MULTIPLE: subtableFormat = readMultipleSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.ALTERNATE: subtableFormat = readAlternateSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.LIGATURE: subtableFormat = readLigatureSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.CONTEXTUAL: subtableFormat = readContextualSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.CHAINED_CONTEXTUAL: subtableFormat = readChainedContextualSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.REVERSE_CHAINED_SINGLE: subtableFormat = readReverseChainedSingleSubTable ( lookupType, lookupFlags, subtableOffset ); break; case GSUBLookupType.EXTENSION: subtableFormat = readExtensionSubTable ( lookupType, lookupFlags, lookupSequence, subtableSequence, subtableOffset ); break; default: break; } extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_SUBSTITUTION, lookupType, lookupFlags, lookupSequence, subtableSequence, subtableFormat ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphPositioningTable.DeviceTable readPosDeviceTable(long subtableOffset, long deviceTableOffset) throws IOException { long cp = in.getCurrentPos(); in.seekSet(subtableOffset + deviceTableOffset); // read start size int ss = in.readTTFUShort(); // read end size int es = in.readTTFUShort(); // read delta format int df = in.readTTFUShort(); int s1; int m1; int dm; int dd; int s2; if ( df == 1 ) { s1 = 14; m1 = 0x3; dm = 1; dd = 4; s2 = 2; } else if ( df == 2 ) { s1 = 12; m1 = 0xF; dm = 7; dd = 16; s2 = 4; } else if ( df == 3 ) { s1 = 8; m1 = 0xFF; dm = 127; dd = 256; s2 = 8; } else { log.debug ( "unsupported device table delta format: " + df + ", ignoring device table" ); return null; } // read deltas int n = ( es - ss ) + 1; if ( n < 0 ) { log.debug ( "invalid device table delta count: " + n + ", ignoring device table" ); return null; } int[] da = new int [ n ]; for ( int i = 0; ( i < n ) && ( s2 > 0 );) { int p = in.readTTFUShort(); for ( int j = 0, k = 16 / s2; j < k; j++ ) { int d = ( p >> s1 ) & m1; if ( d > dm ) { d -= dd; } if ( i < n ) { da [ i++ ] = d; } else { break; } p <<= s2; } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphPositioningTable.Value readPosValue(long subtableOffset, int valueFormat) throws IOException { // XPlacement int xp; if ( ( valueFormat & GlyphPositioningTable.Value.X_PLACEMENT ) != 0 ) { xp = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); } else { xp = 0; } // YPlacement int yp; if ( ( valueFormat & GlyphPositioningTable.Value.Y_PLACEMENT ) != 0 ) { yp = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); } else { yp = 0; } // XAdvance int xa; if ( ( valueFormat & GlyphPositioningTable.Value.X_ADVANCE ) != 0 ) { xa = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); } else { xa = 0; } // YAdvance int ya; if ( ( valueFormat & GlyphPositioningTable.Value.Y_ADVANCE ) != 0 ) { ya = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); } else { ya = 0; } // XPlaDevice GlyphPositioningTable.DeviceTable xpd; if ( ( valueFormat & GlyphPositioningTable.Value.X_PLACEMENT_DEVICE ) != 0 ) { int xpdo = in.readTTFUShort(); xpd = readPosDeviceTable ( subtableOffset, xpdo ); } else { xpd = null; } // YPlaDevice GlyphPositioningTable.DeviceTable ypd; if ( ( valueFormat & GlyphPositioningTable.Value.Y_PLACEMENT_DEVICE ) != 0 ) { int ypdo = in.readTTFUShort(); ypd = readPosDeviceTable ( subtableOffset, ypdo ); } else { ypd = null; } // XAdvDevice GlyphPositioningTable.DeviceTable xad; if ( ( valueFormat & GlyphPositioningTable.Value.X_ADVANCE_DEVICE ) != 0 ) { int xado = in.readTTFUShort(); xad = readPosDeviceTable ( subtableOffset, xado ); } else { xad = null; } // YAdvDevice GlyphPositioningTable.DeviceTable yad; if ( ( valueFormat & GlyphPositioningTable.Value.Y_ADVANCE_DEVICE ) != 0 ) { int yado = in.readTTFUShort(); yad = readPosDeviceTable ( subtableOffset, yado ); } else { yad = null; } return new GlyphPositioningTable.Value ( xp, yp, xa, ya, xpd, ypd, xad, yad ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readSinglePosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read value format int vf = in.readTTFUShort(); // read value GlyphPositioningTable.Value v = readPosValue ( subtableOffset, vf ); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " single positioning subtable format: " + subtableFormat + " (delta)" ); log.debug(tableTag + " single positioning coverage table offset: " + co ); log.debug(tableTag + " single positioning value: " + v ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " single positioning coverage", subtableOffset + co ); // store results seMapping = ct; seEntries.add ( v ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readSinglePosTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read value format int vf = in.readTTFUShort(); // read value count int nv = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " single positioning subtable format: " + subtableFormat + " (mapped)" ); log.debug(tableTag + " single positioning coverage table offset: " + co ); log.debug(tableTag + " single positioning value count: " + nv ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " single positioning coverage", subtableOffset + co ); // read positioning values GlyphPositioningTable.Value[] pva = new GlyphPositioningTable.Value[nv]; for ( int i = 0, n = nv; i < n; i++ ) { GlyphPositioningTable.Value pv = readPosValue ( subtableOffset, vf ); if (log.isDebugEnabled()) { log.debug(tableTag + " single positioning value[" + i + "]: " + pv ); } pva[i] = pv; } // store results seMapping = ct; seEntries.add ( pva ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readSinglePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positionining subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readSinglePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readSinglePosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported single positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphPositioningTable.PairValues readPosPairValues(long subtableOffset, boolean hasGlyph, int vf1, int vf2) throws IOException { // read glyph (if present) int glyph; if ( hasGlyph ) { glyph = in.readTTFUShort(); } else { glyph = 0; } // read first value (if present) GlyphPositioningTable.Value v1; if ( vf1 != 0 ) { v1 = readPosValue ( subtableOffset, vf1 ); } else { v1 = null; } // read second value (if present) GlyphPositioningTable.Value v2; if ( vf2 != 0 ) { v2 = readPosValue ( subtableOffset, vf2 ); } else { v2 = null; } return new GlyphPositioningTable.PairValues ( glyph, v1, v2 ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphPositioningTable.PairValues[] readPosPairSetTable(long subtableOffset, int pairSetTableOffset, int vf1, int vf2) throws IOException { String tableTag = "GPOS"; long cp = in.getCurrentPos(); in.seekSet(subtableOffset + pairSetTableOffset); // read pair values count int npv = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " pair set table offset: " + pairSetTableOffset ); log.debug(tableTag + " pair set table values count: " + npv ); } // read pair values GlyphPositioningTable.PairValues[] pva = new GlyphPositioningTable.PairValues [ npv ]; for ( int i = 0, n = npv; i < n; i++ ) { GlyphPositioningTable.PairValues pv = readPosPairValues ( subtableOffset, true, vf1, vf2 ); pva [ i ] = pv; if (log.isDebugEnabled()) { log.debug(tableTag + " pair set table value[" + i + "]: " + pv); } } in.seekSet(cp); return pva; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readPairPosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read value format for first glyph int vf1 = in.readTTFUShort(); // read value format for second glyph int vf2 = in.readTTFUShort(); // read number (count) of pair sets int nps = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " pair positioning subtable format: " + subtableFormat + " (glyphs)" ); log.debug(tableTag + " pair positioning coverage table offset: " + co ); log.debug(tableTag + " pair positioning value format #1: " + vf1 ); log.debug(tableTag + " pair positioning value format #2: " + vf2 ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " pair positioning coverage", subtableOffset + co ); // read pair value matrix GlyphPositioningTable.PairValues[][] pvm = new GlyphPositioningTable.PairValues [ nps ][]; for ( int i = 0, n = nps; i < n; i++ ) { // read pair set offset int pso = in.readTTFUShort(); // read pair set table at offset pvm [ i ] = readPosPairSetTable ( subtableOffset, pso, vf1, vf2 ); } // store results seMapping = ct; seEntries.add ( pvm ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readPairPosTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read value format for first glyph int vf1 = in.readTTFUShort(); // read value format for second glyph int vf2 = in.readTTFUShort(); // read class def 1 offset int cd1o = in.readTTFUShort(); // read class def 2 offset int cd2o = in.readTTFUShort(); // read number (count) of classes in class def 1 table int nc1 = in.readTTFUShort(); // read number (count) of classes in class def 2 table int nc2 = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " pair positioning subtable format: " + subtableFormat + " (glyph classes)" ); log.debug(tableTag + " pair positioning coverage table offset: " + co ); log.debug(tableTag + " pair positioning value format #1: " + vf1 ); log.debug(tableTag + " pair positioning value format #2: " + vf2 ); log.debug(tableTag + " pair positioning class def table #1 offset: " + cd1o ); log.debug(tableTag + " pair positioning class def table #2 offset: " + cd2o ); log.debug(tableTag + " pair positioning class #1 count: " + nc1 ); log.debug(tableTag + " pair positioning class #2 count: " + nc2 ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " pair positioning coverage", subtableOffset + co ); // read class definition table #1 GlyphClassTable cdt1 = readClassDefTable ( tableTag + " pair positioning class definition #1", subtableOffset + cd1o ); // read class definition table #2 GlyphClassTable cdt2 = readClassDefTable ( tableTag + " pair positioning class definition #2", subtableOffset + cd2o ); // read pair value matrix GlyphPositioningTable.PairValues[][] pvm = new GlyphPositioningTable.PairValues [ nc1 ] [ nc2 ]; for ( int i = 0; i < nc1; i++ ) { for ( int j = 0; j < nc2; j++ ) { GlyphPositioningTable.PairValues pv = readPosPairValues ( subtableOffset, false, vf1, vf2 ); pvm [ i ] [ j ] = pv; if (log.isDebugEnabled()) { log.debug(tableTag + " pair set table value[" + i + "][" + j + "]: " + pv); } } } // store results seMapping = ct; seEntries.add ( cdt1 ); seEntries.add ( cdt2 ); seEntries.add ( Integer.valueOf ( nc1 ) ); seEntries.add ( Integer.valueOf ( nc2 ) ); seEntries.add ( pvm ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readPairPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readPairPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readPairPosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported pair positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private GlyphPositioningTable.Anchor readPosAnchor(long anchorTableOffset) throws IOException { GlyphPositioningTable.Anchor a; long cp = in.getCurrentPos(); in.seekSet(anchorTableOffset); // read anchor table format int af = in.readTTFUShort(); if ( af == 1 ) { // read x coordinate int x = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read y coordinate int y = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); a = new GlyphPositioningTable.Anchor ( x, y ); } else if ( af == 2 ) { // read x coordinate int x = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read y coordinate int y = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read anchor point index int ap = in.readTTFUShort(); a = new GlyphPositioningTable.Anchor ( x, y, ap ); } else if ( af == 3 ) { // read x coordinate int x = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read y coordinate int y = ttf.convertTTFUnit2PDFUnit ( in.readTTFShort() ); // read x device table offset int xdo = in.readTTFUShort(); // read y device table offset int ydo = in.readTTFUShort(); // read x device table (if present) GlyphPositioningTable.DeviceTable xd; if ( xdo != 0 ) { xd = readPosDeviceTable ( cp, xdo ); } else { xd = null; } // read y device table (if present) GlyphPositioningTable.DeviceTable yd; if ( ydo != 0 ) { yd = readPosDeviceTable ( cp, ydo ); } else { yd = null; } a = new GlyphPositioningTable.Anchor ( x, y, xd, yd ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported positioning anchor format: " + af ); } in.seekSet(cp); return a; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readCursivePosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read entry/exit count int ec = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " cursive positioning subtable format: " + subtableFormat ); log.debug(tableTag + " cursive positioning coverage table offset: " + co ); log.debug(tableTag + " cursive positioning entry/exit count: " + ec ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " cursive positioning coverage", subtableOffset + co ); // read entry/exit records GlyphPositioningTable.Anchor[] aa = new GlyphPositioningTable.Anchor [ ec * 2 ]; for ( int i = 0, n = ec; i < n; i++ ) { // read entry anchor offset int eno = in.readTTFUShort(); // read exit anchor offset int exo = in.readTTFUShort(); // read entry anchor GlyphPositioningTable.Anchor ena; if ( eno > 0 ) { ena = readPosAnchor ( subtableOffset + eno ); } else { ena = null; } // read exit anchor GlyphPositioningTable.Anchor exa; if ( exo > 0 ) { exa = readPosAnchor ( subtableOffset + exo ); } else { exa = null; } aa [ ( i * 2 ) + 0 ] = ena; aa [ ( i * 2 ) + 1 ] = exa; if (log.isDebugEnabled()) { if ( ena != null ) { log.debug(tableTag + " cursive entry anchor [" + i + "]: " + ena ); } if ( exa != null ) { log.debug(tableTag + " cursive exit anchor [" + i + "]: " + exa ); } } } // store results seMapping = ct; seEntries.add ( aa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readCursivePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readCursivePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported cursive positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readMarkToBasePosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read mark coverage offset int mco = in.readTTFUShort(); // read base coverage offset int bco = in.readTTFUShort(); // read mark class count int nmc = in.readTTFUShort(); // read mark array offset int mao = in.readTTFUShort(); // read base array offset int bao = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-base positioning subtable format: " + subtableFormat ); log.debug(tableTag + " mark-to-base positioning mark coverage table offset: " + mco ); log.debug(tableTag + " mark-to-base positioning base coverage table offset: " + bco ); log.debug(tableTag + " mark-to-base positioning mark class count: " + nmc ); log.debug(tableTag + " mark-to-base positioning mark array offset: " + mao ); log.debug(tableTag + " mark-to-base positioning base array offset: " + bao ); } // read mark coverage table GlyphCoverageTable mct = readCoverageTable ( tableTag + " mark-to-base positioning mark coverage", subtableOffset + mco ); // read base coverage table GlyphCoverageTable bct = readCoverageTable ( tableTag + " mark-to-base positioning base coverage", subtableOffset + bco ); // read mark anchor array // seek to mark array in.seekSet(subtableOffset + mao); // read mark count int nm = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-base positioning mark count: " + nm ); } // read mark anchor array, where i:{0...markCount} GlyphPositioningTable.MarkAnchor[] maa = new GlyphPositioningTable.MarkAnchor [ nm ]; for ( int i = 0; i < nm; i++ ) { // read mark class int mc = in.readTTFUShort(); // read mark anchor offset int ao = in.readTTFUShort(); GlyphPositioningTable.Anchor a; if ( ao > 0 ) { a = readPosAnchor ( subtableOffset + mao + ao ); } else { a = null; } GlyphPositioningTable.MarkAnchor ma; if ( a != null ) { ma = new GlyphPositioningTable.MarkAnchor ( mc, a ); } else { ma = null; } maa [ i ] = ma; if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-base positioning mark anchor[" + i + "]: " + ma); } } // read base anchor matrix // seek to base array in.seekSet(subtableOffset + bao); // read base count int nb = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-base positioning base count: " + nb ); } // read anchor matrix, where i:{0...baseCount - 1}, j:{0...markClassCount - 1} GlyphPositioningTable.Anchor[][] bam = new GlyphPositioningTable.Anchor [ nb ] [ nmc ]; for ( int i = 0; i < nb; i++ ) { for ( int j = 0; j < nmc; j++ ) { // read base anchor offset int ao = in.readTTFUShort(); GlyphPositioningTable.Anchor a; if ( ao > 0 ) { a = readPosAnchor ( subtableOffset + bao + ao ); } else { a = null; } bam [ i ] [ j ] = a; if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-base positioning base anchor[" + i + "][" + j + "]: " + a); } } } // store results seMapping = mct; seEntries.add ( bct ); seEntries.add ( Integer.valueOf ( nmc ) ); seEntries.add ( maa ); seEntries.add ( bam ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMarkToBasePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMarkToBasePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark-to-base positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readMarkToLigaturePosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read mark coverage offset int mco = in.readTTFUShort(); // read ligature coverage offset int lco = in.readTTFUShort(); // read mark class count int nmc = in.readTTFUShort(); // read mark array offset int mao = in.readTTFUShort(); // read ligature array offset int lao = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-ligature positioning subtable format: " + subtableFormat ); log.debug(tableTag + " mark-to-ligature positioning mark coverage table offset: " + mco ); log.debug(tableTag + " mark-to-ligature positioning ligature coverage table offset: " + lco ); log.debug(tableTag + " mark-to-ligature positioning mark class count: " + nmc ); log.debug(tableTag + " mark-to-ligature positioning mark array offset: " + mao ); log.debug(tableTag + " mark-to-ligature positioning ligature array offset: " + lao ); } // read mark coverage table GlyphCoverageTable mct = readCoverageTable ( tableTag + " mark-to-ligature positioning mark coverage", subtableOffset + mco ); // read ligature coverage table GlyphCoverageTable lct = readCoverageTable ( tableTag + " mark-to-ligature positioning ligature coverage", subtableOffset + lco ); // read mark anchor array // seek to mark array in.seekSet(subtableOffset + mao); // read mark count int nm = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-ligature positioning mark count: " + nm ); } // read mark anchor array, where i:{0...markCount} GlyphPositioningTable.MarkAnchor[] maa = new GlyphPositioningTable.MarkAnchor [ nm ]; for ( int i = 0; i < nm; i++ ) { // read mark class int mc = in.readTTFUShort(); // read mark anchor offset int ao = in.readTTFUShort(); GlyphPositioningTable.Anchor a; if ( ao > 0 ) { a = readPosAnchor ( subtableOffset + mao + ao ); } else { a = null; } GlyphPositioningTable.MarkAnchor ma; if ( a != null ) { ma = new GlyphPositioningTable.MarkAnchor ( mc, a ); } else { ma = null; } maa [ i ] = ma; if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-ligature positioning mark anchor[" + i + "]: " + ma); } } // read ligature anchor matrix // seek to ligature array in.seekSet(subtableOffset + lao); // read ligature count int nl = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-ligature positioning ligature count: " + nl ); } // read ligature attach table offsets int[] laoa = new int [ nl ]; for ( int i = 0; i < nl; i++ ) { laoa [ i ] = in.readTTFUShort(); } // iterate over ligature attach tables, recording maximum component count int mxc = 0; for ( int i = 0; i < nl; i++ ) { int lato = laoa [ i ]; in.seekSet ( subtableOffset + lao + lato ); // read component count int cc = in.readTTFUShort(); if ( cc > mxc ) { mxc = cc; } } if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-ligature positioning maximum component count: " + mxc ); } // read anchor matrix, where i:{0...ligatureCount - 1}, j:{0...maxComponentCount - 1}, k:{0...markClassCount - 1} GlyphPositioningTable.Anchor[][][] lam = new GlyphPositioningTable.Anchor [ nl ][][]; for ( int i = 0; i < nl; i++ ) { int lato = laoa [ i ]; // seek to ligature attach table for ligature[i] in.seekSet ( subtableOffset + lao + lato ); // read component count int cc = in.readTTFUShort(); GlyphPositioningTable.Anchor[][] lcm = new GlyphPositioningTable.Anchor [ cc ] [ nmc ]; for ( int j = 0; j < cc; j++ ) { for ( int k = 0; k < nmc; k++ ) { // read ligature anchor offset int ao = in.readTTFUShort(); GlyphPositioningTable.Anchor a; if ( ao > 0 ) { a = readPosAnchor ( subtableOffset + lao + lato + ao ); } else { a = null; } lcm [ j ] [ k ] = a; if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-ligature positioning ligature anchor[" + i + "][" + j + "][" + k + "]: " + a); } } } lam [ i ] = lcm; } // store results seMapping = mct; seEntries.add ( lct ); seEntries.add ( Integer.valueOf ( nmc ) ); seEntries.add ( Integer.valueOf ( mxc ) ); seEntries.add ( maa ); seEntries.add ( lam ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMarkToLigaturePosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMarkToLigaturePosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark-to-ligature positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readMarkToMarkPosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read mark #1 coverage offset int m1co = in.readTTFUShort(); // read mark #2 coverage offset int m2co = in.readTTFUShort(); // read mark class count int nmc = in.readTTFUShort(); // read mark #1 array offset int m1ao = in.readTTFUShort(); // read mark #2 array offset int m2ao = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-mark positioning subtable format: " + subtableFormat ); log.debug(tableTag + " mark-to-mark positioning mark #1 coverage table offset: " + m1co ); log.debug(tableTag + " mark-to-mark positioning mark #2 coverage table offset: " + m2co ); log.debug(tableTag + " mark-to-mark positioning mark class count: " + nmc ); log.debug(tableTag + " mark-to-mark positioning mark #1 array offset: " + m1ao ); log.debug(tableTag + " mark-to-mark positioning mark #2 array offset: " + m2ao ); } // read mark #1 coverage table GlyphCoverageTable mct1 = readCoverageTable ( tableTag + " mark-to-mark positioning mark #1 coverage", subtableOffset + m1co ); // read mark #2 coverage table GlyphCoverageTable mct2 = readCoverageTable ( tableTag + " mark-to-mark positioning mark #2 coverage", subtableOffset + m2co ); // read mark #1 anchor array // seek to mark array in.seekSet(subtableOffset + m1ao); // read mark count int nm1 = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-mark positioning mark #1 count: " + nm1 ); } // read mark anchor array, where i:{0...mark1Count} GlyphPositioningTable.MarkAnchor[] maa = new GlyphPositioningTable.MarkAnchor [ nm1 ]; for ( int i = 0; i < nm1; i++ ) { // read mark class int mc = in.readTTFUShort(); // read mark anchor offset int ao = in.readTTFUShort(); GlyphPositioningTable.Anchor a; if ( ao > 0 ) { a = readPosAnchor ( subtableOffset + m1ao + ao ); } else { a = null; } GlyphPositioningTable.MarkAnchor ma; if ( a != null ) { ma = new GlyphPositioningTable.MarkAnchor ( mc, a ); } else { ma = null; } maa [ i ] = ma; if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-mark positioning mark #1 anchor[" + i + "]: " + ma); } } // read mark #2 anchor matrix // seek to mark #2 array in.seekSet(subtableOffset + m2ao); // read mark #2 count int nm2 = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-mark positioning mark #2 count: " + nm2 ); } // read anchor matrix, where i:{0...mark2Count - 1}, j:{0...markClassCount - 1} GlyphPositioningTable.Anchor[][] mam = new GlyphPositioningTable.Anchor [ nm2 ] [ nmc ]; for ( int i = 0; i < nm2; i++ ) { for ( int j = 0; j < nmc; j++ ) { // read mark anchor offset int ao = in.readTTFUShort(); GlyphPositioningTable.Anchor a; if ( ao > 0 ) { a = readPosAnchor ( subtableOffset + m2ao + ao ); } else { a = null; } mam [ i ] [ j ] = a; if (log.isDebugEnabled()) { log.debug(tableTag + " mark-to-mark positioning mark #2 anchor[" + i + "][" + j + "]: " + a); } } } // store results seMapping = mct1; seEntries.add ( mct2 ); seEntries.add ( Integer.valueOf ( nmc ) ); seEntries.add ( maa ); seEntries.add ( mam ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readMarkToMarkPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readMarkToMarkPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark-to-mark positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readContextualPosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read rule set count int nrs = in.readTTFUShort(); // read rule set offsets int[] rsoa = new int [ nrs ]; for ( int i = 0; i < nrs; i++ ) { rsoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " contextual positioning subtable format: " + subtableFormat + " (glyphs)" ); log.debug(tableTag + " contextual positioning coverage table offset: " + co ); log.debug(tableTag + " contextual positioning rule set count: " + nrs ); for ( int i = 0; i < nrs; i++ ) { log.debug(tableTag + " contextual positioning rule set offset[" + i + "]: " + rsoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " contextual positioning coverage", subtableOffset + co ); } else { ct = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ nrs ]; String header = null; for ( int i = 0; i < nrs; i++ ) { GlyphTable.RuleSet rs; int rso = rsoa [ i ]; if ( rso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + rso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { GlyphTable.GlyphSequenceRule r; int ro = roa [ j ]; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + rso + ro ); // read glyph count int ng = in.readTTFUShort(); // read rule lookup count int nl = in.readTTFUShort(); // read glyphs int[] glyphs = new int [ ng - 1 ]; for ( int k = 0, nk = glyphs.length; k < nk; k++ ) { glyphs [ k ] = in.readTTFUShort(); } // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual positioning lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.GlyphSequenceRule ( lookups, ng, glyphs ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readContextualPosTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read class def table offset int cdo = in.readTTFUShort(); // read class rule set count int ngc = in.readTTFUShort(); // read class rule set offsets int[] csoa = new int [ ngc ]; for ( int i = 0; i < ngc; i++ ) { csoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " contextual positioning subtable format: " + subtableFormat + " (glyph classes)" ); log.debug(tableTag + " contextual positioning coverage table offset: " + co ); log.debug(tableTag + " contextual positioning class set count: " + ngc ); for ( int i = 0; i < ngc; i++ ) { log.debug(tableTag + " contextual positioning class set offset[" + i + "]: " + csoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " contextual positioning coverage", subtableOffset + co ); } else { ct = null; } // read class definition table GlyphClassTable cdt; if ( cdo > 0 ) { cdt = readClassDefTable ( tableTag + " contextual positioning class definition", subtableOffset + cdo ); } else { cdt = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ ngc ]; String header = null; for ( int i = 0; i < ngc; i++ ) { int cso = csoa [ i ]; GlyphTable.RuleSet rs; if ( cso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + cso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { int ro = roa [ j ]; GlyphTable.ClassSequenceRule r; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + cso + ro ); // read glyph count int ng = in.readTTFUShort(); // read rule lookup count int nl = in.readTTFUShort(); // read classes int[] classes = new int [ ng - 1 ]; for ( int k = 0, nk = classes.length; k < nk; k++ ) { classes [ k ] = in.readTTFUShort(); } // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual positioning lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.ClassSequenceRule ( lookups, ng, classes ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( cdt ); seEntries.add ( Integer.valueOf ( ngc ) ); seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readContextualPosTableFormat3(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read glyph (input sequence length) count int ng = in.readTTFUShort(); // read positioning lookup count int nl = in.readTTFUShort(); // read glyph coverage offsets, one per glyph input sequence length count int[] gcoa = new int [ ng ]; for ( int i = 0; i < ng; i++ ) { gcoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " contextual positioning subtable format: " + subtableFormat + " (glyph sets)" ); log.debug(tableTag + " contextual positioning glyph input sequence length count: " + ng ); log.debug(tableTag + " contextual positioning lookup count: " + nl ); for ( int i = 0; i < ng; i++ ) { log.debug(tableTag + " contextual positioning coverage table offset[" + i + "]: " + gcoa[i] ); } } // read coverage tables GlyphCoverageTable[] gca = new GlyphCoverageTable [ ng ]; for ( int i = 0; i < ng; i++ ) { int gco = gcoa [ i ]; GlyphCoverageTable gct; if ( gco > 0 ) { gct = readCoverageTable ( tableTag + " contextual positioning coverage[" + i + "]", subtableOffset + gcoa[i] ); } else { gct = null; } gca [ i ] = gct; } // read rule lookups String header = null; if (log.isDebugEnabled()) { header = tableTag + " contextual positioning lookups: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); // construct rule, rule set, and rule set array GlyphTable.Rule r = new GlyphTable.CoverageSequenceRule ( lookups, ng, gca ); GlyphTable.RuleSet rs = new GlyphTable.HomogeneousRuleSet ( new GlyphTable.Rule[] {r} ); GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet[] {rs}; // store results assert ( gca != null ) && ( gca.length > 0 ); seMapping = gca[0]; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readContextualPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readContextualPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readContextualPosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readContextualPosTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported contextual positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readChainedContextualPosTableFormat1(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read rule set count int nrs = in.readTTFUShort(); // read rule set offsets int[] rsoa = new int [ nrs ]; for ( int i = 0; i < nrs; i++ ) { rsoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " chained contextual positioning subtable format: " + subtableFormat + " (glyphs)" ); log.debug(tableTag + " chained contextual positioning coverage table offset: " + co ); log.debug(tableTag + " chained contextual positioning rule set count: " + nrs ); for ( int i = 0; i < nrs; i++ ) { log.debug(tableTag + " chained contextual positioning rule set offset[" + i + "]: " + rsoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " chained contextual positioning coverage", subtableOffset + co ); } else { ct = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ nrs ]; String header = null; for ( int i = 0; i < nrs; i++ ) { GlyphTable.RuleSet rs; int rso = rsoa [ i ]; if ( rso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + rso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { GlyphTable.ChainedGlyphSequenceRule r; int ro = roa [ j ]; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + rso + ro ); // read backtrack glyph count int nbg = in.readTTFUShort(); // read backtrack glyphs int[] backtrackGlyphs = new int [ nbg ]; for ( int k = 0, nk = backtrackGlyphs.length; k < nk; k++ ) { backtrackGlyphs [ k ] = in.readTTFUShort(); } // read input glyph count int nig = in.readTTFUShort(); // read glyphs int[] glyphs = new int [ nig - 1 ]; for ( int k = 0, nk = glyphs.length; k < nk; k++ ) { glyphs [ k ] = in.readTTFUShort(); } // read lookahead glyph count int nlg = in.readTTFUShort(); // read lookahead glyphs int[] lookaheadGlyphs = new int [ nlg ]; for ( int k = 0, nk = lookaheadGlyphs.length; k < nk; k++ ) { lookaheadGlyphs [ k ] = in.readTTFUShort(); } // read rule lookup count int nl = in.readTTFUShort(); // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual positioning lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.ChainedGlyphSequenceRule ( lookups, nig, glyphs, backtrackGlyphs, lookaheadGlyphs ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readChainedContextualPosTableFormat2(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read coverage offset int co = in.readTTFUShort(); // read backtrack class def table offset int bcdo = in.readTTFUShort(); // read input class def table offset int icdo = in.readTTFUShort(); // read lookahead class def table offset int lcdo = in.readTTFUShort(); // read class set count int ngc = in.readTTFUShort(); // read class set offsets int[] csoa = new int [ ngc ]; for ( int i = 0; i < ngc; i++ ) { csoa [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " chained contextual positioning subtable format: " + subtableFormat + " (glyph classes)" ); log.debug(tableTag + " chained contextual positioning coverage table offset: " + co ); log.debug(tableTag + " chained contextual positioning class set count: " + ngc ); for ( int i = 0; i < ngc; i++ ) { log.debug(tableTag + " chained contextual positioning class set offset[" + i + "]: " + csoa[i] ); } } // read coverage table GlyphCoverageTable ct; if ( co > 0 ) { ct = readCoverageTable ( tableTag + " chained contextual positioning coverage", subtableOffset + co ); } else { ct = null; } // read backtrack class definition table GlyphClassTable bcdt; if ( bcdo > 0 ) { bcdt = readClassDefTable ( tableTag + " contextual positioning backtrack class definition", subtableOffset + bcdo ); } else { bcdt = null; } // read input class definition table GlyphClassTable icdt; if ( icdo > 0 ) { icdt = readClassDefTable ( tableTag + " contextual positioning input class definition", subtableOffset + icdo ); } else { icdt = null; } // read lookahead class definition table GlyphClassTable lcdt; if ( lcdo > 0 ) { lcdt = readClassDefTable ( tableTag + " contextual positioning lookahead class definition", subtableOffset + lcdo ); } else { lcdt = null; } // read rule sets GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet [ ngc ]; String header = null; for ( int i = 0; i < ngc; i++ ) { int cso = csoa [ i ]; GlyphTable.RuleSet rs; if ( cso > 0 ) { // seek to rule set [ i ] in.seekSet ( subtableOffset + cso ); // read rule count int nr = in.readTTFUShort(); // read rule offsets int[] roa = new int [ nr ]; GlyphTable.Rule[] ra = new GlyphTable.Rule [ nr ]; for ( int j = 0; j < nr; j++ ) { roa [ j ] = in.readTTFUShort(); } // read glyph sequence rules for ( int j = 0; j < nr; j++ ) { GlyphTable.ChainedClassSequenceRule r; int ro = roa [ j ]; if ( ro > 0 ) { // seek to rule [ j ] in.seekSet ( subtableOffset + cso + ro ); // read backtrack glyph class count int nbc = in.readTTFUShort(); // read backtrack glyph classes int[] backtrackClasses = new int [ nbc ]; for ( int k = 0, nk = backtrackClasses.length; k < nk; k++ ) { backtrackClasses [ k ] = in.readTTFUShort(); } // read input glyph class count int nic = in.readTTFUShort(); // read input glyph classes int[] classes = new int [ nic - 1 ]; for ( int k = 0, nk = classes.length; k < nk; k++ ) { classes [ k ] = in.readTTFUShort(); } // read lookahead glyph class count int nlc = in.readTTFUShort(); // read lookahead glyph classes int[] lookaheadClasses = new int [ nlc ]; for ( int k = 0, nk = lookaheadClasses.length; k < nk; k++ ) { lookaheadClasses [ k ] = in.readTTFUShort(); } // read rule lookup count int nl = in.readTTFUShort(); // read rule lookups if (log.isDebugEnabled()) { header = tableTag + " contextual positioning lookups @rule[" + i + "][" + j + "]: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); r = new GlyphTable.ChainedClassSequenceRule ( lookups, nic, classes, backtrackClasses, lookaheadClasses ); } else { r = null; } ra [ j ] = r; } rs = new GlyphTable.HomogeneousRuleSet ( ra ); } else { rs = null; } rsa [ i ] = rs; } // store results seMapping = ct; seEntries.add ( icdt ); seEntries.add ( bcdt ); seEntries.add ( lcdt ); seEntries.add ( Integer.valueOf ( ngc ) ); seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readChainedContextualPosTableFormat3(int lookupType, int lookupFlags, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read backtrack glyph count int nbg = in.readTTFUShort(); // read backtrack glyph coverage offsets int[] bgcoa = new int [ nbg ]; for ( int i = 0; i < nbg; i++ ) { bgcoa [ i ] = in.readTTFUShort(); } // read input glyph count int nig = in.readTTFUShort(); // read backtrack glyph coverage offsets int[] igcoa = new int [ nig ]; for ( int i = 0; i < nig; i++ ) { igcoa [ i ] = in.readTTFUShort(); } // read lookahead glyph count int nlg = in.readTTFUShort(); // read backtrack glyph coverage offsets int[] lgcoa = new int [ nlg ]; for ( int i = 0; i < nlg; i++ ) { lgcoa [ i ] = in.readTTFUShort(); } // read positioning lookup count int nl = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " chained contextual positioning subtable format: " + subtableFormat + " (glyph sets)" ); log.debug(tableTag + " chained contextual positioning backtrack glyph count: " + nbg ); for ( int i = 0; i < nbg; i++ ) { log.debug(tableTag + " chained contextual positioning backtrack coverage table offset[" + i + "]: " + bgcoa[i] ); } log.debug(tableTag + " chained contextual positioning input glyph count: " + nig ); for ( int i = 0; i < nig; i++ ) { log.debug(tableTag + " chained contextual positioning input coverage table offset[" + i + "]: " + igcoa[i] ); } log.debug(tableTag + " chained contextual positioning lookahead glyph count: " + nlg ); for ( int i = 0; i < nlg; i++ ) { log.debug(tableTag + " chained contextual positioning lookahead coverage table offset[" + i + "]: " + lgcoa[i] ); } log.debug(tableTag + " chained contextual positioning lookup count: " + nl ); } // read backtrack coverage tables GlyphCoverageTable[] bgca = new GlyphCoverageTable[nbg]; for ( int i = 0; i < nbg; i++ ) { int bgco = bgcoa [ i ]; GlyphCoverageTable bgct; if ( bgco > 0 ) { bgct = readCoverageTable ( tableTag + " chained contextual positioning backtrack coverage[" + i + "]", subtableOffset + bgco ); } else { bgct = null; } bgca[i] = bgct; } // read input coverage tables GlyphCoverageTable[] igca = new GlyphCoverageTable[nig]; for ( int i = 0; i < nig; i++ ) { int igco = igcoa [ i ]; GlyphCoverageTable igct; if ( igco > 0 ) { igct = readCoverageTable ( tableTag + " chained contextual positioning input coverage[" + i + "]", subtableOffset + igco ); } else { igct = null; } igca[i] = igct; } // read lookahead coverage tables GlyphCoverageTable[] lgca = new GlyphCoverageTable[nlg]; for ( int i = 0; i < nlg; i++ ) { int lgco = lgcoa [ i ]; GlyphCoverageTable lgct; if ( lgco > 0 ) { lgct = readCoverageTable ( tableTag + " chained contextual positioning lookahead coverage[" + i + "]", subtableOffset + lgco ); } else { lgct = null; } lgca[i] = lgct; } // read rule lookups String header = null; if (log.isDebugEnabled()) { header = tableTag + " chained contextual positioning lookups: "; } GlyphTable.RuleLookup[] lookups = readRuleLookups ( nl, header ); // construct rule, rule set, and rule set array GlyphTable.Rule r = new GlyphTable.ChainedCoverageSequenceRule ( lookups, nig, igca, bgca, lgca ); GlyphTable.RuleSet rs = new GlyphTable.HomogeneousRuleSet ( new GlyphTable.Rule[] {r} ); GlyphTable.RuleSet[] rsa = new GlyphTable.RuleSet[] {rs}; // store results assert ( igca != null ) && ( igca.length > 0 ); seMapping = igca[0]; seEntries.add ( rsa ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readChainedContextualPosTable(int lookupType, int lookupFlags, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readChainedContextualPosTableFormat1 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 2 ) { readChainedContextualPosTableFormat2 ( lookupType, lookupFlags, subtableOffset, sf ); } else if ( sf == 3 ) { readChainedContextualPosTableFormat3 ( lookupType, lookupFlags, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported chained contextual positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readExtensionPosTableFormat1(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset, int subtableFormat) throws IOException { String tableTag = "GPOS"; in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read extension lookup type int lt = in.readTTFUShort(); // read extension offset long eo = in.readTTFULong(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " extension positioning subtable format: " + subtableFormat ); log.debug(tableTag + " extension positioning lookup type: " + lt ); log.debug(tableTag + " extension positioning lookup table offset: " + eo ); } // read referenced subtable from extended offset readGPOSSubtable ( lt, lookupFlags, lookupSequence, subtableSequence, subtableOffset + eo ); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private int readExtensionPosTable(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read positioning subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readExtensionPosTableFormat1 ( lookupType, lookupFlags, lookupSequence, subtableSequence, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported extension positioning subtable format: " + sf ); } return sf; }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGPOSSubtable(int lookupType, int lookupFlags, int lookupSequence, int subtableSequence, long subtableOffset) throws IOException { initATSubState(); int subtableFormat = -1; switch ( lookupType ) { case GPOSLookupType.SINGLE: subtableFormat = readSinglePosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.PAIR: subtableFormat = readPairPosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.CURSIVE: subtableFormat = readCursivePosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.MARK_TO_BASE: subtableFormat = readMarkToBasePosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.MARK_TO_LIGATURE: subtableFormat = readMarkToLigaturePosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.MARK_TO_MARK: subtableFormat = readMarkToMarkPosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.CONTEXTUAL: subtableFormat = readContextualPosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.CHAINED_CONTEXTUAL: subtableFormat = readChainedContextualPosTable ( lookupType, lookupFlags, subtableOffset ); break; case GPOSLookupType.EXTENSION: subtableFormat = readExtensionPosTable ( lookupType, lookupFlags, lookupSequence, subtableSequence, subtableOffset ); break; default: break; } extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_POSITIONING, lookupType, lookupFlags, lookupSequence, subtableSequence, subtableFormat ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readLookupTable(String tableTag, int lookupSequence, long lookupTable) throws IOException { boolean isGSUB = tableTag.equals ( "GSUB" ); boolean isGPOS = tableTag.equals ( "GPOS" ); in.seekSet(lookupTable); // read lookup type int lt = in.readTTFUShort(); // read lookup flags int lf = in.readTTFUShort(); // read sub-table count int ns = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { String lts; if ( isGSUB ) { lts = GSUBLookupType.toString ( lt ); } else if ( isGPOS ) { lts = GPOSLookupType.toString ( lt ); } else { lts = "?"; } log.debug(tableTag + " lookup table type: " + lt + " (" + lts + ")" ); log.debug(tableTag + " lookup table flags: " + lf + " (" + LookupFlag.toString ( lf ) + ")" ); log.debug(tableTag + " lookup table subtable count: " + ns ); } // read subtable offsets int[] soa = new int[ns]; for ( int i = 0; i < ns; i++ ) { int so = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " lookup table subtable offset: " + so ); } soa[i] = so; } // read mark filtering set if ( ( lf & LookupFlag.USE_MARK_FILTERING_SET ) != 0 ) { // read mark filtering set int fs = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " lookup table mark filter set: " + fs ); } } // read subtables for ( int i = 0; i < ns; i++ ) { int so = soa[i]; if ( isGSUB ) { readGSUBSubtable ( lt, lf, lookupSequence, i, lookupTable + so ); } else if ( isGPOS ) { readGPOSSubtable ( lt, lf, lookupSequence, i, lookupTable + so ); } } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readLookupList(String tableTag, long lookupList) throws IOException { in.seekSet(lookupList); // read lookup record count int nl = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " lookup list record count: " + nl ); } if ( nl > 0 ) { int[] loa = new int[nl]; // read lookup records for ( int i = 0, n = nl; i < n; i++ ) { int lo = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " lookup table offset: " + lo ); } loa[i] = lo; } // read lookup tables for ( int i = 0, n = nl; i < n; i++ ) { if (log.isDebugEnabled()) { log.debug(tableTag + " lookup index: " + i ); } readLookupTable ( tableTag, i, lookupList + loa [ i ] ); } } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readCommonLayoutTables(String tableTag, long scriptList, long featureList, long lookupList) throws IOException { if ( scriptList > 0 ) { readScriptList ( tableTag, scriptList ); } if ( featureList > 0 ) { readFeatureList ( tableTag, featureList ); } if ( lookupList > 0 ) { readLookupList ( tableTag, lookupList ); } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFClassDefTable(String tableTag, int lookupSequence, long subtableOffset) throws IOException { initATSubState(); in.seekSet(subtableOffset); // subtable is a bare class definition table GlyphClassTable ct = readClassDefTable ( tableTag + " glyph class definition table", subtableOffset ); // store results seMapping = ct; // extract subtable extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_DEFINITION, GDEFLookupType.GLYPH_CLASS, 0, lookupSequence, 0, 1 ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFAttachmentTable(String tableTag, int lookupSequence, long subtableOffset) throws IOException { initATSubState(); in.seekSet(subtableOffset); // read coverage offset int co = in.readTTFUShort(); // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " attachment point coverage table offset: " + co ); } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " attachment point coverage", subtableOffset + co ); // store results seMapping = ct; // extract subtable extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_DEFINITION, GDEFLookupType.ATTACHMENT_POINT, 0, lookupSequence, 0, 1 ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFLigatureCaretTable(String tableTag, int lookupSequence, long subtableOffset) throws IOException { initATSubState(); in.seekSet(subtableOffset); // read coverage offset int co = in.readTTFUShort(); // read ligature glyph count int nl = in.readTTFUShort(); // read ligature glyph table offsets int[] lgto = new int [ nl ]; for ( int i = 0; i < nl; i++ ) { lgto [ i ] = in.readTTFUShort(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " ligature caret coverage table offset: " + co ); log.debug(tableTag + " ligature caret ligature glyph count: " + nl ); for ( int i = 0; i < nl; i++ ) { log.debug(tableTag + " ligature glyph table offset[" + i + "]: " + lgto[i] ); } } // read coverage table GlyphCoverageTable ct = readCoverageTable ( tableTag + " ligature caret coverage", subtableOffset + co ); // store results seMapping = ct; // extract subtable extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_DEFINITION, GDEFLookupType.LIGATURE_CARET, 0, lookupSequence, 0, 1 ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFMarkAttachmentTable(String tableTag, int lookupSequence, long subtableOffset) throws IOException { initATSubState(); in.seekSet(subtableOffset); // subtable is a bare class definition table GlyphClassTable ct = readClassDefTable ( tableTag + " glyph class definition table", subtableOffset ); // store results seMapping = ct; // extract subtable extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_DEFINITION, GDEFLookupType.MARK_ATTACHMENT, 0, lookupSequence, 0, 1 ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFMarkGlyphsTableFormat1(String tableTag, int lookupSequence, long subtableOffset, int subtableFormat) throws IOException { initATSubState(); in.seekSet(subtableOffset); // skip over format (already known) in.skip ( 2 ); // read mark set class count int nmc = in.readTTFUShort(); long[] mso = new long [ nmc ]; // read mark set coverage offsets for ( int i = 0; i < nmc; i++ ) { mso [ i ] = in.readTTFULong(); } // dump info if debugging if (log.isDebugEnabled()) { log.debug(tableTag + " mark set subtable format: " + subtableFormat + " (glyph sets)" ); log.debug(tableTag + " mark set class count: " + nmc ); for ( int i = 0; i < nmc; i++ ) { log.debug(tableTag + " mark set coverage table offset[" + i + "]: " + mso[i] ); } } // read mark set coverage tables, one per class GlyphCoverageTable[] msca = new GlyphCoverageTable[nmc]; for ( int i = 0; i < nmc; i++ ) { msca[i] = readCoverageTable ( tableTag + " mark set coverage[" + i + "]", subtableOffset + mso[i] ); } // create combined class table from per-class coverage tables GlyphClassTable ct = GlyphClassTable.createClassTable ( Arrays.asList ( msca ) ); // store results seMapping = ct; // extract subtable extractSESubState ( GlyphTable.GLYPH_TABLE_TYPE_DEFINITION, GDEFLookupType.MARK_ATTACHMENT, 0, lookupSequence, 0, 1 ); resetATSubState(); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEFMarkGlyphsTable(String tableTag, int lookupSequence, long subtableOffset) throws IOException { in.seekSet(subtableOffset); // read mark set subtable format int sf = in.readTTFUShort(); if ( sf == 1 ) { readGDEFMarkGlyphsTableFormat1 ( tableTag, lookupSequence, subtableOffset, sf ); } else { throw new AdvancedTypographicTableFormatException ( "unsupported mark glyph sets subtable format: " + sf ); } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGDEF() throws IOException { String tableTag = "GDEF"; // Initialize temporary state initATState(); // Read glyph definition (GDEF) table TTFDirTabEntry dirTab = ttf.getDirectoryEntry ( tableTag ); if ( gdef != null ) { if (log.isDebugEnabled()) { log.debug(tableTag + ": ignoring duplicate table"); } } else if (dirTab != null) { ttf.seekTab(in, tableTag, 0); long version = in.readTTFULong(); if (log.isDebugEnabled()) { log.debug(tableTag + " version: " + ( version / 65536 ) + "." + ( version % 65536 )); } // glyph class definition table offset (may be null) int cdo = in.readTTFUShort(); // attach point list offset (may be null) int apo = in.readTTFUShort(); // ligature caret list offset (may be null) int lco = in.readTTFUShort(); // mark attach class definition table offset (may be null) int mao = in.readTTFUShort(); // mark glyph sets definition table offset (may be null) int mgo; if ( version >= 0x00010002 ) { mgo = in.readTTFUShort(); } else { mgo = 0; } if (log.isDebugEnabled()) { log.debug(tableTag + " glyph class definition table offset: " + cdo ); log.debug(tableTag + " attachment point list offset: " + apo ); log.debug(tableTag + " ligature caret list offset: " + lco ); log.debug(tableTag + " mark attachment class definition table offset: " + mao ); log.debug(tableTag + " mark glyph set definitions table offset: " + mgo ); } // initialize subtable sequence number int seqno = 0; // obtain offset to start of gdef table long to = dirTab.getOffset(); // (optionally) read glyph class definition subtable if ( cdo != 0 ) { readGDEFClassDefTable ( tableTag, seqno++, to + cdo ); } // (optionally) read glyph attachment point subtable if ( apo != 0 ) { readGDEFAttachmentTable ( tableTag, seqno++, to + apo ); } // (optionally) read ligature caret subtable if ( lco != 0 ) { readGDEFLigatureCaretTable ( tableTag, seqno++, to + lco ); } // (optionally) read mark attachment class subtable if ( mao != 0 ) { readGDEFMarkAttachmentTable ( tableTag, seqno++, to + mao ); } // (optionally) read mark glyph sets subtable if ( mgo != 0 ) { readGDEFMarkGlyphsTable ( tableTag, seqno++, to + mgo ); } GlyphDefinitionTable gdef; if ( ( gdef = constructGDEF() ) != null ) { this.gdef = gdef; } } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGSUB() throws IOException { String tableTag = "GSUB"; // Initialize temporary state initATState(); // Read glyph substitution (GSUB) table TTFDirTabEntry dirTab = ttf.getDirectoryEntry ( tableTag ); if ( gpos != null ) { if (log.isDebugEnabled()) { log.debug(tableTag + ": ignoring duplicate table"); } } else if (dirTab != null) { ttf.seekTab(in, tableTag, 0); int version = in.readTTFLong(); if (log.isDebugEnabled()) { log.debug(tableTag + " version: " + ( version / 65536 ) + "." + ( version % 65536 )); } int slo = in.readTTFUShort(); int flo = in.readTTFUShort(); int llo = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " script list offset: " + slo ); log.debug(tableTag + " feature list offset: " + flo ); log.debug(tableTag + " lookup list offset: " + llo ); } long to = dirTab.getOffset(); readCommonLayoutTables ( tableTag, to + slo, to + flo, to + llo ); GlyphSubstitutionTable gsub; if ( ( gsub = constructGSUB() ) != null ) { this.gsub = gsub; } } }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
private void readGPOS() throws IOException { String tableTag = "GPOS"; // Initialize temporary state initATState(); // Read glyph positioning (GPOS) table TTFDirTabEntry dirTab = ttf.getDirectoryEntry ( tableTag ); if ( gpos != null ) { if (log.isDebugEnabled()) { log.debug(tableTag + ": ignoring duplicate table"); } } else if (dirTab != null) { ttf.seekTab(in, tableTag, 0); int version = in.readTTFLong(); if (log.isDebugEnabled()) { log.debug(tableTag + " version: " + ( version / 65536 ) + "." + ( version % 65536 )); } int slo = in.readTTFUShort(); int flo = in.readTTFUShort(); int llo = in.readTTFUShort(); if (log.isDebugEnabled()) { log.debug(tableTag + " script list offset: " + slo ); log.debug(tableTag + " feature list offset: " + flo ); log.debug(tableTag + " lookup list offset: " + llo ); } long to = dirTab.getOffset(); readCommonLayoutTables ( tableTag, to + slo, to + flo, to + llo ); GlyphPositioningTable gpos; if ( ( gpos = constructGPOS() ) != null ) { this.gpos = gpos; } } }
// in src/java/org/apache/fop/util/DataURLUtil.java
public static String createDataURL(InputStream in, String mediatype) throws IOException { return org.apache.xmlgraphics.util.uri.DataURLUtil.createDataURL(in, mediatype); }
// in src/java/org/apache/fop/util/DataURLUtil.java
public static void writeDataURL(InputStream in, String mediatype, Writer writer) throws IOException { org.apache.xmlgraphics.util.uri.DataURLUtil.writeDataURL(in, mediatype, writer); }
// in src/java/org/apache/fop/util/WriterOutputStream.java
public void close() throws IOException { writerOutputStream.close(); }
// in src/java/org/apache/fop/util/WriterOutputStream.java
public void flush() throws IOException { writerOutputStream.flush(); }
// in src/java/org/apache/fop/util/WriterOutputStream.java
public void write(byte[] buf, int offset, int length) throws IOException { writerOutputStream.write(buf, offset, length); }
// in src/java/org/apache/fop/util/WriterOutputStream.java
public void write(byte[] buf) throws IOException { writerOutputStream.write(buf); }
// in src/java/org/apache/fop/util/WriterOutputStream.java
public void write(int b) throws IOException { writerOutputStream.write(b); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (entityResolver != null) { return entityResolver.resolveEntity(publicId, systemId); } else { return null; } }
// in src/java/org/apache/fop/util/CloseBlockerOutputStream.java
public void close() throws IOException { try { flush(); } catch (IOException ioe) { //ignore } }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
public ImageInfo preloadImage(String uri, Source src, ImageContext context) throws IOException { if (!ImageUtil.hasInputStream(src)) { return null; } ImageInfo info = null; if (batikAvailable) { try { Loader loader = new Loader(); info = loader.getImage(uri, src, context); } catch (NoClassDefFoundError e) { batikAvailable = false; log.warn("Batik not in class path", e); return null; } } if (info != null) { ImageUtil.closeQuietly(src); //Image is fully read } return info; }
// in src/java/org/apache/fop/image/loader/batik/ImageLoaderSVG.java
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!MimeConstants.MIME_SVG.equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from an SVG image"); } Image img = info.getOriginalImage(); if (!(img instanceof ImageXMLDOM)) { throw new IllegalArgumentException( "ImageInfo was expected to contain the SVG document as DOM"); } ImageXMLDOM svgImage = (ImageXMLDOM)img; if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(svgImage.getRootNamespace())) { throw new IllegalArgumentException( "The Image is not in the SVG namespace: " + svgImage.getRootNamespace()); } return svgImage; }
// in src/java/org/apache/fop/image/loader/batik/ImageLoaderWMF.java
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!ImageWMF.MIME_WMF.equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from a WMF image"); } Image img = info.getOriginalImage(); if (!(img instanceof ImageWMF)) { throw new IllegalArgumentException( "ImageInfo was expected to contain the Windows Metafile (WMF)"); } ImageWMF wmfImage = (ImageWMF)img; return wmfImage; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
public ImageInfo preloadImage(String uri, Source src, ImageContext context) throws IOException { ImageInfo info = null; if (batikAvailable) { try { Loader loader = new Loader(); if (!loader.isSupportedSource(src)) { return null; } info = loader.getImage(uri, src, context); } catch (NoClassDefFoundError e) { batikAvailable = false; log.warn("Batik not in class path", e); return null; } } if (info != null) { ImageUtil.closeQuietly(src); //Image is fully read } return info; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
public boolean parse(String[] args) throws FOPException, IOException { boolean optionsParsed = true; try { optionsParsed = parseOptions(args); if (optionsParsed) { if (showConfiguration == Boolean.TRUE) { dumpConfiguration(); } checkSettings(); setUserConfig(); if (flushCache) { flushCache(); } //Factory config is set up, now we can create the user agent foUserAgent = factory.newFOUserAgent(); foUserAgent.getRendererOptions().putAll(renderingOptions); if (targetResolution != 0) { foUserAgent.setTargetResolution(targetResolution); } addXSLTParameter("fop-output-format", getOutputFormat()); addXSLTParameter("fop-version", Version.getVersion()); foUserAgent.setConserveMemoryPolicy(conserveMemoryPolicy); if (!useComplexScriptFeatures) { foUserAgent.setComplexScriptFeaturesEnabled(false); } } else { return false; } } catch (FOPException e) { printUsage(System.err); throw e; } catch (java.io.FileNotFoundException e) { printUsage(System.err); throw e; } inputHandler = createInputHandler(); if (MimeConstants.MIME_FOP_AWT_PREVIEW.equals(outputmode)) { //set the system look&feel for the preview dialog try { UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName()); } catch (Exception e) { System.err.println("Couldn't set system look & feel!"); } AWTRenderer renderer = new AWTRenderer(foUserAgent, inputHandler, true, true); foUserAgent.setRendererOverride(renderer); } else if (MimeConstants.MIME_FOP_AREA_TREE.equals(outputmode) && mimicRenderer != null) { // render from FO to Intermediate Format Renderer targetRenderer = foUserAgent.getRendererFactory().createRenderer( foUserAgent, mimicRenderer); XMLRenderer xmlRenderer = new XMLRenderer(foUserAgent); //Tell the XMLRenderer to mimic the target renderer xmlRenderer.mimicRenderer(targetRenderer); //Make sure the prepared XMLRenderer is used foUserAgent.setRendererOverride(xmlRenderer); } else if (MimeConstants.MIME_FOP_IF.equals(outputmode) && mimicRenderer != null) { // render from FO to Intermediate Format IFSerializer serializer = new IFSerializer(); serializer.setContext(new IFContext(foUserAgent)); IFDocumentHandler targetHandler = foUserAgent.getRendererFactory().createDocumentHandler( foUserAgent, mimicRenderer); serializer.mimicDocumentHandler(targetHandler); //Make sure the prepared serializer is used foUserAgent.setDocumentHandlerOverride(serializer); } return true; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private void setUserConfig() throws FOPException, IOException { if (userConfigFile == null) { return; } try { factory.setUserConfig(userConfigFile); } catch (SAXException e) { throw new FOPException(e); } }
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void writeGenerated(Writer w) throws IOException { w.write("<!-- !!! THIS IS A GENERATED FILE !!! -->\n"); w.write("<!-- If updates are needed, then: -->\n"); w.write("<!-- * run 'ant codegen-hyphenation-classes', -->\n"); w.write("<!-- which will generate a new file classes.xml -->\n"); w.write("<!-- in 'src/java/org/apache/fop/hyphenation' -->\n"); w.write("<!-- * commit the changed file -->\n"); }
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void fromJava(boolean hexcode, String outfilePath) throws IOException { File f = new File(outfilePath); if (f.exists()) { f.delete(); } f.createNewFile(); FileOutputStream fw = new FileOutputStream(f); OutputStreamWriter ow = new OutputStreamWriter(fw, "utf-8"); int maxChar; maxChar = Character.MAX_VALUE; ow.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); License.writeXMLLicenseId(ow); ow.write("\n"); writeGenerated(ow); ow.write("\n"); ow.write("<classes>\n"); // loop over the first Unicode plane for (int code = Character.MIN_VALUE; code <= maxChar; ++code) { // skip surrogate area if (code == Character.MIN_SURROGATE) { code = Character.MAX_SURROGATE; continue; } // we are only interested in LC, UC and TC letters which are their own LC, // and in 'other letters' if (!(((Character.isLowerCase(code) || Character.isUpperCase(code) || Character.isTitleCase(code)) && code == Character.toLowerCase(code)) || Character.getType(code) == Character.OTHER_LETTER)) { continue; } // skip a number of blocks Character.UnicodeBlock ubi = Character.UnicodeBlock.of(code); if (ubi.equals(Character.UnicodeBlock.SUPERSCRIPTS_AND_SUBSCRIPTS) || ubi.equals(Character.UnicodeBlock.LETTERLIKE_SYMBOLS) || ubi.equals(Character.UnicodeBlock.ALPHABETIC_PRESENTATION_FORMS) || ubi.equals(Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) || ubi.equals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS) || ubi.equals(Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A) || ubi.equals(Character.UnicodeBlock.HANGUL_SYLLABLES)) { continue; } int uppercode = Character.toUpperCase(code); int titlecode = Character.toTitleCase(code); StringBuilder s = new StringBuilder(); if (hexcode) { s.append("0x" + Integer.toHexString(code) + " "); } s.append(Character.toChars(code)); if (uppercode != code) { s.append(Character.toChars(uppercode)); } if (titlecode != code && titlecode != uppercode) { s.append(Character.toChars(titlecode)); } ow.write(s.toString() + "\n"); } ow.write("</classes>\n"); ow.flush(); ow.close(); }
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void fromUCD(boolean hexcode, String unidataPath, String outfilePath) throws IOException, URISyntaxException { URI unidata; if (unidataPath.endsWith("/")) { unidata = new URI(unidataPath); } else { unidata = new URI(unidataPath + "/"); } String scheme = unidata.getScheme(); if (scheme == null || !(scheme.equals("file") || scheme.equals("http"))) { throw new FileNotFoundException ("URI with file or http scheme required for UNIDATA input directory"); } File f = new File(outfilePath); if (f.exists()) { f.delete(); } f.createNewFile(); FileOutputStream fw = new FileOutputStream(f); OutputStreamWriter ow = new OutputStreamWriter(fw, "utf-8"); URI inuri = unidata.resolve("Blocks.txt"); InputStream inis = null; if (scheme.equals("file")) { File in = new File(inuri); inis = new FileInputStream(in); } else if (scheme.equals("http")) { inis = inuri.toURL().openStream(); } InputStreamReader insr = new InputStreamReader(inis, "utf-8"); BufferedReader inbr = new BufferedReader(insr); Map blocks = new HashMap(); for (String line = inbr.readLine(); line != null; line = inbr.readLine()) { if (line.startsWith("#") || line.matches("^\\s*$")) { continue; } String[] parts = line.split(";"); String block = parts[1].trim(); String[] indices = parts[0].split("\\.\\."); int[] ind = {Integer.parseInt(indices[0], 16), Integer.parseInt(indices[1], 16)}; blocks.put(block, ind); } inbr.close(); inuri = unidata.resolve("UnicodeData.txt"); if (scheme.equals("file")) { File in = new File(inuri); inis = new FileInputStream(in); } else if (scheme.equals("http")) { inis = inuri.toURL().openStream(); } insr = new InputStreamReader(inis, "utf-8"); inbr = new BufferedReader(insr); int maxChar; maxChar = Character.MAX_VALUE; ow.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); License.writeXMLLicenseId(ow); ow.write("\n"); writeGenerated(ow); ow.write("\n"); ow.write("<classes>\n"); for (String line = inbr.readLine(); line != null; line = inbr.readLine()) { String[] fields = line.split(";", NUM_FIELDS); int code = Integer.parseInt(fields[UNICODE], 16); if (code > maxChar) { break; } if (((fields[GENERAL_CATEGORY].equals("Ll") || fields[GENERAL_CATEGORY].equals("Lu") || fields[GENERAL_CATEGORY].equals("Lt")) && ("".equals(fields[SIMPLE_LOWERCASE_MAPPING]) || fields[UNICODE].equals(fields[SIMPLE_LOWERCASE_MAPPING]))) || fields[GENERAL_CATEGORY].equals("Lo")) { String[] blockNames = {"Superscripts and Subscripts", "Letterlike Symbols", "Alphabetic Presentation Forms", "Halfwidth and Fullwidth Forms", "CJK Unified Ideographs", "CJK Unified Ideographs Extension A", "Hangul Syllables"}; int j; for (j = 0; j < blockNames.length; ++j) { int[] ind = (int[]) blocks.get(blockNames[j]); if (code >= ind[0] && code <= ind[1]) { break; } } if (j < blockNames.length) { continue; } int uppercode = -1; int titlecode = -1; if (!"".equals(fields[SIMPLE_UPPERCASE_MAPPING])) { uppercode = Integer.parseInt(fields[SIMPLE_UPPERCASE_MAPPING], 16); } if (!"".equals(fields[SIMPLE_TITLECASE_MAPPING])) { titlecode = Integer.parseInt(fields[SIMPLE_TITLECASE_MAPPING], 16); } StringBuilder s = new StringBuilder(); if (hexcode) { s.append("0x" + fields[UNICODE].replaceFirst("^0+", "").toLowerCase() + " "); } s.append(Character.toChars(code)); if (uppercode != -1 && uppercode != code) { s.append(Character.toChars(uppercode)); } if (titlecode != -1 && titlecode != code && titlecode != uppercode) { s.append(Character.toChars(titlecode)); } ow.write(s.toString() + "\n"); } } ow.write("</classes>\n"); ow.flush(); ow.close(); inbr.close(); }
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void fromTeX(boolean hexcode, String lettersPath, String outfilePath) throws IOException { File in = new File(lettersPath); File f = new File(outfilePath); if (f.exists()) { f.delete(); } f.createNewFile(); FileOutputStream fw = new FileOutputStream(f); OutputStreamWriter ow = new OutputStreamWriter(fw, "utf-8"); FileInputStream inis = new FileInputStream(in); InputStreamReader insr = new InputStreamReader(inis, "utf-8"); BufferedReader inbr = new BufferedReader(insr); ow.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); License.writeXMLLicenseId(ow); ow.write("\n"); writeGenerated(ow); ow.write("\n"); ow.write("<classes>\n"); for (String line = inbr.readLine(); line != null; line = inbr.readLine()) { String[] codes = line.split("\\s+"); if (!(codes[0].equals("\\L") || codes[0].equals("\\l"))) { continue; } if (codes.length == 3) { ow.write("\"" + line + "\" has two codes"); continue; } if (codes[0].equals("\\l") && codes.length != 2) { ow.write("\"" + line + "\" should have one code"); continue; } else if (codes[0].equals("\\L") && codes.length != 4) { ow.write("\"" + line + "\" should have three codes"); continue; } if (codes[0].equals("\\l") || (codes[0].equals("\\L") && codes[1].equals(codes[3]))) { StringBuilder s = new StringBuilder(); if (hexcode) { s.append("0x" + codes[1].replaceFirst("^0+", "").toLowerCase() + " "); } s.append(Character.toChars(Integer.parseInt(codes[1], 16))); if (codes[0].equals("\\L")) { s.append(Character.toChars(Integer.parseInt(codes[2], 16))); } ow.write(s.toString() + "\n"); } } ow.write("</classes>\n"); ow.flush(); ow.close(); inbr.close(); }
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void main(String[] args) throws IOException, URISyntaxException { String type = "ucd"; String prefix = "--"; String infile = null; String outfile = null; boolean hexcode = false; int i; for (i = 0; i < args.length && args[i].startsWith(prefix); ++i) { String option = args[i].substring(prefix.length()); if (option.equals("java") || option.equals("ucd") || option.equals("tex")) { type = option; } else if (option.equals("hexcode")) { hexcode = true; } else { System.err.println("Unknown option: " + option); System.exit(1); } } if (i < args.length) { outfile = args[i]; } else { System.err.println("Output file is required; aborting"); System.exit(1); } if (++i < args.length) { infile = args[i]; } if (type.equals("java") && infile != null) { System.err.println("Type java does not allow an infile"); System.exit(1); } else if (type.equals("ucd") && infile == null) { infile = UNICODE_DIR; } else if (type.equals("tex") && infile == null) { System.err.println("Type tex requires an input file"); System.exit(1); } if (type.equals("java")) { fromJava(hexcode, outfile); } else if (type.equals("ucd")) { fromUCD(hexcode, infile, outfile); } else if (type.equals("tex")) { fromTeX(hexcode, infile, outfile); } else { System.err.println("Unknown type: " + type + ", nothing done"); System.exit(1); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int readType ( String line, BufferedReader b, List lines ) throws IOException { lines.add ( line ); return 0; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int readLevels ( String line, BufferedReader b, List lines ) throws IOException { boolean done = false; int n = 0; lines.add ( line ); while ( ! done ) { switch ( testPrefix ( b, PFX_LEVELS ) ) { case 0: // within current levels if ( ( line = b.readLine() ) != null ) { n++; if ( ( line.length() > 0 ) && ! line.startsWith("#") ) { lines.add ( line ); } } else { done = true; } break; case 1: // end of current levels case -1: // eof default: done = true; break; } } return n; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int testPrefix ( BufferedReader b, String pfx ) throws IOException { int rv = 0; int pfxLen = pfx.length(); b.mark ( pfxLen ); for ( int i = 0, n = pfxLen; i < n; i++ ) { int c = b.read(); if ( c < 0 ) { rv = -1; break; } else if ( c != pfx.charAt ( i ) ) { rv = 0; break; } else { rv = 1; } } b.reset(); return rv; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void dumpData ( PrintWriter out, String outFileName ) throws IOException { File f = new File ( outFileName ); File p = f.getParentFile(); if ( td != null ) { String pfxTD = "TD"; dumpResourcesDescriptor ( out, pfxTD, td.length ); dumpResourcesData ( p, f.getName(), pfxTD, td ); } if ( ld != null ) { String pfxTD = "LD"; dumpResourcesDescriptor ( out, pfxTD, ld.length ); dumpResourcesData ( p, f.getName(), pfxTD, ld ); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void dumpResourcesData ( File btcDir, String btcName, String prefix, int[][] data ) throws IOException { String btdName = extractDataFileName ( btcName ); for ( int i = 0, n = data.length; i < n; i++ ) { File f = new File ( btcDir, btdName + "$" + prefix + i + ".ser" ); ObjectOutputStream os = new ObjectOutputStream ( new FileOutputStream ( f ) ); os.writeObject ( data[i] ); os.close(); } }
// in src/codegen/unicode/java/org/apache/fop/util/License.java
public static void writeJavaLicenseId(Writer w) throws IOException { w.write("/*\n"); for (int i = 0; i < LICENSE.length; ++i) { if (LICENSE[i].equals("")) { w.write(" *\n"); } else { w.write(" * " + LICENSE[i] + "\n"); } } w.write(" */\n"); w.write("\n"); w.write("/* " + ID + " */\n"); }
// in src/codegen/unicode/java/org/apache/fop/util/License.java
public static void writeXMLLicenseId(Writer w) throws IOException { for (int i = 0; i < LICENSE.length; ++i) { w.write(String.format("<!-- %-" + maxLength + "s -->\n", new Object[] {LICENSE[i]})); } w.write("\n"); w.write("<!-- " + ID + " -->\n"); }
// in src/codegen/unicode/java/org/apache/fop/util/License.java
public static void main(String[] args) throws IOException { StringWriter w = new StringWriter(); if (args.length == 0 || args[0].equals("--java")) { writeJavaLicenseId(w); } else if (args[0].equals("--xml")) { writeXMLLicenseId(w); } System.out.println(w.toString()); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
protected void updateTranslationFile(File modelFile) throws IOException { try { boolean resultExists = getTranslationFile().exists(); SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); //Generate fresh generated translation file as template Source src = new StreamSource(modelFile.toURI().toURL().toExternalForm()); StreamSource xslt1 = new StreamSource( getClass().getResourceAsStream(MODEL2TRANSLATION)); if (xslt1.getInputStream() == null) { throw new FileNotFoundException(MODEL2TRANSLATION + " not found"); } DOMResult domres = new DOMResult(); Transformer transformer = tFactory.newTransformer(xslt1); transformer.transform(src, domres); final Node generated = domres.getNode(); Node sourceDocument; if (resultExists) { //Load existing translation file into memory (because we overwrite it later) src = new StreamSource(getTranslationFile().toURI().toURL().toExternalForm()); domres = new DOMResult(); transformer = tFactory.newTransformer(); transformer.transform(src, domres); sourceDocument = domres.getNode(); } else { //Simply use generated as source document sourceDocument = generated; } //Generate translation file (with potentially new translations) src = new DOMSource(sourceDocument); //The following triggers a bug in older Xalan versions //Result res = new StreamResult(getTranslationFile()); OutputStream out = new java.io.FileOutputStream(getTranslationFile()); out = new java.io.BufferedOutputStream(out); Result res = new StreamResult(out); try { StreamSource xslt2 = new StreamSource( getClass().getResourceAsStream(MERGETRANSLATION)); if (xslt2.getInputStream() == null) { throw new FileNotFoundException(MERGETRANSLATION + " not found"); } transformer = tFactory.newTransformer(xslt2); transformer.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { if ("my:dom".equals(href)) { return new DOMSource(generated); } return null; } }); if (resultExists) { transformer.setParameter("generated-url", "my:dom"); } transformer.transform(src, res); if (resultExists) { log("Translation file updated: " + getTranslationFile()); } else { log("Translation file generated: " + getTranslationFile()); } } finally { IOUtils.closeQuietly(out); } } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
protected long processFileSets(EventProducerCollector collector) throws IOException, EventConventionException, ClassNotFoundException { long lastModified = 0; Iterator<FileSet> iter = filesets.iterator(); while (iter.hasNext()) { FileSet fs = (FileSet)iter.next(); DirectoryScanner ds = fs.getDirectoryScanner(getProject()); String[] srcFiles = ds.getIncludedFiles(); File directory = fs.getDir(getProject()); for (int i = 0, c = srcFiles.length; i < c; i++) { String filename = srcFiles[i]; File src = new File(directory, filename); boolean eventProducerFound = collector.scanFile(src); if (eventProducerFound) { lastModified = Math.max(lastModified, src.lastModified()); } } } return lastModified; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
public boolean scanFile(File src) throws IOException, EventConventionException, ClassNotFoundException { JavaDocBuilder builder = new JavaDocBuilder(this.tagFactory); builder.addSource(src); JavaClass[] classes = builder.getClasses(); boolean eventProducerFound = false; for (int i = 0, c = classes.length; i < c; i++) { JavaClass clazz = classes[i]; if (clazz.isInterface() && implementsInterface(clazz, CLASSNAME_EVENT_PRODUCER)) { processEventProducerInterface(clazz); eventProducerFound = true; } } return eventProducerFound; }
179
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O exception while setting up output file", ioe); }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (java.io.IOException ioe) { log.error("Error with opening URL '" + effURL + "': " + ioe.getMessage()); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (IOException e) { // won't happen. We're operating in-memory. throw new RuntimeException( "Error during base64 encodation of username/password"); }
// in src/java/org/apache/fop/pdf/PDFFactory.java
catch (IOException ioe) { log.error( "Failed to write CIDSet [" + cidFont + "] " + cidFont.getEmbedFontName(), ioe); }
// in src/java/org/apache/fop/pdf/PDFFactory.java
catch (IOException ioe) { log.error( "Failed to embed font [" + desc + "] " + desc.getEmbedFontName(), ioe); return null; }
// in src/java/org/apache/fop/pdf/PDFOutputIntent.java
catch (IOException ioe) { log.error("Ignored I/O exception", ioe); }
// in src/java/org/apache/fop/pdf/PDFStream.java
catch (IOException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/pdf/PDFStream.java
catch (IOException ex) { //TODO throw the exception and catch it elsewhere ex.printStackTrace(); }
// in src/java/org/apache/fop/pdf/PDFEmbeddedFile.java
catch (IOException ioe) { //ignore and just skip this entry as it's optional }
// in src/java/org/apache/fop/pdf/PDFInfo.java
catch (IOException ioe) { log.error("Ignored I/O exception", ioe); }
// in src/java/org/apache/fop/pdf/PDFICCBasedColorSpace.java
catch (IOException ioe) { throw new RuntimeException( "Unexpected IOException loading the sRGB profile: " + ioe.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFOutline.java
catch (IOException ioe) { log.error("Ignored I/O exception", ioe); }
// in src/java/org/apache/fop/tools/anttasks/FileCompare.java
catch (IOException ioe) { System.err.println("ERROR: " + ioe); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (IOException ioe) { throw new BuildException(ioe); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (IOException ioe) { logger.error("Error closing output file", ioe); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(fobj, uri, ioe, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, url, ioe, getLocator()); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (IOException e) { //ignore }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (IOException e) { //ignore }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (IOException e) { //ignore }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new HyphenationException(ioe.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new SAXException(ioe.getMessage()); }
// in src/java/org/apache/fop/hyphenation/SerializeHyphPattern.java
catch (IOException ioe) { System.err.println("Can't write compiled pattern file: " + outfile); System.err.println(ioe); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (IOException ioe) { log.error("I/O error while loading precompiled hyphenation pattern file", ioe); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("I/O problem while trying to load " + name, ioe); } }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("I/O problem while trying to load " + name, ioe); } return null; }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/svg/FOPSAXSVGDocumentFactory.java
catch (IOException ioe) { /**@todo Batik's SAXSVGDocumentFactory should throw IOException, * so we don't have to handle it here. */ throw new SAXException(ioe); }
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
// in src/java/org/apache/fop/svg/PDFGraphics2D.java
catch (IOException ioe) { // ignore exception, will be thrown again later }
// in src/java/org/apache/fop/svg/NativeTextPainter.java
catch (IOException ioe) { //No other possibility than to use a RuntimeException throw new RuntimeException(ioe); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (IOException ioe) { userAgent.displayError(ioe); return null; }
// in src/java/org/apache/fop/svg/AbstractFOPTextPainter.java
catch (IOException ioe) { if (g2d instanceof AFPGraphics2D) { ((AFPGraphics2D)g2d).handleIOException(ioe); } }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (IOException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
catch (IOException ioe) { throw new TransformerException("Error writing the output file", ioe); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException ioe) { // We don't really care about the exception since it's just a // cache file log.warn("I/O exception while reading font cache (" + ioe.getMessage() + "). Discarding font cache file."); try { cacheFile.delete(); } catch (SecurityException ex) { log.warn("Failed to delete font cache file: " + cacheFile.getAbsolutePath()); } }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException ioe) { LogUtil.handleException(log, ioe, true); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException e) { // Should never happen, because URL must be local log.debug("IOError: " + e.getMessage()); return 0; }
// in src/java/org/apache/fop/fonts/FontDetector.java
catch (IOException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/fonts/FontDetector.java
catch (IOException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (IOException ioex) { log.error("Failed to read font metrics file " + metricsFileName, ioex); if (fail) { throw new RuntimeException(ioex.getMessage()); } }
// in src/java/org/apache/fop/fonts/autodetect/WindowsFontDirFinder.java
catch (IOException e) { // should continue if this fails }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
catch (IOException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
catch (IOException ioe) { // Ignore, AFM probably not available under the URI }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
catch (IOException ioe) { // Ignore, PFM probably not available under the URI }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
catch (IOException ioe) { if (afm == null) { // Ignore the exception if we have a valid PFM. PFM is only the fallback. throw ioe; } }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
catch (IOException ioe) { System.err.println("Problem reading font: " + ioe.toString()); ioe.printStackTrace(System.err); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error flushing the PDF document", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error while drawing borders", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageWritingError(this, ioe); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ioe, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); }
// in src/java/org/apache/fop/render/txt/TXTStream.java
catch (IOException e) { throw new RuntimeException(e.toString()); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding page image", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException( "I/O error while painting marks using a bitmap", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, null, ioe, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { handleIOTrouble(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding BufferedImage", ioe); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IOException ioe) { eventProducer.invalidConfiguration(this, ioe); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IOException ioe) { throw new FOPException("Could not create default external resource group file" , ioe); }
// in src/java/org/apache/fop/render/afp/AFPSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, uri); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException( "I/O error while embedding form map resource: " + formMap.getName(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Could not handle resource" + pageSegment.getURI(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("IO error while painting rectangle", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ife) { throw new IFException("IO error while painting borders", ife); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Error while embedding font resources", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
catch (IOException ioe) { //Some JPEG codecs cannot encode CMYK helper.encode(baos); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error writing the PostScript header", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageContent()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in handleExtensionObject()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in clipRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawBorderRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException e) { //Won't happen with Java2D throw new IllegalStateException("Unexpected I/O error"); }
// in src/java/org/apache/fop/render/java2d/Java2DSVGHandler.java
catch (IOException ioe) { SVGEventProducer eventProducer = SVGEventProducer.Provider.get( context.getUserAgent().getEventBroadcaster()); eventProducer.svgRenderingError(this, ioe, getDocumentURI(doc)); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(this, (info != null ? info.toString() : uri), ioe, null); }
// in src/java/org/apache/fop/afp/AFPGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/afp/AFPGraphics2D.java
catch (IOException ioe) { handleIOException(ioe); }
// in src/java/org/apache/fop/afp/parser/UnparsedStructuredField.java
catch (IOException ioe) { //nop }
// in src/java/org/apache/fop/afp/svg/AFPTextHandler.java
catch (IOException ioe) { throw new RuntimeException("Error while embedding font resources", ioe); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (IOException ioe) { endPresentationTextData(); handleUnexpectedIOError(ioe); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (IOException ioe) { endPresentationTextData(); handleUnexpectedIOError(ioe); //Should not occur since we're writing to byte arrays }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
catch (IOException ioe) { AreaEventProducer eventProducer = AreaEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.pageSaveError(this, page.getPageNumberString(), ioe); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, getLocator()); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException ioe) { RendererEventProducer eventProducer = RendererEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.ioError(this, ioe); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException ex) { throw new SAXException(ex); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (IOException ioe) { getResourceEventProducer().imageIOError(this, uri, ioe, getExternalDocument().getLocator()); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( IOException e ) { resetATStateAll(); throw new AdvancedTypographicTableFormatException ( e.getMessage(), e ); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (IOException e) { throw new MissingResourceException(e.getMessage(), base, null); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (IOException ioe) { //wrap in a PropertyException throw new PropertyException(ioe); }
// in src/java/org/apache/fop/util/CloseBlockerOutputStream.java
catch (IOException ioe) { //ignore }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (NoClassDefFoundError ncdfe) { try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } batikAvailable = false; log.warn("Batik not in class path", ncdfe); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (IOException ioe) { // we're more interested in the original exception }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (IOException e) { // If the svg is invalid then it throws an IOException // so there is no way of knowing if it is an svg document log.debug("Error while trying to load stream as an WMF file: " + e.getMessage()); // assuming any exception means this document is not svg // or could not be loaded for some reason try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (IOException ioe) { // we're more interested in the original exception }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (NoClassDefFoundError ncdfe) { if (in != null) { try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } } batikAvailable = false; log.warn("Batik not in class path", ncdfe); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (IOException ioe) { // we're more interested in the original exception }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (IOException e) { // If the svg is invalid then it throws an IOException // so there is no way of knowing if it is an svg document log.debug("Error while trying to load stream as an SVG file: " + e.getMessage()); // assuming any exception means this document is not svg // or could not be loaded for some reason try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (IOException ioe) { // we're more interested in the original exception }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (IOException ioe) { throw new BuildException(ioe); }
91
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O exception while setting up output file", ioe); }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (IOException e) { // won't happen. We're operating in-memory. throw new RuntimeException( "Error during base64 encodation of username/password"); }
// in src/java/org/apache/fop/pdf/PDFStream.java
catch (IOException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/pdf/PDFICCBasedColorSpace.java
catch (IOException ioe) { throw new RuntimeException( "Unexpected IOException loading the sRGB profile: " + ioe.getMessage()); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (IOException ioe) { throw new BuildException(ioe); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new HyphenationException(ioe.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new SAXException(ioe.getMessage()); }
// in src/java/org/apache/fop/svg/FOPSAXSVGDocumentFactory.java
catch (IOException ioe) { /**@todo Batik's SAXSVGDocumentFactory should throw IOException, * so we don't have to handle it here. */ throw new SAXException(ioe); }
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
// in src/java/org/apache/fop/svg/NativeTextPainter.java
catch (IOException ioe) { //No other possibility than to use a RuntimeException throw new RuntimeException(ioe); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (IOException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
catch (IOException ioe) { throw new TransformerException("Error writing the output file", ioe); }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (IOException ioex) { log.error("Failed to read font metrics file " + metricsFileName, ioex); if (fail) { throw new RuntimeException(ioex.getMessage()); } }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
catch (IOException ioe) { if (afm == null) { // Ignore the exception if we have a valid PFM. PFM is only the fallback. throw ioe; } }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error flushing the PDF document", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
catch (IOException ioe) { throw new IFException("I/O error while drawing borders", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pdf/PDFDocumentHandler.java
catch (IOException ioe) { throw new IFException("Error adding embedded file: " + embeddedFile.getSrc(), ioe); }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); }
// in src/java/org/apache/fop/render/txt/TXTStream.java
catch (IOException e) { throw new RuntimeException(e.toString()); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding page image", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException( "I/O error while painting marks using a bitmap", ioe); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/bitmap/AbstractBitmapDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error while encoding BufferedImage", ioe); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IOException ioe) { throw new FOPException("Could not create default external resource group file" , ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
catch (IOException ioe) { throw new IFException( "I/O error while embedding form map resource: " + formMap.getName(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Could not handle resource" + pageSegment.getURI(), ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("IO error while painting rectangle", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ife) { throw new IFException("IO error while painting borders", ife); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("Error while embedding font resources", ioe); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException e) { throw new IFException("I/O error in startDocument()", e); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error writing the PostScript header", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endDocument()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageHeader()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageContent()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in startPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPageTrailer()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in endPage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (IOException ioe) { throw new IFException("I/O error in handleExtensionObject()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endViewport()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in endGroup()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawImage()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in clipRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawBorderRect()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawLine()", ioe); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
catch (IOException ioe) { throw new IFException("I/O error in drawText()", ioe); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startViewport()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException ioe) { throw new IFException("I/O error in startGroup()", ioe); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException e) { //Won't happen with Java2D throw new IllegalStateException("Unexpected I/O error"); }
// in src/java/org/apache/fop/afp/svg/AFPTextHandler.java
catch (IOException ioe) { throw new RuntimeException("Error while embedding font resources", ioe); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException ex) { throw new SAXException(ex); }
// in src/java/org/apache/fop/complexscripts/fonts/OTFAdvancedTypographicTableReader.java
catch ( IOException e ) { resetATStateAll(); throw new AdvancedTypographicTableFormatException ( e.getMessage(), e ); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (IOException e) { throw new MissingResourceException(e.getMessage(), base, null); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (IOException ioe) { //wrap in a PropertyException throw new PropertyException(ioe); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (IOException ioe) { throw new BuildException(ioe); }
11
unknown (Lib) IllegalAccessException 0 0 0 14
            
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (IllegalAccessException e) { LOG.error(e); return null; }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (IllegalAccessException iae) { failed = true; }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + mappingClassName); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/complexscripts/scripts/IndicScriptProcessor.java
catch ( IllegalAccessException e ) { s = null; }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
catch (IllegalAccessException e) { // Problem instantiating the class, simply continue with the backup implementation }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (IllegalAccessException e) { log.error("Error creating the catalog resolver: " + e.getMessage()); eventProducer.catalogResolverNotCreated(this, e.getMessage()); }
9
            
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + mappingClassName); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
9
runtime (Lib) IllegalArgumentException 243
            
// in src/java/org/apache/fop/apps/FOUserAgent.java
public void setFontBaseURL(String fontBaseUrl) { try { getFactory().getFontManager().setFontBaseURL(fontBaseUrl); } catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); } }
// in src/java/org/apache/fop/pdf/PDFObject.java
public String referencePDF() { if (!hasObjectNumber()) { throw new IllegalArgumentException( "Cannot reference this object. It doesn't have an object number"); } String ref = getObjectNumber() + " " + getGeneration() + " R"; return ref; }
// in src/java/org/apache/fop/pdf/PDFPattern.java
public void setName(String name) { if (name.indexOf(" ") >= 0) { throw new IllegalArgumentException( "Pattern name must not contain any spaces"); } this.patternName = name; }
// in src/java/org/apache/fop/pdf/Version.java
public static Version getValueOf(String version) { for (Version pdfVersion : Version.values()) { if (pdfVersion.toString().equals(version)) { return pdfVersion; } } throw new IllegalArgumentException("Invalid PDF version given: " + version); }
// in src/java/org/apache/fop/pdf/PDFFactory.java
public AbstractPDFStream makeFontFile(FontDescriptor desc) { if (desc.getFontType() == FontType.OTHER) { throw new IllegalArgumentException("Trying to embed unsupported font type: " + desc.getFontType()); } CustomFont font = getCustomFont(desc); InputStream in = null; try { Source source = font.getEmbedFileSource(); if (source == null && font.getEmbedResourceName() != null) { source = new StreamSource(this.getClass() .getResourceAsStream(font.getEmbedResourceName())); } if (source == null) { return null; } if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null && source.getSystemId() != null) { try { in = new java.net.URL(source.getSystemId()).openStream(); } catch (MalformedURLException e) { //TODO: Why construct a new exception here, when it is not thrown? new FileNotFoundException( "File not found. URL could not be resolved: " + e.getMessage()); } } if (in == null) { return null; } //Make sure the InputStream is decorated with a BufferedInputStream if (!(in instanceof java.io.BufferedInputStream)) { in = new java.io.BufferedInputStream(in); } if (in == null) { return null; } else { try { AbstractPDFStream embeddedFont; if (desc.getFontType() == FontType.TYPE0) { MultiByteFont mbfont = (MultiByteFont)font; FontFileReader reader = new FontFileReader(in); TTFSubSetFile subset = new TTFSubSetFile(); byte[] subsetFont = subset.readFont(reader, mbfont.getTTCName(), mbfont.getUsedGlyphs()); // Only TrueType CID fonts are supported now embeddedFont = new PDFTTFStream(subsetFont.length); ((PDFTTFStream)embeddedFont).setData(subsetFont, subsetFont.length); } else if (desc.getFontType() == FontType.TYPE1) { PFBParser parser = new PFBParser(); PFBData pfb = parser.parsePFB(in); embeddedFont = new PDFT1Stream(); ((PDFT1Stream)embeddedFont).setData(pfb); } else { byte[] file = IOUtils.toByteArray(in); embeddedFont = new PDFTTFStream(file.length); ((PDFTTFStream)embeddedFont).setData(file, file.length); } /* embeddedFont.getFilterList().addFilter("flate"); if (getDocument().isEncryptionActive()) { getDocument().applyEncryption(embeddedFont); } else { embeddedFont.getFilterList().addFilter("ascii-85"); }*/ return embeddedFont; } finally { in.close(); } } } catch (IOException ioe) { log.error( "Failed to embed font [" + desc + "] " + desc.getEmbedFontName(), ioe); return null; } }
// in src/java/org/apache/fop/pdf/PDFFactory.java
private CustomFont getCustomFont(FontDescriptor desc) { Typeface tempFont; if (desc instanceof LazyFont) { tempFont = ((LazyFont)desc).getRealFont(); } else { tempFont = (Typeface)desc; } if (!(tempFont instanceof CustomFont)) { throw new IllegalArgumentException( "FontDescriptor must be instance of CustomFont, but is a " + desc.getClass().getName()); } return (CustomFont)tempFont; }
// in src/java/org/apache/fop/pdf/PDFFont.java
protected PDFName getPDFNameForFontType(FontType fontType) { if (fontType == FontType.TYPE0) { return new PDFName(fontType.getName()); } else if (fontType == FontType.TYPE1) { return new PDFName(fontType.getName()); } else if (fontType == FontType.MMTYPE1) { return new PDFName(fontType.getName()); } else if (fontType == FontType.TYPE3) { return new PDFName(fontType.getName()); } else if (fontType == FontType.TRUETYPE) { return new PDFName(fontType.getName()); } else { throw new IllegalArgumentException("Unsupported font type: " + fontType.getName()); } }
// in src/java/org/apache/fop/pdf/PDFTextUtil.java
public void setTextRenderingMode(int mode) { if (mode < 0 || mode > 7) { throw new IllegalArgumentException( "Illegal value for text rendering mode. Expected: 0-7"); } if (mode != this.textRenderingMode) { writeTJ(); this.textRenderingMode = mode; write(this.textRenderingMode + " Tr\n"); } }
// in src/java/org/apache/fop/pdf/PDFText.java
protected String toPDFString() { if (getText() == null) { throw new IllegalArgumentException( "The text of this PDFText must not be empty"); } StringBuffer sb = new StringBuffer(64); sb.append("("); sb.append(escapeText(getText())); sb.append(")"); return sb.toString(); }
// in src/java/org/apache/fop/pdf/PDFCIDFont.java
protected String getPDFNameForCIDFontType(CIDFontType cidFontType) { if (cidFontType == CIDFontType.CIDTYPE0) { return cidFontType.getName(); } else if (cidFontType == CIDFontType.CIDTYPE2) { return cidFontType.getName(); } else { throw new IllegalArgumentException("Unsupported CID font type: " + cidFontType.getName()); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public static int outputIndirectObject(PDFObject object, OutputStream stream) throws IOException { if (!object.hasObjectNumber()) { throw new IllegalArgumentException("Not an indirect object"); } byte[] obj = encode(object.getObjectID()); stream.write(obj); int length = object.output(stream); byte[] endobj = encode("\nendobj\n"); stream.write(endobj); return obj.length + length + endobj.length; }
// in src/java/org/apache/fop/pdf/PDFFilterList.java
public void addFilter(String filterType) { if (filterType == null) { return; } if (filterType.equals("flate")) { addFilter(new FlateFilter()); } else if (filterType.equals("null")) { addFilter(new NullFilter()); } else if (filterType.equals("ascii-85")) { if (this.ignoreASCIIFilters) { return; //ignore ASCII filter } addFilter(new ASCII85Filter()); } else if (filterType.equals("ascii-hex")) { if (this.ignoreASCIIFilters) { return; //ignore ASCII filter } addFilter(new ASCIIHexFilter()); } else if (filterType.equals("")) { return; } else { throw new IllegalArgumentException( "Unsupported filter type in stream-filter-list: " + filterType); } }
// in src/java/org/apache/fop/pdf/PDFCIELabColorSpace.java
private PDFArray toPDFArray(String name, float[] whitePoint) { PDFArray wp = new PDFArray(); if (whitePoint == null || whitePoint.length != 3) { throw new IllegalArgumentException(name + " must be given an have 3 components"); } for (int i = 0; i < 3; i++) { wp.add(whitePoint[i]); } return wp; }
// in src/java/org/apache/fop/pdf/PDFShading.java
public void setName(String name) { if (name.indexOf(" ") >= 0) { throw new IllegalArgumentException( "Shading name must not contain any spaces"); } this.shadingName = name; }
// in src/java/org/apache/fop/pdf/VersionController.java
public static VersionController getFixedVersionController(Version version) { if (version.compareTo(Version.V1_4) < 0) { throw new IllegalArgumentException("The PDF version cannot be set below version 1.4"); } return new FixedVersion(version); }
// in src/java/org/apache/fop/pdf/PDFNumber.java
public static String doubleOut(double doubleDown, int dec) { if (dec < 0 || dec > 16) { throw new IllegalArgumentException("Parameter dec must be between 1 and 16"); } StringBuffer buf = new StringBuffer(); DoubleFormatUtil.formatDouble(doubleDown, dec, dec, buf); return buf.toString(); }
// in src/java/org/apache/fop/pdf/PDFNumber.java
protected String toPDFString() { if (getNumber() == null) { throw new IllegalArgumentException( "The number of this PDFNumber must not be empty"); } StringBuffer sb = new StringBuffer(64); sb.append(doubleOut(getNumber().doubleValue(), 10)); return sb.toString(); }
// in src/java/org/apache/fop/pdf/PDFName.java
private static void toHex(char ch, StringBuilder sb) { if (ch >= 256) { throw new IllegalArgumentException( "Only 8-bit characters allowed by this implementation"); } sb.append(DIGITS[ch >>> 4 & 0x0F]); sb.append(DIGITS[ch & 0x0F]); }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void parseArguments(String[] args) { if (args.length > 0) { int idx = 0; if ("--help".equals(args[idx]) || "-?".equals(args[idx]) || "-h".equals(args[idx])) { printHelp(); System.exit(0); } if (idx < args.length - 1 && "-c".equals(args[idx])) { String filename = args[idx + 1]; this.configFile = new File(filename); idx += 2; } if (idx < args.length - 1 && "-f".equals(args[idx])) { this.configMime = args[idx + 1]; idx += 2; } if (idx < args.length) { String name = args[idx]; this.outputFile = new File(name); if (this.outputFile.isDirectory()) { this.mode = GENERATE_RENDERED; this.outputMime = MimeConstants.MIME_PDF; } else if (FilenameUtils.getExtension(name).equalsIgnoreCase("pdf")) { this.mode = GENERATE_RENDERED; this.outputMime = MimeConstants.MIME_PDF; } else if (FilenameUtils.getExtension(name).equalsIgnoreCase("fo")) { this.mode = GENERATE_FO; } else if (FilenameUtils.getExtension(name).equalsIgnoreCase("xml")) { this.mode = GENERATE_XML; } else { throw new IllegalArgumentException( "Operating mode for the output file cannot be determined" + " or is unsupported: " + name); } idx++; } if (idx < args.length) { this.singleFamilyFilter = args[idx]; } } else { System.out.println("use --help or -? for usage information."); } }
// in src/java/org/apache/fop/fo/properties/IndentPropertyMaker.java
public void setPaddingCorresponding(int[] paddingCorresponding) { if ( ( paddingCorresponding == null ) || ( paddingCorresponding.length != 4 ) ) { throw new IllegalArgumentException(); } this.paddingCorresponding = paddingCorresponding; }
// in src/java/org/apache/fop/fo/properties/IndentPropertyMaker.java
public void setBorderWidthCorresponding(int[] borderWidthCorresponding) { if ( ( borderWidthCorresponding == null ) || ( borderWidthCorresponding.length != 4 ) ) { throw new IllegalArgumentException(); } this.borderWidthCorresponding = borderWidthCorresponding; }
// in src/java/org/apache/fop/fo/properties/DimensionPropertyMaker.java
public void setExtraCorresponding(int[][] extraCorresponding) { if ( extraCorresponding == null ) { throw new NullPointerException(); } for ( int i = 0; i < extraCorresponding.length; i++ ) { int[] eca = extraCorresponding[i]; if ( ( eca == null ) || ( eca.length != 4 ) ) { throw new IllegalArgumentException ( "bad sub-array @ [" + i + "]" ); } } this.extraCorresponding = extraCorresponding; }
// in src/java/org/apache/fop/fo/flow/table/EffRow.java
public boolean getFlag(int which) { if (which == FIRST_IN_PART) { return getGridUnit(0).getFlag(GridUnit.FIRST_IN_PART); } else if (which == LAST_IN_PART) { return getGridUnit(0).getFlag(GridUnit.LAST_IN_PART); } else { throw new IllegalArgumentException("Illegal flag queried: " + which); } }
// in src/java/org/apache/fop/fo/pagination/Root.java
public void notifyPageSequenceFinished(int lastPageNumber, int additionalPages) throws IllegalArgumentException { if (additionalPages >= 0) { totalPagesGenerated += additionalPages; endingPageNumberOfPreviousSequence = lastPageNumber; } else { throw new IllegalArgumentException( "Number of additional pages must be zero or greater."); } }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
public void addElementMapping(String mappingClassName) throws IllegalArgumentException { try { ElementMapping mapping = (ElementMapping)Class.forName(mappingClassName).newInstance(); addElementMapping(mapping); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + mappingClassName); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + mappingClassName); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + mappingClassName); } catch (ClassCastException e) { throw new IllegalArgumentException(mappingClassName + " is not an ElementMapping"); } }
// in src/java/org/apache/fop/fo/extensions/ExtensionElementMapping.java
public boolean isAttributeProperty(QName attributeName) { if (!URI.equals(attributeName.getNamespaceURI())) { throw new IllegalArgumentException("The namespace URIs don't match"); } return PROPERTY_ATTRIBUTES.contains(attributeName.getLocalName()); }
// in src/java/org/apache/fop/fo/extensions/InternalElementMapping.java
public boolean isAttributeProperty(QName attributeName) { if (!URI.equals(attributeName.getNamespaceURI())) { throw new IllegalArgumentException("The namespace URIs don't match"); } return PROPERTY_ATTRIBUTES.contains(attributeName.getLocalName()); }
// in src/java/org/apache/fop/svg/PDFGraphics2D.java
public void addNativeImage(org.apache.xmlgraphics.image.loader.Image image, float x, float y, float width, float height) { preparePainting(); String key = image.getInfo().getOriginalURI(); if (key == null) { // Need to include hash code as when invoked from FO you // may have several 'independent' PDFGraphics2D so the // count is not enough. key = "__AddNative_" + hashCode() + "_" + nativeCount; nativeCount++; } PDFImage pdfImage; if (image instanceof ImageRawJPEG) { pdfImage = new ImageRawJPEGAdapter((ImageRawJPEG)image, key); } else if (image instanceof ImageRawCCITTFax) { pdfImage = new ImageRawCCITTFaxAdapter((ImageRawCCITTFax)image, key); } else { throw new IllegalArgumentException( "Unsupported Image subclass: " + image.getClass().getName()); } PDFXObject xObject = this.pdfDoc.addImage(resourceContext, pdfImage); flushPDFDocument(); AffineTransform at = new AffineTransform(); at.translate(x, y); useXObject(xObject, at, width, height); }
// in src/java/org/apache/fop/fonts/EncodingMode.java
public static EncodingMode getEncodingMode(String name) { for (EncodingMode em : EncodingMode.values()) { if (name.equalsIgnoreCase(em.getName())) { return em; } } throw new IllegalArgumentException("Invalid encoding mode: " + name); }
// in src/java/org/apache/fop/fonts/SimpleSingleByteEncoding.java
public char addCharacter(NamedCharacter ch) { if (!ch.hasSingleUnicodeValue()) { throw new IllegalArgumentException("Only NamedCharacters with a single Unicode value" + " are currently supported!"); } if (isFull()) { throw new IllegalStateException("Encoding is full!"); } char newSlot = (char)(getLastChar() + 1); this.mapping.add(ch); this.charMap.put(Character.valueOf(ch.getSingleUnicodeValue()), Character.valueOf(newSlot)); return newSlot; }
// in src/java/org/apache/fop/fonts/SimpleSingleByteEncoding.java
public NamedCharacter getCharacterForIndex(int codePoint) { if (codePoint < 0 || codePoint > 255) { throw new IllegalArgumentException("codePoint must be between 0 and 255"); } if (codePoint <= getLastChar()) { return this.mapping.get(codePoint - 1); } else { return null; } }
// in src/java/org/apache/fop/fonts/CIDFontType.java
public static CIDFontType byName(String name) { if (name.equalsIgnoreCase(CIDFontType.CIDTYPE0.getName())) { return CIDFontType.CIDTYPE0; } else if (name.equalsIgnoreCase(CIDFontType.CIDTYPE2.getName())) { return CIDFontType.CIDTYPE2; } else { throw new IllegalArgumentException("Invalid CID font type: " + name); } }
// in src/java/org/apache/fop/fonts/CIDFontType.java
public static CIDFontType byValue(int value) { if (value == CIDFontType.CIDTYPE0.getValue()) { return CIDFontType.CIDTYPE0; } else if (value == CIDFontType.CIDTYPE2.getValue()) { return CIDFontType.CIDTYPE2; } else { throw new IllegalArgumentException("Invalid CID font type: " + value); } }
// in src/java/org/apache/fop/fonts/FontUtil.java
public static int parseCSS2FontWeight(String text) { int weight = 400; try { weight = Integer.parseInt(text); weight = ((int)weight / 100) * 100; weight = Math.max(weight, 100); weight = Math.min(weight, 900); } catch (NumberFormatException nfe) { //weight is no number, so convert symbolic name to number if (text.equals("normal")) { weight = 400; } else if (text.equals("bold")) { weight = 700; } else { throw new IllegalArgumentException( "Illegal value for font weight: '" + text + "'. Use one of: 100, 200, 300, " + "400, 500, 600, 700, 800, 900, " + "normal (=400), bold (=700)"); } } return weight; }
// in src/java/org/apache/fop/fonts/FontInfo.java
public FontTriplet[] fontLookup(String[] families, String style, int weight) { if (families.length == 0) { throw new IllegalArgumentException("Specify at least one font family"); } // try matching without substitutions List<FontTriplet> matchedTriplets = fontLookup(families, style, weight, false); // if there are no matching font triplets found try with substitutions if (matchedTriplets.size() == 0) { matchedTriplets = fontLookup(families, style, weight, true); } // no matching font triplets found! if (matchedTriplets.size() == 0) { StringBuffer sb = new StringBuffer(); for (int i = 0, c = families.length; i < c; i++) { if (i > 0) { sb.append(", "); } sb.append(families[i]); } throw new IllegalStateException( "fontLookup must return an array with at least one " + "FontTriplet on the last call. Lookup: " + sb.toString()); } FontTriplet[] fontTriplets = new FontTriplet[matchedTriplets.size()]; matchedTriplets.toArray(fontTriplets); // found some matching fonts so return them return fontTriplets; }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static CustomFont loadFont(String fontFileURI, String subFontName, boolean embedded, EncodingMode encodingMode, boolean useKerning, boolean useAdvanced, FontResolver resolver) throws IOException { fontFileURI = fontFileURI.trim(); boolean type1 = isType1(fontFileURI); FontLoader loader; if (type1) { if (encodingMode == EncodingMode.CID) { throw new IllegalArgumentException( "CID encoding mode not supported for Type 1 fonts"); } loader = new Type1FontLoader(fontFileURI, embedded, useKerning, resolver); } else { loader = new TTFFontLoader(fontFileURI, subFontName, embedded, encodingMode, useKerning, useAdvanced, resolver); } return loader.getFont(); }
// in src/java/org/apache/fop/fonts/FontType.java
public static FontType byName(String name) { if (name.equalsIgnoreCase(FontType.OTHER.getName())) { return FontType.OTHER; } else if (name.equalsIgnoreCase(FontType.TYPE0.getName())) { return FontType.TYPE0; } else if (name.equalsIgnoreCase(FontType.TYPE1.getName())) { return FontType.TYPE1; } else if (name.equalsIgnoreCase(FontType.MMTYPE1.getName())) { return FontType.MMTYPE1; } else if (name.equalsIgnoreCase(FontType.TYPE3.getName())) { return FontType.TYPE3; } else if (name.equalsIgnoreCase(FontType.TRUETYPE.getName())) { return FontType.TRUETYPE; } else { throw new IllegalArgumentException("Invalid font type: " + name); } }
// in src/java/org/apache/fop/fonts/FontType.java
public static FontType byValue(int value) { if (value == FontType.OTHER.getValue()) { return FontType.OTHER; } else if (value == FontType.TYPE0.getValue()) { return FontType.TYPE0; } else if (value == FontType.TYPE1.getValue()) { return FontType.TYPE1; } else if (value == FontType.MMTYPE1.getValue()) { return FontType.MMTYPE1; } else if (value == FontType.TYPE3.getValue()) { return FontType.TYPE3; } else if (value == FontType.TRUETYPE.getValue()) { return FontType.TRUETYPE; } else { throw new IllegalArgumentException("Invalid font type: " + value); } }
// in src/java/org/apache/fop/fonts/MultiByteFont.java
private GlyphSequence mapCharsToGlyphs ( CharSequence cs ) { IntBuffer cb = IntBuffer.allocate ( cs.length() ); IntBuffer gb = IntBuffer.allocate ( cs.length() ); int gi; int giMissing = findGlyphIndex ( Typeface.NOT_FOUND ); for ( int i = 0, n = cs.length(); i < n; i++ ) { int cc = cs.charAt ( i ); if ( ( cc >= 0xD800 ) && ( cc < 0xDC00 ) ) { if ( ( i + 1 ) < n ) { int sh = cc; int sl = cs.charAt ( ++i ); if ( ( sl >= 0xDC00 ) && ( sl < 0xE000 ) ) { cc = 0x10000 + ( ( sh - 0xD800 ) << 10 ) + ( ( sl - 0xDC00 ) << 0 ); } else { throw new IllegalArgumentException ( "ill-formed UTF-16 sequence, " + "contains isolated high surrogate at index " + i ); } } else { throw new IllegalArgumentException ( "ill-formed UTF-16 sequence, " + "contains isolated high surrogate at end of sequence" ); } } else if ( ( cc >= 0xDC00 ) && ( cc < 0xE000 ) ) { throw new IllegalArgumentException ( "ill-formed UTF-16 sequence, " + "contains isolated low surrogate at index " + i ); } notifyMapOperation(); gi = findGlyphIndex ( cc ); if ( gi == SingleByteEncoding.NOT_FOUND_CODE_POINT ) { warnMissingGlyph ( (char) cc ); gi = giMissing; } cb.put ( cc ); gb.put ( gi ); } cb.flip(); gb.flip(); return new GlyphSequence ( cb, gb, null ); }
// in src/java/org/apache/fop/fonts/type1/PFBData.java
public void setPFBFormat(int format) { switch (format) { case PFB_RAW: case PFB_PC: this.pfbFormat = format; break; case PFB_MAC: throw new UnsupportedOperationException("Mac format is not yet implemented"); default: throw new IllegalArgumentException("Invalid value for PFB format: " + format); } }
// in src/java/org/apache/fop/fonts/type1/Type1FontLoader.java
private void buildFont(AFMFile afm, PFMFile pfm) { if (afm == null && pfm == null) { throw new IllegalArgumentException("Need at least an AFM or a PFM!"); } singleFont = new SingleByteFont(); singleFont.setFontType(FontType.TYPE1); singleFont.setResolver(this.resolver); if (this.embedded) { singleFont.setEmbedFileName(this.fontFileURI); } returnFont = singleFont; handleEncoding(afm, pfm); handleFontName(afm, pfm); handleMetrics(afm, pfm); }
// in src/java/org/apache/fop/fonts/truetype/TTFFile.java
public boolean readFont(FontFileReader in, String name) throws IOException { /* * Check if TrueType collection, and that the name * exists in the collection */ if (!checkTTC(in, name)) { if (name == null) { throw new IllegalArgumentException( "For TrueType collection you must specify which font " + "to select (-ttcname)"); } else { throw new IOException( "Name does not exist in the TrueType collection: " + name); } } readDirTabs(in); readFontHeader(in); getNumGlyphs(in); if (log.isDebugEnabled()) { log.debug("Number of glyphs in font: " + numberOfGlyphs); } readHorizontalHeader(in); readHorizontalMetrics(in); initAnsiWidths(); readPostScript(in); readOS2(in); determineAscDesc(); if (!isCFF) { readIndexToLocation(in); readGlyf(in); } readName(in); boolean pcltFound = readPCLT(in); // Read cmap table and fill in ansiwidths boolean valid = readCMAP(in); if (!valid) { return false; } // Create cmaps for bfentries createCMaps(); if ( useKerning ) { readKerning(in); } // Read advanced typographic tables. if ( useAdvanced ) { try { OTFAdvancedTypographicTableReader atr = new OTFAdvancedTypographicTableReader ( this, in ); atr.readAll(); this.advancedTableReader = atr; } catch ( AdvancedTypographicTableFormatException e ) { log.warn ( "Encountered format constraint violation in advanced (typographic) table (AT) " + "in font '" + getFullName() + "', ignoring AT data: " + e.getMessage() ); } } guessVerticalMetricsFromGlyphBBox(); return true; }
// in src/java/org/apache/fop/render/print/PrintRenderer.java
private void setRendererOptions() { Map rendererOptions = getUserAgent().getRendererOptions(); Object printerJobO = rendererOptions.get(PrintRenderer.PRINTER_JOB); if (printerJobO != null) { if (!(printerJobO instanceof PrinterJob)) { throw new IllegalArgumentException( "Renderer option " + PrintRenderer.PRINTER_JOB + " must be an instance of java.awt.print.PrinterJob, but an instance of " + printerJobO.getClass().getName() + " was given."); } printerJob = (PrinterJob)printerJobO; printerJob.setPageable(this); } Object o = rendererOptions.get(PrintRenderer.COPIES); if (o != null) { this.copies = getPositiveInteger(o); } initializePrinterJob(); }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
private void processOptions(Map rendererOptions) { Object o = rendererOptions.get(PageableRenderer.PAGES_MODE); if (o != null) { if (o instanceof PagesMode) { this.mode = (PagesMode)o; } else if (o instanceof String) { this.mode = PagesMode.byName((String)o); } else { throw new IllegalArgumentException( "Renderer option " + PageableRenderer.PAGES_MODE + " must be an 'all', 'even', 'odd' or a PagesMode instance."); } } o = rendererOptions.get(PageableRenderer.START_PAGE); if (o != null) { this.startNumber = getPositiveInteger(o); } o = rendererOptions.get(PageableRenderer.END_PAGE); if (o != null) { this.endNumber = getPositiveInteger(o); } if (this.endNumber >= 0 && this.endNumber < this.endNumber) { this.endNumber = this.startNumber; } }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
protected int getPositiveInteger(Object o) { if (o instanceof Integer) { Integer i = (Integer)o; if (i.intValue() < 1) { throw new IllegalArgumentException( "Value must be a positive Integer"); } return i.intValue(); } else if (o instanceof String) { return Integer.parseInt((String)o); } else { throw new IllegalArgumentException( "Value must be a positive integer"); } }
// in src/java/org/apache/fop/render/print/PagesMode.java
public static PagesMode byName(String name) { if (PagesMode.ALL.getName().equalsIgnoreCase(name)) { return PagesMode.ALL; } else if (PagesMode.EVEN.getName().equalsIgnoreCase(name)) { return PagesMode.EVEN; } else if (PagesMode.ODD.getName().equalsIgnoreCase(name)) { return PagesMode.ODD; } else { throw new IllegalArgumentException("Invalid value for PagesMode: " + name); } }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private static boolean booleanValueOf(Object obj) { if (obj instanceof Boolean) { return ((Boolean)obj).booleanValue(); } else if (obj instanceof String) { return Boolean.valueOf((String)obj).booleanValue(); } else { throw new IllegalArgumentException("Boolean or \"true\" or \"false\" expected."); } }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
public void addXMLHandler(String classname) { try { XMLHandler handlerInstance = (XMLHandler)Class.forName(classname).newInstance(); addXMLHandler(handlerInstance); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); } catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + XMLHandler.class.getName()); } }
// in src/java/org/apache/fop/render/RendererFactory.java
public void addRendererMaker(String className) { try { AbstractRendererMaker makerInstance = (AbstractRendererMaker)Class.forName(className).newInstance(); addRendererMaker(makerInstance); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); } catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractRendererMaker.class.getName()); } }
// in src/java/org/apache/fop/render/RendererFactory.java
public void addFOEventHandlerMaker(String className) { try { AbstractFOEventHandlerMaker makerInstance = (AbstractFOEventHandlerMaker)Class.forName(className).newInstance(); addFOEventHandlerMaker(makerInstance); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); } catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractFOEventHandlerMaker.class.getName()); } }
// in src/java/org/apache/fop/render/RendererFactory.java
public void addDocumentHandlerMaker(String className) { try { AbstractIFDocumentHandlerMaker makerInstance = (AbstractIFDocumentHandlerMaker)Class.forName(className).newInstance(); addDocumentHandlerMaker(makerInstance); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); } catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractIFDocumentHandlerMaker.class.getName()); } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected Rectangle getLineBoundingBox(Point start, Point end, int width) { if (start.y == end.y) { int topy = start.y - width / 2; return new Rectangle( start.x, topy, end.x - start.x, width); } else if (start.x == end.y) { int leftx = start.x - width / 2; return new Rectangle( leftx, start.x, width, end.y - start.y); } else { throw new IllegalArgumentException( "Only horizontal or vertical lines are supported at the moment."); } }
// in src/java/org/apache/fop/render/intermediate/IFUtil.java
public static int[][] copyDP ( int[][] dp, int offset, int count ) { if ( ( dp == null ) || ( offset > dp.length ) || ( ( offset + count ) > dp.length ) ) { throw new IllegalArgumentException(); } else { int[][] dpNew = new int [ count ] [ 4 ]; for ( int i = 0, n = count; i < n; i++ ) { int[] paDst = dpNew [ i ]; int[] paSrc = dp [ i + offset ]; for ( int k = 0; k < 4; k++ ) { paDst [ k ] = paSrc [ k ]; } } return dpNew; } }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void setResult(Result result) throws IFException { if (result instanceof StreamResult) { StreamResult streamResult = (StreamResult)result; OutputStream out = streamResult.getOutputStream(); if (out == null) { if (streamResult.getWriter() != null) { throw new IllegalArgumentException( "FOP cannot use a Writer. Please supply an OutputStream!"); } try { URL url = new URL(streamResult.getSystemId()); File f = FileUtils.toFile(url); if (f != null) { out = new java.io.FileOutputStream(f); } else { out = url.openConnection().getOutputStream(); } } catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); } out = new java.io.BufferedOutputStream(out); this.ownOutputStream = true; } if (out == null) { throw new IllegalArgumentException("Need a StreamResult with an OutputStream"); } this.outputStream = out; } else { throw new UnsupportedOperationException( "Unsupported Result subclass: " + result.getClass().getName()); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
private void renderDestination(DestinationData dd) { if (!hasDocumentNavigation()) { return; } String targetID = dd.getIDRef(); if (targetID == null || targetID.length() == 0) { throw new IllegalArgumentException("DestinationData must contain a ID reference"); } PageViewport pv = dd.getPageViewport(); if (pv != null) { GoToXYAction action = getGoToActionForID(targetID, pv.getPageIndex()); NamedDestination namedDestination = new NamedDestination(targetID, action); this.deferredDestinations.add(namedDestination); } else { //Warning already issued by AreaTreeHandler (debug level is sufficient) log.debug("Unresolved destination item received: " + dd.getIDRef()); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
private Bookmark renderBookmarkItem(BookmarkData bookmarkItem) { String targetID = bookmarkItem.getIDRef(); if (targetID == null || targetID.length() == 0) { throw new IllegalArgumentException("DestinationData must contain a ID reference"); } GoToXYAction action = null; PageViewport pv = bookmarkItem.getPageViewport(); if (pv != null) { action = getGoToActionForID(targetID, pv.getPageIndex()); } else { //Warning already issued by AreaTreeHandler (debug level is sufficient) log.debug("Bookmark with IDRef \"" + targetID + "\" has a null PageViewport."); } Bookmark b = new Bookmark( bookmarkItem.getBookmarkTitle(), bookmarkItem.showChildItems(), action); for (int i = 0; i < bookmarkItem.getCount(); i++) { b.addChildBookmark(renderBookmarkItem(bookmarkItem.getSubData(i))); } return b; }
// in src/java/org/apache/fop/render/intermediate/extensions/ActionSet.java
public synchronized String generateNewID(AbstractAction action) { this.lastGeneratedID++; String prefix = action.getIDPrefix(); if (prefix == null) { throw new IllegalArgumentException("Action class is not compatible"); } return prefix + this.lastGeneratedID; }
// in src/java/org/apache/fop/render/pcl/PCLRenderingMode.java
public static PCLRenderingMode valueOf(String name) { if (QUALITY.getName().equalsIgnoreCase(name)) { return QUALITY; } else if (SPEED.getName().equalsIgnoreCase(name)) { return SPEED; } else if (BITMAP.getName().equalsIgnoreCase(name)) { return BITMAP; } else { throw new IllegalArgumentException("Illegal value for enumeration: " + name); } }
// in src/java/org/apache/fop/render/pcl/PCLGenerator.java
public void paintMonochromeBitmap(RenderedImage img, int resolution) throws IOException { if (!isValidPCLResolution(resolution)) { throw new IllegalArgumentException("Invalid PCL resolution: " + resolution); } boolean monochrome = isMonochromeImage(img); if (!monochrome) { throw new IllegalArgumentException("img must be a monochrome image"); } setRasterGraphicsResolution(resolution); writeCommand("*r0f" + img.getHeight() + "t" + img.getWidth() + "s1A"); Raster raster = img.getData(); Encoder encoder = new Encoder(img); // Transfer graphics data int imgw = img.getWidth(); IndexColorModel cm = (IndexColorModel)img.getColorModel(); if (cm.getTransferType() == DataBuffer.TYPE_BYTE) { DataBufferByte dataBuffer = (DataBufferByte)raster.getDataBuffer(); MultiPixelPackedSampleModel packedSampleModel = new MultiPixelPackedSampleModel( DataBuffer.TYPE_BYTE, img.getWidth(), img.getHeight(), 1); if (img.getSampleModel().equals(packedSampleModel) && dataBuffer.getNumBanks() == 1) { //Optimized packed encoding byte[] buf = dataBuffer.getData(); int scanlineStride = packedSampleModel.getScanlineStride(); int idx = 0; int c0 = toGray(cm.getRGB(0)); int c1 = toGray(cm.getRGB(1)); boolean zeroIsWhite = c0 > c1; for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { for (int x = 0, maxx = scanlineStride; x < maxx; x++) { if (zeroIsWhite) { encoder.add8Bits(buf[idx]); } else { encoder.add8Bits((byte)~buf[idx]); } idx++; } encoder.endLine(); } } else { //Optimized non-packed encoding for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { byte[] line = (byte[])raster.getDataElements(0, y, imgw, 1, null); for (int x = 0, maxx = imgw; x < maxx; x++) { encoder.addBit(line[x] == 0); } encoder.endLine(); } } } else { //Safe but slow fallback for (int y = 0, maxy = img.getHeight(); y < maxy; y++) { for (int x = 0, maxx = imgw; x < maxx; x++) { int sample = raster.getSample(x, y, 0); encoder.addBit(sample == 0); } encoder.endLine(); } } // End raster graphics writeCommand("*rB"); }
// in src/java/org/apache/fop/render/afp/AFPShadingMode.java
public static AFPShadingMode valueOf(String name) { if (COLOR.getName().equalsIgnoreCase(name)) { return COLOR; } else if (DITHERED.getName().equalsIgnoreCase(name)) { return DITHERED; } else { throw new IllegalArgumentException("Illegal value for enumeration: " + name); } }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
public void addHandler(String classname) { try { ImageHandler handlerInstance = (ImageHandler)Class.forName(classname).newInstance(); addHandler(handlerInstance); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); } catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ImageHandler.class.getName()); } }
// in src/java/org/apache/fop/render/ps/PSRenderingUtil.java
private boolean booleanValueOf(Object obj) { if (obj instanceof Boolean) { return ((Boolean)obj).booleanValue(); } else if (obj instanceof String) { return Boolean.valueOf((String)obj).booleanValue(); } else { throw new IllegalArgumentException("Boolean or \"true\" or \"false\" expected."); } }
// in src/java/org/apache/fop/render/ps/PSRenderingUtil.java
private int intValueOf(Object obj) { if (obj instanceof Integer) { return ((Integer)obj).intValue(); } else if (obj instanceof String) { return Integer.parseInt((String)obj); } else { throw new IllegalArgumentException("Integer or String with a number expected."); } }
// in src/java/org/apache/fop/render/ps/PSRenderingUtil.java
public void setLanguageLevel(int level) { if (level == 2 || level == 3) { this.languageLevel = level; } else { throw new IllegalArgumentException("Only language levels 2 or 3 are allowed/supported"); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
protected PSResource getFormForImage(String uri) { if (uri == null || "".equals(uri)) { throw new IllegalArgumentException("uri must not be empty or null"); } if (this.formResources == null) { this.formResources = new java.util.HashMap(); } PSResource form = (PSResource)this.formResources.get(uri); if (form == null) { form = new PSImageFormResource(this.formResources.size() + 1, uri); this.formResources.put(uri, form); } return form; }
// in src/java/org/apache/fop/render/java2d/CustomFontMetricsMapper.java
private void initialize(final Source source) throws FontFormatException, IOException { int type = Font.TRUETYPE_FONT; if (FontType.TYPE1.equals(typeface.getFontType())) { type = TYPE1_FONT; //Font.TYPE1_FONT; only available in Java 1.5 } InputStream is = null; if (source instanceof StreamSource) { is = ((StreamSource) source).getInputStream(); } else if (source.getSystemId() != null) { is = new java.net.URL(source.getSystemId()).openStream(); } else { throw new IllegalArgumentException("No font source provided."); } this.font = Font.createFont(type, is); is.close(); }
// in src/java/org/apache/fop/render/extensions/prepress/PageBoundaries.java
private void calculate(Dimension pageSize, String bleed, String cropOffset, String cropBoxSelector) { this.trimBox = new Rectangle(pageSize); this.bleedBox = getBleedBoxRectangle(this.trimBox, bleed); Rectangle cropMarksBox = getCropMarksAreaRectangle(trimBox, cropOffset); //MediaBox includes all of the following three rectangles this.mediaBox = new Rectangle(); this.mediaBox.add(this.trimBox); this.mediaBox.add(this.bleedBox); this.mediaBox.add(cropMarksBox); if ("trim-box".equals(cropBoxSelector)) { this.cropBox = this.trimBox; } else if ("bleed-box".equals(cropBoxSelector)) { this.cropBox = this.bleedBox; } else if ("media-box".equals(cropBoxSelector) || cropBoxSelector == null || "".equals(cropBoxSelector)) { this.cropBox = this.mediaBox; } else { final String err = "The crop-box has invalid value: {0}, " + "possible values of crop-box: (trim-box|bleed-box|media-box)"; throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{cropBoxSelector})); } }
// in src/java/org/apache/fop/render/extensions/prepress/PageBoundaries.java
private static Rectangle getRectangleUsingOffset(Rectangle originalRect, String offset) { if (offset == null || "".equals(offset) || originalRect == null) { return originalRect; } String[] offsets = WHITESPACE_PATTERN.split(offset); int[] coords = new int[4]; // top, right, bottom, left switch (offsets.length) { case 1: coords[0] = getLengthIntValue(offsets[0]); coords[1] = coords[0]; coords[2] = coords[0]; coords[3] = coords[0]; break; case 2: coords[0] = getLengthIntValue(offsets[0]); coords[1] = getLengthIntValue(offsets[1]); coords[2] = coords[0]; coords[3] = coords[1]; break; case 3: coords[0] = getLengthIntValue(offsets[0]); coords[1] = getLengthIntValue(offsets[1]); coords[2] = getLengthIntValue(offsets[2]); coords[3] = coords[1]; break; case 4: coords[0] = getLengthIntValue(offsets[0]); coords[1] = getLengthIntValue(offsets[1]); coords[2] = getLengthIntValue(offsets[2]); coords[3] = getLengthIntValue(offsets[3]); break; default: // TODO throw appropriate exception that can be caught by the event // notification mechanism throw new IllegalArgumentException("Too many arguments"); } return new Rectangle(originalRect.x - coords[3], originalRect.y - coords[0], originalRect.width + coords[3] + coords[1], originalRect.height + coords[0] + coords[2]); }
// in src/java/org/apache/fop/render/extensions/prepress/PageBoundaries.java
private static int getLengthIntValue(final String length) { final String err = "Incorrect length value: {0}"; Matcher m = SIZE_UNIT_PATTERN.matcher(length); if (m.find()) { return FixedLength.getInstance(Double.parseDouble(m.group(1)), m.group(2)).getLength().getValue(); } else { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{length})); } }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
public static Point2D getScale(String scale) { // TODO throw appropriate exceptions that can be caught by the event // notification mechanism final String err = "Extension 'scale' attribute has incorrect value(s): {0}"; if (scale == null || scale.equals("")) { return null; } String[] scales = WHITESPACE_PATTERN.split(scale); double scaleX; try { scaleX = Double.parseDouble(scales[0]); } catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); } double scaleY; switch (scales.length) { case 1: scaleY = scaleX; break; case 2: try { scaleY = Double.parseDouble(scales[1]); } catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); } break; default: throw new IllegalArgumentException("Too many arguments"); } if (scaleX <= 0 || scaleY <= 0) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); } return new Point2D.Double(scaleX, scaleY); }
// in src/java/org/apache/fop/afp/AFPDataObjectFactory.java
public ImageObject createImage(AFPImageObjectInfo imageObjectInfo) { // IOCA bitmap image ImageObject imageObj = factory.createImageObject(); // set data object viewport (i.e. position, rotation, dimension, resolution) imageObj.setViewport(imageObjectInfo); if (imageObjectInfo.hasCompression()) { int compression = imageObjectInfo.getCompression(); switch (compression) { case TIFFImage.COMP_FAX_G3_1D: imageObj.setEncoding(ImageContent.COMPID_G3_MH); break; case TIFFImage.COMP_FAX_G3_2D: imageObj.setEncoding(ImageContent.COMPID_G3_MR); break; case TIFFImage.COMP_FAX_G4_2D: imageObj.setEncoding(ImageContent.COMPID_G3_MMR); break; case ImageContent.COMPID_JPEG: imageObj.setEncoding((byte)compression); break; default: throw new IllegalStateException( "Invalid compression scheme: " + compression); } } ImageContent content = imageObj.getImageSegment().getImageContent(); int bitsPerPixel = imageObjectInfo.getBitsPerPixel(); imageObj.setIDESize((byte) bitsPerPixel); IDEStructureParameter ideStruct; switch (bitsPerPixel) { case 1: //Skip IDE Structure Parameter break; case 4: case 8: //A grayscale image ideStruct = content.needIDEStructureParameter(); ideStruct.setBitsPerComponent(new int[] {bitsPerPixel}); ideStruct.setColorModel(IDEStructureParameter.COLOR_MODEL_YCBCR); break; case 24: ideStruct = content.needIDEStructureParameter(); ideStruct.setDefaultRGBColorModel(); break; case 32: ideStruct = content.needIDEStructureParameter(); ideStruct.setDefaultCMYKColorModel(); break; default: throw new IllegalArgumentException("Unsupported number of bits per pixel: " + bitsPerPixel); } if (bitsPerPixel > 1 && imageObjectInfo.isSubtractive()) { ideStruct = content.needIDEStructureParameter(); ideStruct.setSubtractive(imageObjectInfo.isSubtractive()); } imageObj.setData(imageObjectInfo.getData()); return imageObj; }
// in src/java/org/apache/fop/afp/fonts/CharactersetEncoder.java
public void writeTo(OutputStream out, int offset, int length) throws IOException { if (offset < 0 || length < 0 || offset + length > bytes.length) { throw new IllegalArgumentException(); } out.write(bytes, this.offset + offset, length); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetOrientation.java
public int getWidth(char character) { if (character >= charsWidths.length) { throw new IllegalArgumentException("Invalid character: " + character + " (" + Integer.toString(character) + "), maximum is " + (charsWidths.length - 1)); } return charsWidths[character]; }
// in src/java/org/apache/fop/afp/AFPPaintingState.java
public void setPortraitRotation(int rotation) { if (rotation == 0 || rotation == 90 || rotation == 180 || rotation == 270) { portraitRotation = rotation; } else { throw new IllegalArgumentException("The portrait rotation must be one" + " of the values 0, 90, 180, 270"); } }
// in src/java/org/apache/fop/afp/AFPPaintingState.java
public void setLandscapeRotation(int rotation) { if (rotation == 0 || rotation == 90 || rotation == 180 || rotation == 270) { landscapeRotation = rotation; } else { throw new IllegalArgumentException("The landscape rotation must be one" + " of the values 0, 90, 180, 270"); } }
// in src/java/org/apache/fop/afp/modca/MapPageSegment.java
public void addPageSegment(String name) throws MaximumSizeExceededException { if (getPageSegments().size() > MAX_SIZE) { throw new MaximumSizeExceededException(); } if (name.length() > 8) { throw new IllegalArgumentException("The name of page segment " + name + " must not be longer than 8 characters"); } if (LOG.isDebugEnabled()) { LOG.debug("addPageSegment():: adding page segment " + name); } getPageSegments().add(name); }
// in src/java/org/apache/fop/afp/modca/AxisOrientation.java
public static AxisOrientation getRightHandedAxisOrientationFor(int orientation) { switch (orientation) { case 0: return RIGHT_HANDED_0; case 90: return RIGHT_HANDED_90; case 180: return RIGHT_HANDED_180; case 270: return RIGHT_HANDED_270; default: throw new IllegalArgumentException( "The orientation must be one of the values 0, 90, 180, 270"); } }
// in src/java/org/apache/fop/afp/modca/IncludePageOverlay.java
public void setOrientation(int orientation) { if (orientation == 0 || orientation == 90 || orientation == 180 || orientation == 270) { this.orientation = orientation; } else { throw new IllegalArgumentException( "The orientation must be one of the values 0, 90, 180, 270"); } }
// in src/java/org/apache/fop/afp/modca/triplets/AttributeValueTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = super.getData(); data[2] = 0x00; // Reserved data[3] = 0x00; // Reserved // convert name and value to ebcdic byte[] tleByteValue = null; try { tleByteValue = attVal.getBytes(AFPConstants.EBCIDIC_ENCODING); } catch (UnsupportedEncodingException usee) { tleByteValue = attVal.getBytes(); throw new IllegalArgumentException(attVal + " encoding failed"); } System.arraycopy(tleByteValue, 0, data, 4, tleByteValue.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/triplets/FullyQualifiedNameTriplet.java
public void writeToStream(OutputStream os) throws IOException { byte[] data = getData(); data[2] = type; data[3] = format; // FQName byte[] fqNameBytes; String encoding = AFPConstants.EBCIDIC_ENCODING; if (format == FORMAT_URL) { encoding = AFPConstants.US_ASCII_ENCODING; } try { fqNameBytes = fqName.getBytes(encoding); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( encoding + " encoding failed"); } System.arraycopy(fqNameBytes, 0, data, 4, fqNameBytes.length); os.write(data); }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
public void addFont(int fontReference, AFPFont font, int size, int orientation) throws MaximumSizeExceededException { FontDefinition fontDefinition = new FontDefinition(); fontDefinition.fontReferenceKey = BinaryUtils.convert(fontReference)[0]; switch (orientation) { case 90: fontDefinition.orientation = 0x2D; break; case 180: fontDefinition.orientation = 0x5A; break; case 270: fontDefinition.orientation = (byte) 0x87; break; default: fontDefinition.orientation = 0x00; break; } try { if (font instanceof RasterFont) { RasterFont raster = (RasterFont) font; CharacterSet cs = raster.getCharacterSet(size); if (cs == null) { String msg = "Character set not found for font " + font.getFontName() + " with point size " + size; LOG.error(msg); throw new FontRuntimeException(msg); } fontDefinition.characterSet = cs.getNameBytes(); if (fontDefinition.characterSet.length != 8) { throw new IllegalArgumentException("The character set " + new String(fontDefinition.characterSet, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof OutlineFont) { OutlineFont outline = (OutlineFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof DoubleByteFont) { DoubleByteFont outline = (DoubleByteFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); //TODO Relax requirement for 8 characters if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else { String msg = "Font of type " + font.getClass().getName() + " not recognized."; LOG.error(msg); throw new FontRuntimeException(msg); } if (fontList.size() > 253) { // Throw an exception if the size is exceeded throw new MaximumSizeExceededException(); } else { fontList.add(fontDefinition); } } catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); } }
// in src/java/org/apache/fop/afp/modca/InterchangeSet.java
public static InterchangeSet valueOf(String str) { if (MODCA_PRESENTATION_INTERCHANGE_SET_1.equals(str)) { return new InterchangeSet(SET_1); } else if (MODCA_PRESENTATION_INTERCHANGE_SET_2.equals(str)) { return new InterchangeSet(SET_2); } else if (MODCA_RESOURCE_INTERCHANGE_SET.equals(str)) { return new InterchangeSet(RESOURCE_SET); } else { throw new IllegalArgumentException("Invalid MO:DCA interchange set :" + str); } }
// in src/java/org/apache/fop/afp/modca/MapPageOverlay.java
public void addOverlay(String name) throws MaximumSizeExceededException { if (getOverlays().size() > MAX_SIZE) { throw new MaximumSizeExceededException(); } if (name.length() != 8) { throw new IllegalArgumentException("The name of overlay " + name + " must be 8 characters"); } if (LOG.isDebugEnabled()) { LOG.debug("addOverlay():: adding overlay " + name); } try { byte[] data = name.getBytes(AFPConstants.EBCIDIC_ENCODING); getOverlays().add(data); } catch (UnsupportedEncodingException usee) { LOG.error("addOverlay():: UnsupportedEncodingException translating the name " + name); } }
// in src/java/org/apache/fop/afp/util/CubicBezierApproximator.java
public static double[][] fixedMidPointApproximation(double[] cubicControlPointCoords) { if (cubicControlPointCoords.length < 8) { throw new IllegalArgumentException("Must have at least 8 coordinates"); } //extract point objects from source array Point2D p0 = new Point2D.Double(cubicControlPointCoords[0], cubicControlPointCoords[1]); Point2D p1 = new Point2D.Double(cubicControlPointCoords[2], cubicControlPointCoords[3]); Point2D p2 = new Point2D.Double(cubicControlPointCoords[4], cubicControlPointCoords[5]); Point2D p3 = new Point2D.Double(cubicControlPointCoords[6], cubicControlPointCoords[7]); //calculates the useful base points Point2D pa = getPointOnSegment(p0, p1, 3.0 / 4.0); Point2D pb = getPointOnSegment(p3, p2, 3.0 / 4.0); //get 1/16 of the [P3, P0] segment double dx = (p3.getX() - p0.getX()) / 16.0; double dy = (p3.getY() - p0.getY()) / 16.0; //calculates control point 1 Point2D pc1 = getPointOnSegment(p0, p1, 3.0 / 8.0); //calculates control point 2 Point2D pc2 = getPointOnSegment(pa, pb, 3.0 / 8.0); pc2 = movePoint(pc2, -dx, -dy); //calculates control point 3 Point2D pc3 = getPointOnSegment(pb, pa, 3.0 / 8.0); pc3 = movePoint(pc3, dx, dy); //calculates control point 4 Point2D pc4 = getPointOnSegment(p3, p2, 3.0 / 8.0); //calculates the 3 anchor points Point2D pa1 = getMidPoint(pc1, pc2); Point2D pa2 = getMidPoint(pa, pb); Point2D pa3 = getMidPoint(pc3, pc4); //return the points for the four quadratic curves return new double[][] { {pc1.getX(), pc1.getY(), pa1.getX(), pa1.getY()}, {pc2.getX(), pc2.getY(), pa2.getX(), pa2.getY()}, {pc3.getX(), pc3.getY(), pa3.getX(), pa3.getY()}, {pc4.getX(), pc4.getY(), p3.getX(), p3.getY()}}; }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
private static String getResourceName(UnparsedStructuredField field) throws UnsupportedEncodingException { //The first 8 bytes of the field data represent the resource name byte[] nameBytes = new byte[8]; byte[] fieldData = field.getData(); if (fieldData.length < 8) { throw new IllegalArgumentException("Field data does not contain a resource name"); } System.arraycopy(fieldData, 0, nameBytes, 0, 8); return new String(nameBytes, AFPConstants.EBCIDIC_ENCODING); }
// in src/java/org/apache/fop/afp/util/BinaryUtils.java
public static byte[] convert(String digits) { if (digits.length() % 2 == 0) { // Even number of digits, so ignore } else { // Convert to an even number of digits digits = "0" + digits; } ByteArrayOutputStream baos = new ByteArrayOutputStream(); for (int i = 0; i < digits.length(); i += 2) { char c1 = digits.charAt(i); char c2 = digits.charAt(i + 1); byte b = 0; if ((c1 >= '0') && (c1 <= '9')) { b += ((c1 - '0') * 16); } else if ((c1 >= 'a') && (c1 <= 'f')) { b += ((c1 - 'a' + 10) * 16); } else if ((c1 >= 'A') && (c1 <= 'F')) { b += ((c1 - 'A' + 10) * 16); } else { throw new IllegalArgumentException("Bad hexadecimal digit"); } if ((c2 >= '0') && (c2 <= '9')) { b += (c2 - '0'); } else if ((c2 >= 'a') && (c2 <= 'f')) { b += (c2 - 'a' + 10); } else if ((c2 >= 'A') && (c2 <= 'F')) { b += (c2 - 'A' + 10); } else { throw new IllegalArgumentException("Bad hexadecimal digit"); } baos.write(b); } return (baos.toByteArray()); }
// in src/java/org/apache/fop/afp/ioca/IDEStructureParameter.java
public void setUniformBitsPerComponent(int numComponents, int bitsPerComponent) { if (bitsPerComponent < 0 || bitsPerComponent >= 256) { throw new IllegalArgumentException( "The number of bits per component must be between 0 and 255"); } this.bitsPerIDE = new byte[numComponents]; for (int i = 0; i < numComponents; i++) { this.bitsPerIDE[i] = (byte)bitsPerComponent; } }
// in src/java/org/apache/fop/afp/ioca/IDEStructureParameter.java
public void setBitsPerComponent(int[] bitsPerComponent) { int numComponents = bitsPerComponent.length; this.bitsPerIDE = new byte[numComponents]; for (int i = 0; i < numComponents; i++) { int bits = bitsPerComponent[i]; if (bits < 0 || bits >= 256) { throw new IllegalArgumentException( "The number of bits per component must be between 0 and 255"); } this.bitsPerIDE[i] = (byte)bits; } }
// in src/java/org/apache/fop/afp/ioca/ImageOutputControl.java
public void setOrientation(int orientation) { if (orientation == 0 || orientation == 90 || orientation == 180 || orientation == 270) { this.orientation = orientation; } else { throw new IllegalArgumentException( "The orientation must be one of the values 0, 90, 180, 270"); } }
// in src/java/org/apache/fop/afp/AFPResourceLevelDefaults.java
private static byte getResourceType(String resourceTypeName) { Byte result = (Byte)RESOURCE_TYPE_NAMES.get(resourceTypeName.toLowerCase()); if (result == null) { throw new IllegalArgumentException("Unknown resource type name: " + resourceTypeName); } return result.byteValue(); }
// in src/java/org/apache/fop/events/EventExceptionManager.java
public static void throwException(Event event, String exceptionClass) throws Throwable { if (exceptionClass != null) { ExceptionFactory factory = (ExceptionFactory)EXCEPTION_FACTORIES.get(exceptionClass); if (factory != null) { throw factory.createException(event); } else { throw new IllegalArgumentException( "No such ExceptionFactory available: " + exceptionClass); } } else { String msg = EventFormatter.format(event); //Get original exception as cause if it is given as one of the parameters Throwable t = null; Iterator<Object> iter = event.getParams().values().iterator(); while (iter.hasNext()) { Object o = iter.next(); if (o instanceof Throwable) { t = (Throwable)o; break; } } if (t != null) { throw new RuntimeException(msg, t); } else { throw new RuntimeException(msg); } } }
// in src/java/org/apache/fop/events/model/EventSeverity.java
public static EventSeverity valueOf(String name) { if (INFO.getName().equalsIgnoreCase(name)) { return INFO; } else if (WARN.getName().equalsIgnoreCase(name)) { return WARN; } else if (ERROR.getName().equalsIgnoreCase(name)) { return ERROR; } else if (FATAL.getName().equalsIgnoreCase(name)) { return FATAL; } else { throw new IllegalArgumentException("Illegal value for enumeration: " + name); } }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
public EventProducer getEventProducerFor(Class clazz) { if (!EventProducer.class.isAssignableFrom(clazz)) { throw new IllegalArgumentException( "Class must be an implementation of the EventProducer interface: " + clazz.getName()); } EventProducer producer; producer = (EventProducer)this.proxies.get(clazz); if (producer == null) { producer = createProxyFor(clazz); this.proxies.put(clazz, producer); } return producer; }
// in src/java/org/apache/fop/area/Page.java
public RegionViewport getRegionViewport(int areaClass) { switch (areaClass) { case FO_REGION_BEFORE: return regionBefore; case FO_REGION_START: return regionStart; case FO_REGION_BODY: return regionBody; case FO_REGION_END: return regionEnd; case FO_REGION_AFTER: return regionAfter; default: throw new IllegalArgumentException("No such area class with ID = " + areaClass); } }
// in src/java/org/apache/fop/area/inline/InlineBlockParent.java
Override public void addChildArea(Area childArea) { if (child != null) { throw new IllegalStateException("InlineBlockParent may have only one child area."); } if (childArea instanceof Block) { child = (Block) childArea; //Update extents from the child setIPD(childArea.getAllocIPD()); setBPD(childArea.getAllocBPD()); } else { throw new IllegalArgumentException("The child of an InlineBlockParent must be a" + " Block area"); } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
private void setTraits(Attributes attributes, Area area, Object[] traitSubset) { for (int i = traitSubset.length; --i >= 0;) { Integer trait = (Integer) traitSubset[i]; String traitName = Trait.getTraitName(trait); String value = attributes.getValue(traitName); if (value != null) { Class cl = Trait.getTraitClass(trait); if (cl == Integer.class) { area.addTrait(trait, new Integer(value)); } else if (cl == Boolean.class) { area.addTrait(trait, Boolean.valueOf(value)); } else if (cl == String.class) { area.addTrait(trait, value); if (Trait.PROD_ID.equals(trait) && !idFirstsAssigned.contains(value) && currentPageViewport != null) { currentPageViewport.setFirstWithID(value); idFirstsAssigned.add(value); } } else if (cl == Color.class) { try { area.addTrait(trait, ColorUtil.parseColorString(this.userAgent, value)); } catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); } } else if (cl == InternalLink.class) { area.addTrait(trait, new InternalLink(value)); } else if (cl == Trait.ExternalLink.class) { area.addTrait(trait, Trait.ExternalLink.makeFromTraitValue(value)); } else if (cl == Background.class) { Background bkg = new Background(); try { Color col = ColorUtil.parseColorString( this.userAgent, attributes.getValue("bkg-color")); bkg.setColor(col); } catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); } String uri = attributes.getValue("bkg-img"); if (uri != null) { bkg.setURL(uri); try { ImageManager manager = userAgent.getFactory().getImageManager(); ImageSessionContext sessionContext = userAgent.getImageSessionContext(); ImageInfo info = manager.getImageInfo(uri, sessionContext); bkg.setImageInfo(info); } catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageError(this, uri, e, getLocator()); } catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageNotFound(this, uri, fnfe, getLocator()); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageIOError(this, uri, ioe, getLocator()); } String repeat = attributes.getValue("bkg-repeat"); if (repeat != null) { bkg.setRepeat(repeat); } bkg.setHoriz(XMLUtil.getAttributeAsInt(attributes, "bkg-horz-offset", 0)); bkg.setVertical(XMLUtil.getAttributeAsInt(attributes, "bkg-vert-offset", 0)); } area.addTrait(trait, bkg); } else if (cl == BorderProps.class) { area.addTrait(trait, BorderProps.valueOf(this.userAgent, value)); } } else { if (Trait.FONT.equals(trait)) { String fontName = attributes.getValue("font-name"); if (fontName != null) { String fontStyle = attributes.getValue("font-style"); int fontWeight = XMLUtil.getAttributeAsInt( attributes, "font-weight", Font.WEIGHT_NORMAL); area.addTrait(trait, FontInfo.createFontKey(fontName, fontStyle, fontWeight)); } } } } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
private static CTM getAttributeAsCTM(Attributes attributes, String name) { String s = attributes.getValue(name).trim(); if (s.startsWith("[") && s.endsWith("]")) { s = s.substring(1, s.length() - 1); double[] values = ConversionUtils.toDoubleArray(s, "\\s"); if (values.length != 6) { throw new IllegalArgumentException("CTM must consist of 6 double values!"); } return new CTM(values[0], values[1], values[2], values[3], values[4], values[5]); } else { throw new IllegalArgumentException("CTM must be surrounded by square brackets!"); } }
// in src/java/org/apache/fop/area/Trait.java
protected static ExternalLink makeFromTraitValue(String traitValue) { String dest = null; boolean newWindow = false; String[] values = traitValue.split(","); for (int i = 0, c = values.length; i < c; i++) { String v = values[i]; if (v.startsWith("dest=")) { dest = v.substring(5); } else if (v.startsWith("newWindow=")) { newWindow = Boolean.valueOf(v.substring(10)); } else { throw new IllegalArgumentException( "Malformed trait value for Trait.ExternalLink: " + traitValue); } } return new ExternalLink(dest, newWindow); }
// in src/java/org/apache/fop/area/Area.java
public int getTraitAsInteger(Integer traitCode) { final Object obj = getTrait(traitCode); if (obj instanceof Integer) { return (Integer) obj; } else { throw new IllegalArgumentException("Trait " + traitCode.getClass().getName() + " could not be converted to an integer"); } }
// in src/java/org/apache/fop/area/Span.java
public NormalFlow getNormalFlow(int colRequested) { if (colRequested >= 0 && colRequested < colCount) { return flowAreas.get(colRequested); } else { // internal error throw new IllegalArgumentException("Invalid column number " + colRequested + " requested; only 0-" + (colCount - 1) + " available."); } }
// in src/java/org/apache/fop/traits/BorderProps.java
public static BorderProps valueOf(FOUserAgent foUserAgent, String s) { if (s.startsWith("(") && s.endsWith(")")) { s = s.substring(1, s.length() - 1); Pattern pattern = Pattern.compile("([^,\\(]+(?:\\(.*\\))?)"); Matcher m = pattern.matcher(s); boolean found; found = m.find(); String style = m.group(); found = m.find(); String color = m.group(); found = m.find(); int width = Integer.parseInt(m.group()); int mode = SEPARATE; found = m.find(); if (found) { String ms = m.group(); if ("collapse-inner".equalsIgnoreCase(ms)) { mode = COLLAPSE_INNER; } else if ("collapse-outer".equalsIgnoreCase(ms)) { mode = COLLAPSE_OUTER; } } Color c; try { c = ColorUtil.parseColorString(foUserAgent, color); } catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); } return new BorderProps(style, width, c, mode); } else { throw new IllegalArgumentException("BorderProps must be surrounded by parentheses"); } }
// in src/java/org/apache/fop/traits/Direction.java
public static Direction valueOf(String name) { for (int i = 0; i < DIRECTIONS.length; i++) { if (DIRECTIONS[i].getName().equalsIgnoreCase(name)) { return DIRECTIONS[i]; } } throw new IllegalArgumentException("Illegal direction: " + name); }
// in src/java/org/apache/fop/traits/Direction.java
public static Direction valueOf(int enumValue) { for (int i = 0; i < DIRECTIONS.length; i++) { if (DIRECTIONS[i].getEnumValue() == enumValue) { return DIRECTIONS[i]; } } throw new IllegalArgumentException("Illegal direction: " + enumValue); }
// in src/java/org/apache/fop/traits/WritingMode.java
public static WritingMode valueOf(String name) { for (int i = 0; i < WRITING_MODES.length; i++) { if (WRITING_MODES[i].getName().equalsIgnoreCase(name)) { return WRITING_MODES[i]; } } throw new IllegalArgumentException("Illegal writing mode: " + name); }
// in src/java/org/apache/fop/traits/WritingMode.java
public static WritingMode valueOf(int enumValue) { for (int i = 0; i < WRITING_MODES.length; i++) { if (WRITING_MODES[i].getEnumValue() == enumValue) { return WRITING_MODES[i]; } } throw new IllegalArgumentException("Illegal writing mode: " + enumValue); }
// in src/java/org/apache/fop/traits/RuleStyle.java
public static RuleStyle valueOf(String name) { for (int i = 0; i < STYLES.length; i++) { if (STYLES[i].getName().equalsIgnoreCase(name)) { return STYLES[i]; } } throw new IllegalArgumentException("Illegal rule style: " + name); }
// in src/java/org/apache/fop/traits/RuleStyle.java
public static RuleStyle valueOf(int enumValue) { for (int i = 0; i < STYLES.length; i++) { if (STYLES[i].getEnumValue() == enumValue) { return STYLES[i]; } } throw new IllegalArgumentException("Illegal rule style: " + enumValue); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public static MinOptMax getInstance(int min, int opt, int max) throws IllegalArgumentException { if (min > opt) { throw new IllegalArgumentException("min (" + min + ") > opt (" + opt + ")"); } if (max < opt) { throw new IllegalArgumentException("max (" + max + ") < opt (" + opt + ")"); } return new MinOptMax(min, opt, max); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax mult(int factor) throws IllegalArgumentException { if (factor < 0) { throw new IllegalArgumentException("factor < 0; was: " + factor); } else if (factor == 1) { return this; } else { return getInstance(min * factor, opt * factor, max * factor); } }
// in src/java/org/apache/fop/traits/BorderStyle.java
public static BorderStyle valueOf(String name) { for (int i = 0; i < STYLES.length; i++) { if (STYLES[i].getName().equalsIgnoreCase(name)) { return STYLES[i]; } } throw new IllegalArgumentException("Illegal border style: " + name); }
// in src/java/org/apache/fop/traits/BorderStyle.java
public static BorderStyle valueOf(int enumValue) { for (int i = 0; i < STYLES.length; i++) { if (STYLES[i].getEnumValue() == enumValue) { return STYLES[i]; } } throw new IllegalArgumentException("Illegal border style: " + enumValue); }
// in src/java/org/apache/fop/layoutmgr/SpaceResolver.java
private String toString(Object[] arr1, Object[] arr2) { if (arr1.length != arr2.length) { throw new IllegalArgumentException("The length of both arrays must be equal"); } StringBuffer sb = new StringBuffer("["); for (int i = 0; i < arr1.length; i++) { if (i > 0) { sb.append(", "); } sb.append(String.valueOf(arr1[i])); sb.append("/"); sb.append(String.valueOf(arr2[i])); } sb.append("]"); return sb.toString(); }
// in src/java/org/apache/fop/layoutmgr/PageProvider.java
public Page getPage(boolean isBlank, int index, int relativeTo) { if (relativeTo == RELTO_PAGE_SEQUENCE) { return getPage(isBlank, index); } else if (relativeTo == RELTO_CURRENT_ELEMENT_LIST) { int effIndex = startPageOfCurrentElementList + index; effIndex += startPageOfPageSequence - 1; return getPage(isBlank, effIndex); } else { throw new IllegalArgumentException( "Illegal value for relativeTo: " + relativeTo); } }
// in src/java/org/apache/fop/layoutmgr/LayoutContext.java
public void signalSpanChange(int span) { switch (span) { case Constants.NOT_SET: case Constants.EN_NONE: case Constants.EN_ALL: this.currentSpan = this.nextSpan; this.nextSpan = span; break; default: assert false; throw new IllegalArgumentException("Illegal value on signalSpanChange() for span: " + span); } }
// in src/java/org/apache/fop/layoutmgr/inline/ScaledBaselineTable.java
int getBaseline(int baselineIdentifier) { int offset = 0; if (!isHorizontalWritingMode()) { switch (baselineIdentifier) { case Constants.EN_TOP: case Constants.EN_TEXT_TOP: case Constants.EN_TEXT_BOTTOM: case Constants.EN_BOTTOM: throw new IllegalArgumentException("Baseline " + baselineIdentifier + " only supported for horizontal writing modes"); default: // TODO } } switch (baselineIdentifier) { case Constants.EN_TOP: // fall through case Constants.EN_BEFORE_EDGE: offset = beforeEdgeOffset; break; case Constants.EN_TEXT_TOP: case Constants.EN_TEXT_BEFORE_EDGE: case Constants.EN_HANGING: case Constants.EN_CENTRAL: case Constants.EN_MIDDLE: case Constants.EN_MATHEMATICAL: case Constants.EN_ALPHABETIC: case Constants.EN_IDEOGRAPHIC: case Constants.EN_TEXT_BOTTOM: case Constants.EN_TEXT_AFTER_EDGE: offset = getBaselineDefaultOffset(baselineIdentifier) - dominantBaselineOffset; break; case Constants.EN_BOTTOM: // fall through case Constants.EN_AFTER_EDGE: offset = afterEdgeOffset; break; default: throw new IllegalArgumentException(String.valueOf(baselineIdentifier)); } return offset; }
// in src/java/org/apache/fop/layoutmgr/inline/ScaledBaselineTable.java
private int getBaselineDefaultOffset(int baselineIdentifier) { int offset = 0; switch (baselineIdentifier) { case Constants.EN_TEXT_BEFORE_EDGE: offset = altitude; break; case Constants.EN_HANGING: offset = Math.round(altitude * HANGING_BASELINE_FACTOR); break; case Constants.EN_CENTRAL: offset = (altitude - depth) / 2 + depth; break; case Constants.EN_MIDDLE: offset = xHeight / 2; break; case Constants.EN_MATHEMATICAL: offset = Math.round(altitude * MATHEMATICAL_BASELINE_FACTOR); break; case Constants.EN_ALPHABETIC: offset = 0; break; case Constants.EN_IDEOGRAPHIC: // Fall through case Constants.EN_TEXT_AFTER_EDGE: offset = depth; break; default: throw new IllegalArgumentException(String.valueOf(baselineIdentifier)); } return offset; }
// in src/java/org/apache/fop/layoutmgr/inline/AlignmentContext.java
private void setAlignmentBaselineIdentifier(int alignmentBaseline , int parentDominantBaselineIdentifier) { switch (alignmentBaseline) { case EN_AUTO: // fall through case EN_BASELINE: this.alignmentBaselineIdentifier = parentDominantBaselineIdentifier; break; case EN_BEFORE_EDGE: case EN_TEXT_BEFORE_EDGE: case EN_CENTRAL: case EN_MIDDLE: case EN_AFTER_EDGE: case EN_TEXT_AFTER_EDGE: case EN_IDEOGRAPHIC: case EN_ALPHABETIC: case EN_HANGING: case EN_MATHEMATICAL: this.alignmentBaselineIdentifier = alignmentBaseline; break; default: throw new IllegalArgumentException(String.valueOf(alignmentBaseline)); } }
// in src/java/org/apache/fop/layoutmgr/inline/AlignmentContext.java
private void setBaselineShift(Length baselineShift) { baselineShiftValue = 0; switch (baselineShift.getEnum()) { case EN_BASELINE: //Nothing to do break; case EN_SUB: baselineShiftValue = Math.round(-(xHeight / 2) + parentAlignmentContext.getActualBaselineOffset(EN_ALPHABETIC) ); break; case EN_SUPER: baselineShiftValue = Math.round(parentAlignmentContext.getXHeight() + parentAlignmentContext.getActualBaselineOffset(EN_ALPHABETIC) ); break; case 0: // A <length> or <percentage> value baselineShiftValue = baselineShift.getValue( new SimplePercentBaseContext(null , LengthBase.CUSTOM_BASE , parentAlignmentContext.getLineHeight())); break; default: throw new IllegalArgumentException(String.valueOf(baselineShift.getEnum())); } }
// in src/java/org/apache/fop/layoutmgr/Keep.java
private static int getKeepContextPriority(int context) { switch (context) { case Constants.EN_LINE: return 0; case Constants.EN_COLUMN: return 1; case Constants.EN_PAGE: return 2; case Constants.EN_AUTO: return 3; default: throw new IllegalArgumentException(); } }
// in src/java/org/apache/fop/layoutmgr/AbstractLayoutManager.java
private void verifyNonNullPosition(Position pos) { if (pos == null || pos.getIndex() < 0) { throw new IllegalArgumentException( "Only non-null Positions with an index can be checked"); } }
// in src/java/org/apache/fop/layoutmgr/BreakingAlgorithm.java
protected final KnuthElement handleElementAt(int position, boolean previousIsBox, int allowedBreaks) { KnuthElement element = getElement(position); if (element.isBox()) { handleBox((KnuthBox) element); } else if (element.isGlue()) { handleGlueAt((KnuthGlue) element, position, previousIsBox, allowedBreaks); } else if (element.isPenalty()) { handlePenaltyAt((KnuthPenalty) element, position, allowedBreaks); } else { throw new IllegalArgumentException( "Unknown KnuthElement type: expecting KnuthBox, KnuthGlue or KnuthPenalty"); } return element; }
// in src/java/org/apache/fop/layoutmgr/PositionIterator.java
protected Position getPos(Object nextObj) { if (nextObj instanceof Position) { return (Position)nextObj; } throw new IllegalArgumentException( "Cannot obtain Position from the given object."); }
// in src/java/org/apache/fop/layoutmgr/table/CollapsingBorderModel.java
public static CollapsingBorderModel getBorderModelFor(int borderCollapse) { switch (borderCollapse) { case Constants.EN_COLLAPSE: if (collapse == null) { collapse = new CollapsingBorderModelEyeCatching(); } return collapse; case Constants.EN_COLLAPSE_WITH_PRECEDENCE: throw new UnsupportedOperationException ( "collapse-with-precedence not yet supported" ); default: throw new IllegalArgumentException("Illegal border-collapse mode."); } }
// in src/java/org/apache/fop/layoutmgr/table/CollapsingBorderModel.java
public/*TODO*/ static int getOtherSide(int side) { switch (side) { case CommonBorderPaddingBackground.BEFORE: return CommonBorderPaddingBackground.AFTER; case CommonBorderPaddingBackground.AFTER: return CommonBorderPaddingBackground.BEFORE; case CommonBorderPaddingBackground.START: return CommonBorderPaddingBackground.END; case CommonBorderPaddingBackground.END: return CommonBorderPaddingBackground.START; default: throw new IllegalArgumentException("Illegal parameter: side"); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphMappingTable.java
public int[] getInterval ( int[] interval ) { if ( ( interval == null ) || ( interval.length != 2 ) ) { throw new IllegalArgumentException(); } else { interval[0] = gidStart; interval[1] = gidEnd; } return interval; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphs ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { if ( count < 0 ) { count = getGlyphsAvailable ( offset, reverseOrder, ignoreTester ) [ 0 ]; } int start = index + offset; if ( start < 0 ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else if ( ! reverseOrder && ( ( start + count ) > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start + count ) ); } else if ( reverseOrder && ( ( start + 1 ) < count ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start - count ) ); } if ( glyphs == null ) { glyphs = new int [ count ]; } else if ( glyphs.length != count ) { throw new IllegalArgumentException ( "glyphs array is non-null, but its length (" + glyphs.length + "), is not equal to count (" + count + ")" ); } if ( ! reverseOrder ) { return getGlyphsForward ( start, count, ignoreTester, glyphs, counts ); } else { return getGlyphsReverse ( start, count, ignoreTester, glyphs, counts ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation[] getAssociations ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, GlyphSequence.CharAssociation[] associations, int[] counts ) throws IndexOutOfBoundsException { if ( count < 0 ) { count = getGlyphsAvailable ( offset, reverseOrder, ignoreTester ) [ 0 ]; } int start = index + offset; if ( start < 0 ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else if ( ! reverseOrder && ( ( start + count ) > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start + count ) ); } else if ( reverseOrder && ( ( start + 1 ) < count ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start - count ) ); } if ( associations == null ) { associations = new GlyphSequence.CharAssociation [ count ]; } else if ( associations.length != count ) { throw new IllegalArgumentException ( "associations array is non-null, but its length (" + associations.length + "), is not equal to count (" + count + ")" ); } if ( ! reverseOrder ) { return getAssociationsForward ( start, count, ignoreTester, associations, counts ); } else { return getAssociationsReverse ( start, count, ignoreTester, associations, counts ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int getGlyphForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( ci <= ciMax ) { return gi + delta; } else { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + ciMax ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int getGlyphForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( glyphs == null ) { return -1; } else if ( ci >= glyphs.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + glyphs.length ); } else { return glyphs [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int[] getGlyphsForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( gsa == null ) { return null; } else if ( ci >= gsa.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + gsa.length ); } else { return gsa [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int[] getAlternatesForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( gaa == null ) { return null; } else if ( ci >= gaa.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + gaa.length ); } else { return gaa [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public LigatureSet getLigatureSetForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( ligatureSets == null ) { return null; } else if ( ci >= ligatureSets.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + ligatureSets.length ); } else { return ligatureSets [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java
private static void resolveRuns ( int[] wca, int defaultLevel, int[] ea, int[] la ) { if ( la.length != wca.length ) { throw new IllegalArgumentException ( "levels sequence length must match classes sequence length" ); } else if ( la.length != ea.length ) { throw new IllegalArgumentException ( "levels sequence length must match embeddings sequence length" ); } else { for ( int i = 0, n = ea.length, lPrev = defaultLevel; i < n; ) { int s = i; int e = s; int l = findNextNonRetainedFormattingLevel ( wca, ea, s, lPrev ); while ( e < n ) { if ( la [ e ] != l ) { if ( startsWithRetainedFormattingRun ( wca, ea, e ) ) { e += getLevelRunLength ( ea, e ); } else { break; } } else { e++; } } lPrev = resolveRun ( wca, defaultLevel, ea, la, s, e, l, lPrev ); i = e; } } }
// in src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java
private static void resolveAdjacentBoundaryNeutrals ( int[] wca, int start, int end, int index, int bcNew ) { if ( ( index < start ) || ( index >= end ) ) { throw new IllegalArgumentException(); } else { for ( int i = index - 1; i >= start; i-- ) { int bc = wca [ i ]; if ( bc == BN ) { wca [ i ] = bcNew; } else { break; } } for ( int i = index + 1; i < end; i++ ) { int bc = wca [ i ]; if ( bc == BN ) { wca [ i ] = bcNew; } else { break; } } } }
// in src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java
private static boolean convertToScalar ( CharSequence cs, int[] chars ) throws IllegalArgumentException { boolean triggered = false; if ( chars.length != cs.length() ) { throw new IllegalArgumentException ( "characters array length must match input sequence length" ); } for ( int i = 0, n = chars.length; i < n; ) { int chIn = cs.charAt ( i ); int chOut; if ( chIn < 0xD800 ) { chOut = chIn; } else if ( chIn < 0xDC00 ) { int chHi = chIn; int chLo; if ( ( i + 1 ) < n ) { chLo = cs.charAt ( i + 1 ); if ( ( chLo >= 0xDC00 ) && ( chLo <= 0xDFFF ) ) { chOut = convertToScalar ( chHi, chLo ); } else { throw new IllegalArgumentException ( "isolated high surrogate" ); } } else { throw new IllegalArgumentException ( "truncated surrogate pair" ); } } else if ( chIn < 0xE000 ) { throw new IllegalArgumentException ( "isolated low surrogate" ); } else { chOut = chIn; } if ( ! triggered && triggersBidi ( chOut ) ) { triggered = true; } if ( ( chOut & 0xFF0000 ) == 0 ) { chars [ i++ ] = chOut; } else { chars [ i++ ] = chOut; chars [ i++ ] = -1; } } return triggered; }
// in src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java
private static int convertToScalar ( int chHi, int chLo ) { if ( ( chHi < 0xD800 ) || ( chHi > 0xDBFF ) ) { throw new IllegalArgumentException ( "bad high surrogate" ); } else if ( ( chLo < 0xDC00 ) || ( chLo > 0xDFFF ) ) { throw new IllegalArgumentException ( "bad low surrogate" ); } else { return ( ( ( chHi & 0x03FF ) << 10 ) | ( chLo & 0x03FF ) ) + 0x10000; } }
// in src/java/org/apache/fop/complexscripts/util/NumberConverter.java
private Integer[] formatNumber ( long number, Integer[] token ) { Integer[] fn = null; assert token.length > 0; if ( number < 0 ) { throw new IllegalArgumentException ( "number must be non-negative" ); } else if ( token.length == 1 ) { int s = token[0].intValue(); switch ( s ) { case (int) '1': { fn = formatNumberAsDecimal ( number, (int) '1', 1 ); break; } case (int) 'W': case (int) 'w': { fn = formatNumberAsWord ( number, ( s == (int) 'W' ) ? Character.UPPERCASE_LETTER : Character.LOWERCASE_LETTER ); break; } case (int) 'A': // handled as numeric sequence case (int) 'a': // handled as numeric sequence case (int) 'I': // handled as numeric special case (int) 'i': // handled as numeric special default: { if ( isStartOfDecimalSequence ( s ) ) { fn = formatNumberAsDecimal ( number, s, 1 ); } else if ( isStartOfAlphabeticSequence ( s ) ) { fn = formatNumberAsSequence ( number, s, getSequenceBase ( s ), null ); } else if ( isStartOfNumericSpecial ( s ) ) { fn = formatNumberAsSpecial ( number, s ); } else { fn = null; } break; } } } else if ( ( token.length == 2 ) && ( token[0] == (int) 'W' ) && ( token[1] == (int) 'w' ) ) { fn = formatNumberAsWord ( number, Character.TITLECASE_LETTER ); } else if ( isPaddedOne ( token ) ) { int s = token [ token.length - 1 ].intValue(); fn = formatNumberAsDecimal ( number, s, token.length ); } else { throw new IllegalArgumentException ( "invalid format token: \"" + UTF32.fromUTF32 ( token ) + "\"" ); } if ( fn == null ) { fn = formatNumber ( number, DEFAULT_TOKEN ); } assert fn != null; return fn; }
// in src/java/org/apache/fop/complexscripts/util/UTF32.java
public static Integer[] toUTF32 ( String s, int substitution, boolean errorOnSubstitution ) throws IllegalArgumentException { int n; if ( ( n = s.length() ) == 0 ) { return new Integer[0]; } else { Integer[] sa = new Integer [ n ]; int k = 0; for ( int i = 0; i < n; i++ ) { int c = (int) s.charAt(i); if ( ( c >= 0xD800 ) && ( c < 0xE000 ) ) { int s1 = c; int s2 = ( ( i + 1 ) < n ) ? (int) s.charAt ( i + 1 ) : 0; if ( s1 < 0xDC00 ) { if ( ( s2 >= 0xDC00 ) && ( s2 < 0xE000 ) ) { c = ( ( s1 - 0xD800 ) << 10 ) + ( s2 - 0xDC00 ) + 65536; i++; } else { if ( errorOnSubstitution ) { throw new IllegalArgumentException ( "isolated high (leading) surrogate" ); } else { c = substitution; } } } else { if ( errorOnSubstitution ) { throw new IllegalArgumentException ( "isolated low (trailing) surrogate" ); } else { c = substitution; } } } sa[k++] = c; } if ( k == n ) { return sa; } else { Integer[] na = new Integer [ k ]; System.arraycopy ( sa, 0, na, 0, k ); return na; } } }
// in src/java/org/apache/fop/complexscripts/util/UTF32.java
public static String fromUTF32 ( Integer[] sa ) throws IllegalArgumentException { StringBuffer sb = new StringBuffer(); for ( int s : sa ) { if ( s < 65535 ) { if ( ( s < 0xD800 ) || ( s > 0xDFFF ) ) { sb.append ( (char) s ); } else { String ncr = CharUtilities.charToNCRef(s); throw new IllegalArgumentException ( "illegal scalar value 0x" + ncr.substring(2, ncr.length() - 1) + "; cannot be UTF-16 surrogate" ); } } else if ( s < 1114112 ) { int s1 = ( ( ( s - 65536 ) >> 10 ) & 0x3FF ) + 0xD800; int s2 = ( ( ( s - 65536 ) >> 0 ) & 0x3FF ) + 0xDC00; sb.append ( (char) s1 ); sb.append ( (char) s2 ); } else { String ncr = CharUtilities.charToNCRef(s); throw new IllegalArgumentException ( "illegal scalar value 0x" + ncr.substring(2, ncr.length() - 1) + "; out of range for UTF-16" ); } } return sb.toString(); }
// in src/java/org/apache/fop/util/XMLUtil.java
public static Rectangle2D getAttributeAsRectangle2D(Attributes attributes, String name) { String s = attributes.getValue(name).trim(); double[] values = ConversionUtils.toDoubleArray(s, "\\s"); if (values.length != 4) { throw new IllegalArgumentException("Rectangle must consist of 4 double values!"); } return new Rectangle2D.Double(values[0], values[1], values[2], values[3]); }
// in src/java/org/apache/fop/util/XMLUtil.java
public static Rectangle getAttributeAsRectangle(Attributes attributes, String name) { String s = attributes.getValue(name); if (s == null) { return null; } int[] values = ConversionUtils.toIntArray(s.trim(), "\\s"); if (values.length != 4) { throw new IllegalArgumentException("Rectangle must consist of 4 int values!"); } return new Rectangle(values[0], values[1], values[2], values[3]); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
public void addContentHandlerFactory(String classname) { try { ContentHandlerFactory factory = (ContentHandlerFactory)Class.forName(classname).newInstance(); addContentHandlerFactory(factory); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); } catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ContentHandlerFactory.class.getName()); } }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsJavaAWTColor(String value) throws PropertyException { float red = 0.0f; float green = 0.0f; float blue = 0.0f; int poss = value.indexOf("["); int pose = value.indexOf("]"); try { if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); String[] args = value.split(","); if (args.length != 3) { throw new PropertyException( "Invalid number of arguments for a java.awt.Color: " + value); } red = Float.parseFloat(args[0].trim().substring(2)) / 255f; green = Float.parseFloat(args[1].trim().substring(2)) / 255f; blue = Float.parseFloat(args[2].trim().substring(2)) / 255f; if ((red < 0.0 || red > 1.0) || (green < 0.0 || green > 1.0) || (blue < 0.0 || blue > 1.0)) { throw new PropertyException("Color values out of range"); } } else { throw new IllegalArgumentException( "Invalid format for a java.awt.Color: " + value); } } catch (RuntimeException re) { throw new PropertyException(re); } return new Color(red, green, blue); }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsFopRgbNamedColor(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { String[] args = value.substring(poss + 1, pose).split(","); try { if (args.length != 6) { throw new PropertyException("rgb-named-color() function must have 6 arguments"); } //Set up fallback sRGB value Color sRGB = parseFallback(args, value); /* Get and verify ICC profile name */ String iccProfileName = args[3].trim(); if (iccProfileName == null || "".equals(iccProfileName)) { throw new PropertyException("ICC profile name missing"); } ICC_ColorSpace colorSpace = null; String iccProfileSrc; if (isPseudoProfile(iccProfileName)) { throw new IllegalArgumentException( "Pseudo-profiles are not allowed with fop-rgb-named-color()"); } else { /* Get and verify ICC profile source */ iccProfileSrc = args[4].trim(); if (iccProfileSrc == null || "".equals(iccProfileSrc)) { throw new PropertyException("ICC profile source missing"); } iccProfileSrc = unescapeString(iccProfileSrc); } // color name String colorName = unescapeString(args[5].trim()); /* Ask FOP factory to get ColorSpace for the specified ICC profile source */ if (foUserAgent != null && iccProfileSrc != null) { RenderingIntent renderingIntent = RenderingIntent.AUTO; //TODO connect to fo:color-profile/@rendering-intent colorSpace = (ICC_ColorSpace)foUserAgent.getFactory().getColorSpaceCache().get( iccProfileName, foUserAgent.getBaseURL(), iccProfileSrc, renderingIntent); } if (colorSpace != null) { ICC_Profile profile = colorSpace.getProfile(); if (NamedColorProfileParser.isNamedColorProfile(profile)) { NamedColorProfileParser parser = new NamedColorProfileParser(); NamedColorProfile ncp = parser.parseProfile(profile, iccProfileName, iccProfileSrc); NamedColorSpace ncs = ncp.getNamedColor(colorName); if (ncs != null) { parsedColor = new ColorWithFallback(ncs, new float[] {1.0f}, 1.0f, null, sRGB); } else { log.warn("Color '" + colorName + "' does not exist in named color profile: " + iccProfileSrc); parsedColor = sRGB; } } else { log.warn("ICC profile is no named color profile: " + iccProfileSrc); parsedColor = sRGB; } } else { // ICC profile could not be loaded - use rgb replacement values */ log.warn("Color profile '" + iccProfileSrc + "' not found. Using sRGB replacement values."); parsedColor = sRGB; } } catch (IOException ioe) { //wrap in a PropertyException throw new PropertyException(ioe); } catch (RuntimeException re) { throw new PropertyException(re); //wrap in a PropertyException } } else { throw new PropertyException("Unknown color format: " + value + ". Must be fop-rgb-named-color(r,g,b,NCNAME,src,color-name)"); } return parsedColor; }
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
public static boolean isZeroBlack(RenderedImage img) { if (!isMonochromeImage(img)) { throw new IllegalArgumentException("Image is not a monochrome image!"); } IndexColorModel icm = (IndexColorModel)img.getColorModel(); int gray0 = convertToGray(icm.getRGB(0)); int gray1 = convertToGray(icm.getRGB(1)); return gray0 < gray1; }
// in src/java/org/apache/fop/util/bitmap/DitherUtil.java
public static int[] getBayerBasePattern(int matrix) { int[] result = new int[matrix * matrix]; switch (matrix) { case DITHER_MATRIX_2X2: System.arraycopy(BAYER_D2, 0, result, 0, BAYER_D2.length); break; case DITHER_MATRIX_4X4: System.arraycopy(BAYER_D4, 0, result, 0, BAYER_D4.length); break; case DITHER_MATRIX_8X8: System.arraycopy(BAYER_D8, 0, result, 0, BAYER_D8.length); break; default: throw new IllegalArgumentException("Unsupported dither matrix: " + matrix); } return result; }
// in src/java/org/apache/fop/util/bitmap/DitherUtil.java
public static byte[] getBayerDither(int matrix, int gray255, boolean doubleMatrix) { int ditherIndex; byte[] dither; int[] bayer; switch (matrix) { case DITHER_MATRIX_4X4: ditherIndex = gray255 * 17 / 255; bayer = BAYER_D4; break; case DITHER_MATRIX_8X8: ditherIndex = gray255 * 65 / 255; bayer = BAYER_D8; break; default: throw new IllegalArgumentException("Unsupported dither matrix: " + matrix); } if (doubleMatrix) { if (doubleMatrix && (matrix != DITHER_MATRIX_4X4)) { throw new IllegalArgumentException("doubleMatrix=true is only allowed for 4x4"); } dither = new byte[bayer.length / 8 * 4]; for (int i = 0, c = bayer.length; i < c; i++) { boolean dot = !(bayer[i] < ditherIndex - 1); if (dot) { int byteIdx = i / 4; dither[byteIdx] |= 1 << (i % 4); dither[byteIdx] |= 1 << ((i % 4) + 4); dither[byteIdx + 4] |= 1 << (i % 4); dither[byteIdx + 4] |= 1 << ((i % 4) + 4); } } } else { dither = new byte[bayer.length / 8]; for (int i = 0, c = bayer.length; i < c; i++) { boolean dot = !(bayer[i] < ditherIndex - 1); if (dot) { int byteIdx = i / 8; dither[byteIdx] |= 1 << (i % 8); } } } return dither; }
// in src/java/org/apache/fop/util/BreakUtil.java
private static int getBreakClassPriority(int breakClass) { switch (breakClass) { case Constants.EN_AUTO: return 0; case Constants.EN_COLUMN: return 1; case Constants.EN_PAGE: return 2; case Constants.EN_EVEN_PAGE: return 3; case Constants.EN_ODD_PAGE: return 3; default: throw new IllegalArgumentException( "Illegal value for breakClass: " + breakClass); } }
// in src/java/org/apache/fop/util/text/AdvancedMessageFormat.java
private Part parseField(String field) { String[] parts = COMMA_SEPARATOR_REGEX.split(field, 3); String fieldName = parts[0]; if (parts.length == 1) { if (fieldName.startsWith("#")) { return new FunctionPart(fieldName.substring(1)); } else { return new SimpleFieldPart(fieldName); } } else { String format = parts[1]; PartFactory factory = (PartFactory)PART_FACTORIES.get(format); if (factory == null) { throw new IllegalArgumentException( "No PartFactory available under the name: " + format); } if (parts.length == 2) { return factory.newPart(fieldName, null); } else { return factory.newPart(fieldName, parts[2]); } } }
// in src/java/org/apache/fop/util/text/AdvancedMessageFormat.java
public void write(StringBuffer sb, Map<String, Object> params) { if (!params.containsKey(fieldName)) { throw new IllegalArgumentException( "Message pattern contains unsupported field name: " + fieldName); } Object obj = params.get(fieldName); formatObject(obj, sb); }
// in src/java/org/apache/fop/util/text/HexFieldPart.java
public void write(StringBuffer sb, Map params) { if (!params.containsKey(fieldName)) { throw new IllegalArgumentException( "Message pattern contains unsupported field name: " + fieldName); } Object obj = params.get(fieldName); if (obj instanceof Character) { sb.append(Integer.toHexString(((Character)obj).charValue())); } else if (obj instanceof Number) { sb.append(Integer.toHexString(((Number)obj).intValue())); } else { throw new IllegalArgumentException("Incompatible value for hex field part: " + obj.getClass().getName()); } }
// in src/java/org/apache/fop/util/text/EqualsFieldPart.java
protected void parseValues(String values) { String[] parts = AdvancedMessageFormat.COMMA_SEPARATOR_REGEX.split(values, 3); this.equalsValue = parts[0]; if (parts.length == 1) { throw new IllegalArgumentException( "'equals' format must have at least 2 parameters"); } if (parts.length == 3) { ifValue = AdvancedMessageFormat.unescapeComma(parts[1]); elseValue = AdvancedMessageFormat.unescapeComma(parts[2]); } else { ifValue = AdvancedMessageFormat.unescapeComma(parts[1]); } }
// in src/java/org/apache/fop/util/text/GlyphNameFieldPart.java
private String getGlyphName(Object obj) { if (obj instanceof Character) { return Glyphs.charToGlyphName(((Character)obj).charValue()); } else { throw new IllegalArgumentException( "Value for glyph name part must be a Character but was: " + obj.getClass().getName()); } }
// in src/java/org/apache/fop/util/text/GlyphNameFieldPart.java
public void write(StringBuffer sb, Map params) { if (!params.containsKey(fieldName)) { throw new IllegalArgumentException( "Message pattern contains unsupported field name: " + fieldName); } Object obj = params.get(fieldName); sb.append(getGlyphName(obj)); }
// in src/java/org/apache/fop/image/loader/batik/ImageConverterSVG2G2D.java
public Image convert(final Image src, Map hints) throws ImageException { checkSourceFlavor(src); final ImageXMLDOM svg = (ImageXMLDOM)src; if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(svg.getRootNamespace())) { throw new IllegalArgumentException("XML DOM is not in the SVG namespace: " + svg.getRootNamespace()); } //Prepare float pxToMillimeter = UnitConv.IN2MM / GraphicsConstants.DEFAULT_DPI; Number ptm = (Number)hints.get(ImageProcessingHints.SOURCE_RESOLUTION); if (ptm != null) { pxToMillimeter = (float)(UnitConv.IN2MM / ptm.doubleValue()); } UserAgent ua = createBatikUserAgent(pxToMillimeter); GVTBuilder builder = new GVTBuilder(); final ImageManager imageManager = (ImageManager)hints.get( ImageProcessingHints.IMAGE_MANAGER); final ImageSessionContext sessionContext = (ImageSessionContext)hints.get( ImageProcessingHints.IMAGE_SESSION_CONTEXT); boolean useEnhancedBridgeContext = (imageManager != null && sessionContext != null); final BridgeContext ctx = (useEnhancedBridgeContext ? new GenericFOPBridgeContext(ua, null, imageManager, sessionContext) : new BridgeContext(ua)); Document doc = svg.getDocument(); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(doc); //Build the GVT tree final GraphicsNode root; try { root = builder.build(ctx, clonedDoc); } catch (Exception e) { throw new ImageException("GVT tree could not be built for SVG graphic", e); } //Create the painter int width = svg.getSize().getWidthMpt(); int height = svg.getSize().getHeightMpt(); Dimension imageSize = new Dimension(width, height); Graphics2DImagePainter painter = createPainter(ctx, root, imageSize); //Create g2d image ImageInfo imageInfo = src.getInfo(); ImageGraphics2D g2dImage = new ImageGraphics2D(imageInfo, painter); return g2dImage; }
// in src/java/org/apache/fop/image/loader/batik/ImageLoaderSVG.java
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!MimeConstants.MIME_SVG.equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from an SVG image"); } Image img = info.getOriginalImage(); if (!(img instanceof ImageXMLDOM)) { throw new IllegalArgumentException( "ImageInfo was expected to contain the SVG document as DOM"); } ImageXMLDOM svgImage = (ImageXMLDOM)img; if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(svgImage.getRootNamespace())) { throw new IllegalArgumentException( "The Image is not in the SVG namespace: " + svgImage.getRootNamespace()); } return svgImage; }
// in src/java/org/apache/fop/image/loader/batik/ImageLoaderWMF.java
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!ImageWMF.MIME_WMF.equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from a WMF image"); } Image img = info.getOriginalImage(); if (!(img instanceof ImageWMF)) { throw new IllegalArgumentException( "ImageInfo was expected to contain the Windows Metafile (WMF)"); } ImageWMF wmfImage = (ImageWMF)img; return wmfImage; }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
private InputHandler createInputHandler() { switch (inputmode) { case FO_INPUT: return new InputHandler(fofile); case AREATREE_INPUT: return new AreaTreeInputHandler(areatreefile); case IF_INPUT: return new IFInputHandler(iffile); case XSLT_INPUT: InputHandler handler = new InputHandler(xmlfile, xsltfile, xsltParams); if (useCatalogResolver) { handler.createCatalogResolver(foUserAgent); } return handler; case IMAGE_INPUT: return new ImageInputHandler(imagefile, xsltfile, xsltParams); default: throw new IllegalArgumentException("Error creating InputHandler object."); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void parseTypeProperties ( String line, Map/*<Integer,List>*/ sm, Map/*<String,int[3]>*/ im ) { String[] sa = line.split(";"); if ( sa.length >= 5 ) { int uc = Integer.parseInt ( sa[0], 16 ); int bc = parseBidiClassAny ( sa[4] ); if ( bc >= 0 ) { String ucName = sa[1]; if ( isBlockStart ( ucName ) ) { String ucBlock = getBlockName ( ucName ); if ( ! im.containsKey ( ucBlock ) ) { im.put ( ucBlock, new int[] { uc, -1, bc } ); } else { throw new IllegalArgumentException ( "duplicate start of block '" + ucBlock + "' at entry: " + line ); } } else if ( isBlockEnd ( ucName ) ) { String ucBlock = getBlockName ( ucName ); if ( im.containsKey ( ucBlock ) ) { int[] ba = (int[]) im.get ( ucBlock ); assert ba.length == 3; if ( ba[1] < 0 ) { ba[1] = uc; } else { throw new IllegalArgumentException ( "duplicate end of block '" + ucBlock + "' at entry: " + line ); } } else { throw new IllegalArgumentException ( "missing start of block '" + ucBlock + "' at entry: " + line ); } } else { Integer k = Integer.valueOf ( bc ); List sl; if ( ! sm.containsKey ( k ) ) { sl = new ArrayList(); sm.put ( k, sl ); } else { sl = (List) sm.get ( k ); } assert sl != null; sl.add ( Integer.valueOf ( uc ) ); } } else { throw new IllegalArgumentException ( "invalid bidi class '" + sa[4] + "' at entry: " + line ); } } else { throw new IllegalArgumentException ( "invalid unicode character database entry: " + line ); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int parseBidiClass ( String bidiClass ) { int bc = 0; if ( "L".equals ( bidiClass ) ) { bc = BidiConstants.L; } else if ( "LRE".equals ( bidiClass ) ) { bc = BidiConstants.LRE; } else if ( "LRO".equals ( bidiClass ) ) { bc = BidiConstants.LRO; } else if ( "R".equals ( bidiClass ) ) { bc = BidiConstants.R; } else if ( "AL".equals ( bidiClass ) ) { bc = BidiConstants.AL; } else if ( "RLE".equals ( bidiClass ) ) { bc = BidiConstants.RLE; } else if ( "RLO".equals ( bidiClass ) ) { bc = BidiConstants.RLO; } else if ( "PDF".equals ( bidiClass ) ) { bc = BidiConstants.PDF; } else if ( "EN".equals ( bidiClass ) ) { bc = BidiConstants.EN; } else if ( "ES".equals ( bidiClass ) ) { bc = BidiConstants.ES; } else if ( "ET".equals ( bidiClass ) ) { bc = BidiConstants.ET; } else if ( "AN".equals ( bidiClass ) ) { bc = BidiConstants.AN; } else if ( "CS".equals ( bidiClass ) ) { bc = BidiConstants.CS; } else if ( "NSM".equals ( bidiClass ) ) { bc = BidiConstants.NSM; } else if ( "BN".equals ( bidiClass ) ) { bc = BidiConstants.BN; } else if ( "B".equals ( bidiClass ) ) { bc = BidiConstants.B; } else if ( "S".equals ( bidiClass ) ) { bc = BidiConstants.S; } else if ( "WS".equals ( bidiClass ) ) { bc = BidiConstants.WS; } else if ( "ON".equals ( bidiClass ) ) { bc = BidiConstants.ON; } else { throw new IllegalArgumentException ( "unknown bidi class: " + bidiClass ); } return bc; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badRangeSpec ( String reason, String charRanges ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad range specification: " + reason + ": \"" + charRanges + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badRangeSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad range specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int[] parseLevels ( List lines ) { int[] la = null; // levels array int[] ra = null; // reorder array List tal = new ArrayList(); if ( ( lines != null ) && ( lines.size() >= 3 ) ) { for ( Iterator it = lines.iterator(); it.hasNext(); ) { String line = (String) it.next(); if ( line.startsWith(PFX_LEVELS) ) { if ( la == null ) { la = parseLevelSpec ( line ); if ( verbose ) { if ( ( ++numLevelSpecs % 10 ) == 0 ) { System.out.print("&"); } } } else { throw new IllegalArgumentException ( "redundant levels array: \"" + line + "\"" ); } } else if ( line.startsWith(PFX_REORDER) ) { if ( la == null ) { throw new IllegalArgumentException ( "missing levels array before: \"" + line + "\"" ); } else if ( ra == null ) { ra = parseReorderSpec ( line, la ); } else { throw new IllegalArgumentException ( "redundant reorder array: \"" + line + "\"" ); } } else if ( ( la != null ) && ( ra != null ) ) { int[] ta = parseTestSpec ( line, la ); if ( ta != null ) { if ( verbose ) { if ( ( ++numTestSpecs % 100 ) == 0 ) { System.out.print("!"); } } tal.add ( ta ); } } else if ( la == null ) { throw new IllegalArgumentException ( "missing levels array before: \"" + line + "\"" ); } else if ( ra == null ) { throw new IllegalArgumentException ( "missing reorder array before: \"" + line + "\"" ); } } } if ( ( la != null ) && ( ra != null ) ) { return createLevelData ( la, ra, tal ); } else { return null; } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badLevelSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad level specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badReorderSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad reorder specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int[] createReorderArray ( List reorders, int[] levels ) { int nr = reorders.size(); int nl = levels.length; if ( nr <= nl ) { int[] ra = new int [ nl ]; Iterator it = reorders.iterator(); for ( int i = 0, n = nl; i < n; i++ ) { int r = -1; if ( levels [ i ] >= 0 ) { if ( it.hasNext() ) { r = ( (Integer) it.next() ).intValue(); } } ra [ i ] = r; } return ra; } else { throw new IllegalArgumentException ( "excessive number of reorder array entries, expected no more than " + nl + ", but got " + nr + " entries" ); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badTestSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad test specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int[] createTestArray ( List classes, int bitset, int[] levels ) { int nc = classes.size(); if ( nc <= levels.length ) { int[] ta = new int [ 1 + nc ]; int k = 0; ta [ k++ ] = bitset; for ( Iterator it = classes.iterator(); it.hasNext(); ) { ta [ k++ ] = ( (Integer) it.next() ).intValue(); } return ta; } else { throw new IllegalArgumentException ( "excessive number of test array entries, expected no more than " + levels.length + ", but got " + nc + " entries" ); } }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiClass.java
private static int parseBidiClass ( String bidiClass ) { int bc = 0; if ( "L".equals ( bidiClass ) ) { bc = BidiConstants.L; } else if ( "LRE".equals ( bidiClass ) ) { bc = BidiConstants.LRE; } else if ( "LRO".equals ( bidiClass ) ) { bc = BidiConstants.LRO; } else if ( "R".equals ( bidiClass ) ) { bc = BidiConstants.R; } else if ( "AL".equals ( bidiClass ) ) { bc = BidiConstants.AL; } else if ( "RLE".equals ( bidiClass ) ) { bc = BidiConstants.RLE; } else if ( "RLO".equals ( bidiClass ) ) { bc = BidiConstants.RLO; } else if ( "PDF".equals ( bidiClass ) ) { bc = BidiConstants.PDF; } else if ( "EN".equals ( bidiClass ) ) { bc = BidiConstants.EN; } else if ( "ES".equals ( bidiClass ) ) { bc = BidiConstants.ES; } else if ( "ET".equals ( bidiClass ) ) { bc = BidiConstants.ET; } else if ( "AN".equals ( bidiClass ) ) { bc = BidiConstants.AN; } else if ( "CS".equals ( bidiClass ) ) { bc = BidiConstants.CS; } else if ( "NSM".equals ( bidiClass ) ) { bc = BidiConstants.NSM; } else if ( "BN".equals ( bidiClass ) ) { bc = BidiConstants.BN; } else if ( "B".equals ( bidiClass ) ) { bc = BidiConstants.B; } else if ( "S".equals ( bidiClass ) ) { bc = BidiConstants.S; } else if ( "WS".equals ( bidiClass ) ) { bc = BidiConstants.WS; } else if ( "ON".equals ( bidiClass ) ) { bc = BidiConstants.ON; } else { throw new IllegalArgumentException ( "unknown bidi class: " + bidiClass ); } return bc; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
public void setDestDir(File destDir) { if (!destDir.isDirectory()) { throw new IllegalArgumentException("destDir must be a directory"); } this.destDir = destDir; }
37
            
// in src/java/org/apache/fop/apps/FOUserAgent.java
catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + mappingClassName); }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + mappingClassName); }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + mappingClassName); }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(mappingClassName + " is not an ElementMapping"); }
// in src/java/org/apache/fop/fonts/FontUtil.java
catch (NumberFormatException nfe) { //weight is no number, so convert symbolic name to number if (text.equals("normal")) { weight = 400; } else if (text.equals("bold")) { weight = 700; } else { throw new IllegalArgumentException( "Illegal value for font weight: '" + text + "'. Use one of: 100, 200, 300, " + "400, 500, 600, 700, 800, 900, " + "normal (=400), bold (=700)"); } }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + XMLHandler.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractRendererMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractFOEventHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (ClassCastException e) { throw new IllegalArgumentException(className + " is not an " + AbstractIFDocumentHandlerMaker.class.getName()); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ImageHandler.class.getName()); }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/java/org/apache/fop/afp/modca/triplets/AttributeValueTriplet.java
catch (UnsupportedEncodingException usee) { tleByteValue = attVal.getBytes(); throw new IllegalArgumentException(attVal + " encoding failed"); }
// in src/java/org/apache/fop/afp/modca/triplets/FullyQualifiedNameTriplet.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( encoding + " encoding failed"); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/traits/BorderProps.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + classname); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + classname); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (ClassCastException e) { throw new IllegalArgumentException(classname + " is not an " + ContentHandlerFactory.class.getName()); }
23
            
// in src/java/org/apache/fop/fo/pagination/Root.java
public void notifyPageSequenceFinished(int lastPageNumber, int additionalPages) throws IllegalArgumentException { if (additionalPages >= 0) { totalPagesGenerated += additionalPages; endingPageNumberOfPreviousSequence = lastPageNumber; } else { throw new IllegalArgumentException( "Number of additional pages must be zero or greater."); } }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
public void addElementMapping(String mappingClassName) throws IllegalArgumentException { try { ElementMapping mapping = (ElementMapping)Class.forName(mappingClassName).newInstance(); addElementMapping(mapping); } catch (ClassNotFoundException e) { throw new IllegalArgumentException("Could not find " + mappingClassName); } catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + mappingClassName); } catch (IllegalAccessException e) { throw new IllegalArgumentException("Could not access " + mappingClassName); } catch (ClassCastException e) { throw new IllegalArgumentException(mappingClassName + " is not an ElementMapping"); } }
// in src/java/org/apache/fop/traits/MinOptMax.java
public static MinOptMax getInstance(int min, int opt, int max) throws IllegalArgumentException { if (min > opt) { throw new IllegalArgumentException("min (" + min + ") > opt (" + opt + ")"); } if (max < opt) { throw new IllegalArgumentException("max (" + max + ") < opt (" + opt + ")"); } return new MinOptMax(min, opt, max); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax plusMin(int minOperand) throws IllegalArgumentException { return getInstance(min + minOperand, opt, max); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax minusMin(int minOperand) throws IllegalArgumentException { return getInstance(min - minOperand, opt, max); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax plusMax(int maxOperand) throws IllegalArgumentException { return getInstance(min, opt, max + maxOperand); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax minusMax(int maxOperand) throws IllegalArgumentException { return getInstance(min, opt, max - maxOperand); }
// in src/java/org/apache/fop/traits/MinOptMax.java
public MinOptMax mult(int factor) throws IllegalArgumentException { if (factor < 0) { throw new IllegalArgumentException("factor < 0; was: " + factor); } else if (factor == 1) { return this; } else { return getInstance(min * factor, opt * factor, max * factor); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int getGlyphForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( ci <= ciMax ) { return gi + delta; } else { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + ciMax ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int getGlyphForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( glyphs == null ) { return -1; } else if ( ci >= glyphs.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + glyphs.length ); } else { return glyphs [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int[] getGlyphsForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( gsa == null ) { return null; } else if ( ci >= gsa.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + gsa.length ); } else { return gsa [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public int[] getAlternatesForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( gaa == null ) { return null; } else if ( ci >= gaa.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + gaa.length ); } else { return gaa [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
public LigatureSet getLigatureSetForCoverageIndex ( int ci, int gi ) throws IllegalArgumentException { if ( ligatureSets == null ) { return null; } else if ( ci >= ligatureSets.length ) { throw new IllegalArgumentException ( "coverage index " + ci + " out of range, maximum coverage index is " + ligatureSets.length ); } else { return ligatureSets [ ci ]; } }
// in src/java/org/apache/fop/complexscripts/bidi/UnicodeBidiAlgorithm.java
private static boolean convertToScalar ( CharSequence cs, int[] chars ) throws IllegalArgumentException { boolean triggered = false; if ( chars.length != cs.length() ) { throw new IllegalArgumentException ( "characters array length must match input sequence length" ); } for ( int i = 0, n = chars.length; i < n; ) { int chIn = cs.charAt ( i ); int chOut; if ( chIn < 0xD800 ) { chOut = chIn; } else if ( chIn < 0xDC00 ) { int chHi = chIn; int chLo; if ( ( i + 1 ) < n ) { chLo = cs.charAt ( i + 1 ); if ( ( chLo >= 0xDC00 ) && ( chLo <= 0xDFFF ) ) { chOut = convertToScalar ( chHi, chLo ); } else { throw new IllegalArgumentException ( "isolated high surrogate" ); } } else { throw new IllegalArgumentException ( "truncated surrogate pair" ); } } else if ( chIn < 0xE000 ) { throw new IllegalArgumentException ( "isolated low surrogate" ); } else { chOut = chIn; } if ( ! triggered && triggersBidi ( chOut ) ) { triggered = true; } if ( ( chOut & 0xFF0000 ) == 0 ) { chars [ i++ ] = chOut; } else { chars [ i++ ] = chOut; chars [ i++ ] = -1; } } return triggered; }
// in src/java/org/apache/fop/complexscripts/util/NumberConverter.java
private void parseFormatTokens ( String format ) throws IllegalArgumentException { List<Integer[]> tokens = new ArrayList<Integer[]>(); List<Integer[]> separators = new ArrayList<Integer[]>(); if ( ( format == null ) || ( format.length() == 0 ) ) { format = "1"; } int tokenType = TOKEN_NONE; List<Integer> token = new ArrayList<Integer>(); Integer[] ca = UTF32.toUTF32 ( format, 0, true ); for ( int i = 0, n = ca.length; i < n; i++ ) { int c = ca[i]; int tokenTypeNew = isAlphaNumeric ( c ) ? TOKEN_ALPHANUMERIC : TOKEN_NONALPHANUMERIC; if ( tokenTypeNew != tokenType ) { if ( token.size() > 0 ) { if ( tokenType == TOKEN_ALPHANUMERIC ) { tokens.add ( token.toArray ( new Integer [ token.size() ] ) ); } else { separators.add ( token.toArray ( new Integer [ token.size() ] ) ); } token.clear(); } tokenType = tokenTypeNew; } token.add ( c ); } if ( token.size() > 0 ) { if ( tokenType == TOKEN_ALPHANUMERIC ) { tokens.add ( token.toArray ( new Integer [ token.size() ] ) ); } else { separators.add ( token.toArray ( new Integer [ token.size() ] ) ); } } if ( ! separators.isEmpty() ) { this.prefix = separators.remove ( 0 ); } if ( ! separators.isEmpty() ) { this.suffix = separators.remove ( separators.size() - 1 ); } this.separators = separators.toArray ( new Integer [ separators.size() ] [] ); this.tokens = tokens.toArray ( new Integer [ tokens.size() ] [] ); }
// in src/java/org/apache/fop/complexscripts/util/UTF32.java
public static Integer[] toUTF32 ( String s, int substitution, boolean errorOnSubstitution ) throws IllegalArgumentException { int n; if ( ( n = s.length() ) == 0 ) { return new Integer[0]; } else { Integer[] sa = new Integer [ n ]; int k = 0; for ( int i = 0; i < n; i++ ) { int c = (int) s.charAt(i); if ( ( c >= 0xD800 ) && ( c < 0xE000 ) ) { int s1 = c; int s2 = ( ( i + 1 ) < n ) ? (int) s.charAt ( i + 1 ) : 0; if ( s1 < 0xDC00 ) { if ( ( s2 >= 0xDC00 ) && ( s2 < 0xE000 ) ) { c = ( ( s1 - 0xD800 ) << 10 ) + ( s2 - 0xDC00 ) + 65536; i++; } else { if ( errorOnSubstitution ) { throw new IllegalArgumentException ( "isolated high (leading) surrogate" ); } else { c = substitution; } } } else { if ( errorOnSubstitution ) { throw new IllegalArgumentException ( "isolated low (trailing) surrogate" ); } else { c = substitution; } } } sa[k++] = c; } if ( k == n ) { return sa; } else { Integer[] na = new Integer [ k ]; System.arraycopy ( sa, 0, na, 0, k ); return na; } } }
// in src/java/org/apache/fop/complexscripts/util/UTF32.java
public static String fromUTF32 ( Integer[] sa ) throws IllegalArgumentException { StringBuffer sb = new StringBuffer(); for ( int s : sa ) { if ( s < 65535 ) { if ( ( s < 0xD800 ) || ( s > 0xDFFF ) ) { sb.append ( (char) s ); } else { String ncr = CharUtilities.charToNCRef(s); throw new IllegalArgumentException ( "illegal scalar value 0x" + ncr.substring(2, ncr.length() - 1) + "; cannot be UTF-16 surrogate" ); } } else if ( s < 1114112 ) { int s1 = ( ( ( s - 65536 ) >> 10 ) & 0x3FF ) + 0xD800; int s2 = ( ( ( s - 65536 ) >> 0 ) & 0x3FF ) + 0xDC00; sb.append ( (char) s1 ); sb.append ( (char) s2 ); } else { String ncr = CharUtilities.charToNCRef(s); throw new IllegalArgumentException ( "illegal scalar value 0x" + ncr.substring(2, ncr.length() - 1) + "; out of range for UTF-16" ); } } return sb.toString(); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badRangeSpec ( String reason, String charRanges ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad range specification: " + reason + ": \"" + charRanges + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badRangeSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad range specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badLevelSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad level specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badReorderSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad reorder specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static void badTestSpec ( String reason, CharacterIterator ci ) throws IllegalArgumentException { if ( verbose ) { System.out.println(); } throw new IllegalArgumentException ( "bad test specification: " + reason + ": starting at \"" + remainder ( ci ) + "\"" ); }
17
            
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (IllegalArgumentException are) { failed = true; }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
catch (IllegalArgumentException e) { throw new SAXException(e); }
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (IllegalArgumentException e) { LOG.warn("Error while adding element mapping", e); }
// in src/java/org/apache/fop/fonts/substitute/FontQualifier.java
catch (IllegalArgumentException ex) { log.error("Invalid font-weight value '" + weightString + "'"); return; }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException(e.getMessage()); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (IllegalArgumentException e) { log.error("Error while adding XMLHandler", e); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalArgumentException e) { log.error("Error while adding maker for Renderer", e); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalArgumentException e) { log.error("Error while adding maker for FOEventHandler", e); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (IllegalArgumentException e) { log.error("Error while adding maker for IFDocumentHandler", e); }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException( "Valid values for 'rendering' are 'quality', 'speed' and 'bitmap'." + " Value found: " + rendering); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IllegalArgumentException iae) { eventProducer.invalidConfiguration(this, iae); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (IllegalArgumentException iae) { LogUtil.handleException(log, iae, userAgent.getFactory().validateUserConfigStrictly()); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (IllegalArgumentException e) { log.error("Error while adding ImageHandler", e); }
// in src/java/org/apache/fop/afp/fonts/DoubleByteFont.java
catch (IllegalArgumentException e) { // We shall try and handle characters that have no mapped width metric in font resource charWidth = -1; }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (IllegalArgumentException e) { log.error("Error while adding ContentHandlerFactory", e); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
catch ( IllegalArgumentException e ) { return -1; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
catch ( IllegalArgumentException e ) { throw e; }
4
            
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
catch (IllegalArgumentException e) { throw new SAXException(e); }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException(e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
catch (IllegalArgumentException e) { throw new FOPException( "Valid values for 'rendering' are 'quality', 'speed' and 'bitmap'." + " Value found: " + rendering); }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
catch ( IllegalArgumentException e ) { throw e; }
0
unknown (Lib) IllegalBlockSizeException 0 0 0 1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (IllegalBlockSizeException e) { throw new IllegalStateException(e.getMessage()); }
1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (IllegalBlockSizeException e) { throw new IllegalStateException(e.getMessage()); }
1
runtime (Lib) IllegalStateException 118
            
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(FOUserAgent userAgent) throws FOPException { if (userAgent.getRendererOverride() == null && userAgent.getFOEventHandlerOverride() == null && userAgent.getDocumentHandlerOverride() == null) { throw new IllegalStateException("An overriding renderer," + " FOEventHandler or IFDocumentHandler must be set on the user agent" + " when this factory method is used!"); } return newFop(null, userAgent); }
// in src/java/org/apache/fop/apps/Fop.java
public FormattingResults getResults() { if (foTreeBuilder == null) { throw new IllegalStateException( "Results are only available after calling getDefaultHandler()."); } else { return foTreeBuilder.getResults(); } }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
public byte[] encrypt(byte[] data, PDFObject refObj) { PDFObject o = refObj; while (o != null && !o.hasObjectNumber()) { o = o.getParent(); } if (o == null) { throw new IllegalStateException("No object number could be obtained for a PDF object"); } byte[] key = createEncryptionKey(o.getObjectNumber(), o.getGeneration()); return encryptWithKey(key, data); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
private static byte[] encryptWithKey(byte[] key, byte[] data) { try { final Cipher c = initCipher(key); return c.doFinal(data); } catch (IllegalBlockSizeException e) { throw new IllegalStateException(e.getMessage()); } catch (BadPaddingException e) { throw new IllegalStateException(e.getMessage()); } }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
private static Cipher initCipher(byte[] key) { try { Cipher c = Cipher.getInstance("RC4"); SecretKeySpec keyspec = new SecretKeySpec(key, "RC4"); c.init(Cipher.ENCRYPT_MODE, keyspec); return c; } catch (InvalidKeyException e) { throw new IllegalStateException(e); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); } catch (NoSuchPaddingException e) { throw new UnsupportedOperationException(e); } }
// in src/java/org/apache/fop/pdf/PDFObject.java
public int getObjectNumber() { if (this.objnum == 0) { throw new IllegalStateException("Object has no number assigned: " + this.toString()); } return this.objnum; }
// in src/java/org/apache/fop/pdf/PDFObject.java
public final PDFDocument getDocumentSafely() { final PDFDocument doc = getDocument(); if (doc == null) { throw new IllegalStateException("Parent PDFDocument is unavailable on " + getClass().getName()); } return doc; }
// in src/java/org/apache/fop/pdf/PDFRoot.java
public int getPageMode() { PDFName mode = (PDFName)get("PageMode"); if (mode != null) { for (int i = 0; i < PAGEMODE_NAMES.length; i++) { if (PAGEMODE_NAMES[i].equals(mode)) { return i; } } throw new IllegalStateException("Unknown /PageMode encountered: " + mode); } else { return PAGEMODE_USENONE; } }
// in src/java/org/apache/fop/pdf/PDFFactory.java
private PDFAction getActionForEmbeddedFile(String filename, boolean newWindow) { PDFNames names = getDocument().getRoot().getNames(); if (names == null) { throw new IllegalStateException( "No Names dictionary present." + " Cannot create Launch Action for embedded file: " + filename); } PDFNameTreeNode embeddedFiles = names.getEmbeddedFiles(); if (embeddedFiles == null) { throw new IllegalStateException( "No /EmbeddedFiles name tree present." + " Cannot create Launch Action for embedded file: " + filename); } //Find filespec reference for the embedded file filename = PDFText.toPDFString(filename, '_'); PDFArray files = embeddedFiles.getNames(); PDFReference embeddedFileRef = null; int i = 0; while (i < files.length()) { String name = (String)files.get(i); i++; PDFReference ref = (PDFReference)files.get(i); if (name.equals(filename)) { embeddedFileRef = ref; break; } i++; } if (embeddedFileRef == null) { throw new IllegalStateException( "No embedded file with name " + filename + " present."); } //Finally create the action //PDFLaunch action = new PDFLaunch(embeddedFileRef); //This works with Acrobat 8 but not with Acrobat 9 //The following two options didn't seem to have any effect. //PDFGoToEmbedded action = new PDFGoToEmbedded(embeddedFileRef, 0, newWindow); //PDFGoToRemote action = new PDFGoToRemote(embeddedFileRef, 0, newWindow); //This finally seems to work: StringBuffer scriptBuffer = new StringBuffer(); scriptBuffer.append("this.exportDataObject({cName:\""); scriptBuffer.append(filename); scriptBuffer.append("\", nLaunch:2});"); PDFJavaScriptLaunchAction action = new PDFJavaScriptLaunchAction(scriptBuffer.toString()); return action; }
// in src/java/org/apache/fop/pdf/PDFDeviceColorSpace.java
public String getName() { switch (currentColorSpace) { case DEVICE_CMYK: return "DeviceCMYK"; case DEVICE_GRAY: return "DeviceGray"; case DEVICE_RGB: return "DeviceRGB"; default: throw new IllegalStateException("Unsupported color space in use."); } }
// in src/java/org/apache/fop/pdf/PDFNameTreeNode.java
private PDFArray prepareLimitsArray() { PDFArray limits = (PDFArray)get(LIMITS); if (limits == null) { limits = new PDFArray(this, new Object[2]); put(LIMITS, limits); } if (limits.length() != 2) { throw new IllegalStateException("Limits array must have 2 entries"); } return limits; }
// in src/java/org/apache/fop/pdf/PDFTextUtil.java
private void checkInTextObject() { if (!inTextObject) { throw new IllegalStateException("Not in text object"); } }
// in src/java/org/apache/fop/pdf/PDFTextUtil.java
public void beginTextObject() { if (inTextObject) { throw new IllegalStateException("Already in text object"); } write("BT\n"); this.inTextObject = true; }
// in src/java/org/apache/fop/pdf/PDFPages.java
public void notifyKidRegistered(PDFPage page) { int idx = page.getPageIndex(); if (idx >= 0) { while (idx > this.kids.size() - 1) { this.kids.add(null); } if (this.kids.get(idx) != null) { throw new IllegalStateException("A page already exists at index " + idx + " (zero-based)."); } this.kids.set(idx, page.referencePDF()); } else { this.kids.add(page.referencePDF()); } }
// in src/java/org/apache/fop/pdf/PDFPages.java
public String toPDFString() { StringBuffer sb = new StringBuffer(64); sb.append("<< /Type /Pages\n/Count ") .append(this.getCount()) .append("\n/Kids ["); for (int i = 0; i < kids.size(); i++) { Object kid = kids.get(i); if (kid == null) { throw new IllegalStateException("Gap in the kids list!"); } sb.append(kid).append(" "); } sb.append("] >>"); return sb.toString(); }
// in src/java/org/apache/fop/pdf/PDFText.java
public static final String escapeText(final String text, boolean forceHexMode) { if (text != null && text.length() > 0) { boolean unicode = false; boolean hexMode = false; if (forceHexMode) { hexMode = true; } else { for (int i = 0, c = text.length(); i < c; i++) { if (text.charAt(i) >= 128) { unicode = true; hexMode = true; break; } } } if (hexMode) { final byte[] uniBytes; try { uniBytes = text.getBytes("UTF-16"); } catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); } return toHex(uniBytes); } else { final StringBuffer result = new StringBuffer(text.length() * 2); result.append("("); final int l = text.length(); if (unicode) { // byte order marker (0xfeff) result.append("\\376\\377"); for (int i = 0; i < l; i++) { final char ch = text.charAt(i); final int high = (ch & 0xff00) >>> 8; final int low = ch & 0xff; result.append("\\"); result.append(Integer.toOctalString(high)); result.append("\\"); result.append(Integer.toOctalString(low)); } } else { for (int i = 0; i < l; i++) { final char ch = text.charAt(i); if (ch < 256) { escapeStringChar(ch, result); } else { throw new IllegalStateException( "Can only treat text in 8-bit ASCII/PDFEncoding"); } } } result.append(")"); return result.toString(); } } return "()"; }
// in src/java/org/apache/fop/pdf/PDFColorHandler.java
private void writeColor(StringBuffer codeBuffer, float[] comps, int componentCount, String command) { if (comps.length != componentCount) { throw new IllegalStateException("Color with unexpected component count encountered"); } for (int i = 0, c = comps.length; i < c; i++) { DoubleFormatUtil.formatDouble(comps[i], 4, 4, codeBuffer); codeBuffer.append(" "); } codeBuffer.append(command).append("\n"); }
// in src/java/org/apache/fop/pdf/PDFEncoding.java
public DifferencesBuilder addName(String name) { if (this.currentCode < 0) { throw new IllegalStateException("addDifference(int) must be called first"); } this.differences.add(new PDFName(name)); return this; }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void assignObjectNumber(PDFObject obj) { if (obj == null) { throw new NullPointerException("obj must not be null"); } if (obj.hasObjectNumber()) { throw new IllegalStateException( "Error registering a PDFObject: " + "PDFObject already has an object number"); } PDFDocument currentParent = obj.getDocument(); if (currentParent != null && currentParent != this) { throw new IllegalStateException( "Error registering a PDFObject: " + "PDFObject already has a parent PDFDocument"); } obj.setObjectNumber(++this.objectcount); if (currentParent == null) { obj.setDocument(this); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void addObject(PDFObject obj) { if (obj == null) { throw new NullPointerException("obj must not be null"); } if (!obj.hasObjectNumber()) { throw new IllegalStateException( "Error adding a PDFObject: " + "PDFObject doesn't have an object number"); } //Add object to list this.objects.add(obj); //Add object to special lists where necessary if (obj instanceof PDFFunction) { this.functions.add((PDFFunction) obj); } if (obj instanceof PDFShading) { final String shadingName = "Sh" + (++this.shadingCount); ((PDFShading)obj).setName(shadingName); this.shadings.add((PDFShading) obj); } if (obj instanceof PDFPattern) { final String patternName = "Pa" + (++this.patternCount); ((PDFPattern)obj).setName(patternName); this.patterns.add((PDFPattern) obj); } if (obj instanceof PDFFont) { final PDFFont font = (PDFFont)obj; this.fontMap.put(font.getName(), font); } if (obj instanceof PDFGState) { this.gstates.add((PDFGState) obj); } if (obj instanceof PDFPage) { this.pages.notifyKidRegistered((PDFPage)obj); } if (obj instanceof PDFLaunch) { this.launches.add((PDFLaunch) obj); } if (obj instanceof PDFLink) { this.links.add((PDFLink) obj); } if (obj instanceof PDFFileSpec) { this.filespecs.add((PDFFileSpec) obj); } if (obj instanceof PDFGoToRemote) { this.gotoremotes.add((PDFGoToRemote) obj); } }
// in src/java/org/apache/fop/pdf/PDFT1Stream.java
public int output(java.io.OutputStream stream) throws java.io.IOException { if (pfb == null) { throw new IllegalStateException("pfb must not be null at this point"); } if (log.isDebugEnabled()) { log.debug("Writing " + pfb.getLength() + " bytes of Type 1 font data"); } int length = super.output(stream); log.debug("Embedded Type1 font"); return length; }
// in src/java/org/apache/fop/pdf/VersionController.java
Override public void setPDFVersion(Version version) { throw new IllegalStateException("Cannot change the version of this PDF document."); }
// in src/java/org/apache/fop/pdf/PDFNumberTreeNode.java
private PDFArray prepareLimitsArray() { PDFArray limits = (PDFArray)get(LIMITS); if (limits == null) { limits = new PDFArray(this, new Object[2]); put(LIMITS, limits); } if (limits.length() != 2) { throw new IllegalStateException("Limits array must have 2 entries"); } return limits; }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void writeOutput(SortedMap fontFamilies) throws TransformerConfigurationException, SAXException, IOException { if (this.outputFile.isDirectory()) { System.out.println("Creating one file for each family..."); Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String familyName = (String)entry.getKey(); System.out.println("Creating output file for " + familyName + "..."); String filename; switch(this.mode) { case GENERATE_RENDERED: filename = familyName + ".pdf"; break; case GENERATE_FO: filename = familyName + ".fo"; break; case GENERATE_XML: filename = familyName + ".xml"; break; default: throw new IllegalStateException("Unsupported mode"); } File outFile = new File(this.outputFile, filename); generateXML(fontFamilies, outFile, familyName); } } else { System.out.println("Creating output file..."); generateXML(fontFamilies, this.outputFile, this.singleFamilyFilter); } System.out.println(this.outputFile + " written."); }
// in src/java/org/apache/fop/fo/properties/CondLengthProperty.java
public void setComponent(int cmpId, Property cmpnValue, boolean bIsDefault) { if (isCached) { throw new IllegalStateException( "CondLengthProperty.setComponent() called on a cached value!"); } if (cmpId == CP_LENGTH) { length = cmpnValue; } else if (cmpId == CP_CONDITIONALITY) { conditionality = (EnumProperty)cmpnValue; } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void startDocument() throws SAXException { if (used) { throw new IllegalStateException("FOTreeBuilder (and the Fop class) cannot be reused." + " Please instantiate a new instance."); } used = true; empty = true; rootFObj = null; // allows FOTreeBuilder to be reused if (LOG.isDebugEnabled()) { LOG.debug("Building formatting object tree"); } foEventHandler.startDocument(); this.mainFOHandler = new MainFOHandler(); this.mainFOHandler.startDocument(); this.delegate = this.mainFOHandler; }
// in src/java/org/apache/fop/fo/flow/table/CollapsingBorderResolver.java
void endTable() { throw new IllegalStateException(); }
// in src/java/org/apache/fop/fo/FOText.java
public void remove() { if (this.canRemove) { charBuffer.position(currentPosition); // Slice the buffer at the current position CharBuffer tmp = charBuffer.slice(); // Reset position to before current character charBuffer.position(--currentPosition); if (tmp.hasRemaining()) { // Transfer any remaining characters charBuffer.mark(); charBuffer.put(tmp); charBuffer.reset(); } // Decrease limit charBuffer.limit(charBuffer.limit() - 1); // Make sure following calls fail, unless nextChar() was called this.canRemove = false; } else { throw new IllegalStateException(); } }
// in src/java/org/apache/fop/fo/FOText.java
public void replaceChar(char c) { if (this.canReplace) { charBuffer.put(currentPosition - 1, c); } else { throw new IllegalStateException(); } }
// in src/java/org/apache/fop/fo/FObj.java
public void set(Object o) { if ((flags & F_SET_ALLOWED) == F_SET_ALLOWED) { FONode newNode = (FONode) o; if (currentNode == parentNode.firstChild) { parentNode.firstChild = newNode; } else { FONode.attachSiblings(currentNode.siblings[0], newNode); } if (currentNode.siblings != null && currentNode.siblings[1] != null) { FONode.attachSiblings(newNode, currentNode.siblings[1]); } if (currentNode == parentNode.lastChild) { parentNode.lastChild = newNode; } } else { throw new IllegalStateException(); } }
// in src/java/org/apache/fop/fo/FObj.java
public void remove() { if ((flags & F_REMOVE_ALLOWED) == F_REMOVE_ALLOWED) { parentNode.removeChild(currentNode); if (currentIndex == 0) { //first node removed currentNode = parentNode.firstChild; } else if (currentNode.siblings != null && currentNode.siblings[0] != null) { currentNode = currentNode.siblings[0]; currentIndex--; } else { currentNode = null; } flags &= F_NONE_ALLOWED; } else { throw new IllegalStateException(); } }
// in src/java/org/apache/fop/svg/PDFDocumentGraphics2D.java
protected void startPage() throws IOException { if (pdfContext.isPagePending()) { throw new IllegalStateException("Close page first before starting another"); } //Start page paintingState = new PDFPaintingState(); if (this.initialTransform == null) { //Save initial transformation matrix this.initialTransform = getTransform(); this.initialClip = getClip(); } else { //Reset transformation matrix setTransform(this.initialTransform); setClip(this.initialClip); } currentFontName = ""; currentFontSize = 0; if (currentStream == null) { currentStream = new StringWriter(); } PDFResources pdfResources = this.pdfDoc.getResources(); PDFPage page = this.pdfDoc.getFactory().makePage(pdfResources, width, height); resourceContext = page; pdfContext.setCurrentPage(page); pageRef = page.referencePDF(); currentStream.write("q\n"); AffineTransform at = new AffineTransform(1.0, 0.0, 0.0, -1.0, 0.0, height); currentStream.write("1 0 0 -1 0 " + height + " cm\n"); if (svgWidth != 0) { double scaleX = width / svgWidth; double scaleY = height / svgHeight; at.scale(scaleX, scaleY); currentStream.write("" + PDFNumber.doubleOut(scaleX) + " 0 0 " + PDFNumber.doubleOut(scaleY) + " 0 0 cm\n"); } if (deviceDPI != NORMAL_PDF_RESOLUTION) { double s = NORMAL_PDF_RESOLUTION / deviceDPI; at.scale(s, s); currentStream.write("" + PDFNumber.doubleOut(s) + " 0 0 " + PDFNumber.doubleOut(s) + " 0 0 cm\n"); scale(1 / s, 1 / s); } // Remember the transform we installed. paintingState.concatenate(at); pdfContext.increasePageCount(); }
// in src/java/org/apache/fop/fonts/SimpleSingleByteEncoding.java
public char addCharacter(NamedCharacter ch) { if (!ch.hasSingleUnicodeValue()) { throw new IllegalArgumentException("Only NamedCharacters with a single Unicode value" + " are currently supported!"); } if (isFull()) { throw new IllegalStateException("Encoding is full!"); } char newSlot = (char)(getLastChar() + 1); this.mapping.add(ch); this.charMap.put(Character.valueOf(ch.getSingleUnicodeValue()), Character.valueOf(newSlot)); return newSlot; }
// in src/java/org/apache/fop/fonts/NamedCharacter.java
public char getSingleUnicodeValue() throws IllegalStateException { if (this.unicodeSequence == null) { return CharUtilities.NOT_A_CHARACTER; } if (this.unicodeSequence.length() > 1) { throw new IllegalStateException("getSingleUnicodeValue() may not be called for a" + " named character that has more than one Unicode value (a sequence)" + " associated with the named character!"); } return this.unicodeSequence.charAt(0); }
// in src/java/org/apache/fop/fonts/FontInfo.java
public FontTriplet[] fontLookup(String[] families, String style, int weight) { if (families.length == 0) { throw new IllegalArgumentException("Specify at least one font family"); } // try matching without substitutions List<FontTriplet> matchedTriplets = fontLookup(families, style, weight, false); // if there are no matching font triplets found try with substitutions if (matchedTriplets.size() == 0) { matchedTriplets = fontLookup(families, style, weight, true); } // no matching font triplets found! if (matchedTriplets.size() == 0) { StringBuffer sb = new StringBuffer(); for (int i = 0, c = families.length; i < c; i++) { if (i > 0) { sb.append(", "); } sb.append(families[i]); } throw new IllegalStateException( "fontLookup must return an array with at least one " + "FontTriplet on the last call. Lookup: " + sb.toString()); } FontTriplet[] fontTriplets = new FontTriplet[matchedTriplets.size()]; matchedTriplets.toArray(fontTriplets); // found some matching fonts so return them return fontTriplets; }
// in src/java/org/apache/fop/fonts/MultiByteFont.java
public void setGDEF ( GlyphDefinitionTable gdef ) { if ( ( this.gdef == null ) || ( gdef == null ) ) { this.gdef = gdef; } else { throw new IllegalStateException ( "font already associated with GDEF table" ); } }
// in src/java/org/apache/fop/fonts/MultiByteFont.java
public void setGSUB ( GlyphSubstitutionTable gsub ) { if ( ( this.gsub == null ) || ( gsub == null ) ) { this.gsub = gsub; } else { throw new IllegalStateException ( "font already associated with GSUB table" ); } }
// in src/java/org/apache/fop/fonts/MultiByteFont.java
public void setGPOS ( GlyphPositioningTable gpos ) { if ( ( this.gpos == null ) || ( gpos == null ) ) { this.gpos = gpos; } else { throw new IllegalStateException ( "font already associated with GPOS table" ); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public AFMFile parse(BufferedReader reader, String afmFileName) throws IOException { Stack<Object> stack = new Stack<Object>(); int parseMode = PARSE_NORMAL; while (true) { String line = reader.readLine(); if (line == null) { break; } String key = null; switch (parseMode) { case PARSE_NORMAL: key = parseLine(line, stack); break; case PARSE_CHAR_METRICS: key = parseCharMetrics(line, stack, afmFileName); break; default: throw new IllegalStateException("Invalid parse mode"); } Integer newParseMode = PARSE_MODE_CHANGES.get(key); if (newParseMode != null) { parseMode = newParseMode.intValue(); } } return (AFMFile)stack.pop(); }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addsRGBColorSpace() throws IOException { if (disableSRGBColorSpace) { if (this.pdfAMode != PDFAMode.DISABLED || this.pdfXMode != PDFXMode.DISABLED || this.outputProfileURI != null) { throw new IllegalStateException("It is not possible to disable the sRGB color" + " space if PDF/A or PDF/X functionality is enabled or an" + " output profile is set!"); } } else { if (this.sRGBColorSpace != null) { return; } //Map sRGB as default RGB profile for DeviceRGB this.sRGBColorSpace = PDFICCBasedColorSpace.setupsRGBAsDefaultRGBColorSpace(pdfDoc); } }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
public PDFDocument setupPDFDocument(OutputStream out) throws IOException { if (this.pdfDoc != null) { throw new IllegalStateException("PDFDocument already set up"); } String producer = userAgent.getProducer() != null ? userAgent.getProducer() : ""; if (maxPDFVersion == null) { this.pdfDoc = new PDFDocument(producer); } else { VersionController controller = VersionController.getFixedVersionController(maxPDFVersion); this.pdfDoc = new PDFDocument(producer, controller); } updateInfo(); updatePDFProfiles(); pdfDoc.setFilterMap(filterMap); pdfDoc.outputHeader(out); //Setup encryption if necessary PDFEncryptionManager.setupPDFEncryption(encryptionParams, pdfDoc); addsRGBColorSpace(); if (this.outputProfileURI != null) { addDefaultOutputProfile(); } if (pdfXMode != PDFXMode.DISABLED) { log.debug(pdfXMode + " is active."); log.warn("Note: " + pdfXMode + " support is work-in-progress and not fully implemented, yet!"); addPDFXOutputIntent(); } if (pdfAMode.isPDFA1LevelB()) { log.debug("PDF/A is active. Conformance Level: " + pdfAMode); addPDFA1OutputIntent(); } this.pdfDoc.enableAccessibility(userAgent.isAccessibilityEnabled()); return this.pdfDoc; }
// in src/java/org/apache/fop/render/pdf/ImageRawCCITTFaxAdapter.java
public void setup(PDFDocument doc) { pdfFilter = new CCFFilter(); pdfFilter.setApplied(true); PDFDictionary dict = new PDFDictionary(); dict.put("Columns", this.image.getSize().getWidthPx()); int compression = getImage().getCompression(); switch (compression) { case TIFFImage.COMP_FAX_G3_1D : dict.put("K", 0); break; case TIFFImage.COMP_FAX_G3_2D : dict.put("K", 1); break; case TIFFImage.COMP_FAX_G4_2D : dict.put("K", -1); break; default: throw new IllegalStateException("Invalid compression scheme: " + compression); } ((CCFFilter)pdfFilter).setDecodeParms(dict); super.setup(doc); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
protected void addTraitAttributes(Area area) { Map traitMap = area.getTraits(); if (traitMap != null) { Iterator iter = traitMap.entrySet().iterator(); while (iter.hasNext()) { Map.Entry traitEntry = (Map.Entry) iter.next(); Object key = traitEntry.getKey(); String name = Trait.getTraitName(key); Class clazz = Trait.getTraitClass(key); if ("break-before".equals(name) || "break-after".equals(name)) { continue; } Object value = traitEntry.getValue(); if (key == Trait.FONT) { FontTriplet triplet = (FontTriplet)value; addAttribute("font-name", triplet.getName()); addAttribute("font-style", triplet.getStyle()); addAttribute("font-weight", triplet.getWeight()); } else if (clazz.equals(InternalLink.class)) { InternalLink iLink = (InternalLink)value; addAttribute(name, iLink.xmlAttribute()); } else if (clazz.equals(Background.class)) { Background bkg = (Background)value; //TODO Remove the following line (makes changes in the test checks necessary) addAttribute(name, bkg.toString()); if (bkg.getColor() != null) { addAttribute("bkg-color", ColorUtil.colorToString(bkg.getColor())); } if (bkg.getURL() != null) { addAttribute("bkg-img", bkg.getURL()); String repString; int repeat = bkg.getRepeat(); switch (repeat) { case Constants.EN_REPEAT: repString = "repeat"; break; case Constants.EN_REPEATX: repString = "repeat-x"; break; case Constants.EN_REPEATY: repString = "repeat-y"; break; case Constants.EN_NOREPEAT: repString = "no-repeat"; break; default: throw new IllegalStateException( "Illegal value for repeat encountered: " + repeat); } addAttribute("bkg-repeat", repString); addAttribute("bkg-horz-offset", bkg.getHoriz()); addAttribute("bkg-vert-offset", bkg.getVertical()); } } else if (clazz.equals(Color.class)) { Color c = (Color)value; addAttribute(name, ColorUtil.colorToString(c)); } else if (key == Trait.START_INDENT || key == Trait.END_INDENT) { if (((Integer)value).intValue() != 0) { addAttribute(name, value.toString()); } } else { addAttribute(name, value.toString()); } } } transferForeignObjects(area); }
// in src/java/org/apache/fop/render/intermediate/IFContext.java
public void setUserAgent(FOUserAgent ua) { if (this.userAgent != null) { throw new IllegalStateException("The user agent was already set"); } this.userAgent = ua; }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
protected RenderingContext createRenderingContext() throws IllegalStateException { throw new IllegalStateException("Should never be called!"); }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void startDocument() throws IFException { super.startDocument(); if (this.outputStream == null) { throw new IllegalStateException("OutputStream hasn't been set through setResult()"); } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFDocumentHandler.java
public void startDocument() throws IFException { if (getUserAgent() == null) { throw new IllegalStateException( "User agent must be set before starting document generation"); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
protected void clip() { throw new IllegalStateException("Not used"); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
protected void closePath() { throw new IllegalStateException("Not used"); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
protected void moveTo(float x, float y) { throw new IllegalStateException("Not used"); }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
protected void lineTo(float x, float y) { throw new IllegalStateException("Not used"); }
// in src/java/org/apache/fop/render/AbstractRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { if (userAgent == null) { throw new IllegalStateException("FOUserAgent has not been set on Renderer"); } }
// in src/java/org/apache/fop/render/pcl/PCLRenderingUtil.java
public static Point2D transformedPoint(int x, int y, AffineTransform transform, PCLPageDefinition pageDefinition, int printDirection) { if (log.isTraceEnabled()) { log.trace("Current transform: " + transform); } Point2D.Float orgPoint = new Point2D.Float(x, y); Point2D.Float transPoint = new Point2D.Float(); transform.transform(orgPoint, transPoint); //At this point we have the absolute position in FOP's coordinate system //Now get PCL coordinates taking the current print direction and the logical page //into account. Dimension pageSize = pageDefinition.getPhysicalPageSize(); Rectangle logRect = pageDefinition.getLogicalPageRect(); switch (printDirection) { case 0: transPoint.x -= logRect.x; transPoint.y -= logRect.y; break; case 90: float ty = transPoint.x; transPoint.x = pageSize.height - transPoint.y; transPoint.y = ty; transPoint.x -= logRect.y; transPoint.y -= logRect.x; break; case 180: transPoint.x = pageSize.width - transPoint.x; transPoint.y = pageSize.height - transPoint.y; transPoint.x -= pageSize.width - logRect.x - logRect.width; transPoint.y -= pageSize.height - logRect.y - logRect.height; //The next line is odd and is probably necessary due to the default value of the //Text Length command: "1/2 inch less than maximum text length" //I wonder why this isn't necessary for the 90 degree rotation. *shrug* transPoint.y -= UnitConv.in2mpt(0.5); break; case 270: float tx = transPoint.y; transPoint.y = pageSize.width - transPoint.x; transPoint.x = tx; transPoint.x -= pageSize.height - logRect.y - logRect.height; transPoint.y -= pageSize.width - logRect.x - logRect.width; break; default: throw new IllegalStateException("Illegal print direction: " + printDirection); } return transPoint; }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
public void processPathIteratorFill(PathIterator iter) throws IOException { gen.writeText("\n"); double[] vals = new double[6]; boolean penDown = false; double x = 0; double y = 0; boolean pendingPM0 = true; StringBuffer sb = new StringBuffer(256); penUp(sb); while (!iter.isDone()) { int type = iter.currentSegment(vals); if (type == PathIterator.SEG_CLOSE) { sb.append("PM1;"); iter.next(); continue; } else if (type == PathIterator.SEG_MOVETO) { if (penDown) { penUp(sb); penDown = false; } } else { if (!penDown) { penDown(sb); penDown = true; } } switch (type) { case PathIterator.SEG_MOVETO: x = vals[0]; y = vals[1]; plotAbsolute(x, y, sb); break; case PathIterator.SEG_LINETO: x = vals[0]; y = vals[1]; plotAbsolute(x, y, sb); break; case PathIterator.SEG_CUBICTO: x = vals[4]; y = vals[5]; bezierAbsolute(vals[0], vals[1], vals[2], vals[3], x, y, sb); break; case PathIterator.SEG_QUADTO: double originX = x; double originY = y; x = vals[2]; y = vals[3]; quadraticBezierAbsolute(originX, originY, vals[0], vals[1], x, y, sb); break; default: throw new IllegalStateException("Must not get here"); } if (pendingPM0) { pendingPM0 = false; sb.append("PM;"); } iter.next(); } sb.append("PM2;"); fillPolygon(iter.getWindingRule(), sb); sb.append("\n"); gen.writeText(sb.toString()); }
// in src/java/org/apache/fop/render/rtf/rtflib/tools/TableContext.java
public float getColumnWidth() { if (colIndex < 0) { throw new IllegalStateException("colIndex must not be negative!"); } else if (colIndex >= getNumberOfColumns()) { log.warn("Column width for column " + (colIndex + 1) + " is not defined, using " + INVALID_COLUMN_WIDTH); while (colIndex >= getNumberOfColumns()) { setNextColumnWidth(new Float(INVALID_COLUMN_WIDTH)); } } return ((Float)colWidths.get(colIndex)).floatValue(); }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRenderedImage.java
private boolean encodeInvertedBilevel(ImageEncodingHelper helper, AFPImageObjectInfo imageObjectInfo, OutputStream out) throws IOException { RenderedImage renderedImage = helper.getImage(); if (!BitmapImageUtil.isMonochromeImage(renderedImage)) { throw new IllegalStateException("This method only supports binary images!"); } int tiles = renderedImage.getNumXTiles() * renderedImage.getNumYTiles(); if (tiles > 1) { return false; } SampleModel sampleModel = renderedImage.getSampleModel(); SampleModel expectedSampleModel = new MultiPixelPackedSampleModel(DataBuffer.TYPE_BYTE, renderedImage.getWidth(), renderedImage.getHeight(), 1); if (!expectedSampleModel.equals(sampleModel)) { return false; //Pixels are not packed } imageObjectInfo.setBitsPerPixel(1); Raster raster = renderedImage.getTile(0, 0); DataBuffer buffer = raster.getDataBuffer(); if (buffer instanceof DataBufferByte) { DataBufferByte byteBuffer = (DataBufferByte)buffer; log.debug("Encoding image as inverted bi-level..."); byte[] rawData = byteBuffer.getData(); int remaining = rawData.length; int pos = 0; byte[] data = new byte[4096]; while (remaining > 0) { int size = Math.min(remaining, data.length); for (int i = 0; i < size; i++) { data[i] = (byte)~rawData[pos]; //invert bits pos++; } out.write(data, 0, size); remaining -= size; } return true; } return false; }
// in src/java/org/apache/fop/render/afp/AFPImageHandlerRawJPEG.java
public void handleImage(RenderingContext context, Image image, Rectangle pos) throws IOException { AFPRenderingContext afpContext = (AFPRenderingContext)context; AFPImageObjectInfo imageObjectInfo = (AFPImageObjectInfo)createDataObjectInfo(); AFPPaintingState paintingState = afpContext.getPaintingState(); // set resource information setResourceInformation(imageObjectInfo, image.getInfo().getOriginalURI(), afpContext.getForeignAttributes()); setDefaultResourceLevel(imageObjectInfo, afpContext.getResourceManager()); // Positioning imageObjectInfo.setObjectAreaInfo(createObjectAreaInfo(paintingState, pos)); updateIntrinsicSize(imageObjectInfo, paintingState, image.getSize()); // Image content ImageRawJPEG jpeg = (ImageRawJPEG)image; imageObjectInfo.setCompression(ImageContent.COMPID_JPEG); ColorSpace cs = jpeg.getColorSpace(); switch (cs.getType()) { case ColorSpace.TYPE_GRAY: imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS11); imageObjectInfo.setColor(false); imageObjectInfo.setBitsPerPixel(8); break; case ColorSpace.TYPE_RGB: imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS11); imageObjectInfo.setColor(true); imageObjectInfo.setBitsPerPixel(24); break; case ColorSpace.TYPE_CMYK: imageObjectInfo.setMimeType(MimeConstants.MIME_AFP_IOCA_FS45); imageObjectInfo.setColor(true); imageObjectInfo.setBitsPerPixel(32); break; default: throw new IllegalStateException( "Color space of JPEG image not supported: " + cs); } boolean included = afpContext.getResourceManager().tryIncludeObject(imageObjectInfo); if (!included) { log.debug("Embedding undecoded JPEG as IOCA image..."); InputStream inputStream = jpeg.createInputStream(); try { imageObjectInfo.setData(IOUtils.toByteArray(inputStream)); } finally { IOUtils.closeQuietly(inputStream); } // Create image afpContext.getResourceManager().createObject(imageObjectInfo); } }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private void generateFormForImage(PSGenerator gen, PSImageFormResource form) throws IOException { final String uri = form.getImageURI(); ImageManager manager = userAgent.getFactory().getImageManager(); ImageInfo info = null; try { ImageSessionContext sessionContext = userAgent.getImageSessionContext(); info = manager.getImageInfo(uri, sessionContext); //Create a rendering context for form creation PSRenderingContext formContext = new PSRenderingContext( userAgent, gen, fontInfo, true); ImageFlavor[] flavors; ImageHandlerRegistry imageHandlerRegistry = userAgent.getFactory().getImageHandlerRegistry(); flavors = imageHandlerRegistry.getSupportedFlavors(formContext); Map hints = ImageUtil.getDefaultHints(sessionContext); org.apache.xmlgraphics.image.loader.Image img = manager.getImage( info, flavors, hints, sessionContext); ImageHandler basicHandler = imageHandlerRegistry.getHandler(formContext, img); if (basicHandler == null) { throw new UnsupportedOperationException( "No ImageHandler available for image: " + img.getInfo() + " (" + img.getClass().getName() + ")"); } if (!(basicHandler instanceof PSImageHandler)) { throw new IllegalStateException( "ImageHandler implementation doesn't behave properly." + " It should have returned false in isCompatible(). Class: " + basicHandler.getClass().getName()); } PSImageHandler handler = (PSImageHandler)basicHandler; if (log.isTraceEnabled()) { log.trace("Using ImageHandler: " + handler.getClass().getName()); } handler.generateForm(formContext, img, form); } catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.imageError(resTracker, (info != null ? info.toString() : uri), ie, null); } }
// in src/java/org/apache/fop/render/ps/ImageEncoderCCITTFax.java
public String getImplicitFilter() { PSDictionary dict = new PSDictionary(); dict.put("/Columns", new Integer(ccitt.getSize().getWidthPx())); int compression = ccitt.getCompression(); switch (compression) { case TIFFImage.COMP_FAX_G3_1D : dict.put("/K", new Integer(0)); break; case TIFFImage.COMP_FAX_G3_2D : dict.put("/K", new Integer(1)); break; case TIFFImage.COMP_FAX_G4_2D : dict.put("/K", new Integer(-1)); break; default: throw new IllegalStateException( "Invalid compression scheme: " + compression); } return dict.toString() + " /CCITTFaxDecode"; }
// in src/java/org/apache/fop/render/ps/FontResourceCache.java
private String getPostScriptNameForFontKey(String key) { int pos = key.indexOf('_'); String postFix = null; if (pos > 0) { postFix = key.substring(pos); key = key.substring(0, pos); } Map<String, Typeface> fonts = fontInfo.getFonts(); Typeface tf = fonts.get(key); if (tf instanceof LazyFont) { tf = ((LazyFont)tf).getRealFont(); } if (tf == null) { throw new IllegalStateException("Font not available: " + key); } if (postFix == null) { return tf.getFontName(); } else { return tf.getFontName() + postFix; } }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
public void drawBorderRect(Rectangle rect, BorderProps top, BorderProps bottom, BorderProps left, BorderProps right) throws IFException { if (top != null || bottom != null || left != null || right != null) { try { this.borderPainter.drawBorders(rect, top, bottom, left, right); } catch (IOException e) { //Won't happen with Java2D throw new IllegalStateException("Unexpected I/O error"); } } }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
protected void clip() { if (currentPath == null) { throw new IllegalStateException("No current path available!"); } state.updateClip(currentPath); currentPath = null; }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public static void renderText(TextArea text, Graphics2D g2d, Font font) { Color col = (Color) text.getTrait(Trait.COLOR); g2d.setColor(col); float textCursor = 0; Iterator iter = text.getChildAreas().iterator(); while (iter.hasNext()) { InlineArea child = (InlineArea)iter.next(); if (child instanceof WordArea) { WordArea word = (WordArea)child; String s = word.getWord(); int[] letterAdjust = word.getLetterAdjustArray(); GlyphVector gv = g2d.getFont().createGlyphVector(g2d.getFontRenderContext(), s); double additionalWidth = 0.0; if (letterAdjust == null && text.getTextLetterSpaceAdjust() == 0 && text.getTextWordSpaceAdjust() == 0) { //nop } else { int[] offsets = getGlyphOffsets(s, font, text, letterAdjust); float cursor = 0.0f; for (int i = 0; i < offsets.length; i++) { Point2D pt = gv.getGlyphPosition(i); pt.setLocation(cursor, pt.getY()); gv.setGlyphPosition(i, pt); cursor += offsets[i] / 1000f; } additionalWidth = cursor - gv.getLogicalBounds().getWidth(); } g2d.drawGlyphVector(gv, textCursor, 0); textCursor += gv.getLogicalBounds().getWidth() + additionalWidth; } else if (child instanceof SpaceArea) { SpaceArea space = (SpaceArea)child; String s = space.getSpace(); char sp = s.charAt(0); int tws = (space.isAdjustable() ? text.getTextWordSpaceAdjust() + 2 * text.getTextLetterSpaceAdjust() : 0); textCursor += (font.getCharWidth(sp) + tws) / 1000f; } else { throw new IllegalStateException("Unsupported child element: " + child); } } }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException { if (pageIndex >= getNumberOfPages()) { return NO_SUCH_PAGE; } if (state != null) { throw new IllegalStateException("state must be null"); } Graphics2D graphics = (Graphics2D) g; try { PageViewport viewport = getPageViewport(pageIndex); AffineTransform at = graphics.getTransform(); state = new Java2DGraphicsState(graphics, this.fontInfo, at); // reset the current Positions currentBPPosition = 0; currentIPPosition = 0; renderPageAreas(viewport.getPage()); return PAGE_EXISTS; } catch (FOPException e) { log.error(e); return NO_SUCH_PAGE; } finally { state = null; } }
// in src/java/org/apache/fop/render/java2d/Java2DBorderPainter.java
protected void clip() { if (currentPath == null) { throw new IllegalStateException("No current path available!"); } getG2DState().updateClip(currentPath); currentPath = null; }
// in src/java/org/apache/fop/afp/DataStream.java
public void endDocument() throws IOException { if (complete) { String msg = "Invalid state - document already ended."; LOG.warn("endDocument():: " + msg); throw new IllegalStateException(msg); } if (currentPageObject != null) { // End the current page if necessary endPage(); } if (currentPageGroup != null) { // End the current page group if necessary endPageGroup(); } // Write out document if (document != null) { document.endDocument(); document.writeToStream(this.outputStream); } this.outputStream.flush(); this.complete = true; this.document = null; this.outputStream = null; }
// in src/java/org/apache/fop/afp/AFPDataObjectFactory.java
public ImageObject createImage(AFPImageObjectInfo imageObjectInfo) { // IOCA bitmap image ImageObject imageObj = factory.createImageObject(); // set data object viewport (i.e. position, rotation, dimension, resolution) imageObj.setViewport(imageObjectInfo); if (imageObjectInfo.hasCompression()) { int compression = imageObjectInfo.getCompression(); switch (compression) { case TIFFImage.COMP_FAX_G3_1D: imageObj.setEncoding(ImageContent.COMPID_G3_MH); break; case TIFFImage.COMP_FAX_G3_2D: imageObj.setEncoding(ImageContent.COMPID_G3_MR); break; case TIFFImage.COMP_FAX_G4_2D: imageObj.setEncoding(ImageContent.COMPID_G3_MMR); break; case ImageContent.COMPID_JPEG: imageObj.setEncoding((byte)compression); break; default: throw new IllegalStateException( "Invalid compression scheme: " + compression); } } ImageContent content = imageObj.getImageSegment().getImageContent(); int bitsPerPixel = imageObjectInfo.getBitsPerPixel(); imageObj.setIDESize((byte) bitsPerPixel); IDEStructureParameter ideStruct; switch (bitsPerPixel) { case 1: //Skip IDE Structure Parameter break; case 4: case 8: //A grayscale image ideStruct = content.needIDEStructureParameter(); ideStruct.setBitsPerComponent(new int[] {bitsPerPixel}); ideStruct.setColorModel(IDEStructureParameter.COLOR_MODEL_YCBCR); break; case 24: ideStruct = content.needIDEStructureParameter(); ideStruct.setDefaultRGBColorModel(); break; case 32: ideStruct = content.needIDEStructureParameter(); ideStruct.setDefaultCMYKColorModel(); break; default: throw new IllegalArgumentException("Unsupported number of bits per pixel: " + bitsPerPixel); } if (bitsPerPixel > 1 && imageObjectInfo.isSubtractive()) { ideStruct = content.needIDEStructureParameter(); ideStruct.setSubtractive(imageObjectInfo.isSubtractive()); } imageObj.setData(imageObjectInfo.getData()); return imageObj; }
// in src/java/org/apache/fop/afp/AFPDataObjectFactory.java
public IncludeObject createInclude(String includeName, AFPDataObjectInfo dataObjectInfo) { IncludeObject includeObj = factory.createInclude(includeName); if (dataObjectInfo instanceof AFPImageObjectInfo) { // IOCA image object includeObj.setObjectType(IncludeObject.TYPE_IMAGE); } else if (dataObjectInfo instanceof AFPGraphicsObjectInfo) { // graphics object includeObj.setObjectType(IncludeObject.TYPE_GRAPHIC); } else { // object container includeObj.setObjectType(IncludeObject.TYPE_OTHER); // set mandatory object classification (type other) Registry.ObjectType objectType = dataObjectInfo.getObjectType(); if (objectType != null) { // set object classification final boolean dataInContainer = true; final boolean containerHasOEG = false; // environment parameters set in include final boolean dataInOCD = true; includeObj.setObjectClassification( // object scope not defined ObjectClassificationTriplet.CLASS_TIME_VARIANT_PRESENTATION_OBJECT, objectType, dataInContainer, containerHasOEG, dataInOCD); } else { throw new IllegalStateException( "Failed to set Object Classification Triplet on Object Container."); } } AFPObjectAreaInfo objectAreaInfo = dataObjectInfo.getObjectAreaInfo(); int xOffset = objectAreaInfo.getX(); int yOffset = objectAreaInfo.getY(); includeObj.setObjectAreaOffset(xOffset, yOffset); int width = objectAreaInfo.getWidth(); int height = objectAreaInfo.getHeight(); includeObj.setObjectAreaSize(width, height); int rotation = objectAreaInfo.getRotation(); includeObj.setObjectAreaOrientation(rotation); int widthRes = objectAreaInfo.getWidthRes(); int heightRes = objectAreaInfo.getHeightRes(); includeObj.setMeasurementUnits(widthRes, heightRes); includeObj.setMappingOption(MappingOptionTriplet.SCALE_TO_FIT); return includeObj; }
// in src/java/org/apache/fop/afp/goca/GraphicsSetProcessColor.java
public void writeToStream(OutputStream os) throws IOException { float[] colorComponents = color.getColorComponents(null); // COLSPCE byte colspace; ColorSpace cs = color.getColorSpace(); int colSpaceType = cs.getType(); ByteArrayOutputStream baout = new ByteArrayOutputStream(); byte[] colsizes; if (colSpaceType == ColorSpace.TYPE_CMYK) { colspace = CMYK; colsizes = new byte[] {0x08, 0x08, 0x08, 0x08}; for (int i = 0; i < colorComponents.length; i++) { baout.write(Math.round(colorComponents[i] * 255)); } } else if (colSpaceType == ColorSpace.TYPE_RGB) { colspace = RGB; colsizes = new byte[] {0x08, 0x08, 0x08, 0x00}; for (int i = 0; i < colorComponents.length; i++) { baout.write(Math.round(colorComponents[i] * 255)); } } else if (cs instanceof CIELabColorSpace) { colspace = CIELAB; colsizes = new byte[] {0x08, 0x08, 0x08, 0x00}; DataOutput dout = new java.io.DataOutputStream(baout); //According to GOCA, I'd expect the multiplicator below to be 255f, not 100f //But only IBM AFP Workbench seems to support Lab colors and it requires "c * 100f" int l = Math.round(colorComponents[0] * 100f); int a = Math.round(colorComponents[1] * 255f) - 128; int b = Math.round(colorComponents[2] * 255f) - 128; dout.writeByte(l); dout.writeByte(a); dout.writeByte(b); } else { throw new IllegalStateException(); } int len = getDataLength(); byte[] data = new byte[12]; data[0] = getOrderCode(); // GSPCOL order code data[1] = (byte) (len - 2); // LEN data[2] = 0x00; // reserved; must be zero data[3] = colspace; // COLSPCE data[4] = 0x00; // reserved; must be zero data[5] = 0x00; // reserved; must be zero data[6] = 0x00; // reserved; must be zero data[7] = 0x00; // reserved; must be zero data[8] = colsizes[0]; // COLSIZE(S) data[9] = colsizes[1]; data[10] = colsizes[2]; data[11] = colsizes[3]; os.write(data); baout.writeTo(os); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
private static int determineOrientation(byte orientation) { int degrees = 0; switch (orientation) { case 0x00: degrees = 0; break; case 0x2D: degrees = 90; break; case 0x5A: degrees = 180; break; case (byte) 0x87: degrees = 270; break; default: throw new IllegalStateException("Invalid orientation: " + orientation); } return degrees; }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
public void addMapPageSegment(String name) { try { needMapPageSegment().addPageSegment(name); } catch (MaximumSizeExceededException e) { //Should not happen, handled internally throw new IllegalStateException("Internal error: " + e.getMessage()); } }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
protected EventProducer createProxyFor(Class clazz) { final EventProducerModel producerModel = getEventProducerModel(clazz); if (producerModel == null) { throw new IllegalStateException("Event model doesn't contain the definition for " + clazz.getName()); } return (EventProducer)Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] {clazz}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); EventMethodModel methodModel = producerModel.getMethod(methodName); String eventID = producerModel.getInterfaceName() + "." + methodName; if (methodModel == null) { throw new IllegalStateException( "Event model isn't consistent" + " with the EventProducer interface. Please rebuild FOP!" + " Affected method: " + eventID); } Map params = new java.util.HashMap(); int i = 1; Iterator iter = methodModel.getParameters().iterator(); while (iter.hasNext()) { EventMethodModel.Parameter param = (EventMethodModel.Parameter)iter.next(); params.put(param.getName(), args[i]); i++; } Event ev = new Event(args[0], eventID, methodModel.getSeverity(), params); broadcastEvent(ev); if (ev.getSeverity() == EventSeverity.FATAL) { EventExceptionManager.throwException(ev, methodModel.getExceptionClass()); } return null; } }); }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); EventMethodModel methodModel = producerModel.getMethod(methodName); String eventID = producerModel.getInterfaceName() + "." + methodName; if (methodModel == null) { throw new IllegalStateException( "Event model isn't consistent" + " with the EventProducer interface. Please rebuild FOP!" + " Affected method: " + eventID); } Map params = new java.util.HashMap(); int i = 1; Iterator iter = methodModel.getParameters().iterator(); while (iter.hasNext()) { EventMethodModel.Parameter param = (EventMethodModel.Parameter)iter.next(); params.put(param.getName(), args[i]); i++; } Event ev = new Event(args[0], eventID, methodModel.getSeverity(), params); broadcastEvent(ev); if (ev.getSeverity() == EventSeverity.FATAL) { EventExceptionManager.throwException(ev, methodModel.getExceptionClass()); } return null; }
// in src/java/org/apache/fop/area/PageViewport.java
public String getKey() { if (this.pageKey == null) { throw new IllegalStateException("No page key set on the PageViewport: " + toString()); } return this.pageKey; }
// in src/java/org/apache/fop/area/inline/InlineBlockParent.java
Override public void addChildArea(Area childArea) { if (child != null) { throw new IllegalStateException("InlineBlockParent may have only one child area."); } if (childArea instanceof Block) { child = (Block) childArea; //Update extents from the child setIPD(childArea.getAllocIPD()); setBPD(childArea.getAllocBPD()); } else { throw new IllegalArgumentException("The child of an InlineBlockParent must be a" + " Block area"); } }
// in src/java/org/apache/fop/area/inline/Leader.java
public String getRuleStyleAsString() { switch (getRuleStyle()) { case Constants.EN_DOTTED: return "dotted"; case Constants.EN_DASHED: return "dashed"; case Constants.EN_SOLID: return "solid"; case Constants.EN_DOUBLE: return "double"; case Constants.EN_GROOVE: return "groove"; case Constants.EN_RIDGE: return "ridge"; case Constants.EN_NONE: return "none"; default: throw new IllegalStateException("Unsupported rule style: " + getRuleStyle()); } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) { if (!areaStack.isEmpty()) { PageSequence pageSequence = (PageSequence)areaStack.peek(); treeModel.startPageSequence(pageSequence); areaStack.pop(); } if (currentPageViewport != null) { throw new IllegalStateException("currentPageViewport must be null"); } Rectangle viewArea = XMLUtil.getAttributeAsRectangle(attributes, "bounds"); int pageNumber = XMLUtil.getAttributeAsInt(attributes, "nr", -1); String key = attributes.getValue("key"); String pageNumberString = attributes.getValue("formatted-nr"); String pageMaster = attributes.getValue("simple-page-master-name"); boolean blank = XMLUtil.getAttributeAsBoolean(attributes, "blank", false); currentPageViewport = new PageViewport(viewArea, pageNumber, pageNumberString, pageMaster, blank); transferForeignObjects(attributes, currentPageViewport); currentPageViewport.setKey(key); pageViewportsByKey.put(key, currentPageViewport); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) { RegionViewport rv = getCurrentRegionViewport(); if (rv != null) { throw new IllegalStateException("Current RegionViewport must be null"); } Rectangle2D viewArea = XMLUtil.getAttributeAsRectangle2D(attributes, "rect"); rv = new RegionViewport(viewArea); transferForeignObjects(attributes, rv); rv.setClip(XMLUtil.getAttributeAsBoolean(attributes, "clipped", false)); setAreaAttributes(attributes, rv); setTraits(attributes, rv, SUBSET_COMMON); setTraits(attributes, rv, SUBSET_BOX); setTraits(attributes, rv, SUBSET_COLOR); areaStack.push(rv); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) { BodyRegion body = getCurrentBodyRegion(); if (body != null) { throw new IllegalStateException("Current BodyRegion must be null"); } String regionName = attributes.getValue("name"); int columnCount = XMLUtil.getAttributeAsInt(attributes, "columnCount", 1); int columnGap = XMLUtil.getAttributeAsInt(attributes, "columnGap", 0); RegionViewport rv = getCurrentRegionViewport(); body = new BodyRegion(FO_REGION_BODY, regionName, rv, columnCount, columnGap); transferForeignObjects(attributes, body); body.setCTM(getAttributeAsCTM(attributes, "ctm")); setAreaAttributes(attributes, body); setTraits(attributes, body, SUBSET_BORDER_PADDING); rv.setRegionReference(body); currentPageViewport.getPage().setRegionViewport(FO_REGION_BODY, rv); areaStack.push(body); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) { if (getCurrentText() != null) { throw new IllegalStateException("Current Text must be null"); } TextArea text = new TextArea(); setAreaAttributes(attributes, text); setTraits(attributes, text, SUBSET_COMMON); setTraits(attributes, text, SUBSET_BOX); setTraits(attributes, text, SUBSET_COLOR); setTraits(attributes, text, SUBSET_FONT); text.setBaselineOffset(XMLUtil.getAttributeAsInt(attributes, "baseline", 0)); text.setBlockProgressionOffset(XMLUtil.getAttributeAsInt(attributes, "offset", 0)); text.setTextLetterSpaceAdjust(XMLUtil.getAttributeAsInt(attributes, "tlsadjust", 0)); text.setTextWordSpaceAdjust(XMLUtil.getAttributeAsInt(attributes, "twsadjust", 0)); Area parent = (Area)areaStack.peek(); parent.addChildArea(text); areaStack.push(text); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
private void assertObjectOfClass(Object obj, Class clazz) { if (!clazz.isInstance(obj)) { throw new IllegalStateException("Object is not an instance of " + clazz.getName() + " but of " + obj.getClass().getName()); } }
// in src/java/org/apache/fop/area/Trait.java
private String getRepeatString() { switch (getRepeat()) { case EN_REPEAT: return "repeat"; case EN_REPEATX: return "repeat-x"; case EN_REPEATY: return "repeat-y"; case EN_NOREPEAT: return "no-repeat"; default: throw new IllegalStateException("Illegal repeat style: " + getRepeat()); } }
// in src/java/org/apache/fop/area/Trait.java
private static int getConstantForRepeat(String repeat) { if ("repeat".equalsIgnoreCase(repeat)) { return EN_REPEAT; } else if ("repeat-x".equalsIgnoreCase(repeat)) { return EN_REPEATX; } else if ("repeat-y".equalsIgnoreCase(repeat)) { return EN_REPEATY; } else if ("no-repeat".equalsIgnoreCase(repeat)) { return EN_NOREPEAT; } else { throw new IllegalStateException("Illegal repeat style: " + repeat); } }
// in src/java/org/apache/fop/area/RenderPagesModel.java
Override public void addPage(PageViewport page) { super.addPage(page); // for links the renderer needs to prepare the page // it is more appropriate to do this after queued pages but // it will mean that the renderer has not prepared a page that // could be referenced boolean ready = renderer.supportsOutOfOrder() && page.isResolved(); if (ready) { if (!renderer.supportsOutOfOrder() && page.getPageSequence().isFirstPage(page)) { renderer.startPageSequence(getCurrentPageSequence()); } try { renderer.renderPage(page); } catch (RuntimeException re) { String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, re); throw re; } catch (IOException ioe) { RendererEventProducer eventProducer = RendererEventProducer.Provider.get( renderer.getUserAgent().getEventBroadcaster()); eventProducer.ioError(this, ioe); } catch (FOPException e) { //TODO use error handler to handle this FOPException or propagate exception String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, e); throw new IllegalStateException("Fatal error occurred. Cannot continue. " + e.getClass().getName() + ": " + err); } page.clear(); } else { preparePage(page); } // check prepared pages boolean cont = checkPreparedPages(page, false); if (cont) { processOffDocumentItems(pendingODI); pendingODI.clear(); } }
// in src/java/org/apache/fop/area/Span.java
public NormalFlow moveToNextFlow() { if (hasMoreFlows()) { curFlowIdx++; return getNormalFlow(curFlowIdx); } else { throw new IllegalStateException("(Internal error.) No more flows left in span."); } }
// in src/java/org/apache/fop/layoutmgr/PageBreaker.java
protected void startPart(BlockSequence list, int breakClass) { AbstractBreaker.log.debug("startPart() breakClass=" + getBreakClassName(breakClass)); if (pslm.getCurrentPage() == null) { throw new IllegalStateException("curPage must not be null"); } if (!pageBreakHandled) { //firstPart is necessary because we need the first page before we start the //algorithm so we have a BPD and IPD. This may subject to change later when we //start handling more complex cases. if (!firstPart) { // if this is the first page that will be created by // the current BlockSequence, it could have a break // condition that must be satisfied; // otherwise, we may simply need a new page handleBreakTrait(breakClass); } pageProvider.setStartOfNextElementList(pslm.getCurrentPageNum(), pslm.getCurrentPV().getCurrentSpan().getCurrentFlowIndex(), this.spanAllActive); } pageBreakHandled = false; // add static areas and resolve any new id areas // finish page and add to area tree firstPart = false; }
// in src/java/org/apache/fop/layoutmgr/SpaceResolver.java
private void resolve() { if (breakPoss != null) { if (hasFirstPart()) { removeConditionalBorderAndPadding(firstPart, firstPartLengths, true); performSpaceResolutionRule1(firstPart, firstPartLengths, true); performSpaceResolutionRules2to3(firstPart, firstPartLengths); } if (hasSecondPart()) { removeConditionalBorderAndPadding(secondPart, secondPartLengths, false); performSpaceResolutionRule1(secondPart, secondPartLengths, false); performSpaceResolutionRules2to3(secondPart, secondPartLengths); } if (noBreak != null) { performSpaceResolutionRules2to3(noBreak, noBreakLengths); } } else { if (isFirst) { removeConditionalBorderAndPadding(secondPart, secondPartLengths, false); performSpaceResolutionRule1(secondPart, secondPartLengths, false); } if (isLast) { removeConditionalBorderAndPadding(firstPart, firstPartLengths, true); performSpaceResolutionRule1(firstPart, firstPartLengths, true); } if (hasFirstPart()) { //Now that we've handled isFirst/isLast conditions, we need to look at the //active part in its normal order so swap it back. LOG.trace("Swapping first and second parts."); UnresolvedListElementWithLength[] tempList; MinOptMax[] tempLengths; tempList = secondPart; tempLengths = secondPartLengths; secondPart = firstPart; secondPartLengths = firstPartLengths; firstPart = tempList; firstPartLengths = tempLengths; if (hasFirstPart()) { throw new IllegalStateException("Didn't expect more than one parts in a" + "no-break condition."); } } performSpaceResolutionRules2to3(secondPart, secondPartLengths); } }
// in src/java/org/apache/fop/layoutmgr/SpaceResolver.java
private void generate(ListIterator iter) { MinOptMax spaceBeforeBreak = sum(firstPartLengths); MinOptMax spaceAfterBreak = sum(secondPartLengths); boolean hasPrecedingNonBlock = false; if (breakPoss != null) { if (spaceBeforeBreak.isNonZero()) { iter.add(new KnuthPenalty(0, KnuthPenalty.INFINITE, false, null, true)); iter.add(new KnuthGlue(spaceBeforeBreak, null, true)); if (breakPoss.isForcedBreak()) { //Otherwise, the preceding penalty and glue will be cut off iter.add(new KnuthBox(0, null, true)); } } iter.add(new KnuthPenalty(breakPoss.getPenaltyWidth(), breakPoss.getPenaltyValue(), false, breakPoss.getBreakClass(), new SpaceHandlingBreakPosition(this, breakPoss), false)); if (breakPoss.getPenaltyValue() <= -KnuthPenalty.INFINITE) { return; //return early. Not necessary (even wrong) to add additional elements } // No break // TODO: We can't use a MinOptMax for glue2, // because min <= opt <= max is not always true - why? MinOptMax noBreakLength = sum(noBreakLengths); MinOptMax spaceSum = spaceBeforeBreak.plus(spaceAfterBreak); int glue2width = noBreakLength.getOpt() - spaceSum.getOpt(); int glue2stretch = noBreakLength.getStretch() - spaceSum.getStretch(); int glue2shrink = noBreakLength.getShrink() - spaceSum.getShrink(); if (glue2width != 0 || glue2stretch != 0 || glue2shrink != 0) { iter.add(new KnuthGlue(glue2width, glue2stretch, glue2shrink, null, true)); } } else { if (spaceBeforeBreak.isNonZero()) { throw new IllegalStateException("spaceBeforeBreak should be 0 in this case"); } } Position pos = null; if (breakPoss == null) { pos = new SpaceHandlingPosition(this); } if (spaceAfterBreak.isNonZero() || pos != null) { iter.add(new KnuthBox(0, pos, true)); } if (spaceAfterBreak.isNonZero()) { iter.add(new KnuthPenalty(0, KnuthPenalty.INFINITE, false, null, true)); iter.add(new KnuthGlue(spaceAfterBreak, null, true)); hasPrecedingNonBlock = true; } if (isLast && hasPrecedingNonBlock) { //Otherwise, the preceding penalty and glue will be cut off iter.add(new KnuthBox(0, null, true)); } }
// in src/java/org/apache/fop/layoutmgr/SpaceResolver.java
public void notifySpaceSituation() { if (resolver.breakPoss != null) { throw new IllegalStateException("Only applicable to no-break situations"); } for (int i = 0; i < resolver.secondPart.length; i++) { resolver.secondPart[i].notifyLayoutManager(resolver.secondPartLengths[i]); } }
// in src/java/org/apache/fop/layoutmgr/BlockContainerLayoutManager.java
Override public void addAreas(PositionIterator parentIter, LayoutContext layoutContext) { getParentArea(null); // if this will create the first block area in a page // and display-align is bottom or center, add space before if (layoutContext.getSpaceBefore() > 0) { addBlockSpacing(0.0, MinOptMax.getInstance(layoutContext.getSpaceBefore())); } LayoutManager childLM; LayoutManager lastLM = null; LayoutContext lc = new LayoutContext(0); lc.setSpaceAdjust(layoutContext.getSpaceAdjust()); // set space after in the LayoutContext for children if (layoutContext.getSpaceAfter() > 0) { lc.setSpaceAfter(layoutContext.getSpaceAfter()); } BlockContainerPosition bcpos = null; PositionIterator childPosIter; // "unwrap" the NonLeafPositions stored in parentIter // and put them in a new list; List<Position> positionList = new LinkedList<Position>(); Position pos; Position firstPos = null; Position lastPos = null; while (parentIter.hasNext()) { pos = parentIter.next(); if (pos.getIndex() >= 0) { if (firstPos == null) { firstPos = pos; } lastPos = pos; } Position innerPosition = pos; if (pos instanceof NonLeafPosition) { innerPosition = pos.getPosition(); } if (pos instanceof BlockContainerPosition) { if (bcpos != null) { throw new IllegalStateException("Only one BlockContainerPosition allowed"); } bcpos = (BlockContainerPosition)pos; //Add child areas inside the reference area //bcpos.getBreaker().addContainedAreas(); } else if (innerPosition == null) { //ignore (probably a Position for a simple penalty between blocks) } else if (innerPosition.getLM() == this && !(innerPosition instanceof MappingPosition)) { // pos was created by this BlockLM and was inside a penalty // allowing or forbidding a page break // nothing to do } else { // innerPosition was created by another LM positionList.add(innerPosition); lastLM = innerPosition.getLM(); } } addId(); addMarkersToPage(true, isFirst(firstPos), isLast(lastPos)); if (bcpos == null) { // the Positions in positionList were inside the elements // created by the LineLM childPosIter = new PositionIterator(positionList.listIterator()); while ((childLM = childPosIter.getNextChildLM()) != null) { // set last area flag lc.setFlags(LayoutContext.LAST_AREA, (layoutContext.isLastArea() && childLM == lastLM)); lc.setStackLimitBP(layoutContext.getStackLimitBP()); // Add the line areas to Area childLM.addAreas(childPosIter, lc); } } else { //Add child areas inside the reference area bcpos.getBreaker().addContainedAreas(); } addMarkersToPage(false, isFirst(firstPos), isLast(lastPos)); TraitSetter.addSpaceBeforeAfter(viewportBlockArea, layoutContext.getSpaceAdjust(), effSpaceBefore, effSpaceAfter); flush(); viewportBlockArea = null; referenceArea = null; resetSpaces(); notifyEndOfLayout(); }
// in src/java/org/apache/fop/layoutmgr/BlockStackingLayoutManager.java
public KeepProperty getKeepTogetherProperty() { throw new IllegalStateException(); }
// in src/java/org/apache/fop/layoutmgr/BlockStackingLayoutManager.java
public KeepProperty getKeepWithPreviousProperty() { throw new IllegalStateException(); }
// in src/java/org/apache/fop/layoutmgr/BlockStackingLayoutManager.java
public KeepProperty getKeepWithNextProperty() { throw new IllegalStateException(); }
// in src/java/org/apache/fop/layoutmgr/FlowLayoutManager.java
List getNextKnuthElements(LayoutContext context, int alignment, Position restartPosition, LayoutManager restartLM) { List<ListElement> elements = new LinkedList<ListElement>(); boolean isRestart = (restartPosition != null); // always reset in case of restart (exception: see below) boolean doReset = isRestart; LayoutManager currentChildLM; Stack<LayoutManager> lmStack = new Stack<LayoutManager>(); if (isRestart) { currentChildLM = restartPosition.getLM(); if (currentChildLM == null) { throw new IllegalStateException("Cannot find layout manager to restart from"); } if (restartLM != null && restartLM.getParent() == this) { currentChildLM = restartLM; } else { while (currentChildLM.getParent() != this) { lmStack.push(currentChildLM); currentChildLM = currentChildLM.getParent(); } doReset = false; } setCurrentChildLM(currentChildLM); } else { currentChildLM = getChildLM(); } while (currentChildLM != null) { if (!isRestart || doReset) { if (doReset) { currentChildLM.reset(); // TODO won't work with forced breaks } if (addChildElements(elements, currentChildLM, context, alignment, null, null, null) != null) { return elements; } } else { if (addChildElements(elements, currentChildLM, context, alignment, lmStack, restartPosition, restartLM) != null) { return elements; } // restarted; force reset as of next child doReset = true; } currentChildLM = getChildLM(); } SpaceResolver.resolveElementList(elements); setFinished(true); assert !elements.isEmpty(); return elements; }
// in src/java/org/apache/fop/layoutmgr/FlowLayoutManager.java
Override public Area getParentArea(Area childArea) { BlockParent parentArea = null; int aclass = childArea.getAreaClass(); if (aclass == Area.CLASS_NORMAL) { parentArea = getCurrentPV().getCurrentFlow(); } else if (aclass == Area.CLASS_BEFORE_FLOAT) { parentArea = getCurrentPV().getBodyRegion().getBeforeFloat(); } else if (aclass == Area.CLASS_FOOTNOTE) { parentArea = getCurrentPV().getBodyRegion().getFootnote(); } else { throw new IllegalStateException("(internal error) Invalid " + "area class (" + aclass + ") requested."); } this.currentAreas[aclass] = parentArea; setCurrentArea(parentArea); return parentArea; }
// in src/java/org/apache/fop/layoutmgr/AbstractPageSequenceLayoutManager.java
public void reset() { throw new IllegalStateException(); }
// in src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java
private void addWordLevels ( int[] levels ) { int numLevels = ( levels != null ) ? levels.length : 0; if ( numLevels > 0 ) { int need = wordLevelsIndex + numLevels; if ( need <= wordLevels.length ) { System.arraycopy ( levels, 0, wordLevels, wordLevelsIndex, numLevels ); } else { throw new IllegalStateException ( "word levels array too short: expect at least " + need + " entries, but has only " + wordLevels.length + " entries" ); } } wordLevelsIndex += numLevels; }
// in src/java/org/apache/fop/layoutmgr/inline/TextLayoutManager.java
private boolean addGlyphPositionAdjustments(AreaInfo wordAreaInfo) { boolean adjusted = false; int[][] gpa = wordAreaInfo.gposAdjustments; int numAdjusts = ( gpa != null ) ? gpa.length : 0; int wordLength = wordAreaInfo.getWordLength(); if ( numAdjusts > 0 ) { int need = gposAdjustmentsIndex + numAdjusts; if ( need <= gposAdjustments.length ) { for ( int i = 0, n = wordLength, j = 0; i < n; i++ ) { if ( i < numAdjusts ) { int[] wpa1 = gposAdjustments [ gposAdjustmentsIndex + i ]; int[] wpa2 = gpa [ j++ ]; for ( int k = 0; k < 4; k++ ) { int a = wpa2 [ k ]; if ( a != 0 ) { wpa1 [ k ] += a; adjusted = true; } } } } } else { throw new IllegalStateException ( "gpos adjustments array too short: expect at least " + need + " entries, but has only " + gposAdjustments.length + " entries" ); } } gposAdjustmentsIndex += wordLength; return adjusted; }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
public PageSequenceLayoutManager getPSLM() { throw new IllegalStateException("getPSLM() is illegal for " + getClass().getName()); }
// in src/java/org/apache/fop/layoutmgr/AbstractBreaker.java
protected int getNextBlockList(LayoutContext childLC, int nextSequenceStartsOn, Position positionAtIPDChange, LayoutManager restartAtLM, List<KnuthElement> firstElements) { updateLayoutContext(childLC); //Make sure the span change signal is reset childLC.signalSpanChange(Constants.NOT_SET); BlockSequence blockList; List<KnuthElement> returnedList; if (firstElements == null) { returnedList = getNextKnuthElements(childLC, alignment); } else if (positionAtIPDChange == null) { /* * No restartable element found after changing IPD break. Simply add the * non-restartable elements found after the break. */ returnedList = firstElements; /* * Remove the last 3 penalty-filler-forced break elements that were added by * the Knuth algorithm. They will be re-added later on. */ ListIterator iter = returnedList.listIterator(returnedList.size()); for (int i = 0; i < 3; i++) { iter.previous(); iter.remove(); } } else { returnedList = getNextKnuthElements(childLC, alignment, positionAtIPDChange, restartAtLM); returnedList.addAll(0, firstElements); } if (returnedList != null) { if (returnedList.isEmpty()) { nextSequenceStartsOn = handleSpanChange(childLC, nextSequenceStartsOn); return nextSequenceStartsOn; } blockList = new BlockSequence(nextSequenceStartsOn, getCurrentDisplayAlign()); //Only implemented by the PSLM nextSequenceStartsOn = handleSpanChange(childLC, nextSequenceStartsOn); Position breakPosition = null; if (ElementListUtils.endsWithForcedBreak(returnedList)) { KnuthPenalty breakPenalty = (KnuthPenalty) ListUtil .removeLast(returnedList); breakPosition = breakPenalty.getPosition(); log.debug("PLM> break - " + getBreakClassName(breakPenalty.getBreakClass())); switch (breakPenalty.getBreakClass()) { case Constants.EN_PAGE: nextSequenceStartsOn = Constants.EN_ANY; break; case Constants.EN_COLUMN: //TODO Fix this when implementing multi-column layout nextSequenceStartsOn = Constants.EN_COLUMN; break; case Constants.EN_ODD_PAGE: nextSequenceStartsOn = Constants.EN_ODD_PAGE; break; case Constants.EN_EVEN_PAGE: nextSequenceStartsOn = Constants.EN_EVEN_PAGE; break; default: throw new IllegalStateException("Invalid break class: " + breakPenalty.getBreakClass()); } } blockList.addAll(returnedList); BlockSequence seq; seq = blockList.endBlockSequence(breakPosition); if (seq != null) { blockLists.add(seq); } } return nextSequenceStartsOn; }
// in src/java/org/apache/fop/layoutmgr/AbstractLayoutManager.java
public Position notifyPos(Position pos) { if (pos.getIndex() >= 0) { throw new IllegalStateException("Position already got its index"); } pos.setIndex(++lastGeneratedPosition); return pos; }
// in src/java/org/apache/fop/layoutmgr/BreakingAlgorithm.java
protected int handleIpdChange() { throw new IllegalStateException(); }
// in src/java/org/apache/fop/layoutmgr/LayoutManagerMapping.java
public LayoutManager makeLayoutManager(FONode node) { List lms = new ArrayList(); makeLayoutManagers(node, lms); if (lms.size() == 0) { throw new IllegalStateException("LayoutManager for class " + node.getClass() + " is missing."); } else if (lms.size() > 1) { throw new IllegalStateException("Duplicate LayoutManagers for class " + node.getClass() + " found, only one may be declared."); } return (LayoutManager) lms.get(0); }
// in src/java/org/apache/fop/layoutmgr/table/CollapsingBorderModel.java
private static int getStylePreferenceValue(int style) { switch (style) { case Constants.EN_DOUBLE: return 0; case Constants.EN_SOLID: return -1; case Constants.EN_DASHED: return -2; case Constants.EN_DOTTED: return -3; case Constants.EN_RIDGE: return -4; case Constants.EN_OUTSET: return -5; case Constants.EN_GROOVE: return -6; case Constants.EN_INSET: return -7; default: throw new IllegalStateException("Illegal border style: " + style); } }
// in src/java/org/apache/fop/layoutmgr/table/CollapsingBorderModel.java
private static int getHolderPreferenceValue(int id) { switch (id) { case Constants.FO_TABLE_CELL: return 0; case Constants.FO_TABLE_ROW: return -1; case Constants.FO_TABLE_HEADER: case Constants.FO_TABLE_FOOTER: case Constants.FO_TABLE_BODY: return -2; case Constants.FO_TABLE_COLUMN: return -3; // TODO colgroup case Constants.FO_TABLE: return -4; default: throw new IllegalStateException(); } }
// in src/java/org/apache/fop/layoutmgr/StaticContentLayoutManager.java
public List getNextKnuthElements(LayoutContext context, int alignment) { throw new IllegalStateException(); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubtable.java
public synchronized void setTable ( GlyphTable table ) throws IllegalStateException { WeakReference r = this.table; if ( table == null ) { this.table = null; if ( r != null ) { r.clear(); } } else if ( r == null ) { this.table = new WeakReference ( table ); } else { throw new IllegalStateException ( "table already set" ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubtable.java
public static int getFlags ( GlyphSubtable[] subtables ) throws IllegalStateException { if ( ( subtables == null ) || ( subtables.length == 0 ) ) { return 0; } else { int flags = 0; // obtain first non-zero value of flags in array of subtables for ( int i = 0, n = subtables.length; i < n; i++ ) { int f = subtables[i].getFlags(); if ( flags == 0 ) { flags = f; break; } } // enforce flag consistency for ( int i = 0, n = subtables.length; i < n; i++ ) { int f = subtables[i].getFlags(); if ( f != flags ) { throw new IllegalStateException ( "inconsistent lookup flags " + f + ", expected " + flags ); } } return flags | ( usesReverseScan ( subtables ) ? LF_INTERNAL_USE_REVERSE_SCAN : 0 ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphTable.java
protected void addSubtable ( GlyphSubtable subtable ) { // ensure table is not frozen if ( frozen ) { throw new IllegalStateException ( "glyph table is frozen, subtable addition prohibited" ); } // set subtable's table reference to this table subtable.setTable ( this ); // add subtable to this table's subtable collection String lid = subtable.getLookupId(); if ( lookupTables.containsKey ( lid ) ) { LookupTable lt = (LookupTable) lookupTables.get ( lid ); lt.addSubtable ( subtable ); } else { LookupTable lt = new LookupTable ( lid, subtable ); lookupTables.put ( lid, lt ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphTable.java
public boolean addSubtable ( GlyphSubtable subtable ) { boolean added = false; // ensure table is not frozen if ( frozen ) { throw new IllegalStateException ( "glyph table is frozen, subtable addition prohibited" ); } // validate subtable to ensure consistency with current subtables validateSubtable ( subtable ); // insert subtable into ordered list for ( ListIterator/*<GlyphSubtable>*/ lit = subtables.listIterator(0); lit.hasNext(); ) { GlyphSubtable st = (GlyphSubtable) lit.next(); int d; if ( ( d = subtable.compareTo ( st ) ) < 0 ) { // insert within list lit.set ( subtable ); lit.add ( st ); added = true; } else if ( d == 0 ) { // duplicate entry is ignored added = false; subtable = null; } } // append at end of list if ( ! added && ( subtable != null ) ) { subtables.add ( subtable ); added = true; } return added; }
// in src/codegen/unicode/java/org/apache/fop/complexscripts/bidi/GenerateBidiTestData.java
private static int[] createLevelData ( int[] la, int[] ra, List tal ) { int nl = la.length; int[] data = new int [ 1 + nl * 2 + ( ( nl + 1 ) * tal.size() ) ]; int k = 0; data [ k++ ] = nl; for ( int i = 0, n = nl; i < n; i++ ) { data [ k++ ] = la [ i ]; } int nr = ra.length; for ( int i = 0, n = nr; i < n; i++ ) { data [ k++ ] = ra [ i ]; } for ( Iterator it = tal.iterator(); it.hasNext(); ) { int[] ta = (int[]) it.next(); if ( ta == null ) { throw new IllegalStateException ( "null test array" ); } else if ( ta.length == ( nl + 1 ) ) { for ( int i = 0, n = ta.length; i < n; i++ ) { data [ k++ ] = ta [ i ]; } } else { throw new IllegalStateException ( "test array length error, expected " + ( nl + 1 ) + " entries, got " + ta.length + " entries" ); } } assert k == data.length; return data; }
6
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (IllegalBlockSizeException e) { throw new IllegalStateException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (BadPaddingException e) { throw new IllegalStateException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (InvalidKeyException e) { throw new IllegalStateException(e); }
// in src/java/org/apache/fop/render/java2d/Java2DPainter.java
catch (IOException e) { //Won't happen with Java2D throw new IllegalStateException("Unexpected I/O error"); }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException e) { //Should not happen, handled internally throw new IllegalStateException("Internal error: " + e.getMessage()); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (FOPException e) { //TODO use error handler to handle this FOPException or propagate exception String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, e); throw new IllegalStateException("Fatal error occurred. Cannot continue. " + e.getClass().getName() + ": " + err); }
4
            
// in src/java/org/apache/fop/fonts/NamedCharacter.java
public char getSingleUnicodeValue() throws IllegalStateException { if (this.unicodeSequence == null) { return CharUtilities.NOT_A_CHARACTER; } if (this.unicodeSequence.length() > 1) { throw new IllegalStateException("getSingleUnicodeValue() may not be called for a" + " named character that has more than one Unicode value (a sequence)" + " associated with the named character!"); } return this.unicodeSequence.charAt(0); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
protected RenderingContext createRenderingContext() throws IllegalStateException { throw new IllegalStateException("Should never be called!"); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubtable.java
public synchronized void setTable ( GlyphTable table ) throws IllegalStateException { WeakReference r = this.table; if ( table == null ) { this.table = null; if ( r != null ) { r.clear(); } } else if ( r == null ) { this.table = new WeakReference ( table ); } else { throw new IllegalStateException ( "table already set" ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubtable.java
public static int getFlags ( GlyphSubtable[] subtables ) throws IllegalStateException { if ( ( subtables == null ) || ( subtables.length == 0 ) ) { return 0; } else { int flags = 0; // obtain first non-zero value of flags in array of subtables for ( int i = 0, n = subtables.length; i < n; i++ ) { int f = subtables[i].getFlags(); if ( flags == 0 ) { flags = f; break; } } // enforce flag consistency for ( int i = 0, n = subtables.length; i < n; i++ ) { int f = subtables[i].getFlags(); if ( f != flags ) { throw new IllegalStateException ( "inconsistent lookup flags " + f + ", expected " + flags ); } } return flags | ( usesReverseScan ( subtables ) ? LF_INTERNAL_USE_REVERSE_SCAN : 0 ); } }
2
            
// in src/java/org/apache/fop/layoutmgr/PageSequenceLayoutManager.java
catch (IllegalStateException e) { // empty title; do nothing }
// in src/java/org/apache/fop/layoutmgr/inline/ContentLayoutManager.java
catch (IllegalStateException e) { log.warn("Title has no content"); throw e; }
1
            
// in src/java/org/apache/fop/layoutmgr/inline/ContentLayoutManager.java
catch (IllegalStateException e) { log.warn("Title has no content"); throw e; }
0
unknown (Lib) ImageException 1
            
// in src/java/org/apache/fop/image/loader/batik/ImageConverterSVG2G2D.java
public Image convert(final Image src, Map hints) throws ImageException { checkSourceFlavor(src); final ImageXMLDOM svg = (ImageXMLDOM)src; if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(svg.getRootNamespace())) { throw new IllegalArgumentException("XML DOM is not in the SVG namespace: " + svg.getRootNamespace()); } //Prepare float pxToMillimeter = UnitConv.IN2MM / GraphicsConstants.DEFAULT_DPI; Number ptm = (Number)hints.get(ImageProcessingHints.SOURCE_RESOLUTION); if (ptm != null) { pxToMillimeter = (float)(UnitConv.IN2MM / ptm.doubleValue()); } UserAgent ua = createBatikUserAgent(pxToMillimeter); GVTBuilder builder = new GVTBuilder(); final ImageManager imageManager = (ImageManager)hints.get( ImageProcessingHints.IMAGE_MANAGER); final ImageSessionContext sessionContext = (ImageSessionContext)hints.get( ImageProcessingHints.IMAGE_SESSION_CONTEXT); boolean useEnhancedBridgeContext = (imageManager != null && sessionContext != null); final BridgeContext ctx = (useEnhancedBridgeContext ? new GenericFOPBridgeContext(ua, null, imageManager, sessionContext) : new BridgeContext(ua)); Document doc = svg.getDocument(); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(doc); //Build the GVT tree final GraphicsNode root; try { root = builder.build(ctx, clonedDoc); } catch (Exception e) { throw new ImageException("GVT tree could not be built for SVG graphic", e); } //Create the painter int width = svg.getSize().getWidthMpt(); int height = svg.getSize().getHeightMpt(); Dimension imageSize = new Dimension(width, height); Graphics2DImagePainter painter = createPainter(ctx, root, imageSize); //Create g2d image ImageInfo imageInfo = src.getInfo(); ImageGraphics2D g2dImage = new ImageGraphics2D(imageInfo, painter); return g2dImage; }
1
            
// in src/java/org/apache/fop/image/loader/batik/ImageConverterSVG2G2D.java
catch (Exception e) { throw new ImageException("GVT tree could not be built for SVG graphic", e); }
8
            
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImageUsingImageHandler(ImageInfo info, Rectangle rect) throws ImageException, IOException { ImageManager manager = getFopFactory().getImageManager(); ImageSessionContext sessionContext = getUserAgent().getImageSessionContext(); ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry(); //Load and convert the image to a supported format RenderingContext context = createRenderingContext(); Map hints = createDefaultImageProcessingHints(sessionContext); context.putHints(hints); ImageFlavor[] flavors = imageHandlerRegistry.getSupportedFlavors(context); org.apache.xmlgraphics.image.loader.Image img = manager.getImage( info, flavors, hints, sessionContext); try { drawImage(img, rect, context); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageWritingError(this, ioe); } }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImage(Image image, Rectangle rect, RenderingContext context) throws IOException, ImageException { drawImage(image, rect, context, false, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImage(Image image, Rectangle rect, RenderingContext context, boolean convert, Map additionalHints) throws IOException, ImageException { ImageManager manager = getFopFactory().getImageManager(); ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry(); Image effImage; context.putHints(additionalHints); if (convert) { Map hints = createDefaultImageProcessingHints(getUserAgent().getImageSessionContext()); if (additionalHints != null) { hints.putAll(additionalHints); } effImage = manager.convertImage(image, imageHandlerRegistry.getSupportedFlavors(context), hints); } else { effImage = image; } //First check for a dynamically registered handler ImageHandler handler = imageHandlerRegistry.getHandler(context, effImage); if (handler == null) { throw new UnsupportedOperationException( "No ImageHandler available for image: " + effImage.getInfo() + " (" + effImage.getClass().getName() + ")"); } if (log.isTraceEnabled()) { log.trace("Using ImageHandler: " + handler.getClass().getName()); } handler.handleImage(context, effImage, rect); }
// in src/java/org/apache/fop/render/ps/PSPainter.java
protected void drawImageUsingImageHandler(ImageInfo info, Rectangle rect) throws ImageException, IOException { if (!getPSUtil().isOptimizeResources() || PSImageUtils.isImageInlined(info, (PSRenderingContext)createRenderingContext())) { super.drawImageUsingImageHandler(info, rect); } else { if (log.isDebugEnabled()) { log.debug("Image " + info + " is embedded as a form later"); } //Don't load image at this time, just put a form placeholder in the stream PSResource form = documentHandler.getFormForImage(info.getOriginalURI()); PSImageUtils.drawForm(form, info, rect, getGenerator()); } }
// in src/java/org/apache/fop/image/loader/batik/ImageConverterSVG2G2D.java
public Image convert(final Image src, Map hints) throws ImageException { checkSourceFlavor(src); final ImageXMLDOM svg = (ImageXMLDOM)src; if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(svg.getRootNamespace())) { throw new IllegalArgumentException("XML DOM is not in the SVG namespace: " + svg.getRootNamespace()); } //Prepare float pxToMillimeter = UnitConv.IN2MM / GraphicsConstants.DEFAULT_DPI; Number ptm = (Number)hints.get(ImageProcessingHints.SOURCE_RESOLUTION); if (ptm != null) { pxToMillimeter = (float)(UnitConv.IN2MM / ptm.doubleValue()); } UserAgent ua = createBatikUserAgent(pxToMillimeter); GVTBuilder builder = new GVTBuilder(); final ImageManager imageManager = (ImageManager)hints.get( ImageProcessingHints.IMAGE_MANAGER); final ImageSessionContext sessionContext = (ImageSessionContext)hints.get( ImageProcessingHints.IMAGE_SESSION_CONTEXT); boolean useEnhancedBridgeContext = (imageManager != null && sessionContext != null); final BridgeContext ctx = (useEnhancedBridgeContext ? new GenericFOPBridgeContext(ua, null, imageManager, sessionContext) : new BridgeContext(ua)); Document doc = svg.getDocument(); //Cloning SVG DOM as Batik attaches non-thread-safe facilities (like the CSS engine) //to it. Document clonedDoc = BatikUtil.cloneSVGDocument(doc); //Build the GVT tree final GraphicsNode root; try { root = builder.build(ctx, clonedDoc); } catch (Exception e) { throw new ImageException("GVT tree could not be built for SVG graphic", e); } //Create the painter int width = svg.getSize().getWidthMpt(); int height = svg.getSize().getHeightMpt(); Dimension imageSize = new Dimension(width, height); Graphics2DImagePainter painter = createPainter(ctx, root, imageSize); //Create g2d image ImageInfo imageInfo = src.getInfo(); ImageGraphics2D g2dImage = new ImageGraphics2D(imageInfo, painter); return g2dImage; }
// in src/java/org/apache/fop/image/loader/batik/ImageLoaderSVG.java
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!MimeConstants.MIME_SVG.equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from an SVG image"); } Image img = info.getOriginalImage(); if (!(img instanceof ImageXMLDOM)) { throw new IllegalArgumentException( "ImageInfo was expected to contain the SVG document as DOM"); } ImageXMLDOM svgImage = (ImageXMLDOM)img; if (!SVGDOMImplementation.SVG_NAMESPACE_URI.equals(svgImage.getRootNamespace())) { throw new IllegalArgumentException( "The Image is not in the SVG namespace: " + svgImage.getRootNamespace()); } return svgImage; }
// in src/java/org/apache/fop/image/loader/batik/ImageLoaderWMF.java
public Image loadImage(ImageInfo info, Map hints, ImageSessionContext session) throws ImageException, IOException { if (!ImageWMF.MIME_WMF.equals(info.getMimeType())) { throw new IllegalArgumentException("ImageInfo must be from a WMF image"); } Image img = info.getOriginalImage(); if (!(img instanceof ImageWMF)) { throw new IllegalArgumentException( "ImageInfo was expected to contain the Windows Metafile (WMF)"); } ImageWMF wmfImage = (ImageWMF)img; return wmfImage; }
// in src/java/org/apache/fop/image/loader/batik/ImageConverterG2D2SVG.java
public Image convert(Image src, Map hints) throws ImageException { checkSourceFlavor(src); ImageGraphics2D g2dImage = (ImageGraphics2D)src; DOMImplementation domImpl = GenericDOMImplementation.getDOMImplementation(); // Create an instance of org.w3c.dom.Document Document document = domImpl.createDocument( SVGDOMImplementation.SVG_NAMESPACE_URI, "svg", null); Element root = document.getDocumentElement(); // Create an SVGGeneratorContext to customize SVG generation SVGGeneratorContext genCtx = SVGGeneratorContext.createDefault(document); genCtx.setComment("Generated by Apache Batik's SVGGraphics2D"); genCtx.setEmbeddedFontsOn(true); // Create an instance of the SVG Generator SVGGraphics2D g2d = new SVGGraphics2D(genCtx, true); ImageSize size = src.getSize(); Dimension dim = size.getDimensionMpt(); g2d.setSVGCanvasSize(dim); //SVGGraphics2D doesn't generate the viewBox by itself root.setAttribute("viewBox", "0 0 " + dim.width + " " + dim.height); g2dImage.getGraphics2DImagePainter().paint(g2d, new Rectangle2D.Float(0, 0, dim.width, dim.height)); //Populate the document root with the generated SVG content. g2d.getRoot(root); //Return the generated SVG image ImageXMLDOM svgImage = new ImageXMLDOM(src.getInfo(), document, BatikImageFlavors.SVG_DOM); g2d.dispose(); return svgImage; }
15
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageError(fobj, uri, e, fobj.getLocator()); }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, url, e, getLocator()); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, uri, ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : INSTREAM_OBJECT_URI), ie, null); }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
catch (ImageException e) { throw new IOException( "Image conversion error while converting the image to a bitmap" + " as a fallback measure: " + e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (ImageException ie) { throw new IFException( "Error while painting marks using a bitmap", ie); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, null, ie, null); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.imageError(resTracker, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.imageError(this, (info != null ? info.toString() : uri), ie, null); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( this.userAgent.getEventBroadcaster()); eventProducer.imageError(this, uri, e, getLocator()); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (ImageException ie) { getResourceEventProducer().imageError(this, uri, ie, getExternalDocument().getLocator()); }
2
            
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
catch (ImageException e) { throw new IOException( "Image conversion error while converting the image to a bitmap" + " as a fallback measure: " + e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (ImageException ie) { throw new IFException( "Error while painting marks using a bitmap", ie); }
0
runtime (Domain) IncompatibleSubtableException
public class IncompatibleSubtableException extends RuntimeException {
    /**
     * Instantiate incompatible subtable exception
     */
    public IncompatibleSubtableException() {
        super();
    }
    /**
     * Instantiate incompatible subtable exception
     * @param message a message string
     */
    public IncompatibleSubtableException(String message) {
        super(message);
    }
}
0 0 0 0 0 0
unknown (Lib) IndexOutOfBoundsException 20
            
// in src/java/org/apache/fop/fo/FOText.java
public int bidiLevelAt ( int position ) throws IndexOutOfBoundsException { if ( ( position < 0 ) || ( position >= length() ) ) { throw new IndexOutOfBoundsException(); } else if ( bidiLevels != null ) { return bidiLevels [ position ]; } else { return -1; } }
// in src/java/org/apache/fop/fonts/SingleByteFont.java
public SimpleSingleByteEncoding getAdditionalEncoding(int index) throws IndexOutOfBoundsException { if (hasAdditionalEncodings()) { return this.additionalEncodings.get(index); } else { throw new IndexOutOfBoundsException("No additional encodings available"); } }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException { try { if (pageIndex >= getNumberOfPages()) { return null; } PageFormat pageFormat = new PageFormat(); Paper paper = new Paper(); Rectangle2D dim = getPageViewport(pageIndex).getViewArea(); double width = dim.getWidth(); double height = dim.getHeight(); // if the width is greater than the height assume landscape mode // and swap the width and height values in the paper format if (width > height) { paper.setImageableArea(0, 0, height / 1000d, width / 1000d); paper.setSize(height / 1000d, width / 1000d); pageFormat.setOrientation(PageFormat.LANDSCAPE); } else { paper.setImageableArea(0, 0, width / 1000d, height / 1000d); paper.setSize(width / 1000d, height / 1000d); pageFormat.setOrientation(PageFormat.PORTRAIT); } pageFormat.setPaper(paper); return pageFormat; } catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); } }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException { try { if (pageIndex >= getNumberOfPages()) { return null; } PageFormat pageFormat = new PageFormat(); Paper paper = new Paper(); Rectangle2D dim = getPageViewport(pageIndex).getViewArea(); double width = dim.getWidth(); double height = dim.getHeight(); // if the width is greater than the height assume lanscape mode // and swap the width and height values in the paper format if (width > height) { paper.setImageableArea(0, 0, height / 1000d, width / 1000d); paper.setSize(height / 1000d, width / 1000d); pageFormat.setOrientation(PageFormat.LANDSCAPE); } else { paper.setImageableArea(0, 0, width / 1000d, height / 1000d); paper.setSize(width / 1000d, height / 1000d); pageFormat.setOrientation(PageFormat.PORTRAIT); } pageFormat.setPaper(paper); return pageFormat; } catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); } }
// in src/java/org/apache/fop/area/inline/WordArea.java
public int bidiLevelAt ( int position ) { if ( position > word.length() ) { throw new IndexOutOfBoundsException(); } else if ( levels != null ) { return levels [ position ]; } else { return -1; } }
// in src/java/org/apache/fop/area/inline/WordArea.java
public int[] glyphPositionAdjustmentsAt ( int position ) { if ( position > word.length() ) { throw new IndexOutOfBoundsException(); } else if ( gposAdjustments != null ) { return gposAdjustments [ position ]; } else { return null; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningState.java
public boolean adjust ( GlyphPositioningTable.Value v, int offset ) { assert v != null; if ( ( index + offset ) < indexLast ) { return v.adjust ( adjustments [ index + offset ], fontSize ); } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningState.java
public int[] getAdjustment ( int offset ) throws IndexOutOfBoundsException { if ( ( index + offset ) < indexLast ) { return adjustments [ index + offset ]; } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public void setPosition ( int index ) throws IndexOutOfBoundsException { if ( ( index >= 0 ) && ( index <= indexLast ) ) { this.index = index; } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int consume ( int count ) throws IndexOutOfBoundsException { if ( ( consumed + count ) <= indexLast ) { consumed += count; return consumed; } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int getGlyph ( int offset ) throws IndexOutOfBoundsException { int i = index + offset; if ( ( i >= 0 ) && ( i < indexLast ) ) { return igs.getGlyph ( i ); } else { throw new IndexOutOfBoundsException ( "attempting index at " + i ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public void setGlyph ( int offset, int glyph ) throws IndexOutOfBoundsException { int i = index + offset; if ( ( i >= 0 ) && ( i < indexLast ) ) { igs.setGlyph ( i, glyph ); } else { throw new IndexOutOfBoundsException ( "attempting index at " + i ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation getAssociation ( int offset ) throws IndexOutOfBoundsException { int i = index + offset; if ( ( i >= 0 ) && ( i < indexLast ) ) { return igs.getAssociation ( i ); } else { throw new IndexOutOfBoundsException ( "attempting index at " + i ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphs ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { if ( count < 0 ) { count = getGlyphsAvailable ( offset, reverseOrder, ignoreTester ) [ 0 ]; } int start = index + offset; if ( start < 0 ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else if ( ! reverseOrder && ( ( start + count ) > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start + count ) ); } else if ( reverseOrder && ( ( start + 1 ) < count ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start - count ) ); } if ( glyphs == null ) { glyphs = new int [ count ]; } else if ( glyphs.length != count ) { throw new IllegalArgumentException ( "glyphs array is non-null, but its length (" + glyphs.length + "), is not equal to count (" + count + ")" ); } if ( ! reverseOrder ) { return getGlyphsForward ( start, count, ignoreTester, glyphs, counts ); } else { return getGlyphsReverse ( start, count, ignoreTester, glyphs, counts ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation[] getAssociations ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, GlyphSequence.CharAssociation[] associations, int[] counts ) throws IndexOutOfBoundsException { if ( count < 0 ) { count = getGlyphsAvailable ( offset, reverseOrder, ignoreTester ) [ 0 ]; } int start = index + offset; if ( start < 0 ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else if ( ! reverseOrder && ( ( start + count ) > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start + count ) ); } else if ( reverseOrder && ( ( start + 1 ) < count ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start - count ) ); } if ( associations == null ) { associations = new GlyphSequence.CharAssociation [ count ]; } else if ( associations.length != count ) { throw new IllegalArgumentException ( "associations array is non-null, but its length (" + associations.length + "), is not equal to count (" + count + ")" ); } if ( ! reverseOrder ) { return getAssociationsForward ( start, count, ignoreTester, associations, counts ); } else { return getAssociationsReverse ( start, count, ignoreTester, associations, counts ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int erase ( int offset, int[] glyphs ) throws IndexOutOfBoundsException { int start = index + offset; if ( ( start < 0 ) || ( start > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else { int erased = 0; for ( int i = start - index, n = indexLast - start; i < n; i++ ) { int gi = getGlyph ( i ); if ( gi == glyphs [ erased ] ) { setGlyph ( i, 65535 ); erased++; } } return erased; } }
2
            
// in src/java/org/apache/fop/render/print/PageableRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); }
38
            
// in src/java/org/apache/fop/fo/FOText.java
public int bidiLevelAt ( int position ) throws IndexOutOfBoundsException { if ( ( position < 0 ) || ( position >= length() ) ) { throw new IndexOutOfBoundsException(); } else if ( bidiLevels != null ) { return bidiLevels [ position ]; } else { return -1; } }
// in src/java/org/apache/fop/fonts/SingleByteFont.java
public SimpleSingleByteEncoding getAdditionalEncoding(int index) throws IndexOutOfBoundsException { if (hasAdditionalEncodings()) { return this.additionalEncodings.get(index); } else { throw new IndexOutOfBoundsException("No additional encodings available"); } }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException { try { if (pageIndex >= getNumberOfPages()) { return null; } PageFormat pageFormat = new PageFormat(); Paper paper = new Paper(); Rectangle2D dim = getPageViewport(pageIndex).getViewArea(); double width = dim.getWidth(); double height = dim.getHeight(); // if the width is greater than the height assume landscape mode // and swap the width and height values in the paper format if (width > height) { paper.setImageableArea(0, 0, height / 1000d, width / 1000d); paper.setSize(height / 1000d, width / 1000d); pageFormat.setOrientation(PageFormat.LANDSCAPE); } else { paper.setImageableArea(0, 0, width / 1000d, height / 1000d); paper.setSize(width / 1000d, height / 1000d); pageFormat.setOrientation(PageFormat.PORTRAIT); } pageFormat.setPaper(paper); return pageFormat; } catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); } }
// in src/java/org/apache/fop/render/print/PageableRenderer.java
public Printable getPrintable(int pageIndex) throws IndexOutOfBoundsException { return this; }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public PageFormat getPageFormat(int pageIndex) throws IndexOutOfBoundsException { try { if (pageIndex >= getNumberOfPages()) { return null; } PageFormat pageFormat = new PageFormat(); Paper paper = new Paper(); Rectangle2D dim = getPageViewport(pageIndex).getViewArea(); double width = dim.getWidth(); double height = dim.getHeight(); // if the width is greater than the height assume lanscape mode // and swap the width and height values in the paper format if (width > height) { paper.setImageableArea(0, 0, height / 1000d, width / 1000d); paper.setSize(height / 1000d, width / 1000d); pageFormat.setOrientation(PageFormat.LANDSCAPE); } else { paper.setImageableArea(0, 0, width / 1000d, height / 1000d); paper.setSize(width / 1000d, height / 1000d); pageFormat.setOrientation(PageFormat.PORTRAIT); } pageFormat.setPaper(paper); return pageFormat; } catch (FOPException fopEx) { throw new IndexOutOfBoundsException(fopEx.getMessage()); } }
// in src/java/org/apache/fop/render/awt/AWTRenderer.java
public Printable getPrintable(int pageIndex) throws IndexOutOfBoundsException { return this; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningState.java
public int[] getAdjustment ( int offset ) throws IndexOutOfBoundsException { if ( ( index + offset ) < indexLast ) { return adjustments [ index + offset ]; } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public void setPosition ( int index ) throws IndexOutOfBoundsException { if ( ( index >= 0 ) && ( index <= indexLast ) ) { this.index = index; } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int consume ( int count ) throws IndexOutOfBoundsException { if ( ( consumed + count ) <= indexLast ) { consumed += count; return consumed; } else { throw new IndexOutOfBoundsException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int getGlyph ( int offset ) throws IndexOutOfBoundsException { int i = index + offset; if ( ( i >= 0 ) && ( i < indexLast ) ) { return igs.getGlyph ( i ); } else { throw new IndexOutOfBoundsException ( "attempting index at " + i ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int getGlyph() throws IndexOutOfBoundsException { return getGlyph ( 0 ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public void setGlyph ( int offset, int glyph ) throws IndexOutOfBoundsException { int i = index + offset; if ( ( i >= 0 ) && ( i < indexLast ) ) { igs.setGlyph ( i, glyph ); } else { throw new IndexOutOfBoundsException ( "attempting index at " + i ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation getAssociation ( int offset ) throws IndexOutOfBoundsException { int i = index + offset; if ( ( i >= 0 ) && ( i < indexLast ) ) { return igs.getAssociation ( i ); } else { throw new IndexOutOfBoundsException ( "attempting index at " + i ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation getAssociation() throws IndexOutOfBoundsException { return getAssociation ( 0 ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphs ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { if ( count < 0 ) { count = getGlyphsAvailable ( offset, reverseOrder, ignoreTester ) [ 0 ]; } int start = index + offset; if ( start < 0 ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else if ( ! reverseOrder && ( ( start + count ) > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start + count ) ); } else if ( reverseOrder && ( ( start + 1 ) < count ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start - count ) ); } if ( glyphs == null ) { glyphs = new int [ count ]; } else if ( glyphs.length != count ) { throw new IllegalArgumentException ( "glyphs array is non-null, but its length (" + glyphs.length + "), is not equal to count (" + count + ")" ); } if ( ! reverseOrder ) { return getGlyphsForward ( start, count, ignoreTester, glyphs, counts ); } else { return getGlyphsReverse ( start, count, ignoreTester, glyphs, counts ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
private int[] getGlyphsForward ( int start, int count, GlyphTester ignoreTester, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { int counted = 0; int ignored = 0; for ( int i = start, n = indexLast, k = 0; i < n; i++ ) { int gi = getGlyph ( i - index ); if ( gi == 65535 ) { ignored++; } else { if ( ( ignoreTester == null ) || ! ignoreTester.test ( gi, getLookupFlags() ) ) { if ( k < count ) { glyphs [ k++ ] = gi; counted++; } else { break; } } else { ignored++; } } } if ( ( counts != null ) && ( counts.length > 1 ) ) { counts[0] = counted; counts[1] = ignored; } return glyphs; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
private int[] getGlyphsReverse ( int start, int count, GlyphTester ignoreTester, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { int counted = 0; int ignored = 0; for ( int i = start, k = 0; i >= 0; i-- ) { int gi = getGlyph ( i - index ); if ( gi == 65535 ) { ignored++; } else { if ( ( ignoreTester == null ) || ! ignoreTester.test ( gi, getLookupFlags() ) ) { if ( k < count ) { glyphs [ k++ ] = gi; counted++; } else { break; } } else { ignored++; } } } if ( ( counts != null ) && ( counts.length > 1 ) ) { counts[0] = counted; counts[1] = ignored; } return glyphs; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphs ( int offset, int count, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { return getGlyphs ( offset, count, offset < 0, ignoreDefault, glyphs, counts ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphs() throws IndexOutOfBoundsException { return getGlyphs ( 0, indexLast - index, false, null, null, null ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getIgnoredGlyphs ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, int[] glyphs, int[] counts ) throws IndexOutOfBoundsException { return getGlyphs ( offset, count, reverseOrder, new NotGlyphTester ( ignoreTester ), glyphs, counts ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getIgnoredGlyphs ( int offset, int count ) throws IndexOutOfBoundsException { return getIgnoredGlyphs ( offset, count, offset < 0, ignoreDefault, null, null ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphsAvailable ( int offset, boolean reverseOrder, GlyphTester ignoreTester ) throws IndexOutOfBoundsException { int start = index + offset; if ( ( start < 0 ) || ( start > indexLast ) ) { return new int[] { 0, 0 }; } else if ( ! reverseOrder ) { return getGlyphsAvailableForward ( start, ignoreTester ); } else { return getGlyphsAvailableReverse ( start, ignoreTester ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
private int[] getGlyphsAvailableForward ( int start, GlyphTester ignoreTester ) throws IndexOutOfBoundsException { int counted = 0; int ignored = 0; if ( ignoreTester == null ) { counted = indexLast - start; } else { for ( int i = start, n = indexLast; i < n; i++ ) { int gi = getGlyph ( i - index ); if ( gi == 65535 ) { ignored++; } else { if ( ignoreTester.test ( gi, getLookupFlags() ) ) { ignored++; } else { counted++; } } } } return new int[] { counted, ignored }; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
private int[] getGlyphsAvailableReverse ( int start, GlyphTester ignoreTester ) throws IndexOutOfBoundsException { int counted = 0; int ignored = 0; if ( ignoreTester == null ) { counted = start + 1; } else { for ( int i = start; i >= 0; i-- ) { int gi = getGlyph ( i - index ); if ( gi == 65535 ) { ignored++; } else { if ( ignoreTester.test ( gi, getLookupFlags() ) ) { ignored++; } else { counted++; } } } } return new int[] { counted, ignored }; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphsAvailable ( int offset, boolean reverseOrder ) throws IndexOutOfBoundsException { return getGlyphsAvailable ( offset, reverseOrder, ignoreDefault ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int[] getGlyphsAvailable ( int offset ) throws IndexOutOfBoundsException { return getGlyphsAvailable ( offset, offset < 0 ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation[] getAssociations ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, GlyphSequence.CharAssociation[] associations, int[] counts ) throws IndexOutOfBoundsException { if ( count < 0 ) { count = getGlyphsAvailable ( offset, reverseOrder, ignoreTester ) [ 0 ]; } int start = index + offset; if ( start < 0 ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else if ( ! reverseOrder && ( ( start + count ) > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start + count ) ); } else if ( reverseOrder && ( ( start + 1 ) < count ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + ( start - count ) ); } if ( associations == null ) { associations = new GlyphSequence.CharAssociation [ count ]; } else if ( associations.length != count ) { throw new IllegalArgumentException ( "associations array is non-null, but its length (" + associations.length + "), is not equal to count (" + count + ")" ); } if ( ! reverseOrder ) { return getAssociationsForward ( start, count, ignoreTester, associations, counts ); } else { return getAssociationsReverse ( start, count, ignoreTester, associations, counts ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
private GlyphSequence.CharAssociation[] getAssociationsForward ( int start, int count, GlyphTester ignoreTester, GlyphSequence.CharAssociation[] associations, int[] counts ) throws IndexOutOfBoundsException { int counted = 0; int ignored = 0; for ( int i = start, n = indexLast, k = 0; i < n; i++ ) { int gi = getGlyph ( i - index ); if ( gi == 65535 ) { ignored++; } else { if ( ( ignoreTester == null ) || ! ignoreTester.test ( gi, getLookupFlags() ) ) { if ( k < count ) { associations [ k++ ] = getAssociation ( i - index ); counted++; } else { break; } } else { ignored++; } } } if ( ( counts != null ) && ( counts.length > 1 ) ) { counts[0] = counted; counts[1] = ignored; } return associations; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
private GlyphSequence.CharAssociation[] getAssociationsReverse ( int start, int count, GlyphTester ignoreTester, GlyphSequence.CharAssociation[] associations, int[] counts ) throws IndexOutOfBoundsException { int counted = 0; int ignored = 0; for ( int i = start, k = 0; i >= 0; i-- ) { int gi = getGlyph ( i - index ); if ( gi == 65535 ) { ignored++; } else { if ( ( ignoreTester == null ) || ! ignoreTester.test ( gi, getLookupFlags() ) ) { if ( k < count ) { associations [ k++ ] = getAssociation ( i - index ); counted++; } else { break; } } else { ignored++; } } } if ( ( counts != null ) && ( counts.length > 1 ) ) { counts[0] = counted; counts[1] = ignored; } return associations; }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation[] getAssociations ( int offset, int count ) throws IndexOutOfBoundsException { return getAssociations ( offset, count, offset < 0, ignoreDefault, null, null ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation[] getIgnoredAssociations ( int offset, int count, boolean reverseOrder, GlyphTester ignoreTester, GlyphSequence.CharAssociation[] associations, int[] counts ) throws IndexOutOfBoundsException { return getAssociations ( offset, count, reverseOrder, new NotGlyphTester ( ignoreTester ), associations, counts ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public GlyphSequence.CharAssociation[] getIgnoredAssociations ( int offset, int count ) throws IndexOutOfBoundsException { return getIgnoredAssociations ( offset, count, offset < 0, ignoreDefault, null, null ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public boolean replaceInput ( int offset, int count, GlyphSequence gs, int gsOffset, int gsCount ) throws IndexOutOfBoundsException { int nig = ( igs != null ) ? igs.getGlyphCount() : 0; int position = getPosition() + offset; if ( position < 0 ) { position = 0; } else if ( position > nig ) { position = nig; } if ( ( count < 0 ) || ( ( position + count ) > nig ) ) { count = nig - position; } int nrg = ( gs != null ) ? gs.getGlyphCount() : 0; if ( gsOffset < 0 ) { gsOffset = 0; } else if ( gsOffset > nrg ) { gsOffset = nrg; } if ( ( gsCount < 0 ) || ( ( gsOffset + gsCount ) > nrg ) ) { gsCount = nrg - gsOffset; } int ng = nig + gsCount - count; IntBuffer gb = IntBuffer.allocate ( ng ); List al = new ArrayList ( ng ); for ( int i = 0, n = position; i < n; i++ ) { gb.put ( igs.getGlyph ( i ) ); al.add ( igs.getAssociation ( i ) ); } for ( int i = gsOffset, n = gsOffset + gsCount; i < n; i++ ) { gb.put ( gs.getGlyph ( i ) ); al.add ( gs.getAssociation ( i ) ); } for ( int i = position + count, n = nig; i < n; i++ ) { gb.put ( igs.getGlyph ( i ) ); al.add ( igs.getAssociation ( i ) ); } gb.flip(); if ( igs.compareGlyphs ( gb ) != 0 ) { this.igs = new GlyphSequence ( igs.getCharacters(), gb, al ); this.indexLast = gb.limit(); return true; } else { return false; } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public boolean replaceInput ( int offset, int count, GlyphSequence gs ) throws IndexOutOfBoundsException { return replaceInput ( offset, count, gs, 0, gs.getGlyphCount() ); }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphProcessingState.java
public int erase ( int offset, int[] glyphs ) throws IndexOutOfBoundsException { int start = index + offset; if ( ( start < 0 ) || ( start > indexLast ) ) { throw new IndexOutOfBoundsException ( "will attempt index at " + start ); } else { int erased = 0; for ( int i = start - index, n = indexLast - start; i < n; i++ ) { int gi = getGlyph ( i ); if ( gi == glyphs [ erased ] ) { setGlyph ( i, 65535 ); erased++; } } return erased; } }
// in src/java/org/apache/fop/complexscripts/util/GlyphSequence.java
public int getGlyph ( int index ) throws IndexOutOfBoundsException { return glyphs.get ( index ); }
// in src/java/org/apache/fop/complexscripts/util/GlyphSequence.java
public void setGlyph ( int index, int gi ) throws IndexOutOfBoundsException { if ( gi > 65535 ) { gi = 65535; } glyphs.put ( index, gi ); }
// in src/java/org/apache/fop/complexscripts/util/GlyphSequence.java
public CharAssociation getAssociation ( int index ) throws IndexOutOfBoundsException { return (CharAssociation) associations.get ( index ); }
0 0 0
unknown (Lib) InstantiationException 0 0 0 10
            
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + mappingClassName); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/complexscripts/scripts/IndicScriptProcessor.java
catch ( InstantiationException e ) { s = null; }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
catch (InstantiationException e) { // Problem instantiating the class, simply continue with the backup implementation }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (InstantiationException e) { log.error("Error creating the catalog resolver: " + e.getMessage()); eventProducer.catalogResolverNotCreated(this, e.getMessage()); }
7
            
// in src/java/org/apache/fop/fo/ElementMappingRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + mappingClassName); }
// in src/java/org/apache/fop/render/XMLHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/RendererFactory.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + className); }
// in src/java/org/apache/fop/render/ImageHandlerRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
// in src/java/org/apache/fop/util/ContentHandlerFactoryRegistry.java
catch (InstantiationException e) { throw new IllegalArgumentException("Could not instantiate " + classname); }
7
unknown (Lib) InvalidKeyException 0 0 0 1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (InvalidKeyException e) { throw new IllegalStateException(e); }
1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (InvalidKeyException e) { throw new IllegalStateException(e); }
1
unknown (Lib) InvocationTargetException 0 0 0 5
            
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (InvocationTargetException e) { LOG.error(e); return null; }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (InvocationTargetException are) { failed = true; }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/complexscripts/scripts/IndicScriptProcessor.java
catch ( InvocationTargetException e ) { s = null; }
2
            
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
2
runtime (Domain) LayoutException
public class LayoutException extends RuntimeException {

    private static final long serialVersionUID = 5157080040923740433L;

    private String localizedMessage;
    private LayoutManager layoutManager;

    /**
     * Constructs a new layout exception with the specified detail message.
     * @param message the detail message.
     */
    public LayoutException(String message) {
        this(message, null);
    }

    /**
     * Constructs a new layout exception with the specified detail message.
     * @param message the detail message
     * @param lm the layout manager that throws the exception
     */
    public LayoutException(String message, LayoutManager lm) {
        super(message);
        this.layoutManager = lm;
    }

    /**
     * Sets the localized message for this exception.
     * @param msg the localized message
     */
    public void setLocalizedMessage(String msg) {
        this.localizedMessage = msg;
    }

    /** {@inheritDoc} */
    public String getLocalizedMessage() {
        if (this.localizedMessage != null) {
            return this.localizedMessage;
        } else {
            return super.getLocalizedMessage();
        }
    }

    /**
     * Returns the layout manager that detected the problem.
     * @return the layout manager (or null)
     */
    public LayoutManager getLayoutManager() {
        return this.layoutManager;
    }

    /** Exception factory for {@link LayoutException}. */
    public static class LayoutExceptionFactory implements ExceptionFactory {

        /** {@inheritDoc} */
        public Throwable createException(Event event) {
            Object source = event.getSource();
            LayoutManager lm = (source instanceof LayoutManager) ? (LayoutManager)source : null;
            String msg = EventFormatter.format(event, Locale.ENGLISH);
            LayoutException ex = new LayoutException(msg, lm);
            if (!Locale.ENGLISH.equals(Locale.getDefault())) {
                ex.setLocalizedMessage(EventFormatter.format(event));
            }
            return ex;
        }

        /** {@inheritDoc} */
        public Class<LayoutException> getExceptionClass() {
            return LayoutException.class;
        }

    }
}
0 0 0 0 0 0
unknown (Lib) LinkageError 0 0 0 1
            
// in src/java/org/apache/fop/util/bitmap/BitmapImageUtil.java
catch (LinkageError le) { // This can happen if fop was build with support for a // particular provider (e.g. a binary fop distribution) // but the required support files (i.e. JAI) are not // available in the current runtime environment. // Simply continue with the backup implementation. }
0 0
unknown (Lib) MalformedURLException 2
            
// in src/java/org/apache/fop/apps/FOURIResolver.java
public String checkBaseURL(String base) throws MalformedURLException { // replace back slash with forward slash to ensure windows file:/// URLS are supported base = base.replace('\\', '/'); if (!base.endsWith("/")) { // The behavior described by RFC 3986 regarding resolution of relative // references may be misleading for normal users: // file://path/to/resources + myResource.res -> file://path/to/myResource.res // file://path/to/resources/ + myResource.res -> file://path/to/resources/myResource.res // We assume that even when the ending slash is missing, users have the second // example in mind base += "/"; } File dir = new File(base); if (dir.isDirectory()) { return dir.toURI().toASCIIString(); } else { URI baseURI; try { baseURI = new URI(base); String scheme = baseURI.getScheme(); boolean directoryExists = true; if ("file".equals(scheme)) { dir = FileUtils.toFile(baseURI.toURL()); directoryExists = dir.isDirectory(); } if (scheme == null || !directoryExists) { String message = "base " + base + " is not a valid directory"; if (throwExceptions) { throw new MalformedURLException(message); } log.error(message); } return baseURI.toASCIIString(); } catch (URISyntaxException e) { //TODO not ideal: our base URLs are actually base URIs. throw new MalformedURLException(e.getMessage()); } } }
1
            
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (URISyntaxException e) { //TODO not ideal: our base URLs are actually base URIs. throw new MalformedURLException(e.getMessage()); }
9
            
// in src/java/org/apache/fop/apps/FOURIResolver.java
public String checkBaseURL(String base) throws MalformedURLException { // replace back slash with forward slash to ensure windows file:/// URLS are supported base = base.replace('\\', '/'); if (!base.endsWith("/")) { // The behavior described by RFC 3986 regarding resolution of relative // references may be misleading for normal users: // file://path/to/resources + myResource.res -> file://path/to/myResource.res // file://path/to/resources/ + myResource.res -> file://path/to/resources/myResource.res // We assume that even when the ending slash is missing, users have the second // example in mind base += "/"; } File dir = new File(base); if (dir.isDirectory()) { return dir.toURI().toASCIIString(); } else { URI baseURI; try { baseURI = new URI(base); String scheme = baseURI.getScheme(); boolean directoryExists = true; if ("file".equals(scheme)) { dir = FileUtils.toFile(baseURI.toURL()); directoryExists = dir.isDirectory(); } if (scheme == null || !directoryExists) { String message = "base " + base + " is not a valid directory"; if (throwExceptions) { throw new MalformedURLException(message); } log.error(message); } return baseURI.toASCIIString(); } catch (URISyntaxException e) { //TODO not ideal: our base URLs are actually base URIs. throw new MalformedURLException(e.getMessage()); } } }
// in src/java/org/apache/fop/apps/FopFactory.java
Override public void setFontBaseURL(String fontBase) throws MalformedURLException { super.setFontBaseURL(getFOURIResolver().checkBaseURL(fontBase)); }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setBaseURL(String base) throws MalformedURLException { this.base = foURIResolver.checkBaseURL(base); }
// in src/java/org/apache/fop/apps/FopFactory.java
Deprecated public void setFontBaseURL(String fontBase) throws MalformedURLException { getFontManager().setFontBaseURL(fontBase); }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setHyphenBaseURL(final String hyphenBase) throws MalformedURLException { if (hyphenBase != null) { setHyphenationTreeResolver( new HyphenationTreeResolver() { public Source resolve(String href) { return resolveURI(href, hyphenBase); } }); }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
private URL[] createUrls(String mainJar) throws MalformedURLException { ArrayList urls = new ArrayList(); urls.add(new File(mainJar).toURI().toURL()); File[] libFiles = new File("lib").listFiles(); for (int i = 0; i < libFiles.length; i++) { if (libFiles[i].getPath().endsWith(".jar")) { urls.add(libFiles[i].toURI().toURL()); } } return (URL[]) urls.toArray(new URL[urls.size()]); }
// in src/java/org/apache/fop/fonts/FontManager.java
public void setFontBaseURL(String fontBase) throws MalformedURLException { this.fontBase = fontBase; }
// in src/java/org/apache/fop/fonts/FontLoader.java
public static InputStream openFontUri(FontResolver resolver, String uri) throws IOException, MalformedURLException { InputStream in = null; if (resolver != null) { Source source = resolver.resolve(uri); if (source == null) { String err = "Cannot load font: failed to create Source for font file " + uri; throw new IOException(err); } if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null && source.getSystemId() != null) { in = new java.net.URL(source.getSystemId()).openStream(); } if (in == null) { String err = "Cannot load font: failed to create InputStream from" + " Source for font file " + uri; throw new IOException(err); } } else { in = new URL(uri).openStream(); } return in; }
// in src/java/org/apache/fop/cli/Main.java
public static URL[] getJARList() throws MalformedURLException { String fopHome = System.getProperty("fop.home"); File baseDir; if (fopHome != null) { baseDir = new File(fopHome).getAbsoluteFile(); } else { baseDir = new File(".").getAbsoluteFile().getParentFile(); } File buildDir; if ("build".equals(baseDir.getName())) { buildDir = baseDir; baseDir = baseDir.getParentFile(); } else { buildDir = new File(baseDir, "build"); } File fopJar = new File(buildDir, "fop.jar"); if (!fopJar.exists()) { fopJar = new File(baseDir, "fop.jar"); } if (!fopJar.exists()) { throw new RuntimeException("fop.jar not found in directory: " + baseDir.getAbsolutePath() + " (or below)"); } List jars = new java.util.ArrayList(); jars.add(fopJar.toURI().toURL()); File[] files; FileFilter filter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".jar"); } }; File libDir = new File(baseDir, "lib"); if (!libDir.exists()) { libDir = baseDir; } files = libDir.listFiles(filter); if (files != null) { for (int i = 0, size = files.length; i < size; i++) { jars.add(files[i].toURI().toURL()); } } String optionalLib = System.getProperty("fop.optional.lib"); if (optionalLib != null) { files = new File(optionalLib).listFiles(filter); if (files != null) { for (int i = 0, size = files.length; i < size; i++) { jars.add(files[i].toURI().toURL()); } } } URL[] urls = (URL[])jars.toArray(new URL[jars.size()]); /* for (int i = 0, c = urls.length; i < c; i++) { System.out.println(urls[i]); }*/ return urls; }
23
            
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mfue) { handleException(mfue, "Could not convert filename '" + href + "' to URL", throwExceptions); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mue) { try { // the above failed, we give it another go in case // the href contains only a path then file: is // assumed absoluteURL = new URL("file:" + href); } catch (MalformedURLException mfue) { handleException(mfue, "Error with URL '" + href + "'", throwExceptions); } }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mfue) { handleException(mfue, "Error with URL '" + href + "'", throwExceptions); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mfue) { handleException(mfue, "Error with base URL '" + base + "'", throwExceptions); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (MalformedURLException mfue) { handleException(mfue, "Error with URL; base '" + base + "' " + "href '" + href + "'", throwExceptions); }
// in src/java/org/apache/fop/apps/FOUserAgent.java
catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, strict); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, strict); }
// in src/java/org/apache/fop/pdf/PDFFactory.java
catch (MalformedURLException e) { //TODO: Why construct a new exception here, when it is not thrown? new FileNotFoundException( "File not found. URL could not be resolved: " + e.getMessage()); }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (MalformedURLException mue) { mue.printStackTrace(); }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (MalformedURLException mue) { mue.printStackTrace(); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (MalformedURLException mfue) { logger.error("Error creating base URL from base directory", mfue); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (MalformedURLException mfue) { logger.error("Error creating base URL from XSL-FO input file", mfue); }
// in src/java/org/apache/fop/servlet/ServletContextURIResolver.java
catch (MalformedURLException mfue) { throw new TransformerException( "Error accessing resource using servlet context: " + path, mfue); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + f + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + file + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/fonts/FontManagerConfigurator.java
catch (MalformedURLException mfue) { LogUtil.handleException(log, mfue, true); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (MalformedURLException mfue) { // do nothing }
// in src/java/org/apache/fop/fonts/autodetect/FontFileFinder.java
catch (MalformedURLException e) { log.debug("MalformedURLException" + e.getMessage()); }
// in src/java/org/apache/fop/fonts/FontInfoConfigurator.java
catch (MalformedURLException e) { LogUtil.handleException(log, e, strict); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); }
// in src/java/org/apache/fop/render/ps/PSFontUtils.java
catch (MalformedURLException e) { new FileNotFoundException( "File not found. URL could not be resolved: " + e.getMessage()); }
5
            
// in src/java/org/apache/fop/apps/FOUserAgent.java
catch (MalformedURLException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/servlet/ServletContextURIResolver.java
catch (MalformedURLException mfue) { throw new TransformerException( "Error accessing resource using servlet context: " + path, mfue); }
// in src/java/org/apache/fop/hyphenation/HyphenationTree.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + f + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (MalformedURLException e) { throw new HyphenationException("Error converting the File '" + file + "' to a URL: " + e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException e) { try { tmpUrl = new File (urlString).toURI().toURL (); } catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); } }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfExternalGraphic.java
catch (MalformedURLException ee) { throw new ExternalGraphicException("The attribute 'src' of " + "<fo:external-graphic> has a invalid value: '" + urlString + "' (" + ee + ")"); }
1
checked (Domain) MaximumSizeExceededException
public class MaximumSizeExceededException extends Exception {

    private static final long serialVersionUID = 7823120005542216446L;

    /**
     * Default constructor
     */
    public MaximumSizeExceededException() {
        super();
    }

}
3
            
// in src/java/org/apache/fop/afp/modca/MapPageSegment.java
public void addPageSegment(String name) throws MaximumSizeExceededException { if (getPageSegments().size() > MAX_SIZE) { throw new MaximumSizeExceededException(); } if (name.length() > 8) { throw new IllegalArgumentException("The name of page segment " + name + " must not be longer than 8 characters"); } if (LOG.isDebugEnabled()) { LOG.debug("addPageSegment():: adding page segment " + name); } getPageSegments().add(name); }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
public void addFont(int fontReference, AFPFont font, int size, int orientation) throws MaximumSizeExceededException { FontDefinition fontDefinition = new FontDefinition(); fontDefinition.fontReferenceKey = BinaryUtils.convert(fontReference)[0]; switch (orientation) { case 90: fontDefinition.orientation = 0x2D; break; case 180: fontDefinition.orientation = 0x5A; break; case 270: fontDefinition.orientation = (byte) 0x87; break; default: fontDefinition.orientation = 0x00; break; } try { if (font instanceof RasterFont) { RasterFont raster = (RasterFont) font; CharacterSet cs = raster.getCharacterSet(size); if (cs == null) { String msg = "Character set not found for font " + font.getFontName() + " with point size " + size; LOG.error(msg); throw new FontRuntimeException(msg); } fontDefinition.characterSet = cs.getNameBytes(); if (fontDefinition.characterSet.length != 8) { throw new IllegalArgumentException("The character set " + new String(fontDefinition.characterSet, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof OutlineFont) { OutlineFont outline = (OutlineFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof DoubleByteFont) { DoubleByteFont outline = (DoubleByteFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); //TODO Relax requirement for 8 characters if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else { String msg = "Font of type " + font.getClass().getName() + " not recognized."; LOG.error(msg); throw new FontRuntimeException(msg); } if (fontList.size() > 253) { // Throw an exception if the size is exceeded throw new MaximumSizeExceededException(); } else { fontList.add(fontDefinition); } } catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); } }
// in src/java/org/apache/fop/afp/modca/MapPageOverlay.java
public void addOverlay(String name) throws MaximumSizeExceededException { if (getOverlays().size() > MAX_SIZE) { throw new MaximumSizeExceededException(); } if (name.length() != 8) { throw new IllegalArgumentException("The name of overlay " + name + " must be 8 characters"); } if (LOG.isDebugEnabled()) { LOG.debug("addOverlay():: adding overlay " + name); } try { byte[] data = name.getBytes(AFPConstants.EBCIDIC_ENCODING); getOverlays().add(data); } catch (UnsupportedEncodingException usee) { LOG.error("addOverlay():: UnsupportedEncodingException translating the name " + name); } }
0 3
            
// in src/java/org/apache/fop/afp/modca/MapPageSegment.java
public void addPageSegment(String name) throws MaximumSizeExceededException { if (getPageSegments().size() > MAX_SIZE) { throw new MaximumSizeExceededException(); } if (name.length() > 8) { throw new IllegalArgumentException("The name of page segment " + name + " must not be longer than 8 characters"); } if (LOG.isDebugEnabled()) { LOG.debug("addPageSegment():: adding page segment " + name); } getPageSegments().add(name); }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
public void addFont(int fontReference, AFPFont font, int size, int orientation) throws MaximumSizeExceededException { FontDefinition fontDefinition = new FontDefinition(); fontDefinition.fontReferenceKey = BinaryUtils.convert(fontReference)[0]; switch (orientation) { case 90: fontDefinition.orientation = 0x2D; break; case 180: fontDefinition.orientation = 0x5A; break; case 270: fontDefinition.orientation = (byte) 0x87; break; default: fontDefinition.orientation = 0x00; break; } try { if (font instanceof RasterFont) { RasterFont raster = (RasterFont) font; CharacterSet cs = raster.getCharacterSet(size); if (cs == null) { String msg = "Character set not found for font " + font.getFontName() + " with point size " + size; LOG.error(msg); throw new FontRuntimeException(msg); } fontDefinition.characterSet = cs.getNameBytes(); if (fontDefinition.characterSet.length != 8) { throw new IllegalArgumentException("The character set " + new String(fontDefinition.characterSet, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof OutlineFont) { OutlineFont outline = (OutlineFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else if (font instanceof DoubleByteFont) { DoubleByteFont outline = (DoubleByteFont) font; CharacterSet cs = outline.getCharacterSet(); fontDefinition.characterSet = cs.getNameBytes(); // There are approximately 72 points to 1 inch or 20 1440ths per point. fontDefinition.scale = 20 * size / 1000; fontDefinition.codePage = cs.getCodePage().getBytes( AFPConstants.EBCIDIC_ENCODING); //TODO Relax requirement for 8 characters if (fontDefinition.codePage.length != 8) { throw new IllegalArgumentException("The code page " + new String(fontDefinition.codePage, AFPConstants.EBCIDIC_ENCODING) + " must have a fixed length of 8 characters."); } } else { String msg = "Font of type " + font.getClass().getName() + " not recognized."; LOG.error(msg); throw new FontRuntimeException(msg); } if (fontList.size() > 253) { // Throw an exception if the size is exceeded throw new MaximumSizeExceededException(); } else { fontList.add(fontDefinition); } } catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); } }
// in src/java/org/apache/fop/afp/modca/MapPageOverlay.java
public void addOverlay(String name) throws MaximumSizeExceededException { if (getOverlays().size() > MAX_SIZE) { throw new MaximumSizeExceededException(); } if (name.length() != 8) { throw new IllegalArgumentException("The name of overlay " + name + " must be 8 characters"); } if (LOG.isDebugEnabled()) { LOG.debug("addOverlay():: adding overlay " + name); } try { byte[] data = name.getBytes(AFPConstants.EBCIDIC_ENCODING); getOverlays().add(data); } catch (UnsupportedEncodingException usee) { LOG.error("addOverlay():: UnsupportedEncodingException translating the name " + name); } }
5
            
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException msee) { mapCodedFont = factory.createMapCodedFont(); mapCodedFonts.add(mapCodedFont); try { mapCodedFont.addFont(fontRef, font, size, orientation); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createFont():: resulted in a MaximumSizeExceededException"); } }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createFont():: resulted in a MaximumSizeExceededException"); }
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException e) { //Should not happen, handled internally throw new IllegalStateException("Internal error: " + e.getMessage()); }
// in src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java
catch (MaximumSizeExceededException msee) { mpo = new MapPageOverlay(); getMapPageOverlays().add(mpo); try { mpo.addOverlay(name); } catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createOverlay():: resulted in a MaximumSizeExceededException"); } }
// in src/java/org/apache/fop/afp/modca/AbstractEnvironmentGroup.java
catch (MaximumSizeExceededException ex) { // Should never happen (but log just in case) LOG.error("createOverlay():: resulted in a MaximumSizeExceededException"); }
1
            
// in src/java/org/apache/fop/afp/modca/ActiveEnvironmentGroup.java
catch (MaximumSizeExceededException e) { //Should not happen, handled internally throw new IllegalStateException("Internal error: " + e.getMessage()); }
1
unknown (Lib) MissingResourceException 4
            
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
private static EventModel loadModel(Class resourceBaseClass) { String resourceName = "event-model.xml"; InputStream in = resourceBaseClass.getResourceAsStream(resourceName); if (in == null) { throw new MissingResourceException( "File " + resourceName + " not found", DefaultEventBroadcaster.class.getName(), ""); } try { return EventModelParser.parse(new StreamSource(in)); } catch (TransformerException e) { throw new MissingResourceException( "Error reading " + resourceName + ": " + e.getMessage(), DefaultEventBroadcaster.class.getName(), ""); } finally { IOUtils.closeQuietly(in); } }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public static ResourceBundle getXMLBundle(String baseName, Locale locale, ClassLoader loader) throws MissingResourceException { if (loader == null) { throw new NullPointerException("loader must not be null"); } if (baseName == null) { throw new NullPointerException("baseName must not be null"); } assert locale != null; ResourceBundle bundle; if (!locale.equals(Locale.getDefault())) { bundle = handleGetXMLBundle(baseName, "_" + locale, false, loader); if (bundle != null) { return bundle; } } bundle = handleGetXMLBundle(baseName, "_" + Locale.getDefault(), true, loader); if (bundle != null) { return bundle; } throw new MissingResourceException( baseName + " (" + locale + ")", baseName + '_' + locale, null); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
private static ResourceBundle handleGetXMLBundle(String base, String locale, boolean loadBase, final ClassLoader loader) { XMLResourceBundle bundle = null; String bundleName = base + locale; Object cacheKey = loader != null ? (Object) loader : (Object) "null"; Hashtable loaderCache; //<String, ResourceBundle> synchronized (cache) { loaderCache = (Hashtable)cache.get(cacheKey); if (loaderCache == null) { loaderCache = new Hashtable(); cache.put(cacheKey, loaderCache); } } ResourceBundle result = (ResourceBundle)loaderCache.get(bundleName); if (result != null) { if (result == MISSINGBASE) { return null; } if (result == MISSING) { if (!loadBase) { return null; } String extension = strip(locale); if (extension == null) { return null; } return handleGetXMLBundle(base, extension, loadBase, loader); } return result; } final String fileName = bundleName.replace('.', '/') + ".xml"; InputStream stream = (InputStream)AccessController .doPrivileged(new PrivilegedAction() { public Object run() { return loader == null ? ClassLoader.getSystemResourceAsStream(fileName) : loader.getResourceAsStream(fileName); } }); if (stream != null) { try { try { bundle = new XMLResourceBundle(stream); } finally { stream.close(); } bundle.setLocale(locale); } catch (IOException e) { throw new MissingResourceException(e.getMessage(), base, null); } } String extension = strip(locale); if (bundle != null) { if (extension != null) { ResourceBundle parent = handleGetXMLBundle(base, extension, true, loader); if (parent != null) { bundle.setParent(parent); } } loaderCache.put(bundleName, bundle); return bundle; } if (extension != null) { ResourceBundle fallback = handleGetXMLBundle(base, extension, loadBase, loader); if (fallback != null) { loaderCache.put(bundleName, fallback); return fallback; } } loaderCache.put(bundleName, loadBase ? MISSINGBASE : MISSING); return null; }
2
            
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
catch (TransformerException e) { throw new MissingResourceException( "Error reading " + resourceName + ": " + e.getMessage(), DefaultEventBroadcaster.class.getName(), ""); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (IOException e) { throw new MissingResourceException(e.getMessage(), base, null); }
2
            
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public static ResourceBundle getXMLBundle(String baseName, ClassLoader loader) throws MissingResourceException { return getXMLBundle(baseName, Locale.getDefault(), loader); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public static ResourceBundle getXMLBundle(String baseName, Locale locale, ClassLoader loader) throws MissingResourceException { if (loader == null) { throw new NullPointerException("loader must not be null"); } if (baseName == null) { throw new NullPointerException("baseName must not be null"); } assert locale != null; ResourceBundle bundle; if (!locale.equals(Locale.getDefault())) { bundle = handleGetXMLBundle(baseName, "_" + locale, false, loader); if (bundle != null) { return bundle; } } bundle = handleGetXMLBundle(baseName, "_" + Locale.getDefault(), true, loader); if (bundle != null) { return bundle; } throw new MissingResourceException( baseName + " (" + locale + ")", baseName + '_' + locale, null); }
1
            
// in src/java/org/apache/fop/events/EventFormatter.java
catch ( MissingResourceException e ) { if ( log.isTraceEnabled() ) { log.trace ( "No XMLResourceBundle for " + baseName + " available." ); } bundle = null; }
0 0
runtime (Domain) NestedRuntimeException
public abstract class NestedRuntimeException extends RuntimeException {

    /** Root cause of this nested exception */
    private Throwable underlyingException;

    /**
     * Construct a <code>NestedRuntimeException</code> with the specified detail message.
     * @param msg The detail message.
     */
    public NestedRuntimeException(String msg) {
        super(msg);
    }

    /**
     * Construct a <code>NestedRuntimeException</code> with the specified
     * detail message and nested exception.
     * @param msg The detail message.
     * @param t The nested exception.
     */
    public NestedRuntimeException(String msg, Throwable t) {
        super(msg);
        underlyingException = t;

    }

    /**
     * Gets the original triggering exception
     * @return The original exception as a throwable.
     */
    public Throwable getUnderlyingException() {

        return underlyingException;

    }

    /**
     * Return the detail message, including the message from the nested
     * exception if there is one.
     * @return The detail message.
     */
    public String getMessage() {

        if (underlyingException == null) {
            return super.getMessage();
        } else {
            return super.getMessage()
            + "; nested exception is "
                + underlyingException.getClass().getName();
        }

    }

    /**
     * Print the composite message and the embedded stack trace to the specified stream.
     * @param ps the print stream
     */
    public void printStackTrace(PrintStream ps) {
        if (underlyingException == null) {
            super.printStackTrace(ps);
        } else {
            ps.println(this);
            underlyingException.printStackTrace(ps);
        }
    }

    /**
     * Print the composite message and the embedded stack trace to the specified writer.
     * @param pw the print writer
     */
    public void printStackTrace(PrintWriter pw) {
        if (underlyingException == null) {
            super.printStackTrace(pw);
        } else {
            pw.println(this);
            underlyingException.printStackTrace(pw);
        }
    }

}
0 0 0 0 0 0
unknown (Lib) NoClassDefFoundError 0 0 0 4
            
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (NoClassDefFoundError e) { batikAvailable = false; log.warn("Batik not in class path", e); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderWMF.java
catch (NoClassDefFoundError ncdfe) { try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } batikAvailable = false; log.warn("Batik not in class path", ncdfe); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (NoClassDefFoundError e) { batikAvailable = false; log.warn("Batik not in class path", e); return null; }
// in src/java/org/apache/fop/image/loader/batik/PreloaderSVG.java
catch (NoClassDefFoundError ncdfe) { if (in != null) { try { in.reset(); } catch (IOException ioe) { // we're more interested in the original exception } } batikAvailable = false; log.warn("Batik not in class path", ncdfe); return null; }
0 0
unknown (Lib) NoSuchAlgorithmException 0 0 2
            
// in src/java/org/apache/fop/pdf/FileIDGenerator.java
static FileIDGenerator getDigestFileIDGenerator(PDFDocument document) throws NoSuchAlgorithmException { return new DigestFileIDGenerator(document); }
3
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (NoSuchAlgorithmException e) { fileIDGenerator = FileIDGenerator.getRandomFileIDGenerator(); }
2
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); }
2
unknown (Lib) NoSuchElementException 13
            
// in src/java/org/apache/fop/fo/RecursiveCharIterator.java
public char nextChar() throws NoSuchElementException { if (curCharIter != null) { return curCharIter.nextChar(); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/NullCharIterator.java
public char nextChar() throws NoSuchElementException { throw new NoSuchElementException(); }
// in src/java/org/apache/fop/fo/OneCharIterator.java
public char nextChar() throws NoSuchElementException { if (bFirst) { bFirst = false; return charCode; } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/flow/Character.java
public char nextChar() { if (bFirst) { bFirst = false; return foChar.character; } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/FOText.java
public char nextChar() { if (this.currentPosition < charBuffer.limit()) { this.canRemove = true; this.canReplace = true; return charBuffer.get(currentPosition++); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/FObj.java
public Object next() { if (currentNode != null) { if (currentIndex != 0) { if (currentNode.siblings != null && currentNode.siblings[1] != null) { currentNode = currentNode.siblings[1]; } else { throw new NoSuchElementException(); } } currentIndex++; flags |= (F_SET_ALLOWED | F_REMOVE_ALLOWED); return currentNode; } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/FObj.java
public Object previous() { if (currentNode.siblings != null && currentNode.siblings[0] != null) { currentIndex--; currentNode = currentNode.siblings[0]; flags |= (F_SET_ALLOWED | F_REMOVE_ALLOWED); return currentNode; } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
public Object next() { if (log.isDebugEnabled()) { log.debug("[" + (current + 1) + "]"); } // Renders current page as image BufferedImage pageImage = null; try { pageImage = getPageImage(current++); } catch (FOPException e) { throw new NoSuchElementException(e.getMessage()); } if (COMPRESSION_CCITT_T4.equalsIgnoreCase(writerParams.getCompressionMethod()) || COMPRESSION_CCITT_T6.equalsIgnoreCase(writerParams.getCompressionMethod())) { return pageImage; } else { //Decorate the image with a packed sample model for encoding by the codec SinglePixelPackedSampleModel sppsm; sppsm = (SinglePixelPackedSampleModel)pageImage.getSampleModel(); int bands = sppsm.getNumBands(); int[] off = new int[bands]; int w = pageImage.getWidth(); int h = pageImage.getHeight(); for (int i = 0; i < bands; i++) { off[i] = i; } SampleModel sm = new PixelInterleavedSampleModel( DataBuffer.TYPE_BYTE, w, h, bands, w * bands, off); RenderedImage rimg = new FormatRed(GraphicsUtil.wrap(pageImage), sm); return rimg; } }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public LayoutManager previous() throws NoSuchElementException { if (curPos > 0) { return listLMs.get(--curPos); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public LayoutManager next() throws NoSuchElementException { if (curPos < listLMs.size()) { return listLMs.get(curPos++); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public void remove() throws NoSuchElementException { if (curPos > 0) { listLMs.remove(--curPos); // Note: doesn't actually remove it from the base! } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/layoutmgr/PositionIterator.java
public Position next() throws NoSuchElementException { if (hasNext) { Position retPos = getPos(nextObj); lookAhead(); return retPos; } else { throw new NoSuchElementException("PosIter"); } }
1
            
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
catch (FOPException e) { throw new NoSuchElementException(e.getMessage()); }
8
            
// in src/java/org/apache/fop/fo/RecursiveCharIterator.java
public char nextChar() throws NoSuchElementException { if (curCharIter != null) { return curCharIter.nextChar(); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/NullCharIterator.java
public char nextChar() throws NoSuchElementException { throw new NoSuchElementException(); }
// in src/java/org/apache/fop/fo/OneCharIterator.java
public char nextChar() throws NoSuchElementException { if (bFirst) { bFirst = false; return charCode; } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/fo/CharIterator.java
public Object next() throws NoSuchElementException { return new Character(nextChar()); }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public LayoutManager previous() throws NoSuchElementException { if (curPos > 0) { return listLMs.get(--curPos); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public LayoutManager next() throws NoSuchElementException { if (curPos < listLMs.size()) { return listLMs.get(curPos++); } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public void remove() throws NoSuchElementException { if (curPos > 0) { listLMs.remove(--curPos); // Note: doesn't actually remove it from the base! } else { throw new NoSuchElementException(); } }
// in src/java/org/apache/fop/layoutmgr/PositionIterator.java
public Position next() throws NoSuchElementException { if (hasNext) { Position retPos = getPos(nextObj); lookAhead(); return retPos; } else { throw new NoSuchElementException("PosIter"); } }
0 0 0
unknown (Lib) NoSuchMethodException 0 0 0 5
            
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
catch (NoSuchMethodException e) { LOG.error(e); return null; }
// in src/java/org/apache/fop/tools/anttasks/RunTest.java
catch (NoSuchMethodException are) { failed = true; }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/complexscripts/scripts/IndicScriptProcessor.java
catch ( NoSuchMethodException e ) { s = null; }
2
            
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
2
unknown (Lib) NoSuchPaddingException 0 0 0 1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchPaddingException e) { throw new UnsupportedOperationException(e); }
1
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchPaddingException e) { throw new UnsupportedOperationException(e); }
1
runtime (Lib) NullPointerException 32
            
// in src/java/org/apache/fop/apps/FopFactory.java
public Fop newFop(String outputFormat, FOUserAgent userAgent, OutputStream stream) throws FOPException { if (userAgent == null) { throw new NullPointerException("The userAgent parameter must not be null!"); } return new Fop(outputFormat, userAgent, stream); }
// in src/java/org/apache/fop/pdf/PDFRoot.java
public void setLanguage(Locale locale) { if (locale == null) { throw new NullPointerException("locale must not be null"); } setLanguage(LanguageTags.toLanguageTag(locale)); }
// in src/java/org/apache/fop/pdf/PDFRoot.java
public void setStructTreeRoot(PDFStructTreeRoot structTreeRoot) { if (structTreeRoot == null) { throw new NullPointerException("structTreeRoot must not be null"); } put("StructTreeRoot", structTreeRoot); }
// in src/java/org/apache/fop/pdf/ObjectStream.java
CompressedObjectReference addObject(CompressedObject obj) { if (obj == null) { throw new NullPointerException("obj must not be null"); } CompressedObjectReference reference = new CompressedObjectReference(obj.getObjectNumber(), getObjectNumber(), objects.size()); objects.add(obj); return reference; }
// in src/java/org/apache/fop/pdf/PDFEncryptionManager.java
public static void setupPDFEncryption(PDFEncryptionParams params, PDFDocument pdf) { if (pdf == null) { throw new NullPointerException("PDF document must not be null"); } if (params != null) { if (!checkAvailableAlgorithms()) { if (isJCEAvailable()) { LOG.warn("PDF encryption has been requested, JCE is " + "available but there's no " + "JCE provider available that provides the " + "necessary algorithms. The PDF won't be " + "encrypted."); } else { LOG.warn("PDF encryption has been requested but JCE is " + "unavailable! The PDF won't be encrypted."); } } pdf.setEncryption(params); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void assignObjectNumber(PDFObject obj) { if (obj == null) { throw new NullPointerException("obj must not be null"); } if (obj.hasObjectNumber()) { throw new IllegalStateException( "Error registering a PDFObject: " + "PDFObject already has an object number"); } PDFDocument currentParent = obj.getDocument(); if (currentParent != null && currentParent != this) { throw new IllegalStateException( "Error registering a PDFObject: " + "PDFObject already has a parent PDFDocument"); } obj.setObjectNumber(++this.objectcount); if (currentParent == null) { obj.setDocument(this); } }
// in src/java/org/apache/fop/pdf/PDFDocument.java
public void addObject(PDFObject obj) { if (obj == null) { throw new NullPointerException("obj must not be null"); } if (!obj.hasObjectNumber()) { throw new IllegalStateException( "Error adding a PDFObject: " + "PDFObject doesn't have an object number"); } //Add object to list this.objects.add(obj); //Add object to special lists where necessary if (obj instanceof PDFFunction) { this.functions.add((PDFFunction) obj); } if (obj instanceof PDFShading) { final String shadingName = "Sh" + (++this.shadingCount); ((PDFShading)obj).setName(shadingName); this.shadings.add((PDFShading) obj); } if (obj instanceof PDFPattern) { final String patternName = "Pa" + (++this.patternCount); ((PDFPattern)obj).setName(patternName); this.patterns.add((PDFPattern) obj); } if (obj instanceof PDFFont) { final PDFFont font = (PDFFont)obj; this.fontMap.put(font.getName(), font); } if (obj instanceof PDFGState) { this.gstates.add((PDFGState) obj); } if (obj instanceof PDFPage) { this.pages.notifyKidRegistered((PDFPage)obj); } if (obj instanceof PDFLaunch) { this.launches.add((PDFLaunch) obj); } if (obj instanceof PDFLink) { this.links.add((PDFLink) obj); } if (obj instanceof PDFFileSpec) { this.filespecs.add((PDFFileSpec) obj); } if (obj instanceof PDFGoToRemote) { this.gotoremotes.add((PDFGoToRemote) obj); } }
// in src/java/org/apache/fop/fo/properties/DimensionPropertyMaker.java
public void setExtraCorresponding(int[][] extraCorresponding) { if ( extraCorresponding == null ) { throw new NullPointerException(); } for ( int i = 0; i < extraCorresponding.length; i++ ) { int[] eca = extraCorresponding[i]; if ( ( eca == null ) || ( eca.length != 4 ) ) { throw new IllegalArgumentException ( "bad sub-array @ [" + i + "]" ); } } this.extraCorresponding = extraCorresponding; }
// in src/java/org/apache/fop/fo/FObj.java
void addExtensionAttachment(ExtensionAttachment attachment) { if (attachment == null) { throw new NullPointerException( "Parameter attachment must not be null"); } if (extensionAttachments == null) { extensionAttachments = new java.util.ArrayList<ExtensionAttachment>(); } if (log.isDebugEnabled()) { log.debug("ExtensionAttachment of category " + attachment.getCategory() + " added to " + getName() + ": " + attachment); } extensionAttachments.add(attachment); }
// in src/java/org/apache/fop/fo/FObj.java
public void addForeignAttribute(QName attributeName, String value) { /* TODO: Handle this over FOP's property mechanism so we can use * inheritance. */ if (attributeName == null) { throw new NullPointerException("Parameter attributeName must not be null"); } if (foreignAttributes == null) { foreignAttributes = new java.util.HashMap<QName, String>(); } foreignAttributes.put(attributeName, value); }
// in src/java/org/apache/fop/fonts/EmbedFontInfo.java
public void setEncodingMode(EncodingMode mode) { if (mode == null) { throw new NullPointerException("mode must not be null"); } this.encodingMode = mode; }
// in src/java/org/apache/fop/render/pdf/CTMHelper.java
public static String toPDFString(CTM sourceMatrix) { if (null == sourceMatrix) { throw new NullPointerException("sourceMatrix must not be null"); } final double[] matrix = toPDFArray(sourceMatrix); return constructPDFArray(matrix); }
// in src/java/org/apache/fop/render/pdf/CTMHelper.java
public static String toPDFString(AffineTransform transform, boolean convertMillipoints) { if (null == transform) { throw new NullPointerException("transform must not be null"); } final double[] matrix = new double[6]; transform.getMatrix(matrix); if (convertMillipoints) { //Convert from millipoints to points matrix[4] /= 1000; matrix[5] /= 1000; } return constructPDFArray(matrix); }
// in src/java/org/apache/fop/render/pdf/CTMHelper.java
public static CTM toPDFCTM(CTM sourceMatrix) { if (null == sourceMatrix) { throw new NullPointerException("sourceMatrix must not be null"); } final double[] matrix = toPDFArray(sourceMatrix); return new CTM(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); }
// in src/java/org/apache/fop/render/pdf/CTMHelper.java
public static double[] toPDFArray(CTM sourceMatrix) { if (null == sourceMatrix) { throw new NullPointerException("sourceMatrix must not be null"); } final double[] matrix = sourceMatrix.toArray(); return new double[]{matrix[0], matrix[1], matrix[2], matrix[3], matrix[4] / 1000.0, matrix[5] / 1000.0}; }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
private Typeface getTypeface(String fontName) { if (fontName == null) { throw new NullPointerException("fontName must not be null"); } Typeface tf = getFontInfo().getFonts().get(fontName); if (tf instanceof LazyFont) { tf = ((LazyFont)tf).getRealFont(); } return tf; }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void noteAction(AbstractAction action) { if (action == null) { throw new NullPointerException("action must not be null"); } if (!action.isComplete()) { assert action.hasID(); incompleteActions.put(action.getID(), action); } }
// in src/java/org/apache/fop/render/intermediate/extensions/GoToXYAction.java
public boolean isSame(AbstractAction other) { if (other == null) { throw new NullPointerException("other must not be null"); } if (!(other instanceof GoToXYAction)) { return false; } GoToXYAction otherAction = (GoToXYAction)other; if (this.pageIndex != otherAction.pageIndex) { return false; } if (this.targetLocation == null || otherAction.targetLocation == null) { return false; } if (!getTargetLocation().equals(otherAction.getTargetLocation())) { return false; } return true; }
// in src/java/org/apache/fop/render/intermediate/extensions/URIAction.java
public boolean isSame(AbstractAction other) { if (other == null) { throw new NullPointerException("other must not be null"); } if (!(other instanceof URIAction)) { return false; } URIAction otherAction = (URIAction)other; if (!getURI().equals(otherAction.getURI())) { return false; } if (isNewWindow() != otherAction.isNewWindow()) { return false; } return true; }
// in src/java/org/apache/fop/render/ps/PSPainter.java
private Typeface getTypeface(String fontName) { if (fontName == null) { throw new NullPointerException("fontName must not be null"); } Typeface tf = (Typeface)getFontInfo().getFonts().get(fontName); if (tf instanceof LazyFont) { tf = ((LazyFont)tf).getRealFont(); } return tf; }
// in src/java/org/apache/fop/area/AreaTreeModel.java
public void startPageSequence(PageSequence pageSequence) { if (pageSequence == null) { throw new NullPointerException("pageSequence must not be null"); } if (currentPageSequence != null) { currentPageIndex += currentPageSequence.getPageCount(); } this.currentPageSequence = pageSequence; pageSequenceList.add(currentPageSequence); }
// in src/java/org/apache/fop/layoutmgr/ElementListObserver.java
public static void observe(List elementList, String category, String id) { if (isObservationActive()) { if (category == null) { throw new NullPointerException("category must not be null"); } Iterator i = activeObservers.iterator(); while (i.hasNext()) { ((Observer)i.next()).observe(elementList, category, id); } } }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public static ResourceBundle getXMLBundle(String baseName, Locale locale, ClassLoader loader) throws MissingResourceException { if (loader == null) { throw new NullPointerException("loader must not be null"); } if (baseName == null) { throw new NullPointerException("baseName must not be null"); } assert locale != null; ResourceBundle bundle; if (!locale.equals(Locale.getDefault())) { bundle = handleGetXMLBundle(baseName, "_" + locale, false, loader); if (bundle != null) { return bundle; } } bundle = handleGetXMLBundle(baseName, "_" + Locale.getDefault(), true, loader); if (bundle != null) { return bundle; } throw new MissingResourceException( baseName + " (" + locale + ")", baseName + '_' + locale, null); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
protected Object handleGetObject(String key) { if (key == null) { throw new NullPointerException("key must not be null"); } return resources.get(key); }
// in src/java/org/apache/fop/util/text/AdvancedMessageFormat.java
public void addChild(Part part) { if (part == null) { throw new NullPointerException("part must not be null"); } if (hasSections) { CompositePart composite = (CompositePart) this.parts.get(this.parts.size() - 1); composite.addChild(part); } else { this.parts.add(part); } }
0 0 0 0 0
unknown (Lib) NumberFormatException 1
            
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseWithHash(String value) throws PropertyException { Color parsedColor; try { int len = value.length(); int alpha; if (len == 5 || len == 9) { alpha = Integer.parseInt( value.substring((len == 5) ? 3 : 7), 16); } else { alpha = 0xFF; } int red = 0; int green = 0; int blue = 0; if ((len == 4) || (len == 5)) { //multiply by 0x11 = 17 = 255/15 red = Integer.parseInt(value.substring(1, 2), 16) * 0x11; green = Integer.parseInt(value.substring(2, 3), 16) * 0x11; blue = Integer.parseInt(value.substring(3, 4), 16) * 0X11; } else if ((len == 7) || (len == 9)) { red = Integer.parseInt(value.substring(1, 3), 16); green = Integer.parseInt(value.substring(3, 5), 16); blue = Integer.parseInt(value.substring(5, 7), 16); } else { throw new NumberFormatException(); } parsedColor = new Color(red, green, blue, alpha); } catch (RuntimeException re) { throw new PropertyException("Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA"); } return parsedColor; }
0 0 13
            
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (NumberFormatException nfe) { LogUtil.handleException(log, nfe, strict); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (NumberFormatException ne) { throw new SAXException("Malformed width in metric file: " + ne.getMessage(), ne); }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
catch (NumberFormatException e) { err = "Invalid " + METRICS_VERSION_ATTR + " attribute value (" + str + ")"; }
// in src/java/org/apache/fop/fonts/substitute/AttributeValue.java
catch (NumberFormatException ex) { value = FontWeightRange.valueOf(token); if (value == null) { value = token; } }
// in src/java/org/apache/fop/fonts/substitute/FontWeightRange.java
catch (NumberFormatException e) { log.error("invalid font-weight value " + weightString); }
// in src/java/org/apache/fop/fonts/FontUtil.java
catch (NumberFormatException nfe) { //weight is no number, so convert symbolic name to number if (text.equals("normal")) { weight = 400; } else if (text.equals("bold")) { weight = 700; } else { throw new IllegalArgumentException( "Illegal value for font weight: '" + text + "'. Use one of: 100, 200, 300, " + "400, 500, 600, 700, 800, 900, " + "normal (=400), bold (=700)"); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch (NumberFormatException nfe) { return new Double(getDoubleValue(line, startpos)); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (NumberFormatException nfe) { //ignore and leave the default above }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (NumberFormatException nfe) { //ignore and leave the default above }
// in src/java/org/apache/fop/render/awt/viewer/GoToPageDialog.java
catch (NumberFormatException nfe) { pageNumberField.setText("???"); }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
catch (NumberFormatException e) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Invalid codepoint number in " + line); }
5
            
// in src/java/org/apache/fop/fonts/FontReader.java
catch (NumberFormatException ne) { throw new SAXException("Malformed width in metric file: " + ne.getMessage(), ne); }
// in src/java/org/apache/fop/fonts/FontUtil.java
catch (NumberFormatException nfe) { //weight is no number, so convert symbolic name to number if (text.equals("normal")) { weight = 400; } else if (text.equals("bold")) { weight = 700; } else { throw new IllegalArgumentException( "Illegal value for font weight: '" + text + "'. Use one of: 100, 200, 300, " + "400, 500, 600, 700, 800, 900, " + "normal (=400), bold (=700)"); } }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/java/org/apache/fop/render/extensions/prepress/PageScale.java
catch (NumberFormatException nfe) { throw new IllegalArgumentException(MessageFormat.format(err, new Object[]{scale})); }
// in src/codegen/unicode/java/org/apache/fop/text/linebreak/GenerateLineBreakUtils.java
catch (NumberFormatException e) { throw new Exception(lineBreakFileName + ':' + lineNumber + ": Invalid codepoint number in " + line); }
3
runtime (Domain) PDFConformanceException
public class PDFConformanceException extends RuntimeException {

    /**
     * Constructs an PDFConformanceException with no detail message.
     * A detail message is a String that describes this particular exception.
     */
    public PDFConformanceException() {
        super();
    }

    /**
     * Constructs an PDFConformanceException with the specified detail
     * message. A detail message is a String that describes this particular
     * exception.
     * @param message the String that contains a detailed message
     */
    public PDFConformanceException(String message) {
        super(message);
    }

}
24
            
// in src/java/org/apache/fop/pdf/PDFProfile.java
protected void validateProfileCombination() { if (pdfAMode != PDFAMode.DISABLED) { if (pdfAMode == PDFAMode.PDFA_1B) { if (pdfXMode != PDFXMode.DISABLED && pdfXMode != PDFXMode.PDFX_3_2003) { throw new PDFConformanceException( pdfAMode + " and " + pdfXMode + " are not compatible!"); } } } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyEncryptionAllowed() { final String err = "{0} doesn't allow encrypted PDFs"; if (isPDFAActive()) { throw new PDFConformanceException(format(err, getPDFAMode())); } if (isPDFXActive()) { throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyPSXObjectsAllowed() { final String err = "PostScript XObjects are prohibited when {0}" + " is active. Convert EPS graphics to another format."; if (isPDFAActive()) { throw new PDFConformanceException(format(err, getPDFAMode())); } if (isPDFXActive()) { throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyTransparencyAllowed(String context) { final String err = "{0} does not allow the use of transparency. ({1})"; if (isPDFAActive()) { throw new PDFConformanceException(MessageFormat.format(err, new Object[] {getPDFAMode(), context})); } if (isPDFXActive()) { throw new PDFConformanceException(MessageFormat.format(err, new Object[] {getPDFXMode(), context})); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyPDFVersion() { final String err = "PDF version must be 1.4 for {0}"; if (getPDFAMode().isPDFA1LevelB() && !Version.V1_4.equals(getDocument().getPDFVersion())) { throw new PDFConformanceException(format(err, getPDFAMode())); } if (getPDFXMode() == PDFXMode.PDFX_3_2003 && !Version.V1_4.equals(getDocument().getPDFVersion())) { throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyTaggedPDF() { if (getPDFAMode().isPDFA1LevelA()) { final String err = "{0} requires the {1} dictionary entry to be set"; PDFDictionary markInfo = getDocument().getRoot().getMarkInfo(); if (markInfo == null) { throw new PDFConformanceException(format( "{0} requires the MarkInfo dictionary to be present", getPDFAMode())); } if (!Boolean.TRUE.equals(markInfo.get("Marked"))) { throw new PDFConformanceException(format(err, new Object[] {getPDFAMode(), "Marked"})); } if (getDocument().getRoot().getStructTreeRoot() == null) { throw new PDFConformanceException(format(err, new Object[] {getPDFAMode(), "StructTreeRoot"})); } if (getDocument().getRoot().getLanguage() == null) { throw new PDFConformanceException(format(err, new Object[] {getPDFAMode(), "Lang"})); } } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyTitleAbsent() { if (isPDFXActive()) { final String err = "{0} requires the title to be set."; throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyAnnotAllowed() { if (!isAnnotationAllowed()) { final String err = "{0} does not allow annotations inside the printable area."; //Note: this rule is simplified. Refer to the standard for details. throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyActionAllowed() { if (isPDFXActive()) { final String err = "{0} does not allow Actions."; throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFProfile.java
public void verifyEmbeddedFilesAllowed() { final String err = "{0} does not allow embedded files."; if (isPDFAActive()) { throw new PDFConformanceException(format(err, getPDFAMode())); } if (isPDFXActive()) { //Implicit since file specs are forbidden throw new PDFConformanceException(format(err, getPDFXMode())); } }
// in src/java/org/apache/fop/pdf/PDFFont.java
protected void validate() { if (getDocumentSafely().getProfile().isFontEmbeddingRequired()) { if (this.getClass() == PDFFont.class) { throw new PDFConformanceException("For " + getDocumentSafely().getProfile() + ", all fonts, even the base 14" + " fonts, have to be embedded! Offending font: " + getBaseFont()); } } }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
protected void populateStreamDict(Object lengthEntry) { final String filterEntry = getFilterList().buildFilterDictEntries(); if (getDocumentSafely().getProfile().getPDFAMode().isPDFA1LevelB() && filterEntry != null && filterEntry.length() > 0) { throw new PDFConformanceException( "The Filter key is prohibited when PDF/A-1 is active"); } put("Type", new PDFName("Metadata")); put("Subtype", new PDFName("XML")); super.populateStreamDict(lengthEntry); }
// in src/java/org/apache/fop/pdf/PDFFontNonBase14.java
protected void validate() { if (getDocumentSafely().getProfile().isFontEmbeddingRequired()) { if (this.getDescriptor().getFontFile() == null) { throw new PDFConformanceException("For " + getDocumentSafely().getProfile() + ", all fonts have to be embedded! Offending font: " + getBaseFont()); } } }
// in src/java/org/apache/fop/svg/PDFGraphics2D.java
protected void applyColor(Color col, boolean fill) { preparePainting(); //TODO Handle this in PDFColorHandler by automatically converting the color. //This won't work properly anyway after the redesign of ColorExt if (col.getColorSpace().getType() == ColorSpace.TYPE_CMYK) { if (pdfDoc.getProfile().getPDFAMode().isPDFA1LevelB()) { //See PDF/A-1, ISO 19005:1:2005(E), 6.2.3.3 //FOP is currently restricted to DeviceRGB if PDF/A-1 is active. throw new PDFConformanceException( "PDF/A-1 does not allow mixing DeviceRGB and DeviceCMYK."); } } boolean doWrite = false; if (fill) { if (paintingState.setBackColor(col)) { doWrite = true; } } else { if (paintingState.setColor(col)) { doWrite = true; } } if (doWrite) { StringBuffer sb = new StringBuffer(); colorHandler.establishColor(sb, col, fill); currentStream.write(sb.toString()); } }
// in src/java/org/apache/fop/render/pdf/AbstractImageAdapter.java
public void setup(PDFDocument doc) { ICC_Profile prof = getEffectiveICCProfile(); PDFDeviceColorSpace pdfCS = toPDFColorSpace(getImageColorSpace()); if (prof != null) { pdfICCStream = setupColorProfile(doc, prof, pdfCS); } if (doc.getProfile().getPDFAMode().isPDFA1LevelB()) { if (pdfCS != null && pdfCS.getColorSpace() != PDFDeviceColorSpace.DEVICE_RGB && pdfCS.getColorSpace() != PDFDeviceColorSpace.DEVICE_GRAY && prof == null) { //See PDF/A-1, ISO 19005:1:2005(E), 6.2.3.3 //FOP is currently restricted to DeviceRGB if PDF/A-1 is active. throw new PDFConformanceException( "PDF/A-1 does not allow mixing DeviceRGB and DeviceCMYK: " + image.getInfo()); } } }
// in src/java/org/apache/fop/render/pdf/PDFRenderingUtil.java
private void addPDFXOutputIntent() throws IOException { addDefaultOutputProfile(); String desc = ColorProfileUtil.getICCProfileDescription(this.outputProfile.getICCProfile()); int deviceClass = this.outputProfile.getICCProfile().getProfileClass(); if (deviceClass != ICC_Profile.CLASS_OUTPUT) { throw new PDFConformanceException(pdfDoc.getProfile().getPDFXMode() + " requires that" + " the DestOutputProfile be an Output Device Profile. " + desc + " does not match that requirement."); } PDFOutputIntent outputIntent = pdfDoc.getFactory().makeOutputIntent(); outputIntent.setSubtype(PDFOutputIntent.GTS_PDFX); outputIntent.setDestOutputProfile(this.outputProfile); outputIntent.setOutputConditionIdentifier(desc); outputIntent.setInfo(outputIntent.getOutputConditionIdentifier()); pdfDoc.getRoot().addOutputIntent(outputIntent); }
0 0 0 0 0
checked (Domain) PDFFilterException
public class PDFFilterException extends Exception {
    /**
     * Create a basic filter exception.
     */
    public PDFFilterException() {
    }

    /**
     * Create a filter exception with a message.
     *
     * @param message the error message
     */
    public PDFFilterException(String message) {
        super(message);
    }
}
3
            
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setColors(int colors) throws PDFFilterException { if (predictor != PREDICTION_NONE) { this.colors = colors; } else { throw new PDFFilterException( "Prediction must not be PREDICTION_NONE in" + " order to set Colors"); } }
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setBitsPerComponent(int bits) throws PDFFilterException { if (predictor != PREDICTION_NONE) { bitsPerComponent = bits; } else { throw new PDFFilterException( "Prediction must not be PREDICTION_NONE in order" + " to set bitsPerComponent"); } }
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setColumns(int columns) throws PDFFilterException { if (predictor != PREDICTION_NONE) { this.columns = columns; } else { throw new PDFFilterException( "Prediction must not be PREDICTION_NONE in" + " order to set Columns"); } }
0 4
            
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setPredictor(int predictor) throws PDFFilterException { this.predictor = predictor; }
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setColors(int colors) throws PDFFilterException { if (predictor != PREDICTION_NONE) { this.colors = colors; } else { throw new PDFFilterException( "Prediction must not be PREDICTION_NONE in" + " order to set Colors"); } }
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setBitsPerComponent(int bits) throws PDFFilterException { if (predictor != PREDICTION_NONE) { bitsPerComponent = bits; } else { throw new PDFFilterException( "Prediction must not be PREDICTION_NONE in order" + " to set bitsPerComponent"); } }
// in src/java/org/apache/fop/pdf/FlateFilter.java
public void setColumns(int columns) throws PDFFilterException { if (predictor != PREDICTION_NONE) { this.columns = columns; } else { throw new PDFFilterException( "Prediction must not be PREDICTION_NONE in" + " order to set Columns"); } }
0 0 0
unknown (Lib) PSDictionaryFormatException 0 0 0 1
            
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (PSDictionaryFormatException e) { PSEventProducer eventProducer = PSEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.postscriptDictionaryParseError(this, content, e); }
0 0
runtime (Domain) PageProductionException
public class PageProductionException extends RuntimeException {

    private static final long serialVersionUID = -5126033718398975158L;

    private String localizedMessage;
    private Locator locator;


    /**
     * Creates a new PageProductionException.
     * @param message the message
     */
    public PageProductionException(String message) {
        super(message);
    }

    /**
     * Creates a new PageProductionException.
     * @param message the message
     * @param locator the optional locator that points to the error in the source file
     */
    public PageProductionException(String message, Locator locator) {
        super(message);
        setLocator(locator);
    }


    /**
     * Set a location associated with the exception.
     * @param locator the locator holding the location.
     */
    public void setLocator(Locator locator) {
        this.locator = locator != null ? new LocatorImpl(locator) : null;
    }


    /**
     * Returns the locattion associated with the exception.
     * @return the locator or null if the location information is not available
     */
    public Locator getLocator() {
        return this.locator;
    }

    /**
     * Sets the localized message for this exception.
     * @param msg the localized message
     */
    public void setLocalizedMessage(String msg) {
        this.localizedMessage = msg;
    }

    /** {@inheritDoc} */
    public String getLocalizedMessage() {
        if (this.localizedMessage != null) {
            return this.localizedMessage;
        } else {
            return super.getLocalizedMessage();
        }
    }

    /** Exception factory for {@link PageProductionException}. */
    public static class PageProductionExceptionFactory implements ExceptionFactory {

        /** {@inheritDoc} */
        public Throwable createException(Event event) {
            Object obj = event.getParam("loc");
            Locator loc = (obj instanceof Locator ? (Locator)obj : null);
            String msg = EventFormatter.format(event, Locale.ENGLISH);
            PageProductionException ex = new PageProductionException(msg, loc);
            if (!Locale.ENGLISH.equals(Locale.getDefault())) {
                ex.setLocalizedMessage(EventFormatter.format(event));
            }
            return ex;
        }

        /** {@inheritDoc} */
        public Class<PageProductionException> getExceptionClass() {
            return PageProductionException.class;
        }

    }
}
2
            
// in src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java
public SimplePageMaster getNextSimplePageMaster(boolean isOddPage, boolean isFirstPage, boolean isLastPage, boolean isBlankPage, String mainFlowName) throws PageProductionException { if (currentSubSequence == null) { currentSubSequence = getNextSubSequence(); if (currentSubSequence == null) { blockLevelEventProducer.missingSubsequencesInPageSequenceMaster(this, masterName, getLocator()); } if (currentSubSequence.isInfinite() && !currentSubSequence.canProcess(mainFlowName)) { throw new PageProductionException( "The current sub-sequence will not terminate whilst processing then main flow"); } } SimplePageMaster pageMaster = currentSubSequence .getNextPageMaster(isOddPage, isFirstPage, isLastPage, isBlankPage); boolean canRecover = true; while (pageMaster == null) { SubSequenceSpecifier nextSubSequence = getNextSubSequence(); if (nextSubSequence == null) { //Sub-sequence exhausted so attempt to reuse it blockLevelEventProducer.pageSequenceMasterExhausted(this, masterName, canRecover & currentSubSequence.isReusable(), getLocator()); currentSubSequence.reset(); if (!currentSubSequence.canProcess(mainFlowName)) { throw new PageProductionException( "The last simple-page-master does not reference the main flow"); } canRecover = false; } else { currentSubSequence = nextSubSequence; } pageMaster = currentSubSequence .getNextPageMaster(isOddPage, isFirstPage, isLastPage, isBlankPage); } return pageMaster; }
0 2
            
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
public SimplePageMaster getNextSimplePageMaster (int page, boolean isFirstPage, boolean isLastPage, boolean isBlank) throws PageProductionException { if (pageSequenceMaster == null) { return simplePageMaster; } boolean isOddPage = ((page % 2) == 1); if (log.isDebugEnabled()) { log.debug("getNextSimplePageMaster(page=" + page + " isOdd=" + isOddPage + " isFirst=" + isFirstPage + " isLast=" + isLastPage + " isBlank=" + isBlank + ")"); } return pageSequenceMaster.getNextSimplePageMaster(isOddPage, isFirstPage, isLastPage, isBlank, getMainFlow().getFlowName()); }
// in src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java
public SimplePageMaster getNextSimplePageMaster(boolean isOddPage, boolean isFirstPage, boolean isLastPage, boolean isBlankPage, String mainFlowName) throws PageProductionException { if (currentSubSequence == null) { currentSubSequence = getNextSubSequence(); if (currentSubSequence == null) { blockLevelEventProducer.missingSubsequencesInPageSequenceMaster(this, masterName, getLocator()); } if (currentSubSequence.isInfinite() && !currentSubSequence.canProcess(mainFlowName)) { throw new PageProductionException( "The current sub-sequence will not terminate whilst processing then main flow"); } } SimplePageMaster pageMaster = currentSubSequence .getNextPageMaster(isOddPage, isFirstPage, isLastPage, isBlankPage); boolean canRecover = true; while (pageMaster == null) { SubSequenceSpecifier nextSubSequence = getNextSubSequence(); if (nextSubSequence == null) { //Sub-sequence exhausted so attempt to reuse it blockLevelEventProducer.pageSequenceMasterExhausted(this, masterName, canRecover & currentSubSequence.isReusable(), getLocator()); currentSubSequence.reset(); if (!currentSubSequence.canProcess(mainFlowName)) { throw new PageProductionException( "The last simple-page-master does not reference the main flow"); } canRecover = false; } else { currentSubSequence = nextSubSequence; } pageMaster = currentSubSequence .getNextPageMaster(isOddPage, isFirstPage, isLastPage, isBlankPage); } return pageMaster; }
0 0 0
unknown (Lib) ParserConfigurationException 0 0 1
            
// in src/java/org/apache/fop/cli/InputHandler.java
private XMLReader getXMLReader() throws ParserConfigurationException, SAXException { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://xml.org/sax/features/namespaces", true); spf.setFeature("http://apache.org/xml/features/xinclude", true); XMLReader xr = spf.newSAXParser().getXMLReader(); return xr; }
6
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (ParserConfigurationException e) { throw new IFException("Error while setting up a DOM for SVG generation", e); }
// in src/java/org/apache/fop/fo/ElementMapping.java
catch (ParserConfigurationException e) { throw new RuntimeException( "Cannot return default DOM implementation: " + e.getMessage()); }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
catch (javax.xml.parsers.ParserConfigurationException e) { log.error("Can't create DOM implementation", e); return null; }
// in src/java/org/apache/fop/fonts/apps/PFMReader.java
catch (javax.xml.parsers.ParserConfigurationException e) { log.error("Can't create DOM implementation", e); return null; }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (ParserConfigurationException e) { if (this.sourcefile != null) { source = new StreamSource(this.sourcefile); } else { source = new StreamSource(in, uri); } }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (ParserConfigurationException e) { // return StreamSource }
2
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (ParserConfigurationException e) { throw new IFException("Error while setting up a DOM for SVG generation", e); }
// in src/java/org/apache/fop/fo/ElementMapping.java
catch (ParserConfigurationException e) { throw new RuntimeException( "Cannot return default DOM implementation: " + e.getMessage()); }
1
unknown (Lib) PrinterException 0 0 1
            
// in src/java/org/apache/fop/render/java2d/Java2DRenderer.java
public int print(Graphics g, PageFormat pageFormat, int pageIndex) throws PrinterException { if (pageIndex >= getNumberOfPages()) { return NO_SUCH_PAGE; } if (state != null) { throw new IllegalStateException("state must be null"); } Graphics2D graphics = (Graphics2D) g; try { PageViewport viewport = getPageViewport(pageIndex); AffineTransform at = graphics.getTransform(); state = new Java2DGraphicsState(graphics, this.fontInfo, at); // reset the current Positions currentBPPosition = 0; currentIPPosition = 0; renderPageAreas(viewport.getPage()); return PAGE_EXISTS; } catch (FOPException e) { log.error(e); return NO_SUCH_PAGE; } finally { state = null; } }
2
            
// in src/java/org/apache/fop/render/print/PrintRenderer.java
catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); }
// in src/java/org/apache/fop/render/awt/viewer/PreviewDialog.java
catch (PrinterException e) { e.printStackTrace(); }
1
            
// in src/java/org/apache/fop/render/print/PrintRenderer.java
catch (PrinterException e) { log.error(e); throw new IOException("Unable to print: " + e.getClass().getName() + ": " + e.getMessage()); }
0
unknown (Domain) PropertyException
public class PropertyException extends FOPException {
    private String propertyName;

    /**
     * Constructor
     * @param detail string containing the detail message
     */
    public PropertyException(String detail) {
        super(detail);
    }

    /**
     * Constructor
     * @param cause the Exception causing this PropertyException
     */
    public PropertyException(Exception cause) {
        super(cause);
        if (cause instanceof PropertyException) {
            this.propertyName = ((PropertyException)cause).propertyName;
        }
    }

    /**
     * Sets the property context information.
     * @param propInfo the property info instance
     */
    public void setPropertyInfo(PropertyInfo propInfo) {
        setLocator(propInfo.getPropertyList().getFObj().getLocator());
        propertyName = propInfo.getPropertyMaker().getName();
    }

    /**
     * Sets the name of the property.
     * @param propertyName the property name
     */
    public void setPropertyName(String propertyName) {
        this.propertyName = propertyName;
    }

    /** {@inheritDoc} */
    public String getMessage() {
        if (propertyName != null) {
            return super.getMessage() + "; property:'" + propertyName + "'";
        } else {
            return super.getMessage();
        }
    }
}
85
            
// in src/java/org/apache/fop/fo/properties/TextDecorationMaker.java
Override public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { ListProperty listProp = (ListProperty) super.convertProperty(p, propertyList, fo); List lst = listProp.getList(); boolean none = false; boolean under = false; boolean over = false; boolean through = false; boolean blink = false; int enumValue = -1; for (int i = lst.size(); --i >= 0;) { Property prop = (Property)lst.get(i); if (prop instanceof NCnameProperty) { prop = checkEnumValues(prop.getString()); lst.set(i, prop); } if (prop != null) { enumValue = prop.getEnum(); } switch (enumValue) { case Constants.EN_NONE: if (under | over | through | blink) { throw new PropertyException("Invalid combination of values"); } none = true; break; case Constants.EN_UNDERLINE: case Constants.EN_NO_UNDERLINE: case Constants.EN_OVERLINE: case Constants.EN_NO_OVERLINE: case Constants.EN_LINE_THROUGH: case Constants.EN_NO_LINE_THROUGH: case Constants.EN_BLINK: case Constants.EN_NO_BLINK: if (none) { throw new PropertyException ("'none' specified, no additional values allowed"); } switch (enumValue) { case Constants.EN_UNDERLINE: case Constants.EN_NO_UNDERLINE: if (!under) { under = true; continue; } case Constants.EN_OVERLINE: case Constants.EN_NO_OVERLINE: if (!over) { over = true; continue; } case Constants.EN_LINE_THROUGH: case Constants.EN_NO_LINE_THROUGH: if (!through) { through = true; continue; } case Constants.EN_BLINK: case Constants.EN_NO_BLINK: if (!blink) { blink = true; continue; } default: throw new PropertyException("Invalid combination of values"); } default: throw new PropertyException("Invalid value specified: " + p); } } return listProp; }
// in src/java/org/apache/fop/fo/properties/CommonTextDecoration.java
private static CommonTextDecoration calcTextDecoration(PropertyList pList) throws PropertyException { CommonTextDecoration deco = null; PropertyList parentList = pList.getParentPropertyList(); if (parentList != null) { //Parent is checked first deco = calcTextDecoration(parentList); } //For rules, see XSL 1.0, chapters 5.5.6 and 7.16.4 Property textDecoProp = pList.getExplicit(Constants.PR_TEXT_DECORATION); if (textDecoProp != null) { List list = textDecoProp.getList(); Iterator i = list.iterator(); while (i.hasNext()) { Property prop = (Property)i.next(); int propEnum = prop.getEnum(); FOUserAgent ua = (pList == null) ? null : (pList.getFObj() == null ? null : pList.getFObj().getUserAgent()); if (propEnum == Constants.EN_NONE) { if (deco != null) { deco.decoration = 0; } return deco; } else if (propEnum == Constants.EN_UNDERLINE) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= UNDERLINE; deco.underColor = pList.get(Constants.PR_COLOR).getColor(ua); } else if (propEnum == Constants.EN_NO_UNDERLINE) { if (deco != null) { deco.decoration &= OVERLINE | LINE_THROUGH | BLINK; deco.underColor = pList.get(Constants.PR_COLOR).getColor(ua); } } else if (propEnum == Constants.EN_OVERLINE) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= OVERLINE; deco.overColor = pList.get(Constants.PR_COLOR).getColor(ua); } else if (propEnum == Constants.EN_NO_OVERLINE) { if (deco != null) { deco.decoration &= UNDERLINE | LINE_THROUGH | BLINK; deco.overColor = pList.get(Constants.PR_COLOR).getColor(ua); } } else if (propEnum == Constants.EN_LINE_THROUGH) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= LINE_THROUGH; deco.throughColor = pList.get(Constants.PR_COLOR).getColor(ua); } else if (propEnum == Constants.EN_NO_LINE_THROUGH) { if (deco != null) { deco.decoration &= UNDERLINE | OVERLINE | BLINK; deco.throughColor = pList.get(Constants.PR_COLOR).getColor(ua); } } else if (propEnum == Constants.EN_BLINK) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= BLINK; } else if (propEnum == Constants.EN_NO_BLINK) { if (deco != null) { deco.decoration &= UNDERLINE | OVERLINE | LINE_THROUGH; } } else { throw new PropertyException("Illegal value encountered: " + prop.getString()); } } } return deco; }
// in src/java/org/apache/fop/fo/properties/URIProperty.java
Override public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { Property p = null; //special treament for data: URIs if (value.matches("(?s)^(url\\(('|\")?)?data:.*$")) { p = new URIProperty(value, false); } else { try { URI specifiedURI = new URI(URISpecification.escapeURI(value)); URIProperty xmlBase = (URIProperty)propertyList.get(PR_X_XML_BASE, true, false); if (xmlBase == null) { //xml:base undefined if (this.propId == PR_X_XML_BASE) { //if current property is xml:base, define a new one p = new URIProperty(specifiedURI); p.setSpecifiedValue(value); } else { //otherwise, just store the specified value (for backward compatibility) p = new URIProperty(value, false); } } else { //xml:base defined, so resolve p = new URIProperty(xmlBase.resolvedURI.resolve(specifiedURI)); p.setSpecifiedValue(value); } } catch (URISyntaxException use) { // Let PropertyList propagate the exception throw new PropertyException("Invalid URI specified"); } } return p; }
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { try { FontShorthandProperty newProp = new FontShorthandProperty(); newProp.setSpecifiedValue(value); String specVal = value; Property prop = null; if ("inherit".equals(specVal)) { /* fill the list with the individual properties from the parent */ for (int i = PROP_IDS.length; --i >= 0;) { prop = propertyList.getFromParent(PROP_IDS[i]); newProp.addProperty(prop, i); } } else { /* initialize list with nulls */ for (int pos = PROP_IDS.length; --pos >= 0;) { newProp.addProperty(null, pos); } prop = checkEnumValues(specVal); if (prop == null) { /* not an enum: * value should consist at least of font-size and font-family * separated by a space * mind the possible spaces from quoted font-family names */ int spaceIndex = value.indexOf(' '); int quoteIndex = (value.indexOf('\'') == -1) ? value.indexOf('\"') : value.indexOf('\''); if (spaceIndex == -1 || (quoteIndex != -1 && spaceIndex > quoteIndex)) { /* no spaces or first space appears after the first * single/double quote, so malformed value string */ throw new PropertyException("Invalid property value: " + "font=\"" + value + "\""); } PropertyMaker m = null; int fromIndex = spaceIndex + 1; int toIndex = specVal.length(); /* at least one space that appears before the first * single/double quote, so extract the individual properties */ boolean fontFamilyParsed = false; int commaIndex = value.indexOf(','); while (!fontFamilyParsed) { /* value contains a (list of) possibly quoted * font-family name(s) */ if (commaIndex == -1) { /* no list, just a single name * (or first name in the list) */ if (quoteIndex != -1) { /* a single name, quoted */ fromIndex = quoteIndex; } m = FObj.getPropertyMakerFor(PROP_IDS[1]); prop = m.make(propertyList, specVal.substring(fromIndex), fo); newProp.addProperty(prop, 1); fontFamilyParsed = true; } else { if (quoteIndex != -1 && quoteIndex < commaIndex) { /* a quoted font-family name as first name * in the comma-separated list * fromIndex = index of the first quote */ fromIndex = quoteIndex; quoteIndex = -1; } else { fromIndex = value.lastIndexOf(' ', commaIndex) + 1; } commaIndex = -1; } } toIndex = fromIndex - 1; fromIndex = value.lastIndexOf(' ', toIndex - 1) + 1; value = specVal.substring(fromIndex, toIndex); int slashIndex = value.indexOf('/'); String fontSize = value.substring(0, (slashIndex == -1) ? value.length() : slashIndex); m = FObj.getPropertyMakerFor(PROP_IDS[0]); prop = m.make(propertyList, fontSize, fo); /* need to make sure subsequent call to LineHeightPropertyMaker.make() * doesn't generate the default font-size property... */ propertyList.putExplicit(PROP_IDS[0], prop); newProp.addProperty(prop, 0); if (slashIndex != -1) { /* line-height */ String lineHeight = value.substring(slashIndex + 1); m = FObj.getPropertyMakerFor(PROP_IDS[2]); prop = m.make(propertyList, lineHeight, fo); newProp.addProperty(prop, 2); } if (fromIndex != 0) { toIndex = fromIndex - 1; value = specVal.substring(0, toIndex); fromIndex = 0; spaceIndex = value.indexOf(' '); do { toIndex = (spaceIndex == -1) ? value.length() : spaceIndex; String val = value.substring(fromIndex, toIndex); for (int i = 6; --i >= 3;) { if (newProp.list.get(i) == null) { /* not set */ m = FObj.getPropertyMakerFor(PROP_IDS[i]); val = m.checkValueKeywords(val); prop = m.checkEnumValues(val); if (prop != null) { newProp.addProperty(prop, i); } } } fromIndex = toIndex + 1; spaceIndex = value.indexOf(' ', fromIndex); } while (toIndex != value.length()); } } else { //TODO: implement enum values log.warn("Enum values other than \"inherit\"" + " not yet supported for the font shorthand."); return null; } } if (newProp.list.get(0) == null || newProp.list.get(1) == null) { throw new PropertyException("Invalid property value: " + "font-size and font-family are required for the font shorthand" + "\nfont=\"" + value + "\""); } return newProp; } catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; } }
// in src/java/org/apache/fop/fo/properties/ReferenceOrientationMaker.java
public Property get(int subpropId, PropertyList propertyList, boolean tryInherit, boolean tryDefault) throws PropertyException { Property p = super.get(0, propertyList, tryInherit, tryDefault); int ro = 0; if (p != null) { ro = p.getNumeric().getValue(); } if ((Math.abs(ro) % 90) == 0 && (Math.abs(ro) / 90) <= 3) { return p; } else { throw new PropertyException("Illegal property value: " + "reference-orientation=\"" + ro + "\" " + "on " + propertyList.getFObj().getName()); } }
// in src/java/org/apache/fop/fo/properties/BorderSpacingShorthandParser.java
protected Property convertValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { List lst = property.getList(); if (lst != null) { if (lst.size() == 1) { Property len = (Property)lst.get(0); return new LengthPairProperty(len); } else if (lst.size() == 2) { Property ipd = (Property)lst.get(0); Property bpd = (Property)lst.get(1); return new LengthPairProperty(ipd, bpd); } } throw new PropertyException("list with 1 or 2 length values expected"); }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { try { Property newProp = null; String pvalue = value; if ("inherit".equals(value)) { newProp = propertyList.getFromParent(this.propId & Constants.PROPERTY_MASK); if ((propId & Constants.COMPOUND_MASK) != 0) { newProp = getSubprop(newProp, propId & Constants.COMPOUND_MASK); } if (!isInherited() && LOG.isWarnEnabled()) { /* check whether explicit value is available on the parent * (for inherited properties, an inherited value will always * be available) */ Property parentExplicit = propertyList.getParentPropertyList() .getExplicit(getPropId()); if (parentExplicit == null) { LOG.warn(FOPropertyMapping.getPropertyName(getPropId()) + "=\"inherit\" on " + propertyList.getFObj().getName() + ", but no explicit value found on the parent FO."); } } } else { // Check for keyword shorthand values to be substituted. pvalue = checkValueKeywords(pvalue.trim()); newProp = checkEnumValues(pvalue); } if (newProp == null) { // Override parsePropertyValue in each subclass of Property.Maker newProp = PropertyParser.parse(pvalue, new PropertyInfo(this, propertyList)); } if (newProp != null) { newProp = convertProperty(newProp, propertyList, fo); } if (newProp == null) { throw new PropertyException("No conversion defined " + pvalue); } return newProp; } catch (PropertyException propEx) { if (fo != null) { propEx.setLocator(fo.getLocator()); } propEx.setPropertyName(getName()); throw propEx; } }
// in src/java/org/apache/fop/fo/expr/FromTableColumnFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { FObj fo = pInfo.getPropertyList().getFObj(); /* obtain property Id for the property for which the function is being * evaluated */ int propId = 0; if (args.length == 0) { propId = pInfo.getPropertyMaker().getPropId(); } else { String propName = args[0].getString(); propId = FOPropertyMapping.getPropertyId(propName); } /* make sure we have a correct property id ... */ if (propId != -1) { /* obtain column number for which the function is being evaluated: */ int columnNumber = -1; int span = 0; if (fo.getNameId() != Constants.FO_TABLE_CELL) { // climb up to the nearest cell do { fo = (FObj) fo.getParent(); } while (fo.getNameId() != Constants.FO_TABLE_CELL && fo.getNameId() != Constants.FO_PAGE_SEQUENCE); if (fo.getNameId() == Constants.FO_TABLE_CELL) { //column-number is available on the cell columnNumber = ((TableCell) fo).getColumnNumber(); span = ((TableCell) fo).getNumberColumnsSpanned(); } else { //means no table-cell was found... throw new PropertyException("from-table-column() may only be used on " + "fo:table-cell or its descendants."); } } else { //column-number is only accurately available through the propertyList columnNumber = pInfo.getPropertyList().get(Constants.PR_COLUMN_NUMBER) .getNumeric().getValue(); span = pInfo.getPropertyList().get(Constants.PR_NUMBER_COLUMNS_SPANNED) .getNumeric().getValue(); } /* return the property from the column */ Table t = ((TableFObj) fo).getTable(); List cols = t.getColumns(); ColumnNumberManager columnIndexManager = t.getColumnNumberManager(); if (cols == null) { //no columns defined => no match: return default value return pInfo.getPropertyList().get(propId, false, true); } else { if (columnIndexManager.isColumnNumberUsed(columnNumber)) { //easiest case: exact match return ((TableColumn) cols.get(columnNumber - 1)).getProperty(propId); } else { //no exact match: try all spans... while (--span > 0 && !columnIndexManager.isColumnNumberUsed(++columnNumber)) { //nop: just increment/decrement } if (columnIndexManager.isColumnNumberUsed(columnNumber)) { return ((TableColumn) cols.get(columnNumber - 1)).getProperty(propId); } else { //no match: return default value return pInfo.getPropertyList().get(propId, false, true); } } } } else { throw new PropertyException("Incorrect parameter to from-table-column() function"); } }
// in src/java/org/apache/fop/fo/expr/AbsFunction.java
public Property eval(Property[] args, PropertyInfo propInfo) throws PropertyException { Numeric num = args[0].getNumeric(); if (num == null) { throw new PropertyException("Non numeric operand to abs function"); } // TODO: What if it has relative components (percent, table-col units)? return (Property) NumericOp.abs(num); }
// in src/java/org/apache/fop/fo/expr/LabelEndFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Length distance = pInfo.getPropertyList().get( Constants.PR_PROVISIONAL_DISTANCE_BETWEEN_STARTS).getLength(); Length separation = pInfo.getPropertyList().getNearestSpecified( Constants.PR_PROVISIONAL_LABEL_SEPARATION).getLength(); PropertyList pList = pInfo.getPropertyList(); while (pList != null && !(pList.getFObj() instanceof ListItem)) { pList = pList.getParentPropertyList(); } if (pList == null) { throw new PropertyException("label-end() called from outside an fo:list-item"); } Length startIndent = pList.get(Constants.PR_START_INDENT).getLength(); LengthBase base = new LengthBase(pInfo.getPropertyList(), LengthBase.CONTAINING_REFAREA_WIDTH); PercentLength refWidth = new PercentLength(1.0, base); Numeric labelEnd = distance; labelEnd = NumericOp.addition(labelEnd, startIndent); //TODO add start-intrusion-adjustment labelEnd = NumericOp.subtraction(labelEnd, separation); labelEnd = NumericOp.subtraction(refWidth, labelEnd); return (Property) labelEnd; }
// in src/java/org/apache/fop/fo/expr/BodyStartFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Numeric distance = pInfo.getPropertyList() .get(Constants.PR_PROVISIONAL_DISTANCE_BETWEEN_STARTS).getNumeric(); PropertyList pList = pInfo.getPropertyList(); while (pList != null && !(pList.getFObj() instanceof ListItem)) { pList = pList.getParentPropertyList(); } if (pList == null) { throw new PropertyException("body-start() called from outside an fo:list-item"); } Numeric startIndent = pList.get(Constants.PR_START_INDENT).getNumeric(); return (Property) NumericOp.addition(distance, startIndent); }
// in src/java/org/apache/fop/fo/expr/FromParentFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { String propName = args[0].getString(); if (propName == null) { throw new PropertyException("Incorrect parameter to from-parent function"); } // NOTE: special cases for shorthand property // Should return COMPUTED VALUE /* * For now, this is the same as inherited-property-value(propName) * (The only difference I can see is that this could work for * non-inherited properties too. Perhaps the result is different for * a property line line-height which "inherits specified"??? */ int propId = FOPropertyMapping.getPropertyId(propName); if (propId < 0) { throw new PropertyException( "Unknown property name used with inherited-property-value function: " + propName); } return pInfo.getPropertyList().getFromParent(propId); }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
private Numeric getResolved(PercentBaseContext context) throws PropertyException { switch (operation) { case ADDITION: return NumericOp.addition2(op1, op2, context); case SUBTRACTION: return NumericOp.subtraction2(op1, op2, context); case MULTIPLY: return NumericOp.multiply2(op1, op2, context); case DIVIDE: return NumericOp.divide2(op1, op2, context); case MODULO: return NumericOp.modulo2(op1, op2, context); case NEGATE: return NumericOp.negate2(op1, context); case ABS: return NumericOp.abs2(op1, context); case MAX: return NumericOp.max2(op1, op2, context); case MIN: return NumericOp.min2(op1, op2, context); default: throw new PropertyException("Unknown expr operation " + operation); } }
// in src/java/org/apache/fop/fo/expr/RoundFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number dbl = args[0].getNumber(); if (dbl == null) { throw new PropertyException("Non number operand to round function"); } double n = dbl.doubleValue(); double r = Math.floor(n + 0.5); if (r == 0.0 && n < 0.0) { r = -r; // round(-0.2) returns -0 not 0 } return NumberProperty.getInstance(r); }
// in src/java/org/apache/fop/fo/expr/PropertyTokenizer.java
void next() throws PropertyException { currentTokenValue = null; currentTokenStartIndex = exprIndex; boolean bSawDecimal; while ( true ) { if (exprIndex >= exprLength) { currentToken = TOK_EOF; return; } char c = expr.charAt(exprIndex++); switch (c) { case ' ': case '\t': case '\r': case '\n': currentTokenStartIndex = exprIndex; break; case ',': currentToken = TOK_COMMA; return; case '+': currentToken = TOK_PLUS; return; case '-': currentToken = TOK_MINUS; return; case '(': currentToken = TOK_LPAR; return; case ')': currentToken = TOK_RPAR; return; case '"': case '\'': exprIndex = expr.indexOf(c, exprIndex); if (exprIndex < 0) { exprIndex = currentTokenStartIndex + 1; throw new PropertyException("missing quote"); } currentTokenValue = expr.substring(currentTokenStartIndex + 1, exprIndex++); currentToken = TOK_LITERAL; return; case '*': /* * if (currentMaybeOperator) { * recognizeOperator = false; */ currentToken = TOK_MULTIPLY; /* * } * else * throw new PropertyException("illegal operator *"); */ return; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': scanDigits(); if (exprIndex < exprLength && expr.charAt(exprIndex) == '.') { exprIndex++; bSawDecimal = true; if (exprIndex < exprLength && isDigit(expr.charAt(exprIndex))) { exprIndex++; scanDigits(); } } else { bSawDecimal = false; } if (exprIndex < exprLength && expr.charAt(exprIndex) == '%') { exprIndex++; currentToken = TOK_PERCENT; } else { // Check for possible unit name following number currentUnitLength = exprIndex; scanName(); currentUnitLength = exprIndex - currentUnitLength; currentToken = (currentUnitLength > 0) ? TOK_NUMERIC : (bSawDecimal ? TOK_FLOAT : TOK_INTEGER); } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); return; case '.': nextDecimalPoint(); return; case '#': // Start of color value nextColor(); return; default: --exprIndex; scanName(); if (exprIndex == currentTokenStartIndex) { throw new PropertyException("illegal character"); } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); if (currentTokenValue.equals("mod")) { currentToken = TOK_MOD; return; } else if (currentTokenValue.equals("div")) { currentToken = TOK_DIV; return; } if (followingParen()) { currentToken = TOK_FUNCTION_LPAR; } else { currentToken = TOK_NCNAME; } return; } } }
// in src/java/org/apache/fop/fo/expr/PropertyTokenizer.java
private void nextDecimalPoint() throws PropertyException { if (exprIndex < exprLength && isDigit(expr.charAt(exprIndex))) { ++exprIndex; scanDigits(); if (exprIndex < exprLength && expr.charAt(exprIndex) == '%') { exprIndex++; currentToken = TOK_PERCENT; } else { // Check for possible unit name following number currentUnitLength = exprIndex; scanName(); currentUnitLength = exprIndex - currentUnitLength; currentToken = (currentUnitLength > 0) ? TOK_NUMERIC : TOK_FLOAT; } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); return; } throw new PropertyException("illegal character '.'"); }
// in src/java/org/apache/fop/fo/expr/PropertyTokenizer.java
private void nextColor() throws PropertyException { if (exprIndex < exprLength) { ++exprIndex; scanHexDigits(); int len = exprIndex - currentTokenStartIndex - 1; if (len % 3 == 0) { currentToken = TOK_COLORSPEC; } else { //Actually not a color at all, but an NCNAME starting with "#" scanRestOfName(); currentToken = TOK_NCNAME; } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); return; } else { throw new PropertyException("illegal character '#'"); } }
// in src/java/org/apache/fop/fo/expr/CIELabColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { float red = args[0].getNumber().floatValue(); float green = args[1].getNumber().floatValue(); float blue = args[2].getNumber().floatValue(); /* Verify sRGB replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("sRGB color values out of range. " + "Arguments to cie-lab-color() must be [0..255] or [0%..100%]"); } float l = args[3].getNumber().floatValue(); float a = args[4].getNumber().floatValue(); float b = args[5].getNumber().floatValue(); if (l < 0 || l > 100) { throw new PropertyException("L* value out of range. Valid range: [0..100]"); } if (a < -127 || a > 127 || b < -127 || b > 127) { throw new PropertyException("a* and b* values out of range. Valid range: [-127..+127]"); } StringBuffer sb = new StringBuffer(); sb.append("cie-lab-color(" + red + "," + green + "," + blue + "," + l + "," + a + "," + b + ")"); FOUserAgent ua = (pInfo == null) ? null : (pInfo.getFO() == null ? null : pInfo.getFO().getUserAgent()); return ColorProperty.getInstance(ua, sb.toString()); }
// in src/java/org/apache/fop/fo/expr/FromNearestSpecifiedValueFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { String propName = args[0].getString(); if (propName == null) { throw new PropertyException( "Incorrect parameter to from-nearest-specified-value function"); } // NOTE: special cases for shorthand property // Should return COMPUTED VALUE int propId = FOPropertyMapping.getPropertyId(propName); if (propId < 0) { throw new PropertyException( "Unknown property name used with inherited-property-value function: " + propName); } return pInfo.getPropertyList().getNearestSpecified(propId); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric addition2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Can't subtract Numerics of different dimensions"); } return numeric(op1.getNumericValue(context) + op2.getNumericValue(context), op1.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric subtraction2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Can't subtract Numerics of different dimensions"); } return numeric(op1.getNumericValue(context) - op2.getNumericValue(context), op1.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric max2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Arguments to max() must have same dimensions"); } return op1.getNumericValue(context) > op2.getNumericValue(context) ? op1 : op2; }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric min2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Arguments to min() must have same dimensions"); } return op1.getNumericValue(context) <= op2.getNumericValue(context) ? op1 : op2; }
// in src/java/org/apache/fop/fo/expr/MaxFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Numeric n1 = args[0].getNumeric(); Numeric n2 = args[1].getNumeric(); if (n1 == null || n2 == null) { throw new PropertyException("Non numeric operands to max function"); } return (Property) NumericOp.max(n1, n2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private void expectRpar() throws PropertyException { if (currentToken != TOK_RPAR) { throw new PropertyException("expected )"); } next(); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property parsePrimaryExpr() throws PropertyException { Property prop; if (currentToken == TOK_COMMA) { //Simply skip commas, for example for font-family next(); } switch (currentToken) { case TOK_LPAR: next(); prop = parseAdditiveExpr(); expectRpar(); return prop; case TOK_LITERAL: prop = StringProperty.getInstance(currentTokenValue); break; case TOK_NCNAME: // Interpret this in context of the property or do it later? prop = new NCnameProperty(currentTokenValue); break; case TOK_FLOAT: prop = NumberProperty.getInstance(new Double(currentTokenValue)); break; case TOK_INTEGER: prop = NumberProperty.getInstance(new Integer(currentTokenValue)); break; case TOK_PERCENT: /* * Get the length base value object from the Maker. If null, then * this property can't have % values. Treat it as a real number. */ double pcval = Double.parseDouble( currentTokenValue.substring(0, currentTokenValue.length() - 1)) / 100.0; PercentBase pcBase = this.propInfo.getPercentBase(); if (pcBase != null) { if (pcBase.getDimension() == 0) { prop = NumberProperty.getInstance(pcval * pcBase.getBaseValue()); } else if (pcBase.getDimension() == 1) { if (pcBase instanceof LengthBase) { if (pcval == 0.0) { prop = FixedLength.ZERO_FIXED_LENGTH; break; } //If the base of the percentage is known //and absolute, it can be resolved by the //parser Length base = ((LengthBase)pcBase).getBaseLength(); if (base != null && base.isAbsolute()) { prop = FixedLength.getInstance(pcval * base.getValue()); break; } } prop = new PercentLength(pcval, pcBase); } else { throw new PropertyException("Illegal percent dimension value"); } } else { // WARNING? Interpret as a decimal fraction, eg. 50% = .5 prop = NumberProperty.getInstance(pcval); } break; case TOK_NUMERIC: // A number plus a valid unit name. int numLen = currentTokenValue.length() - currentUnitLength; String unitPart = currentTokenValue.substring(numLen); double numPart = Double.parseDouble(currentTokenValue.substring(0, numLen)); if (RELUNIT.equals(unitPart)) { prop = (Property) NumericOp.multiply( NumberProperty.getInstance(numPart), propInfo.currentFontSize()); } else { if ("px".equals(unitPart)) { //pass the ratio between target-resolution and //the default resolution of 72dpi float resolution = propInfo.getPropertyList().getFObj() .getUserAgent().getSourceResolution(); prop = FixedLength.getInstance( numPart, unitPart, UnitConv.IN2PT / resolution); } else { //use default resolution of 72dpi prop = FixedLength.getInstance(numPart, unitPart); } } break; case TOK_COLORSPEC: prop = ColorProperty.getInstance(propInfo.getUserAgent(), currentTokenValue); break; case TOK_FUNCTION_LPAR: Function function = (Function)FUNCTION_TABLE.get(currentTokenValue); if (function == null) { throw new PropertyException("no such function: " + currentTokenValue); } next(); // Push new function (for function context: getPercentBase()) propInfo.pushFunction(function); prop = function.eval(parseArgs(function), propInfo); propInfo.popFunction(); return prop; default: // TODO: add the token or the expr to the error message. throw new PropertyException("syntax error"); } next(); return prop; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
Property[] parseArgs(Function function) throws PropertyException { int numReq = function.getRequiredArgsCount(); // # required args int numOpt = function.getOptionalArgsCount(); // # optional args boolean hasVar = function.hasVariableArgs(); // has variable args List<Property> args = new java.util.ArrayList<Property>(numReq + numOpt); if (currentToken == TOK_RPAR) { // No args: func() next(); } else { while (true) { Property p = parseAdditiveExpr(); int i = args.size(); if ( ( i < numReq ) || ( ( i - numReq ) < numOpt ) || hasVar ) { args.add ( p ); } else { throw new PropertyException ( "Unexpected function argument at index " + i ); } // ignore extra args if (currentToken != TOK_COMMA) { break; } next(); } expectRpar(); } int numArgs = args.size(); if ( numArgs < numReq ) { throw new PropertyException("Expected " + numReq + " required arguments, but only " + numArgs + " specified"); } else { for ( int i = 0; i < numOpt; i++ ) { if ( args.size() < ( numReq + i + 1 ) ) { args.add ( function.getOptionalArgDefault ( i, propInfo ) ); } } } return (Property[]) args.toArray ( new Property [ args.size() ] ); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalAddition(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in addition"); } return (Property) NumericOp.addition(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalSubtraction(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in subtraction"); } return (Property) NumericOp.subtraction(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalNegate(Numeric op) throws PropertyException { if (op == null) { throw new PropertyException("Non numeric operand to unary minus"); } return (Property) NumericOp.negate(op); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalMultiply(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in multiplication"); } return (Property) NumericOp.multiply(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalDivide(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in division"); } return (Property) NumericOp.divide(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalModulo(Number op1, Number op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non number operand to modulo"); } return NumberProperty.getInstance(op1.doubleValue() % op2.doubleValue()); }
// in src/java/org/apache/fop/fo/expr/MinFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Numeric n1 = args[0].getNumeric(); Numeric n2 = args[1].getNumeric(); if (n1 == null || n2 == null) { throw new PropertyException("Non numeric operands to min function"); } return (Property) NumericOp.min(n1, n2); }
// in src/java/org/apache/fop/fo/expr/FloorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number dbl = args[0].getNumber(); if (dbl == null) { throw new PropertyException("Non number operand to floor function"); } return NumberProperty.getInstance(Math.floor(dbl.doubleValue())); }
// in src/java/org/apache/fop/fo/expr/RGBICCColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { // Map color profile NCNAME to src from declarations/color-profile element String colorProfileName = args[3].getString(); Declarations decls = (pInfo.getFO() != null ? pInfo.getFO().getRoot().getDeclarations() : null); ColorProfile cp = null; if (decls == null) { //function used in a color-specification //on a FO occurring: //a) before the fo:declarations, //b) or in a document without fo:declarations? //=> return the sRGB fallback if (!ColorUtil.isPseudoProfile(colorProfileName)) { Property[] rgbArgs = new Property[3]; System.arraycopy(args, 0, rgbArgs, 0, 3); return new RGBColorFunction().eval(rgbArgs, pInfo); } } else { cp = decls.getColorProfile(colorProfileName); if (cp == null) { if (!ColorUtil.isPseudoProfile(colorProfileName)) { PropertyException pe = new PropertyException("The " + colorProfileName + " color profile was not declared"); pe.setPropertyInfo(pInfo); throw pe; } } } String src = (cp != null ? cp.getSrc() : ""); float red = 0; float green = 0; float blue = 0; red = args[0].getNumber().floatValue(); green = args[1].getNumber().floatValue(); blue = args[2].getNumber().floatValue(); /* Verify rgb replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("Color values out of range. " + "Arguments to rgb-icc() must be [0..255] or [0%..100%]"); } // rgb-icc is replaced with fop-rgb-icc which has an extra fifth argument containing the // color profile src attribute as it is defined in the color-profile declarations element. StringBuffer sb = new StringBuffer(); sb.append("fop-rgb-icc("); sb.append(red / 255f); sb.append(',').append(green / 255f); sb.append(',').append(blue / 255f); for (int ix = 3; ix < args.length; ix++) { if (ix == 3) { sb.append(',').append(colorProfileName); sb.append(',').append(src); } else { sb.append(',').append(args[ix]); } } sb.append(")"); return ColorProperty.getInstance(pInfo.getUserAgent(), sb.toString()); }
// in src/java/org/apache/fop/fo/expr/RGBNamedColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { // Map color profile NCNAME to src from declarations/color-profile element String colorProfileName = args[3].getString(); String colorName = args[4].getString(); Declarations decls = (pInfo.getFO() != null ? pInfo.getFO().getRoot().getDeclarations() : null); ColorProfile cp = null; if (decls != null) { cp = decls.getColorProfile(colorProfileName); } if (cp == null) { PropertyException pe = new PropertyException("The " + colorProfileName + " color profile was not declared"); pe.setPropertyInfo(pInfo); throw pe; } float red = 0; float green = 0; float blue = 0; red = args[0].getNumber().floatValue(); green = args[1].getNumber().floatValue(); blue = args[2].getNumber().floatValue(); /* Verify rgb replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("sRGB color values out of range. " + "Arguments to rgb-named-color() must be [0..255] or [0%..100%]"); } // rgb-named-color is replaced with fop-rgb-named-color which has an extra argument // containing the color profile src attribute as it is defined in the color-profile // declarations element. StringBuffer sb = new StringBuffer(); sb.append("fop-rgb-named-color("); sb.append(red / 255f); sb.append(',').append(green / 255f); sb.append(',').append(blue / 255f); sb.append(',').append(colorProfileName); sb.append(',').append(cp.getSrc()); sb.append(", '").append(colorName).append('\''); sb.append(")"); return ColorProperty.getInstance(pInfo.getUserAgent(), sb.toString()); }
// in src/java/org/apache/fop/fo/expr/CeilingFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number dbl = args[0].getNumber(); if (dbl == null) { throw new PropertyException("Non number operand to ceiling function"); } return NumberProperty.getInstance(Math.ceil(dbl.doubleValue())); }
// in src/java/org/apache/fop/fo/expr/ProportionalColumnWidthFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number d = args[0].getNumber(); if (d == null) { throw new PropertyException("Non numeric operand to " + "proportional-column-width() function."); } PropertyList pList = pInfo.getPropertyList(); if (!"fo:table-column".equals(pList.getFObj().getName())) { throw new PropertyException("proportional-column-width() function " + "may only be used on fo:table-column."); } Table t = (Table) pList.getParentFObj(); if (t.isAutoLayout()) { throw new PropertyException("proportional-column-width() function " + "may only be used when fo:table has " + "table-layout=\"fixed\"."); } return new TableColLength(d.doubleValue(), pInfo.getFO()); }
// in src/java/org/apache/fop/fo/expr/InheritedPropFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { String propName = args[0].getString(); if (propName == null) { throw new PropertyException("Incorrect parameter to inherited-property-value function"); } int propId = FOPropertyMapping.getPropertyId(propName); if (propId < 0) { throw new PropertyException( "Unknown property name used with inherited-property-value function: " + propName); } return pInfo.getPropertyList().getInherited(propId); }
// in src/java/org/apache/fop/util/ColorUtil.java
public static Color parseColorString(FOUserAgent foUserAgent, String value) throws PropertyException { if (value == null) { return null; } Color parsedColor = colorMap.get(value.toLowerCase()); if (parsedColor == null) { if (value.startsWith("#")) { parsedColor = parseWithHash(value); } else if (value.startsWith("rgb(")) { parsedColor = parseAsRGB(value); } else if (value.startsWith("url(")) { throw new PropertyException( "Colors starting with url( are not yet supported!"); } else if (value.startsWith("java.awt.Color")) { parsedColor = parseAsJavaAWTColor(value); } else if (value.startsWith("system-color(")) { parsedColor = parseAsSystemColor(value); } else if (value.startsWith("fop-rgb-icc")) { parsedColor = parseAsFopRgbIcc(foUserAgent, value); } else if (value.startsWith("fop-rgb-named-color")) { parsedColor = parseAsFopRgbNamedColor(foUserAgent, value); } else if (value.startsWith("cie-lab-color")) { parsedColor = parseAsCIELabColor(foUserAgent, value); } else if (value.startsWith("cmyk")) { parsedColor = parseAsCMYK(value); } if (parsedColor == null) { throw new PropertyException("Unknown Color: " + value); } colorMap.put(value, parsedColor); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsSystemColor(String value) throws PropertyException { int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); } else { throw new PropertyException("Unknown color format: " + value + ". Must be system-color(x)"); } return colorMap.get(value); }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsJavaAWTColor(String value) throws PropertyException { float red = 0.0f; float green = 0.0f; float blue = 0.0f; int poss = value.indexOf("["); int pose = value.indexOf("]"); try { if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); String[] args = value.split(","); if (args.length != 3) { throw new PropertyException( "Invalid number of arguments for a java.awt.Color: " + value); } red = Float.parseFloat(args[0].trim().substring(2)) / 255f; green = Float.parseFloat(args[1].trim().substring(2)) / 255f; blue = Float.parseFloat(args[2].trim().substring(2)) / 255f; if ((red < 0.0 || red > 1.0) || (green < 0.0 || green > 1.0) || (blue < 0.0 || blue > 1.0)) { throw new PropertyException("Color values out of range"); } } else { throw new IllegalArgumentException( "Invalid format for a java.awt.Color: " + value); } } catch (RuntimeException re) { throw new PropertyException(re); } return new Color(red, green, blue); }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsRGB(String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); try { String[] args = value.split(","); if (args.length != 3) { throw new PropertyException( "Invalid number of arguments: rgb(" + value + ")"); } float red = parseComponent255(args[0], value); float green = parseComponent255(args[1], value); float blue = parseComponent255(args[2], value); //Convert to ints to synchronize the behaviour with toRGBFunctionCall() int r = (int)(red * 255 + 0.5); int g = (int)(green * 255 + 0.5); int b = (int)(blue * 255 + 0.5); parsedColor = new Color(r, g, b); } catch (RuntimeException re) { //wrap in a PropertyException throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be rgb(r,g,b)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static float parseComponent255(String str, String function) throws PropertyException { float component; str = str.trim(); if (str.endsWith("%")) { component = Float.parseFloat(str.substring(0, str.length() - 1)) / 100f; } else { component = Float.parseFloat(str) / 255f; } if ((component < 0.0 || component > 1.0)) { throw new PropertyException("Color value out of range for " + function + ": " + str + ". Valid range: [0..255] or [0%..100%]"); } return component; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static float parseComponent(String argument, float min, float max, String function) throws PropertyException { float component = Float.parseFloat(argument.trim()); if ((component < min || component > max)) { throw new PropertyException("Color value out of range for " + function + ": " + argument + ". Valid range: [" + min + ".." + max + "]"); } return component; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseWithHash(String value) throws PropertyException { Color parsedColor; try { int len = value.length(); int alpha; if (len == 5 || len == 9) { alpha = Integer.parseInt( value.substring((len == 5) ? 3 : 7), 16); } else { alpha = 0xFF; } int red = 0; int green = 0; int blue = 0; if ((len == 4) || (len == 5)) { //multiply by 0x11 = 17 = 255/15 red = Integer.parseInt(value.substring(1, 2), 16) * 0x11; green = Integer.parseInt(value.substring(2, 3), 16) * 0x11; blue = Integer.parseInt(value.substring(3, 4), 16) * 0X11; } else if ((len == 7) || (len == 9)) { red = Integer.parseInt(value.substring(1, 3), 16); green = Integer.parseInt(value.substring(3, 5), 16); blue = Integer.parseInt(value.substring(5, 7), 16); } else { throw new NumberFormatException(); } parsedColor = new Color(red, green, blue, alpha); } catch (RuntimeException re) { throw new PropertyException("Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsFopRgbIcc(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { String[] args = value.substring(poss + 1, pose).split(","); try { if (args.length < 5) { throw new PropertyException("Too few arguments for rgb-icc() function"); } //Set up fallback sRGB value Color sRGB = parseFallback(args, value); /* Get and verify ICC profile name */ String iccProfileName = args[3].trim(); if (iccProfileName == null || "".equals(iccProfileName)) { throw new PropertyException("ICC profile name missing"); } ColorSpace colorSpace = null; String iccProfileSrc = null; if (isPseudoProfile(iccProfileName)) { if (CMYK_PSEUDO_PROFILE.equalsIgnoreCase(iccProfileName)) { colorSpace = ColorSpaces.getDeviceCMYKColorSpace(); } else if (SEPARATION_PSEUDO_PROFILE.equalsIgnoreCase(iccProfileName)) { colorSpace = new NamedColorSpace(args[5], sRGB, SEPARATION_PSEUDO_PROFILE, null); } else { assert false : "Incomplete implementation"; } } else { /* Get and verify ICC profile source */ iccProfileSrc = args[4].trim(); if (iccProfileSrc == null || "".equals(iccProfileSrc)) { throw new PropertyException("ICC profile source missing"); } iccProfileSrc = unescapeString(iccProfileSrc); } /* ICC profile arguments */ int componentStart = 4; if (colorSpace instanceof NamedColorSpace) { componentStart++; } float[] iccComponents = new float[args.length - componentStart - 1]; for (int ix = componentStart; ++ix < args.length;) { iccComponents[ix - componentStart - 1] = Float.parseFloat(args[ix].trim()); } if (colorSpace instanceof NamedColorSpace && iccComponents.length == 0) { iccComponents = new float[] {1.0f}; //full tint if not specified } /* Ask FOP factory to get ColorSpace for the specified ICC profile source */ if (foUserAgent != null && iccProfileSrc != null) { RenderingIntent renderingIntent = RenderingIntent.AUTO; //TODO connect to fo:color-profile/@rendering-intent colorSpace = foUserAgent.getFactory().getColorSpaceCache().get( iccProfileName, foUserAgent.getBaseURL(), iccProfileSrc, renderingIntent); } if (colorSpace != null) { // ColorSpace is available if (ColorSpaces.isDeviceColorSpace(colorSpace)) { //Device-specific colors are handled differently: //sRGB is the primary color with the CMYK as the alternative Color deviceColor = new Color(colorSpace, iccComponents, 1.0f); float[] rgbComps = sRGB.getRGBColorComponents(null); parsedColor = new ColorWithAlternatives( rgbComps[0], rgbComps[1], rgbComps[2], new Color[] {deviceColor}); } else { parsedColor = new ColorWithFallback( colorSpace, iccComponents, 1.0f, null, sRGB); } } else { // ICC profile could not be loaded - use rgb replacement values */ log.warn("Color profile '" + iccProfileSrc + "' not found. Using sRGB replacement values."); parsedColor = sRGB; } } catch (RuntimeException re) { throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be fop-rgb-icc(r,g,b,NCNAME,src,....)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsFopRgbNamedColor(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { String[] args = value.substring(poss + 1, pose).split(","); try { if (args.length != 6) { throw new PropertyException("rgb-named-color() function must have 6 arguments"); } //Set up fallback sRGB value Color sRGB = parseFallback(args, value); /* Get and verify ICC profile name */ String iccProfileName = args[3].trim(); if (iccProfileName == null || "".equals(iccProfileName)) { throw new PropertyException("ICC profile name missing"); } ICC_ColorSpace colorSpace = null; String iccProfileSrc; if (isPseudoProfile(iccProfileName)) { throw new IllegalArgumentException( "Pseudo-profiles are not allowed with fop-rgb-named-color()"); } else { /* Get and verify ICC profile source */ iccProfileSrc = args[4].trim(); if (iccProfileSrc == null || "".equals(iccProfileSrc)) { throw new PropertyException("ICC profile source missing"); } iccProfileSrc = unescapeString(iccProfileSrc); } // color name String colorName = unescapeString(args[5].trim()); /* Ask FOP factory to get ColorSpace for the specified ICC profile source */ if (foUserAgent != null && iccProfileSrc != null) { RenderingIntent renderingIntent = RenderingIntent.AUTO; //TODO connect to fo:color-profile/@rendering-intent colorSpace = (ICC_ColorSpace)foUserAgent.getFactory().getColorSpaceCache().get( iccProfileName, foUserAgent.getBaseURL(), iccProfileSrc, renderingIntent); } if (colorSpace != null) { ICC_Profile profile = colorSpace.getProfile(); if (NamedColorProfileParser.isNamedColorProfile(profile)) { NamedColorProfileParser parser = new NamedColorProfileParser(); NamedColorProfile ncp = parser.parseProfile(profile, iccProfileName, iccProfileSrc); NamedColorSpace ncs = ncp.getNamedColor(colorName); if (ncs != null) { parsedColor = new ColorWithFallback(ncs, new float[] {1.0f}, 1.0f, null, sRGB); } else { log.warn("Color '" + colorName + "' does not exist in named color profile: " + iccProfileSrc); parsedColor = sRGB; } } else { log.warn("ICC profile is no named color profile: " + iccProfileSrc); parsedColor = sRGB; } } else { // ICC profile could not be loaded - use rgb replacement values */ log.warn("Color profile '" + iccProfileSrc + "' not found. Using sRGB replacement values."); parsedColor = sRGB; } } catch (IOException ioe) { //wrap in a PropertyException throw new PropertyException(ioe); } catch (RuntimeException re) { throw new PropertyException(re); //wrap in a PropertyException } } else { throw new PropertyException("Unknown color format: " + value + ". Must be fop-rgb-named-color(r,g,b,NCNAME,src,color-name)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsCIELabColor(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { try { String[] args = value.substring(poss + 1, pose).split(","); if (args.length != 6) { throw new PropertyException("cie-lab-color() function must have 6 arguments"); } //Set up fallback sRGB value float red = parseComponent255(args[0], value); float green = parseComponent255(args[1], value); float blue = parseComponent255(args[2], value); Color sRGB = new Color(red, green, blue); float l = parseComponent(args[3], 0f, 100f, value); float a = parseComponent(args[4], -127f, 127f, value); float b = parseComponent(args[5], -127f, 127f, value); //Assuming the XSL-FO spec uses the D50 white point CIELabColorSpace cs = ColorSpaces.getCIELabColorSpaceD50(); //use toColor() to have components normalized Color labColor = cs.toColor(l, a, b, 1.0f); //Convert to ColorWithFallback parsedColor = new ColorWithFallback(labColor, sRGB); } catch (RuntimeException re) { throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be cie-lab-color(r,g,b,Lightness,a-value,b-value)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsCMYK(String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); String[] args = value.split(","); try { if (args.length != 4) { throw new PropertyException( "Invalid number of arguments: cmyk(" + value + ")"); } float cyan = parseComponent1(args[0], value); float magenta = parseComponent1(args[1], value); float yellow = parseComponent1(args[2], value); float black = parseComponent1(args[3], value); float[] comps = new float[] {cyan, magenta, yellow, black}; Color cmykColor = DeviceCMYKColorSpace.createCMYKColor(comps); float[] rgbComps = cmykColor.getRGBColorComponents(null); parsedColor = new ColorWithAlternatives(rgbComps[0], rgbComps[1], rgbComps[2], new Color[] {cmykColor}); } catch (RuntimeException re) { throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be cmyk(c,m,y,k)"); } return parsedColor; }
9
            
// in src/java/org/apache/fop/fo/properties/URIProperty.java
catch (URISyntaxException use) { // Let PropertyList propagate the exception throw new PropertyException("Invalid URI specified"); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { //wrap in a PropertyException throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException("Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA"); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (IOException ioe) { //wrap in a PropertyException throw new PropertyException(ioe); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); //wrap in a PropertyException }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
182
            
// in src/java/org/apache/fop/fo/StaticPropertyList.java
public Property get(int propId, boolean bTryInherit, boolean bTryDefault) throws PropertyException { Property p = values[propId]; if (p == null) { p = super.get(propId, bTryInherit, bTryDefault); values[propId] = p; } return p; }
// in src/java/org/apache/fop/fo/properties/PageDimensionMaker.java
public Property get(int subpropId, PropertyList propertyList, boolean tryInherit, boolean tryDefault) throws PropertyException { Property p = super.get(0, propertyList, tryInherit, tryDefault); FObj fo = propertyList.getFObj(); String fallbackValue = (propId == Constants.PR_PAGE_HEIGHT) ? fo.getUserAgent().getPageHeight() : fo.getUserAgent().getPageWidth(); if (p.getEnum() == Constants.EN_INDEFINITE) { int otherId = (propId == Constants.PR_PAGE_HEIGHT) ? Constants.PR_PAGE_WIDTH : Constants.PR_PAGE_HEIGHT; int writingMode = propertyList.get(Constants.PR_WRITING_MODE).getEnum(); int refOrientation = propertyList.get(Constants.PR_REFERENCE_ORIENTATION) .getNumeric().getValue(); if (propertyList.getExplicit(otherId) != null && propertyList.getExplicit(otherId).getEnum() == Constants.EN_INDEFINITE) { //both set to "indefinite": //determine which one of the two defines the dimension //in block-progression-direction, and set the other to //"auto" if ((writingMode != Constants.EN_TB_RL && (refOrientation == 0 || refOrientation == 180 || refOrientation == -180)) || (writingMode == Constants.EN_TB_RL && (refOrientation == 90 || refOrientation == 270 || refOrientation == -270))) { //set page-width to "auto" = use the fallback from FOUserAgent if (propId == Constants.PR_PAGE_WIDTH) { Property.log.warn("Both page-width and page-height set to " + "\"indefinite\". Forcing page-width to \"auto\""); return make(propertyList, fallbackValue, fo); } } else { //set page-height to "auto" = use fallback from FOUserAgent Property.log.warn("Both page-width and page-height set to " + "\"indefinite\". Forcing page-height to \"auto\""); if (propId == Constants.PR_PAGE_HEIGHT) { return make(propertyList, fallbackValue, fo); } } } } else if (p.isAuto()) { return make(propertyList, fallbackValue, fo); } return p; }
// in src/java/org/apache/fop/fo/properties/LengthProperty.java
Override public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof EnumProperty) { return new EnumLength(p); } if (p instanceof LengthProperty) { return p; } if (p instanceof NumberProperty) { //Assume pixels (like in HTML) when there's no unit float resolution = propertyList.getFObj().getUserAgent().getSourceResolution(); return FixedLength.getInstance( p.getNumeric().getNumericValue(), "px", UnitConv.IN2PT / resolution); } Length val = p.getLength(); if (val != null) { return (Property) val; } /* always null ?? */ return convertPropertyDatatype(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/TextDecorationMaker.java
Override public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { ListProperty listProp = (ListProperty) super.convertProperty(p, propertyList, fo); List lst = listProp.getList(); boolean none = false; boolean under = false; boolean over = false; boolean through = false; boolean blink = false; int enumValue = -1; for (int i = lst.size(); --i >= 0;) { Property prop = (Property)lst.get(i); if (prop instanceof NCnameProperty) { prop = checkEnumValues(prop.getString()); lst.set(i, prop); } if (prop != null) { enumValue = prop.getEnum(); } switch (enumValue) { case Constants.EN_NONE: if (under | over | through | blink) { throw new PropertyException("Invalid combination of values"); } none = true; break; case Constants.EN_UNDERLINE: case Constants.EN_NO_UNDERLINE: case Constants.EN_OVERLINE: case Constants.EN_NO_OVERLINE: case Constants.EN_LINE_THROUGH: case Constants.EN_NO_LINE_THROUGH: case Constants.EN_BLINK: case Constants.EN_NO_BLINK: if (none) { throw new PropertyException ("'none' specified, no additional values allowed"); } switch (enumValue) { case Constants.EN_UNDERLINE: case Constants.EN_NO_UNDERLINE: if (!under) { under = true; continue; } case Constants.EN_OVERLINE: case Constants.EN_NO_OVERLINE: if (!over) { over = true; continue; } case Constants.EN_LINE_THROUGH: case Constants.EN_NO_LINE_THROUGH: if (!through) { through = true; continue; } case Constants.EN_BLINK: case Constants.EN_NO_BLINK: if (!blink) { blink = true; continue; } default: throw new PropertyException("Invalid combination of values"); } default: throw new PropertyException("Invalid value specified: " + p); } } return listProp; }
// in src/java/org/apache/fop/fo/properties/ColorProperty.java
Override public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof ColorProperty) { return p; } FObj fobj = (fo == null ? propertyList.getFObj() : fo); FOUserAgent ua = (fobj == null ? null : fobj.getUserAgent()); Color val = p.getColor(ua); if (val != null) { return new ColorProperty(val); } return convertPropertyDatatype(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/ColorProperty.java
public static ColorProperty getInstance(FOUserAgent foUserAgent, String value) throws PropertyException { ColorProperty instance = new ColorProperty( ColorUtil.parseColorString( foUserAgent, value)); return CACHE.fetch(instance); }
// in src/java/org/apache/fop/fo/properties/CommonFont.java
public static CommonFont getInstance(PropertyList pList) throws PropertyException { FontFamilyProperty fontFamily = (FontFamilyProperty) pList.get(Constants.PR_FONT_FAMILY); EnumProperty fontSelectionStrategy = (EnumProperty) pList.get(Constants.PR_FONT_SELECTION_STRATEGY); EnumProperty fontStretch = (EnumProperty) pList.get(Constants.PR_FONT_STRETCH); EnumProperty fontStyle = (EnumProperty) pList.get(Constants.PR_FONT_STYLE); EnumProperty fontVariant = (EnumProperty) pList.get(Constants.PR_FONT_VARIANT); EnumProperty fontWeight = (EnumProperty) pList.get(Constants.PR_FONT_WEIGHT); Numeric fontSizeAdjust = pList.get(Constants.PR_FONT_SIZE_ADJUST).getNumeric(); Length fontSize = pList.get(Constants.PR_FONT_SIZE).getLength(); CommonFont commonFont = new CommonFont(fontFamily, fontSelectionStrategy, fontStretch, fontStyle, fontVariant, fontWeight, fontSize, fontSizeAdjust); return CACHE.fetch(commonFont); }
// in src/java/org/apache/fop/fo/properties/KeepProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof KeepProperty) { return p; } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/FontShorthandParser.java
public Property getValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { int index = -1; Property newProp; switch (propId) { case Constants.PR_FONT_SIZE: index = 0; break; case Constants.PR_FONT_FAMILY: index = 1; break; case Constants.PR_LINE_HEIGHT: index = 2; break; case Constants.PR_FONT_STYLE: index = 3; break; case Constants.PR_FONT_VARIANT: index = 4; break; case Constants.PR_FONT_WEIGHT: index = 5; break; default: //nop } newProp = (Property) property.getList().get(index); return newProp; }
// in src/java/org/apache/fop/fo/properties/CondLengthProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof KeepProperty) { return p; } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/CompoundPropertyMaker.java
public Property get(int subpropertyId, PropertyList propertyList, boolean tryInherit, boolean tryDefault) throws PropertyException { Property p = super.get(subpropertyId, propertyList, tryInherit, tryDefault); if (subpropertyId != 0 && p != null) { p = getSubprop(p, subpropertyId); } return p; }
// in src/java/org/apache/fop/fo/properties/CompoundPropertyMaker.java
protected Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { // Delegate to the subproperty maker to do conversions. p = shorthandMaker.convertProperty(p, propertyList, fo); if (p != null) { Property prop = makeCompound(propertyList, fo); CompoundDatatype pval = (CompoundDatatype) prop.getObject(); for (int i = 0; i < Constants.COMPOUND_COUNT; i++) { PropertyMaker submaker = subproperties[i]; if (submaker != null && submaker.setByShorthand) { pval.setComponent(submaker.getPropId() & Constants.COMPOUND_MASK, p, false); } } return prop; } return null; }
// in src/java/org/apache/fop/fo/properties/CompoundPropertyMaker.java
public Property make(PropertyList propertyList) throws PropertyException { if (defaultValue != null) { return make(propertyList, defaultValue, propertyList.getParentFObj()); } else { return makeCompound(propertyList, propertyList.getParentFObj()); } }
// in src/java/org/apache/fop/fo/properties/CompoundPropertyMaker.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { Property p = super.make(propertyList, value, fo); p = convertProperty(p, propertyList, fo); return p; }
// in src/java/org/apache/fop/fo/properties/CompoundPropertyMaker.java
public Property make(Property baseProperty, int subpropertyId, PropertyList propertyList, String value, FObj fo) throws PropertyException { if (baseProperty == null) { baseProperty = makeCompound(propertyList, fo); } PropertyMaker spMaker = getSubpropMaker(subpropertyId); if (spMaker != null) { Property p = spMaker.make(propertyList, value, fo); if (p != null) { return setSubprop(baseProperty, subpropertyId & Constants.COMPOUND_MASK, p); } } else { //getLogger().error("compound property component " // + partName + " unknown."); } return baseProperty; }
// in src/java/org/apache/fop/fo/properties/CompoundPropertyMaker.java
protected Property makeCompound(PropertyList propertyList, FObj parentFO) throws PropertyException { Property p = makeNewProperty(); CompoundDatatype data = (CompoundDatatype) p.getObject(); for (int i = 0; i < Constants.COMPOUND_COUNT; i++) { PropertyMaker subpropertyMaker = subproperties[i]; if (subpropertyMaker != null) { Property subproperty = subpropertyMaker.make(propertyList); data.setComponent(subpropertyMaker.getPropId() & Constants.COMPOUND_MASK, subproperty, true); } } return p; }
// in src/java/org/apache/fop/fo/properties/SpaceProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof SpaceProperty) { return p; } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/EnumNumber.java
public double getNumericValue(PercentBaseContext context) throws PropertyException { log.error("getNumericValue() called on " + enumProperty + " number"); return 0; }
// in src/java/org/apache/fop/fo/properties/IndentPropertyMaker.java
public Property compute(PropertyList propertyList) throws PropertyException { if (propertyList.getFObj().getUserAgent() .isBreakIndentInheritanceOnReferenceAreaBoundary()) { return computeAlternativeRuleset(propertyList); } else { return computeConforming(propertyList); } }
// in src/java/org/apache/fop/fo/properties/IndentPropertyMaker.java
public Property computeConforming(PropertyList propertyList) throws PropertyException { PropertyList pList = getWMPropertyList(propertyList); if (pList == null) { return null; } // Calculate the values as described in 5.3.2. Numeric padding = getCorresponding(paddingCorresponding, propertyList).getNumeric(); Numeric border = getCorresponding(borderWidthCorresponding, propertyList).getNumeric(); int marginProp = pList.selectFromWritingMode(lrtb, rltb, tbrl, tblr); // Calculate the absolute margin. if (propertyList.getExplicitOrShorthand(marginProp) == null) { Property indent = propertyList.getExplicit(baseMaker.propId); if (indent == null) { //Neither indent nor margin is specified, use inherited return null; } else { //Use explicit indent directly return indent; } } else { //Margin is used Numeric margin = propertyList.get(marginProp).getNumeric(); Numeric v = FixedLength.ZERO_FIXED_LENGTH; if (!propertyList.getFObj().generatesReferenceAreas()) { // The inherited_value_of([start|end]-indent) v = NumericOp.addition(v, propertyList.getInherited(baseMaker.propId).getNumeric()); } // The corresponding absolute margin-[right|left}. v = NumericOp.addition(v, margin); v = NumericOp.addition(v, padding); v = NumericOp.addition(v, border); return (Property) v; } }
// in src/java/org/apache/fop/fo/properties/IndentPropertyMaker.java
public Property computeAlternativeRuleset(PropertyList propertyList) throws PropertyException { PropertyList pList = getWMPropertyList(propertyList); if (pList == null) { return null; } // Calculate the values as described in 5.3.2. Numeric padding = getCorresponding(paddingCorresponding, propertyList).getNumeric(); Numeric border = getCorresponding(borderWidthCorresponding, propertyList).getNumeric(); int marginProp = pList.selectFromWritingMode(lrtb, rltb, tbrl, tblr); //Determine whether the nearest anscestor indent was specified through //start-indent|end-indent or through a margin property. boolean marginNearest = false; PropertyList pl = propertyList.getParentPropertyList(); while (pl != null) { if (pl.getExplicit(baseMaker.propId) != null) { break; } else if (pl.getExplicitOrShorthand(marginProp) != null) { marginNearest = true; break; } pl = pl.getParentPropertyList(); } // Calculate the absolute margin. if (propertyList.getExplicitOrShorthand(marginProp) == null) { Property indent = propertyList.getExplicit(baseMaker.propId); if (indent == null) { //Neither start-indent nor margin is specified, use inherited if (isInherited(propertyList) || !marginNearest) { return null; } else { return FixedLength.ZERO_FIXED_LENGTH; } } else { return indent; } } else { //Margin is used Numeric margin = propertyList.get(marginProp).getNumeric(); Numeric v = FixedLength.ZERO_FIXED_LENGTH; if (isInherited(propertyList)) { // The inherited_value_of([start|end]-indent) v = NumericOp.addition(v, propertyList.getInherited(baseMaker.propId).getNumeric()); } // The corresponding absolute margin-[right|left}. v = NumericOp.addition(v, margin); v = NumericOp.addition(v, padding); v = NumericOp.addition(v, border); return (Property) v; } }
// in src/java/org/apache/fop/fo/properties/IndentPropertyMaker.java
private Property getCorresponding(int[] corresponding, PropertyList propertyList) throws PropertyException { PropertyList pList = getWMPropertyList(propertyList); if (pList != null) { int wmcorr = pList.selectFromWritingMode ( corresponding[0], corresponding[1], corresponding[2], corresponding[3] ); return propertyList.get(wmcorr); } else { return null; } }
// in src/java/org/apache/fop/fo/properties/SpacingPropertyMaker.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p.getEnum() == Constants.EN_NORMAL) { return p; } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/LineHeightPropertyMaker.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { /* if value was specified as a number/length/percentage then * conditionality and precedence components are overridden */ Property p = super.make(propertyList, value, fo); p.getSpace().setConditionality( EnumProperty.getInstance(Constants.EN_RETAIN, "RETAIN"), true); p.getSpace().setPrecedence( EnumProperty.getInstance(Constants.EN_FORCE, "FORCE"), true); return p; }
// in src/java/org/apache/fop/fo/properties/LineHeightPropertyMaker.java
protected Property compute(PropertyList propertyList) throws PropertyException { // recalculate based on last specified value // Climb up propertylist and find last spec'd value Property specProp = propertyList.getNearestSpecified(propId); if (specProp != null) { String specVal = specProp.getSpecifiedValue(); if (specVal != null) { return make(propertyList, specVal, propertyList.getParentFObj()); } } return null; }
// in src/java/org/apache/fop/fo/properties/LineHeightPropertyMaker.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { Numeric numval = p.getNumeric(); if (numval != null && numval.getDimension() == 0) { if (getPercentBase(propertyList) instanceof LengthBase) { Length base = ((LengthBase)getPercentBase(propertyList)).getBaseLength(); if (base != null && base.isAbsolute()) { p = FixedLength.getInstance( numval.getNumericValue() * base.getNumericValue()); } else { p = new PercentLength( numval.getNumericValue(), getPercentBase(propertyList)); } } Property spaceProp = super.convertProperty(p, propertyList, fo); spaceProp.setSpecifiedValue(String.valueOf(numval.getNumericValue())); return spaceProp; } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/ListProperty.java
Override public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof ListProperty) { return p; } else { return new ListProperty(p); } }
// in src/java/org/apache/fop/fo/properties/BackgroundPositionShorthand.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { Property p = super.make(propertyList, value, fo); if (p.getList().size() == 1) { /* only background-position-horizontal specified * through the shorthand, as a length or percentage: * background-position-vertical=50% (see: XSL-FO 1.1 -- 7.31.2) */ PropertyMaker m = FObj.getPropertyMakerFor( Constants.PR_BACKGROUND_POSITION_VERTICAL); p.getList().add(1, m.make(propertyList, "50%", fo)); } return p; }
// in src/java/org/apache/fop/fo/properties/BackgroundPositionShorthand.java
public int getBaseLength(PercentBaseContext context) throws PropertyException { return 0; }
// in src/java/org/apache/fop/fo/properties/BackgroundPositionShorthand.java
public Property getValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { int index = -1; List propList = property.getList(); if (propId == Constants.PR_BACKGROUND_POSITION_HORIZONTAL) { index = 0; } else if (propId == Constants.PR_BACKGROUND_POSITION_VERTICAL) { index = 1; } if (index >= 0) { return maker.convertProperty( (Property) propList.get(index), propertyList, propertyList.getFObj()); } // else: invalid index? shouldn't happen... return null; }
// in src/java/org/apache/fop/fo/properties/CommonTextDecoration.java
public static CommonTextDecoration createFromPropertyList(PropertyList pList) throws PropertyException { return calcTextDecoration(pList); }
// in src/java/org/apache/fop/fo/properties/CommonTextDecoration.java
private static CommonTextDecoration calcTextDecoration(PropertyList pList) throws PropertyException { CommonTextDecoration deco = null; PropertyList parentList = pList.getParentPropertyList(); if (parentList != null) { //Parent is checked first deco = calcTextDecoration(parentList); } //For rules, see XSL 1.0, chapters 5.5.6 and 7.16.4 Property textDecoProp = pList.getExplicit(Constants.PR_TEXT_DECORATION); if (textDecoProp != null) { List list = textDecoProp.getList(); Iterator i = list.iterator(); while (i.hasNext()) { Property prop = (Property)i.next(); int propEnum = prop.getEnum(); FOUserAgent ua = (pList == null) ? null : (pList.getFObj() == null ? null : pList.getFObj().getUserAgent()); if (propEnum == Constants.EN_NONE) { if (deco != null) { deco.decoration = 0; } return deco; } else if (propEnum == Constants.EN_UNDERLINE) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= UNDERLINE; deco.underColor = pList.get(Constants.PR_COLOR).getColor(ua); } else if (propEnum == Constants.EN_NO_UNDERLINE) { if (deco != null) { deco.decoration &= OVERLINE | LINE_THROUGH | BLINK; deco.underColor = pList.get(Constants.PR_COLOR).getColor(ua); } } else if (propEnum == Constants.EN_OVERLINE) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= OVERLINE; deco.overColor = pList.get(Constants.PR_COLOR).getColor(ua); } else if (propEnum == Constants.EN_NO_OVERLINE) { if (deco != null) { deco.decoration &= UNDERLINE | LINE_THROUGH | BLINK; deco.overColor = pList.get(Constants.PR_COLOR).getColor(ua); } } else if (propEnum == Constants.EN_LINE_THROUGH) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= LINE_THROUGH; deco.throughColor = pList.get(Constants.PR_COLOR).getColor(ua); } else if (propEnum == Constants.EN_NO_LINE_THROUGH) { if (deco != null) { deco.decoration &= UNDERLINE | OVERLINE | BLINK; deco.throughColor = pList.get(Constants.PR_COLOR).getColor(ua); } } else if (propEnum == Constants.EN_BLINK) { if (deco == null) { deco = new CommonTextDecoration(); } deco.decoration |= BLINK; } else if (propEnum == Constants.EN_NO_BLINK) { if (deco != null) { deco.decoration &= UNDERLINE | OVERLINE | LINE_THROUGH; } } else { throw new PropertyException("Illegal value encountered: " + prop.getString()); } } } return deco; }
// in src/java/org/apache/fop/fo/properties/CommonAccessibility.java
public static CommonAccessibility getInstance(PropertyList propertyList) throws PropertyException { String sourceDocument = propertyList.get(Constants.PR_SOURCE_DOCUMENT).getString(); if ("none".equals(sourceDocument)) { sourceDocument = null; } String role = propertyList.get(Constants.PR_ROLE).getString(); if ("none".equals(role)) { role = null; } if (sourceDocument == null && role == null) { return DEFAULT_INSTANCE; } else { return new CommonAccessibility(sourceDocument, role); } }
// in src/java/org/apache/fop/fo/properties/URIProperty.java
Override public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { Property p = null; //special treament for data: URIs if (value.matches("(?s)^(url\\(('|\")?)?data:.*$")) { p = new URIProperty(value, false); } else { try { URI specifiedURI = new URI(URISpecification.escapeURI(value)); URIProperty xmlBase = (URIProperty)propertyList.get(PR_X_XML_BASE, true, false); if (xmlBase == null) { //xml:base undefined if (this.propId == PR_X_XML_BASE) { //if current property is xml:base, define a new one p = new URIProperty(specifiedURI); p.setSpecifiedValue(value); } else { //otherwise, just store the specified value (for backward compatibility) p = new URIProperty(value, false); } } else { //xml:base defined, so resolve p = new URIProperty(xmlBase.resolvedURI.resolve(specifiedURI)); p.setSpecifiedValue(value); } } catch (URISyntaxException use) { // Let PropertyList propagate the exception throw new PropertyException("Invalid URI specified"); } } return p; }
// in src/java/org/apache/fop/fo/properties/FontWeightPropertyMaker.java
public Property make(PropertyList pList, String value, FObj fo) throws PropertyException { if ("inherit".equals(value)) { return super.make(pList, value, fo); } else { String pValue = checkValueKeywords(value); Property newProp = checkEnumValues(pValue); int enumValue = ( newProp != null ) ? newProp.getEnum() : -1; if (enumValue == Constants.EN_BOLDER || enumValue == Constants.EN_LIGHTER) { /* check for relative enum values, compute in relation to parent */ Property parentProp = pList.getInherited(Constants.PR_FONT_WEIGHT); if (enumValue == Constants.EN_BOLDER) { enumValue = parentProp.getEnum(); switch (enumValue) { case Constants.EN_100: newProp = EnumProperty.getInstance(Constants.EN_200, "200"); break; case Constants.EN_200: newProp = EnumProperty.getInstance(Constants.EN_300, "300"); break; case Constants.EN_300: newProp = EnumProperty.getInstance(Constants.EN_400, "400"); break; case Constants.EN_400: newProp = EnumProperty.getInstance(Constants.EN_500, "500"); break; case Constants.EN_500: newProp = EnumProperty.getInstance(Constants.EN_600, "600"); break; case Constants.EN_600: newProp = EnumProperty.getInstance(Constants.EN_700, "700"); break; case Constants.EN_700: newProp = EnumProperty.getInstance(Constants.EN_800, "800"); break; case Constants.EN_800: case Constants.EN_900: newProp = EnumProperty.getInstance(Constants.EN_900, "900"); break; default: //nop } } else { enumValue = parentProp.getEnum(); switch (enumValue) { case Constants.EN_100: case Constants.EN_200: newProp = EnumProperty.getInstance(Constants.EN_100, "100"); break; case Constants.EN_300: newProp = EnumProperty.getInstance(Constants.EN_200, "200"); break; case Constants.EN_400: newProp = EnumProperty.getInstance(Constants.EN_300, "300"); break; case Constants.EN_500: newProp = EnumProperty.getInstance(Constants.EN_400, "400"); break; case Constants.EN_600: newProp = EnumProperty.getInstance(Constants.EN_500, "500"); break; case Constants.EN_700: newProp = EnumProperty.getInstance(Constants.EN_600, "600"); break; case Constants.EN_800: newProp = EnumProperty.getInstance(Constants.EN_700, "700"); break; case Constants.EN_900: newProp = EnumProperty.getInstance(Constants.EN_800, "800"); break; default: //nop } } } else if (enumValue == -1) { /* neither a keyword, nor an enum * still maybe a valid expression, so send it through the parser... */ newProp = PropertyParser.parse(value, new PropertyInfo(this, pList)); } if (newProp != null) { newProp = convertProperty(newProp, pList, fo); } return newProp; } }
// in src/java/org/apache/fop/fo/properties/EnumProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof EnumProperty) { return p; } else { return super.convertProperty(p, propertyList, fo); } }
// in src/java/org/apache/fop/fo/properties/BorderWidthPropertyMaker.java
public Property get(int subpropId, PropertyList propertyList, boolean bTryInherit, boolean bTryDefault) throws PropertyException { Property p = super.get(subpropId, propertyList, bTryInherit, bTryDefault); // Calculate the values as described in 7.7.20. Property style = propertyList.get(borderStyleId); if (style.getEnum() == Constants.EN_NONE) { return FixedLength.ZERO_FIXED_LENGTH; } return p; }
// in src/java/org/apache/fop/fo/properties/FontStretchPropertyMaker.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { // if it is a relative font stretch value get current parent value and step // up or down accordingly if (p.getEnum() == EN_NARROWER) { return computeNextAbsoluteFontStretch(propertyList.getFromParent(this.getPropId()), -1); } else if (p.getEnum() == EN_WIDER) { return computeNextAbsoluteFontStretch(propertyList.getFromParent(this.getPropId()), 1); } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/TableBorderPrecedence.java
public Property make(PropertyList propertyList) throws PropertyException { FObj fo = propertyList.getFObj(); switch (fo.getNameId()) { case Constants.FO_TABLE: return num6; case Constants.FO_TABLE_CELL: return num5; case Constants.FO_TABLE_COLUMN: return num4; case Constants.FO_TABLE_ROW: return num3; case Constants.FO_TABLE_BODY: return num2; case Constants.FO_TABLE_HEADER: return num1; case Constants.FO_TABLE_FOOTER: return num0; default: return null; } }
// in src/java/org/apache/fop/fo/properties/LengthRangeProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof LengthRangeProperty) { return p; } if (this.propId == PR_BLOCK_PROGRESSION_DIMENSION || this.propId == PR_INLINE_PROGRESSION_DIMENSION) { Length len = p.getLength(); if (len != null) { if (isNegativeLength(len)) { log.warn(FObj.decorateWithContextInfo( "Replaced negative value (" + len + ") for " + getName() + " with 0mpt", fo)); p = FixedLength.ZERO_FIXED_LENGTH; } } } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { try { FontShorthandProperty newProp = new FontShorthandProperty(); newProp.setSpecifiedValue(value); String specVal = value; Property prop = null; if ("inherit".equals(specVal)) { /* fill the list with the individual properties from the parent */ for (int i = PROP_IDS.length; --i >= 0;) { prop = propertyList.getFromParent(PROP_IDS[i]); newProp.addProperty(prop, i); } } else { /* initialize list with nulls */ for (int pos = PROP_IDS.length; --pos >= 0;) { newProp.addProperty(null, pos); } prop = checkEnumValues(specVal); if (prop == null) { /* not an enum: * value should consist at least of font-size and font-family * separated by a space * mind the possible spaces from quoted font-family names */ int spaceIndex = value.indexOf(' '); int quoteIndex = (value.indexOf('\'') == -1) ? value.indexOf('\"') : value.indexOf('\''); if (spaceIndex == -1 || (quoteIndex != -1 && spaceIndex > quoteIndex)) { /* no spaces or first space appears after the first * single/double quote, so malformed value string */ throw new PropertyException("Invalid property value: " + "font=\"" + value + "\""); } PropertyMaker m = null; int fromIndex = spaceIndex + 1; int toIndex = specVal.length(); /* at least one space that appears before the first * single/double quote, so extract the individual properties */ boolean fontFamilyParsed = false; int commaIndex = value.indexOf(','); while (!fontFamilyParsed) { /* value contains a (list of) possibly quoted * font-family name(s) */ if (commaIndex == -1) { /* no list, just a single name * (or first name in the list) */ if (quoteIndex != -1) { /* a single name, quoted */ fromIndex = quoteIndex; } m = FObj.getPropertyMakerFor(PROP_IDS[1]); prop = m.make(propertyList, specVal.substring(fromIndex), fo); newProp.addProperty(prop, 1); fontFamilyParsed = true; } else { if (quoteIndex != -1 && quoteIndex < commaIndex) { /* a quoted font-family name as first name * in the comma-separated list * fromIndex = index of the first quote */ fromIndex = quoteIndex; quoteIndex = -1; } else { fromIndex = value.lastIndexOf(' ', commaIndex) + 1; } commaIndex = -1; } } toIndex = fromIndex - 1; fromIndex = value.lastIndexOf(' ', toIndex - 1) + 1; value = specVal.substring(fromIndex, toIndex); int slashIndex = value.indexOf('/'); String fontSize = value.substring(0, (slashIndex == -1) ? value.length() : slashIndex); m = FObj.getPropertyMakerFor(PROP_IDS[0]); prop = m.make(propertyList, fontSize, fo); /* need to make sure subsequent call to LineHeightPropertyMaker.make() * doesn't generate the default font-size property... */ propertyList.putExplicit(PROP_IDS[0], prop); newProp.addProperty(prop, 0); if (slashIndex != -1) { /* line-height */ String lineHeight = value.substring(slashIndex + 1); m = FObj.getPropertyMakerFor(PROP_IDS[2]); prop = m.make(propertyList, lineHeight, fo); newProp.addProperty(prop, 2); } if (fromIndex != 0) { toIndex = fromIndex - 1; value = specVal.substring(0, toIndex); fromIndex = 0; spaceIndex = value.indexOf(' '); do { toIndex = (spaceIndex == -1) ? value.length() : spaceIndex; String val = value.substring(fromIndex, toIndex); for (int i = 6; --i >= 3;) { if (newProp.list.get(i) == null) { /* not set */ m = FObj.getPropertyMakerFor(PROP_IDS[i]); val = m.checkValueKeywords(val); prop = m.checkEnumValues(val); if (prop != null) { newProp.addProperty(prop, i); } } } fromIndex = toIndex + 1; spaceIndex = value.indexOf(' ', fromIndex); } while (toIndex != value.length()); } } else { //TODO: implement enum values log.warn("Enum values other than \"inherit\"" + " not yet supported for the font shorthand."); return null; } } if (newProp.list.get(0) == null || newProp.list.get(1) == null) { throw new PropertyException("Invalid property value: " + "font-size and font-family are required for the font shorthand" + "\nfont=\"" + value + "\""); } return newProp; } catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; } }
// in src/java/org/apache/fop/fo/properties/GenericShorthandParser.java
public Property getValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { // Check for keyword "inherit" if (property.getList().size() == 1) { String sval = getElement(property, 0).getString(); if (sval != null && sval.equals("inherit")) { return propertyList.getFromParent(propId); } } return convertValueForProperty(propId, property, maker, propertyList); }
// in src/java/org/apache/fop/fo/properties/GenericShorthandParser.java
protected Property convertValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { Property prop = null; // Try each of the stored values in turn Iterator iprop = property.getList().iterator(); while (iprop.hasNext() && prop == null) { Property p = (Property)iprop.next(); prop = maker.convertShorthandProperty(propertyList, p, null); } return prop; }
// in src/java/org/apache/fop/fo/properties/ReferenceOrientationMaker.java
public Property get(int subpropId, PropertyList propertyList, boolean tryInherit, boolean tryDefault) throws PropertyException { Property p = super.get(0, propertyList, tryInherit, tryDefault); int ro = 0; if (p != null) { ro = p.getNumeric().getValue(); } if ((Math.abs(ro) % 90) == 0 && (Math.abs(ro) / 90) <= 3) { return p; } else { throw new PropertyException("Illegal property value: " + "reference-orientation=\"" + ro + "\" " + "on " + propertyList.getFObj().getName()); } }
// in src/java/org/apache/fop/fo/properties/CorrespondingPropertyMaker.java
public Property compute(PropertyList propertyList) throws PropertyException { PropertyList pList = getWMPropertyList(propertyList); if (pList == null) { return null; } int correspondingId = pList.selectFromWritingMode(lrtb, rltb, tbrl, tblr); Property p = propertyList.getExplicitOrShorthand(correspondingId); if (p != null) { FObj parentFO = propertyList.getParentFObj(); p = baseMaker.convertProperty(p, propertyList, parentFO); } return p; }
// in src/java/org/apache/fop/fo/properties/SpacePropertyMaker.java
public Property compute(PropertyList propertyList) throws PropertyException { Property prop = super.compute(propertyList); if (prop != null && prop instanceof SpaceProperty) { ((SpaceProperty)prop).setConditionality( EnumProperty.getInstance(Constants.EN_RETAIN, "RETAIN"), false); } return prop; }
// in src/java/org/apache/fop/fo/properties/CommonHyphenation.java
public static CommonHyphenation getInstance(PropertyList propertyList) throws PropertyException { StringProperty language = (StringProperty) propertyList.get(Constants.PR_LANGUAGE); StringProperty country = (StringProperty) propertyList.get(Constants.PR_COUNTRY); StringProperty script = (StringProperty) propertyList.get(Constants.PR_SCRIPT); EnumProperty hyphenate = (EnumProperty) propertyList.get(Constants.PR_HYPHENATE); CharacterProperty hyphenationCharacter = (CharacterProperty) propertyList.get(Constants.PR_HYPHENATION_CHARACTER); NumberProperty hyphenationPushCharacterCount = (NumberProperty) propertyList.get(Constants.PR_HYPHENATION_PUSH_CHARACTER_COUNT); NumberProperty hyphenationRemainCharacterCount = (NumberProperty) propertyList.get(Constants.PR_HYPHENATION_REMAIN_CHARACTER_COUNT); CommonHyphenation instance = new CommonHyphenation( language, country, script, hyphenate, hyphenationCharacter, hyphenationPushCharacterCount, hyphenationRemainCharacterCount); return CACHE.fetch(instance); }
// in src/java/org/apache/fop/fo/properties/FontSizePropertyMaker.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { Property p = super.make(propertyList, value, fo); if (p instanceof PercentLength) { Property pp = propertyList.getFromParent(this.propId); p = FixedLength.getInstance( pp.getLength().getValue() * ((PercentLength)p).getPercentage() / 100); } return p; }
// in src/java/org/apache/fop/fo/properties/FontSizePropertyMaker.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p.getEnum() == EN_LARGER || p.getEnum() == EN_SMALLER) { // get the corresponding property from parent Property pp = propertyList.getFromParent(this.propId); int baseFontSize = computeClosestAbsoluteFontSize(pp.getLength().getValue()); if (p.getEnum() == EN_LARGER) { return FixedLength.getInstance( Math.round(baseFontSize * FONT_SIZE_GROWTH_FACTOR)); } else { return FixedLength.getInstance( Math.round(baseFontSize / FONT_SIZE_GROWTH_FACTOR)); } } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
public static CommonBorderPaddingBackground getInstance(PropertyList pList) throws PropertyException { CommonBorderPaddingBackground newInstance = new CommonBorderPaddingBackground(pList); CommonBorderPaddingBackground cachedInstance = null; /* if padding-* and background-position-* resolve to absolute lengths * the whole instance can be cached */ if ((newInstance.padding[BEFORE] == null || newInstance.padding[BEFORE].getLength().isAbsolute()) && (newInstance.padding[AFTER] == null || newInstance.padding[AFTER].getLength().isAbsolute()) && (newInstance.padding[START] == null || newInstance.padding[START].getLength().isAbsolute()) && (newInstance.padding[END] == null || newInstance.padding[END].getLength().isAbsolute()) && (newInstance.backgroundPositionHorizontal == null || newInstance.backgroundPositionHorizontal.isAbsolute()) && (newInstance.backgroundPositionVertical == null || newInstance.backgroundPositionVertical.isAbsolute())) { cachedInstance = CACHE.fetch(newInstance); } synchronized (newInstance.backgroundImage.intern()) { /* for non-cached, or not-yet-cached instances, preload the image */ if ((cachedInstance == null || cachedInstance == newInstance) && !("".equals(newInstance.backgroundImage))) { //Additional processing: preload image String uri = URISpecification.getURL(newInstance.backgroundImage); FObj fobj = pList.getFObj(); FOUserAgent userAgent = pList.getFObj().getUserAgent(); ImageManager manager = userAgent.getFactory().getImageManager(); ImageSessionContext sessionContext = userAgent.getImageSessionContext(); ImageInfo info; try { info = manager.getImageInfo(uri, sessionContext); newInstance.backgroundImageInfo = info; } catch (ImageException e) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageError(fobj, uri, e, fobj.getLocator()); } catch (FileNotFoundException fnfe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageNotFound(fobj, uri, fnfe, fobj.getLocator()); } catch (IOException ioe) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( fobj.getUserAgent().getEventBroadcaster()); eventProducer.imageIOError(fobj, uri, ioe, fobj.getLocator()); } }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
private void initBorderInfo(PropertyList pList, int side, int colorProp, int styleProp, int widthProp, int paddingProp) throws PropertyException { padding[side] = pList.get(paddingProp).getCondLength(); // If style = none, force width to 0, don't get Color (spec 7.7.20) int style = pList.get(styleProp).getEnum(); if (style != Constants.EN_NONE) { FOUserAgent ua = pList.getFObj().getUserAgent(); setBorderInfo(BorderInfo.getInstance(style, pList.get(widthProp).getCondLength(), pList.get(colorProp).getColor(ua)), side); } }
// in src/java/org/apache/fop/fo/properties/PageBreakShorthandParser.java
public Property getValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { if (propId == Constants.PR_KEEP_WITH_PREVIOUS || propId == Constants.PR_KEEP_WITH_NEXT || propId == Constants.PR_KEEP_TOGETHER) { if (property.getEnum() == Constants.EN_AVOID) { return maker.make(null, Constants.CP_WITHIN_PAGE, propertyList, "always", propertyList.getFObj()); } } else if (propId == Constants.PR_BREAK_BEFORE || propId == Constants.PR_BREAK_AFTER) { switch (property.getEnum()) { case Constants.EN_ALWAYS: return EnumProperty.getInstance(Constants.EN_PAGE, "PAGE"); case Constants.EN_LEFT: return EnumProperty.getInstance(Constants.EN_EVEN_PAGE, "EVEN_PAGE"); case Constants.EN_RIGHT: return EnumProperty.getInstance(Constants.EN_ODD_PAGE, "ODD_PAGE"); case Constants.EN_AVOID: default: //nop; } } return null; }
// in src/java/org/apache/fop/fo/properties/WhiteSpaceShorthandParser.java
public Property getValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { switch (property.getEnum()) { case Constants.EN_PRE: switch (propId) { case Constants.PR_LINEFEED_TREATMENT: case Constants.PR_WHITE_SPACE_TREATMENT: return EnumProperty.getInstance(Constants.EN_PRESERVE, "PRESERVE"); case Constants.PR_WHITE_SPACE_COLLAPSE: return EnumProperty.getInstance(Constants.EN_FALSE, "FALSE"); case Constants.PR_WRAP_OPTION: return EnumProperty.getInstance(Constants.EN_NO_WRAP, "NO_WRAP"); default: //nop } case Constants.EN_NO_WRAP: if (propId == Constants.PR_WRAP_OPTION) { return EnumProperty.getInstance(Constants.EN_NO_WRAP, "NO_WRAP"); } case Constants.EN_NORMAL: default: //nop } return null; }
// in src/java/org/apache/fop/fo/properties/NumberProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof NumberProperty) { return p; } if (p instanceof EnumProperty) { return EnumNumber.getInstance(p); } Number val = p.getNumber(); if (val != null) { return getInstance(val.doubleValue()); } return convertPropertyDatatype(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/NumberProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof EnumProperty) { return EnumNumber.getInstance(p); } Number val = p.getNumber(); if (val != null) { int i = Math.round(val.floatValue()); if (i <= 0) { i = 1; } return getInstance(i); } return convertPropertyDatatype(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/BorderSpacingShorthandParser.java
protected Property convertValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { List lst = property.getList(); if (lst != null) { if (lst.size() == 1) { Property len = (Property)lst.get(0); return new LengthPairProperty(len); } else if (lst.size() == 2) { Property ipd = (Property)lst.get(0); Property bpd = (Property)lst.get(1); return new LengthPairProperty(ipd, bpd); } } throw new PropertyException("list with 1 or 2 length values expected"); }
// in src/java/org/apache/fop/fo/properties/LengthPairProperty.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof LengthPairProperty) { return p; } return super.convertProperty(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/properties/XMLLangShorthandParser.java
public Property getValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { String shorthandValue = property.getString(); int hyphenIndex = shorthandValue.indexOf(HYPHEN_MINUS); if (propId == Constants.PR_LANGUAGE) { if (hyphenIndex == -1) { /* only language specified; use the whole property */ return property; } else { /* use only the primary tag */ return StringProperty.getInstance( shorthandValue.substring(0, hyphenIndex)); } } else if (propId == Constants.PR_COUNTRY) { if (hyphenIndex != -1) { int nextHyphenIndex = shorthandValue.indexOf(HYPHEN_MINUS, hyphenIndex + 1); if (nextHyphenIndex != -1) { return StringProperty.getInstance( shorthandValue.substring(hyphenIndex + 1, nextHyphenIndex)); } else { return StringProperty.getInstance( shorthandValue.substring(hyphenIndex + 1)); } } } return null; }
// in src/java/org/apache/fop/fo/properties/FontFamilyProperty.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { if ("inherit".equals(value)) { return super.make(propertyList, value, fo); } else { FontFamilyProperty prop = new FontFamilyProperty(); String tmpVal; int startIndex = 0; int commaIndex = value.indexOf(','); int quoteIndex; int aposIndex; char qChar; boolean parsed = false; while (!parsed) { if (commaIndex == -1) { tmpVal = value.substring(startIndex).trim(); parsed = true; } else { tmpVal = value.substring(startIndex, commaIndex).trim(); startIndex = commaIndex + 1; commaIndex = value.indexOf(',', startIndex); } aposIndex = tmpVal.indexOf('\''); quoteIndex = tmpVal.indexOf('\"'); if (aposIndex != -1 || quoteIndex != -1) { qChar = (aposIndex == -1) ? '\"' : '\''; if (tmpVal.lastIndexOf(qChar) != tmpVal.length() - 1) { log.warn("Skipping malformed value for font-family: " + tmpVal + " in \"" + value + "\"."); tmpVal = ""; } else { tmpVal = tmpVal.substring(1, tmpVal.length() - 1); } } if (!"".equals(tmpVal)) { int dblSpaceIndex = tmpVal.indexOf(" "); while (dblSpaceIndex != -1) { tmpVal = tmpVal.substring(0, dblSpaceIndex) + tmpVal.substring(dblSpaceIndex + 1); dblSpaceIndex = tmpVal.indexOf(" "); } prop.addProperty(StringProperty.getInstance(tmpVal)); } } return CACHE.fetch(prop); } }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property findProperty(PropertyList propertyList, boolean tryInherit) throws PropertyException { Property p = null; if (IS_LOG_TRACE_ENABLED) { LOG.trace("PropertyMaker.findProperty: " + FOPropertyMapping.getPropertyName(propId) + ", " + propertyList.getFObj().getName()); } if (corresponding != null && corresponding.isCorrespondingForced(propertyList)) { p = corresponding.compute(propertyList); } else { p = propertyList.getExplicit(propId); if (p == null) { // check for shorthand specification p = getShorthand(propertyList); } if (p == null) { p = this.compute(propertyList); } } if (p == null && tryInherit) { // else inherit (if has parent and is inheritable) PropertyList parentPropertyList = propertyList.getParentPropertyList(); if (parentPropertyList != null && isInherited()) { p = parentPropertyList.get(propId, true, false); } } return p; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property get(int subpropertyId, PropertyList propertyList, boolean tryInherit, boolean tryDefault) throws PropertyException { Property p = findProperty(propertyList, tryInherit); if (p == null && tryDefault) { // default value for this FO! p = make(propertyList); } return p; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public PercentBase getPercentBase(PropertyList pl) throws PropertyException { if (percentBase == -1) { return null; } else { return new LengthBase(pl, percentBase); } }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property make(PropertyList propertyList) throws PropertyException { if (defaultProperty != null) { if (IS_LOG_TRACE_ENABLED) { LOG.trace("PropertyMaker.make: reusing defaultProperty, " + FOPropertyMapping.getPropertyName(propId)); } return defaultProperty; } if (IS_LOG_TRACE_ENABLED) { LOG.trace("PropertyMaker.make: making default property value, " + FOPropertyMapping.getPropertyName(propId) + ", " + propertyList.getFObj().getName()); } Property p = make(propertyList, defaultValue, propertyList.getParentFObj()); if (!contextDep) { defaultProperty = p; } return p; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { try { Property newProp = null; String pvalue = value; if ("inherit".equals(value)) { newProp = propertyList.getFromParent(this.propId & Constants.PROPERTY_MASK); if ((propId & Constants.COMPOUND_MASK) != 0) { newProp = getSubprop(newProp, propId & Constants.COMPOUND_MASK); } if (!isInherited() && LOG.isWarnEnabled()) { /* check whether explicit value is available on the parent * (for inherited properties, an inherited value will always * be available) */ Property parentExplicit = propertyList.getParentPropertyList() .getExplicit(getPropId()); if (parentExplicit == null) { LOG.warn(FOPropertyMapping.getPropertyName(getPropId()) + "=\"inherit\" on " + propertyList.getFObj().getName() + ", but no explicit value found on the parent FO."); } } } else { // Check for keyword shorthand values to be substituted. pvalue = checkValueKeywords(pvalue.trim()); newProp = checkEnumValues(pvalue); } if (newProp == null) { // Override parsePropertyValue in each subclass of Property.Maker newProp = PropertyParser.parse(pvalue, new PropertyInfo(this, propertyList)); } if (newProp != null) { newProp = convertProperty(newProp, propertyList, fo); } if (newProp == null) { throw new PropertyException("No conversion defined " + pvalue); } return newProp; } catch (PropertyException propEx) { if (fo != null) { propEx.setLocator(fo.getLocator()); } propEx.setPropertyName(getName()); throw propEx; } }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property make(Property baseProperty, int subpropertyId, PropertyList propertyList, String value, FObj fo) throws PropertyException { //getLogger().error("compound property component " // + partName + " unknown."); return baseProperty; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property convertShorthandProperty(PropertyList propertyList, Property prop, FObj fo) throws PropertyException { Property pret = convertProperty(prop, propertyList, fo); if (pret == null) { // If value is a name token, may be keyword or Enum String sval = prop.getNCname(); if (sval != null) { //log.debug("Convert shorthand ncname " + sval); pret = checkEnumValues(sval); if (pret == null) { /* Check for keyword shorthand values to be substituted. */ String pvalue = checkValueKeywords(sval); if (!pvalue.equals(sval)) { //log.debug("Convert shorthand keyword" + pvalue); // Substituted a value: must parse it Property p = PropertyParser.parse(pvalue, new PropertyInfo(this, propertyList)); pret = convertProperty(p, propertyList, fo); } } } } if (pret != null) { /* * log.debug("Return shorthand value " + pret.getString() + * " for " + getPropName()); */ } return pret; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
protected Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { return null; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
protected Property convertPropertyDatatype(Property p, PropertyList propertyList, FObj fo) throws PropertyException { return null; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
protected Property compute(PropertyList propertyList) throws PropertyException { if (corresponding != null) { return corresponding.compute(propertyList); } return null; // standard }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public Property getShorthand(PropertyList propertyList) throws PropertyException { if (shorthands == null) { return null; } Property prop; int n = shorthands.length; for (int i = 0; i < n && shorthands[i] != null; i++) { PropertyMaker shorthand = shorthands[i]; prop = propertyList.getExplicit(shorthand.propId); if (prop != null) { ShorthandParser parser = shorthand.datatypeParser; Property p = parser.getValueForProperty(getPropId(), prop, this, propertyList); if (p != null) { return p; } } } return null; }
// in src/java/org/apache/fop/fo/properties/DimensionPropertyMaker.java
public Property compute(PropertyList propertyList) throws PropertyException { // Based on [width|height] Property p = super.compute(propertyList); if (p == null) { p = baseMaker.make(propertyList); } // Based on min-[width|height] int wmcorr = propertyList.selectFromWritingMode(extraCorresponding[0][0], extraCorresponding[0][1], extraCorresponding[0][2], extraCorresponding[0][3]); Property subprop = propertyList.getExplicitOrShorthand(wmcorr); if (subprop != null) { baseMaker.setSubprop(p, Constants.CP_MINIMUM, subprop); } // Based on max-[width|height] wmcorr = propertyList.selectFromWritingMode(extraCorresponding[1][0], extraCorresponding[1][1], extraCorresponding[1][2], extraCorresponding[1][3]); subprop = propertyList.getExplicitOrShorthand(wmcorr); // TODO: Don't set when NONE. if (subprop != null) { baseMaker.setSubprop(p, Constants.CP_MAXIMUM, subprop); } return p; }
// in src/java/org/apache/fop/fo/properties/BoxPropShorthandParser.java
protected Property convertValueForProperty(int propId, Property property, PropertyMaker maker, PropertyList propertyList) throws PropertyException { String name = FOPropertyMapping.getPropertyName(propId); Property p = null; int count = property.getList().size(); if (name.indexOf("-top") >= 0) { p = getElement(property, 0); } else if (name.indexOf("-right") >= 0) { p = getElement(property, count > 1 ? 1 : 0); } else if (name.indexOf("-bottom") >= 0) { p = getElement(property, count > 2 ? 2 : 0); } else if (name.indexOf("-left") >= 0) { p = getElement(property, count > 3 ? 3 : (count > 1 ? 1 : 0)); } // if p not null, try to convert it to a value of the correct type if (p != null) { return maker.convertShorthandProperty(propertyList, p, null); } return p; }
// in src/java/org/apache/fop/fo/PropertyList.java
public Property getExplicitOrShorthand(int propId) throws PropertyException { /* Handle request for one part of a compound property */ Property p = getExplicit(propId); if (p == null) { p = getShorthand(propId); } return p; }
// in src/java/org/apache/fop/fo/PropertyList.java
public Property getInherited(int propId) throws PropertyException { if (isInherited(propId)) { return getFromParent(propId); } else { // return the "initial" value return makeProperty(propId); } }
// in src/java/org/apache/fop/fo/PropertyList.java
public Property get(int propId) throws PropertyException { return get(propId, true, true); }
// in src/java/org/apache/fop/fo/PropertyList.java
public Property get(int propId, boolean bTryInherit, boolean bTryDefault) throws PropertyException { PropertyMaker propertyMaker = findMaker(propId & Constants.PROPERTY_MASK); if (propertyMaker != null) { return propertyMaker.get(propId & Constants.COMPOUND_MASK, this, bTryInherit, bTryDefault); } return null; }
// in src/java/org/apache/fop/fo/PropertyList.java
public Property getNearestSpecified(int propId) throws PropertyException { Property p = null; PropertyList pList = parentPropertyList; while (pList != null) { p = pList.getExplicit(propId); if (p != null) { return p; } else { pList = pList.parentPropertyList; } } // If no explicit value found on any of the ancestor-nodes, // return initial (default) value. return makeProperty(propId); }
// in src/java/org/apache/fop/fo/PropertyList.java
public Property getFromParent(int propId) throws PropertyException { if (parentPropertyList != null) { return parentPropertyList.get(propId); } else { return makeProperty(propId); } }
// in src/java/org/apache/fop/fo/PropertyList.java
private Property findBaseProperty(Attributes attributes, FObj parentFO, int propId, String basePropertyName, PropertyMaker propertyMaker) throws PropertyException { /* If the baseProperty has already been created, return it * e.g. <fo:leader xxxx="120pt" xxxx.maximum="200pt"... /> */ Property baseProperty = getExplicit(propId); if (baseProperty != null) { return baseProperty; } /* Otherwise If it is specified later in this list of Attributes, create it now * e.g. <fo:leader xxxx.maximum="200pt" xxxx="200pt"... /> */ String basePropertyValue = attributes.getValue(basePropertyName); if (basePropertyValue != null && propertyMaker != null) { baseProperty = propertyMaker.make(this, basePropertyValue, parentFO); return baseProperty; } return null; // could not find base property }
// in src/java/org/apache/fop/fo/PropertyList.java
private Property getShorthand(int propId) throws PropertyException { PropertyMaker propertyMaker = findMaker(propId); if (propertyMaker != null) { return propertyMaker.getShorthand(this); } else { //log.error("no Maker for " + propertyName); return null; } }
// in src/java/org/apache/fop/fo/PropertyList.java
private Property makeProperty(int propId) throws PropertyException { PropertyMaker propertyMaker = findMaker(propId); if (propertyMaker != null) { return propertyMaker.make(this); } else { //log.error("property " + propertyName // + " ignored"); } return null; }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonBorderPaddingBackground getBorderPaddingBackgroundProps() throws PropertyException { return CommonBorderPaddingBackground.getInstance(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonHyphenation getHyphenationProps() throws PropertyException { return CommonHyphenation.getInstance(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonMarginBlock getMarginBlockProps() throws PropertyException { return new CommonMarginBlock(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonMarginInline getMarginInlineProps() throws PropertyException { return new CommonMarginInline(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonAural getAuralProps() throws PropertyException { CommonAural props = new CommonAural(this); return props; }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonRelativePosition getRelativePositionProps() throws PropertyException { return new CommonRelativePosition(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonAbsolutePosition getAbsolutePositionProps() throws PropertyException { return new CommonAbsolutePosition(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonFont getFontProps() throws PropertyException { return CommonFont.getInstance(this); }
// in src/java/org/apache/fop/fo/PropertyList.java
public CommonTextDecoration getTextDecorationProps() throws PropertyException { return CommonTextDecoration.createFromPropertyList(this); }
// in src/java/org/apache/fop/fo/expr/FromTableColumnFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { FObj fo = pInfo.getPropertyList().getFObj(); /* obtain property Id for the property for which the function is being * evaluated */ int propId = 0; if (args.length == 0) { propId = pInfo.getPropertyMaker().getPropId(); } else { String propName = args[0].getString(); propId = FOPropertyMapping.getPropertyId(propName); } /* make sure we have a correct property id ... */ if (propId != -1) { /* obtain column number for which the function is being evaluated: */ int columnNumber = -1; int span = 0; if (fo.getNameId() != Constants.FO_TABLE_CELL) { // climb up to the nearest cell do { fo = (FObj) fo.getParent(); } while (fo.getNameId() != Constants.FO_TABLE_CELL && fo.getNameId() != Constants.FO_PAGE_SEQUENCE); if (fo.getNameId() == Constants.FO_TABLE_CELL) { //column-number is available on the cell columnNumber = ((TableCell) fo).getColumnNumber(); span = ((TableCell) fo).getNumberColumnsSpanned(); } else { //means no table-cell was found... throw new PropertyException("from-table-column() may only be used on " + "fo:table-cell or its descendants."); } } else { //column-number is only accurately available through the propertyList columnNumber = pInfo.getPropertyList().get(Constants.PR_COLUMN_NUMBER) .getNumeric().getValue(); span = pInfo.getPropertyList().get(Constants.PR_NUMBER_COLUMNS_SPANNED) .getNumeric().getValue(); } /* return the property from the column */ Table t = ((TableFObj) fo).getTable(); List cols = t.getColumns(); ColumnNumberManager columnIndexManager = t.getColumnNumberManager(); if (cols == null) { //no columns defined => no match: return default value return pInfo.getPropertyList().get(propId, false, true); } else { if (columnIndexManager.isColumnNumberUsed(columnNumber)) { //easiest case: exact match return ((TableColumn) cols.get(columnNumber - 1)).getProperty(propId); } else { //no exact match: try all spans... while (--span > 0 && !columnIndexManager.isColumnNumberUsed(++columnNumber)) { //nop: just increment/decrement } if (columnIndexManager.isColumnNumberUsed(columnNumber)) { return ((TableColumn) cols.get(columnNumber - 1)).getProperty(propId); } else { //no match: return default value return pInfo.getPropertyList().get(propId, false, true); } } } } else { throw new PropertyException("Incorrect parameter to from-table-column() function"); } }
// in src/java/org/apache/fop/fo/expr/AbsFunction.java
public Property eval(Property[] args, PropertyInfo propInfo) throws PropertyException { Numeric num = args[0].getNumeric(); if (num == null) { throw new PropertyException("Non numeric operand to abs function"); } // TODO: What if it has relative components (percent, table-col units)? return (Property) NumericOp.abs(num); }
// in src/java/org/apache/fop/fo/expr/PropertyInfo.java
public PercentBase getPercentBase() throws PropertyException { PercentBase pcbase = getFunctionPercentBase(); return (pcbase != null) ? pcbase : maker.getPercentBase(plist); }
// in src/java/org/apache/fop/fo/expr/PropertyInfo.java
public Length currentFontSize() throws PropertyException { return plist.get(Constants.PR_FONT_SIZE).getLength(); }
// in src/java/org/apache/fop/fo/expr/LabelEndFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Length distance = pInfo.getPropertyList().get( Constants.PR_PROVISIONAL_DISTANCE_BETWEEN_STARTS).getLength(); Length separation = pInfo.getPropertyList().getNearestSpecified( Constants.PR_PROVISIONAL_LABEL_SEPARATION).getLength(); PropertyList pList = pInfo.getPropertyList(); while (pList != null && !(pList.getFObj() instanceof ListItem)) { pList = pList.getParentPropertyList(); } if (pList == null) { throw new PropertyException("label-end() called from outside an fo:list-item"); } Length startIndent = pList.get(Constants.PR_START_INDENT).getLength(); LengthBase base = new LengthBase(pInfo.getPropertyList(), LengthBase.CONTAINING_REFAREA_WIDTH); PercentLength refWidth = new PercentLength(1.0, base); Numeric labelEnd = distance; labelEnd = NumericOp.addition(labelEnd, startIndent); //TODO add start-intrusion-adjustment labelEnd = NumericOp.subtraction(labelEnd, separation); labelEnd = NumericOp.subtraction(refWidth, labelEnd); return (Property) labelEnd; }
// in src/java/org/apache/fop/fo/expr/BodyStartFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Numeric distance = pInfo.getPropertyList() .get(Constants.PR_PROVISIONAL_DISTANCE_BETWEEN_STARTS).getNumeric(); PropertyList pList = pInfo.getPropertyList(); while (pList != null && !(pList.getFObj() instanceof ListItem)) { pList = pList.getParentPropertyList(); } if (pList == null) { throw new PropertyException("body-start() called from outside an fo:list-item"); } Numeric startIndent = pList.get(Constants.PR_START_INDENT).getNumeric(); return (Property) NumericOp.addition(distance, startIndent); }
// in src/java/org/apache/fop/fo/expr/FromParentFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { String propName = args[0].getString(); if (propName == null) { throw new PropertyException("Incorrect parameter to from-parent function"); } // NOTE: special cases for shorthand property // Should return COMPUTED VALUE /* * For now, this is the same as inherited-property-value(propName) * (The only difference I can see is that this could work for * non-inherited properties too. Perhaps the result is different for * a property line line-height which "inherits specified"??? */ int propId = FOPropertyMapping.getPropertyId(propName); if (propId < 0) { throw new PropertyException( "Unknown property name used with inherited-property-value function: " + propName); } return pInfo.getPropertyList().getFromParent(propId); }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
private Numeric getResolved(PercentBaseContext context) throws PropertyException { switch (operation) { case ADDITION: return NumericOp.addition2(op1, op2, context); case SUBTRACTION: return NumericOp.subtraction2(op1, op2, context); case MULTIPLY: return NumericOp.multiply2(op1, op2, context); case DIVIDE: return NumericOp.divide2(op1, op2, context); case MODULO: return NumericOp.modulo2(op1, op2, context); case NEGATE: return NumericOp.negate2(op1, context); case ABS: return NumericOp.abs2(op1, context); case MAX: return NumericOp.max2(op1, op2, context); case MIN: return NumericOp.min2(op1, op2, context); default: throw new PropertyException("Unknown expr operation " + operation); } }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
public double getNumericValue() throws PropertyException { return getResolved(null).getNumericValue(null); }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
public double getNumericValue(PercentBaseContext context) throws PropertyException { return getResolved(context).getNumericValue(context); }
// in src/java/org/apache/fop/fo/expr/RoundFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number dbl = args[0].getNumber(); if (dbl == null) { throw new PropertyException("Non number operand to round function"); } double n = dbl.doubleValue(); double r = Math.floor(n + 0.5); if (r == 0.0 && n < 0.0) { r = -r; // round(-0.2) returns -0 not 0 } return NumberProperty.getInstance(r); }
// in src/java/org/apache/fop/fo/expr/RGBColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { return ColorProperty.getInstance(pInfo.getUserAgent(), "rgb(" + args[0] + "," + args[1] + "," + args[2] + ")"); }
// in src/java/org/apache/fop/fo/expr/FunctionBase.java
public Property getOptionalArgDefault(int index, PropertyInfo pi) throws PropertyException { if ( index >= getOptionalArgsCount() ) { PropertyException e = new PropertyException ( new IndexOutOfBoundsException ( "illegal optional argument index" ) ); e.setPropertyInfo ( pi ); throw e; } else { return null; } }
// in src/java/org/apache/fop/fo/expr/PropertyTokenizer.java
void next() throws PropertyException { currentTokenValue = null; currentTokenStartIndex = exprIndex; boolean bSawDecimal; while ( true ) { if (exprIndex >= exprLength) { currentToken = TOK_EOF; return; } char c = expr.charAt(exprIndex++); switch (c) { case ' ': case '\t': case '\r': case '\n': currentTokenStartIndex = exprIndex; break; case ',': currentToken = TOK_COMMA; return; case '+': currentToken = TOK_PLUS; return; case '-': currentToken = TOK_MINUS; return; case '(': currentToken = TOK_LPAR; return; case ')': currentToken = TOK_RPAR; return; case '"': case '\'': exprIndex = expr.indexOf(c, exprIndex); if (exprIndex < 0) { exprIndex = currentTokenStartIndex + 1; throw new PropertyException("missing quote"); } currentTokenValue = expr.substring(currentTokenStartIndex + 1, exprIndex++); currentToken = TOK_LITERAL; return; case '*': /* * if (currentMaybeOperator) { * recognizeOperator = false; */ currentToken = TOK_MULTIPLY; /* * } * else * throw new PropertyException("illegal operator *"); */ return; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': scanDigits(); if (exprIndex < exprLength && expr.charAt(exprIndex) == '.') { exprIndex++; bSawDecimal = true; if (exprIndex < exprLength && isDigit(expr.charAt(exprIndex))) { exprIndex++; scanDigits(); } } else { bSawDecimal = false; } if (exprIndex < exprLength && expr.charAt(exprIndex) == '%') { exprIndex++; currentToken = TOK_PERCENT; } else { // Check for possible unit name following number currentUnitLength = exprIndex; scanName(); currentUnitLength = exprIndex - currentUnitLength; currentToken = (currentUnitLength > 0) ? TOK_NUMERIC : (bSawDecimal ? TOK_FLOAT : TOK_INTEGER); } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); return; case '.': nextDecimalPoint(); return; case '#': // Start of color value nextColor(); return; default: --exprIndex; scanName(); if (exprIndex == currentTokenStartIndex) { throw new PropertyException("illegal character"); } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); if (currentTokenValue.equals("mod")) { currentToken = TOK_MOD; return; } else if (currentTokenValue.equals("div")) { currentToken = TOK_DIV; return; } if (followingParen()) { currentToken = TOK_FUNCTION_LPAR; } else { currentToken = TOK_NCNAME; } return; } } }
// in src/java/org/apache/fop/fo/expr/PropertyTokenizer.java
private void nextDecimalPoint() throws PropertyException { if (exprIndex < exprLength && isDigit(expr.charAt(exprIndex))) { ++exprIndex; scanDigits(); if (exprIndex < exprLength && expr.charAt(exprIndex) == '%') { exprIndex++; currentToken = TOK_PERCENT; } else { // Check for possible unit name following number currentUnitLength = exprIndex; scanName(); currentUnitLength = exprIndex - currentUnitLength; currentToken = (currentUnitLength > 0) ? TOK_NUMERIC : TOK_FLOAT; } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); return; } throw new PropertyException("illegal character '.'"); }
// in src/java/org/apache/fop/fo/expr/PropertyTokenizer.java
private void nextColor() throws PropertyException { if (exprIndex < exprLength) { ++exprIndex; scanHexDigits(); int len = exprIndex - currentTokenStartIndex - 1; if (len % 3 == 0) { currentToken = TOK_COLORSPEC; } else { //Actually not a color at all, but an NCNAME starting with "#" scanRestOfName(); currentToken = TOK_NCNAME; } currentTokenValue = expr.substring(currentTokenStartIndex, exprIndex); return; } else { throw new PropertyException("illegal character '#'"); } }
// in src/java/org/apache/fop/fo/expr/CIELabColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { float red = args[0].getNumber().floatValue(); float green = args[1].getNumber().floatValue(); float blue = args[2].getNumber().floatValue(); /* Verify sRGB replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("sRGB color values out of range. " + "Arguments to cie-lab-color() must be [0..255] or [0%..100%]"); } float l = args[3].getNumber().floatValue(); float a = args[4].getNumber().floatValue(); float b = args[5].getNumber().floatValue(); if (l < 0 || l > 100) { throw new PropertyException("L* value out of range. Valid range: [0..100]"); } if (a < -127 || a > 127 || b < -127 || b > 127) { throw new PropertyException("a* and b* values out of range. Valid range: [-127..+127]"); } StringBuffer sb = new StringBuffer(); sb.append("cie-lab-color(" + red + "," + green + "," + blue + "," + l + "," + a + "," + b + ")"); FOUserAgent ua = (pInfo == null) ? null : (pInfo.getFO() == null ? null : pInfo.getFO().getUserAgent()); return ColorProperty.getInstance(ua, sb.toString()); }
// in src/java/org/apache/fop/fo/expr/FromNearestSpecifiedValueFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { String propName = args[0].getString(); if (propName == null) { throw new PropertyException( "Incorrect parameter to from-nearest-specified-value function"); } // NOTE: special cases for shorthand property // Should return COMPUTED VALUE int propId = FOPropertyMapping.getPropertyId(propName); if (propId < 0) { throw new PropertyException( "Unknown property name used with inherited-property-value function: " + propName); } return pInfo.getPropertyList().getNearestSpecified(propId); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric addition(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return addition2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.ADDITION, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric addition2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Can't subtract Numerics of different dimensions"); } return numeric(op1.getNumericValue(context) + op2.getNumericValue(context), op1.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric subtraction(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return subtraction2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.SUBTRACTION, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric subtraction2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Can't subtract Numerics of different dimensions"); } return numeric(op1.getNumericValue(context) - op2.getNumericValue(context), op1.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric multiply(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return multiply2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.MULTIPLY, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric multiply2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { return numeric(op1.getNumericValue(context) * op2.getNumericValue(context), op1.getDimension() + op2.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric divide(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return divide2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.DIVIDE, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric divide2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { return numeric(op1.getNumericValue(context) / op2.getNumericValue(context), op1.getDimension() - op2.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric modulo(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return modulo2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.MODULO, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric modulo2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { return numeric(op1.getNumericValue(context) % op2.getNumericValue(context), op1.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric abs(Numeric op) throws PropertyException { if (op.isAbsolute()) { return abs2(op, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.ABS, op); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric abs2(Numeric op, PercentBaseContext context) throws PropertyException { return numeric(Math.abs(op.getNumericValue(context)), op.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric negate(Numeric op) throws PropertyException { if (op.isAbsolute()) { return negate2(op, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.NEGATE, op); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric negate2(Numeric op, PercentBaseContext context) throws PropertyException { return numeric(-op.getNumericValue(context), op.getDimension()); }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric max(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return max2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.MAX, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric max2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Arguments to max() must have same dimensions"); } return op1.getNumericValue(context) > op2.getNumericValue(context) ? op1 : op2; }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric min(Numeric op1, Numeric op2) throws PropertyException { if (op1.isAbsolute() && op2.isAbsolute()) { return min2(op1, op2, null); } else { return new RelativeNumericProperty(RelativeNumericProperty.MIN, op1, op2); } }
// in src/java/org/apache/fop/fo/expr/NumericOp.java
public static Numeric min2(Numeric op1, Numeric op2, PercentBaseContext context) throws PropertyException { if (op1.getDimension() != op2.getDimension()) { throw new PropertyException("Arguments to min() must have same dimensions"); } return op1.getNumericValue(context) <= op2.getNumericValue(context) ? op1 : op2; }
// in src/java/org/apache/fop/fo/expr/MaxFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Numeric n1 = args[0].getNumeric(); Numeric n2 = args[1].getNumeric(); if (n1 == null || n2 == null) { throw new PropertyException("Non numeric operands to max function"); } return (Property) NumericOp.max(n1, n2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
public static Property parse(String expr, PropertyInfo propInfo) throws PropertyException { try { return new PropertyParser(expr, propInfo).parseProperty(); } catch (PropertyException exc) { exc.setPropertyInfo(propInfo); throw exc; } }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property parseProperty() throws PropertyException { next(); if (currentToken == TOK_EOF) { // if prop value is empty string, force to StringProperty return StringProperty.getInstance(""); } ListProperty propList = null; while (true) { Property prop = parseAdditiveExpr(); if (currentToken == TOK_EOF) { if (propList != null) { propList.addProperty(prop); return propList; } else { return prop; } } else { if (propList == null) { propList = new ListProperty(prop); } else { propList.addProperty(prop); } } // throw new PropertyException("unexpected token"); } // return prop; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property parseAdditiveExpr() throws PropertyException { // Evaluate and put result on the operand stack Property prop = parseMultiplicativeExpr(); loop: while (true) { switch (currentToken) { case TOK_PLUS: next(); prop = evalAddition(prop.getNumeric(), parseMultiplicativeExpr().getNumeric()); break; case TOK_MINUS: next(); prop = evalSubtraction(prop.getNumeric(), parseMultiplicativeExpr().getNumeric()); break; default: break loop; } } return prop; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property parseMultiplicativeExpr() throws PropertyException { Property prop = parseUnaryExpr(); loop: while (true) { switch (currentToken) { case TOK_DIV: next(); prop = evalDivide(prop.getNumeric(), parseUnaryExpr().getNumeric()); break; case TOK_MOD: next(); prop = evalModulo(prop.getNumber(), parseUnaryExpr().getNumber()); break; case TOK_MULTIPLY: next(); prop = evalMultiply(prop.getNumeric(), parseUnaryExpr().getNumeric()); break; default: break loop; } } return prop; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property parseUnaryExpr() throws PropertyException { if (currentToken == TOK_MINUS) { next(); return evalNegate(parseUnaryExpr().getNumeric()); } return parsePrimaryExpr(); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private void expectRpar() throws PropertyException { if (currentToken != TOK_RPAR) { throw new PropertyException("expected )"); } next(); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property parsePrimaryExpr() throws PropertyException { Property prop; if (currentToken == TOK_COMMA) { //Simply skip commas, for example for font-family next(); } switch (currentToken) { case TOK_LPAR: next(); prop = parseAdditiveExpr(); expectRpar(); return prop; case TOK_LITERAL: prop = StringProperty.getInstance(currentTokenValue); break; case TOK_NCNAME: // Interpret this in context of the property or do it later? prop = new NCnameProperty(currentTokenValue); break; case TOK_FLOAT: prop = NumberProperty.getInstance(new Double(currentTokenValue)); break; case TOK_INTEGER: prop = NumberProperty.getInstance(new Integer(currentTokenValue)); break; case TOK_PERCENT: /* * Get the length base value object from the Maker. If null, then * this property can't have % values. Treat it as a real number. */ double pcval = Double.parseDouble( currentTokenValue.substring(0, currentTokenValue.length() - 1)) / 100.0; PercentBase pcBase = this.propInfo.getPercentBase(); if (pcBase != null) { if (pcBase.getDimension() == 0) { prop = NumberProperty.getInstance(pcval * pcBase.getBaseValue()); } else if (pcBase.getDimension() == 1) { if (pcBase instanceof LengthBase) { if (pcval == 0.0) { prop = FixedLength.ZERO_FIXED_LENGTH; break; } //If the base of the percentage is known //and absolute, it can be resolved by the //parser Length base = ((LengthBase)pcBase).getBaseLength(); if (base != null && base.isAbsolute()) { prop = FixedLength.getInstance(pcval * base.getValue()); break; } } prop = new PercentLength(pcval, pcBase); } else { throw new PropertyException("Illegal percent dimension value"); } } else { // WARNING? Interpret as a decimal fraction, eg. 50% = .5 prop = NumberProperty.getInstance(pcval); } break; case TOK_NUMERIC: // A number plus a valid unit name. int numLen = currentTokenValue.length() - currentUnitLength; String unitPart = currentTokenValue.substring(numLen); double numPart = Double.parseDouble(currentTokenValue.substring(0, numLen)); if (RELUNIT.equals(unitPart)) { prop = (Property) NumericOp.multiply( NumberProperty.getInstance(numPart), propInfo.currentFontSize()); } else { if ("px".equals(unitPart)) { //pass the ratio between target-resolution and //the default resolution of 72dpi float resolution = propInfo.getPropertyList().getFObj() .getUserAgent().getSourceResolution(); prop = FixedLength.getInstance( numPart, unitPart, UnitConv.IN2PT / resolution); } else { //use default resolution of 72dpi prop = FixedLength.getInstance(numPart, unitPart); } } break; case TOK_COLORSPEC: prop = ColorProperty.getInstance(propInfo.getUserAgent(), currentTokenValue); break; case TOK_FUNCTION_LPAR: Function function = (Function)FUNCTION_TABLE.get(currentTokenValue); if (function == null) { throw new PropertyException("no such function: " + currentTokenValue); } next(); // Push new function (for function context: getPercentBase()) propInfo.pushFunction(function); prop = function.eval(parseArgs(function), propInfo); propInfo.popFunction(); return prop; default: // TODO: add the token or the expr to the error message. throw new PropertyException("syntax error"); } next(); return prop; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
Property[] parseArgs(Function function) throws PropertyException { int numReq = function.getRequiredArgsCount(); // # required args int numOpt = function.getOptionalArgsCount(); // # optional args boolean hasVar = function.hasVariableArgs(); // has variable args List<Property> args = new java.util.ArrayList<Property>(numReq + numOpt); if (currentToken == TOK_RPAR) { // No args: func() next(); } else { while (true) { Property p = parseAdditiveExpr(); int i = args.size(); if ( ( i < numReq ) || ( ( i - numReq ) < numOpt ) || hasVar ) { args.add ( p ); } else { throw new PropertyException ( "Unexpected function argument at index " + i ); } // ignore extra args if (currentToken != TOK_COMMA) { break; } next(); } expectRpar(); } int numArgs = args.size(); if ( numArgs < numReq ) { throw new PropertyException("Expected " + numReq + " required arguments, but only " + numArgs + " specified"); } else { for ( int i = 0; i < numOpt; i++ ) { if ( args.size() < ( numReq + i + 1 ) ) { args.add ( function.getOptionalArgDefault ( i, propInfo ) ); } } } return (Property[]) args.toArray ( new Property [ args.size() ] ); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalAddition(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in addition"); } return (Property) NumericOp.addition(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalSubtraction(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in subtraction"); } return (Property) NumericOp.subtraction(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalNegate(Numeric op) throws PropertyException { if (op == null) { throw new PropertyException("Non numeric operand to unary minus"); } return (Property) NumericOp.negate(op); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalMultiply(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in multiplication"); } return (Property) NumericOp.multiply(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalDivide(Numeric op1, Numeric op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non numeric operand in division"); } return (Property) NumericOp.divide(op1, op2); }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
private Property evalModulo(Number op1, Number op2) throws PropertyException { if (op1 == null || op2 == null) { throw new PropertyException("Non number operand to modulo"); } return NumberProperty.getInstance(op1.doubleValue() % op2.doubleValue()); }
// in src/java/org/apache/fop/fo/expr/MinFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Numeric n1 = args[0].getNumeric(); Numeric n2 = args[1].getNumeric(); if (n1 == null || n2 == null) { throw new PropertyException("Non numeric operands to min function"); } return (Property) NumericOp.min(n1, n2); }
// in src/java/org/apache/fop/fo/expr/FloorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number dbl = args[0].getNumber(); if (dbl == null) { throw new PropertyException("Non number operand to floor function"); } return NumberProperty.getInstance(Math.floor(dbl.doubleValue())); }
// in src/java/org/apache/fop/fo/expr/CMYKColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { StringBuffer sb = new StringBuffer(); sb.append("cmyk(" + args[0] + "," + args[1] + "," + args[2] + "," + args[3] + ")"); FOUserAgent ua = (pInfo == null) ? null : (pInfo.getFO() == null ? null : pInfo.getFO().getUserAgent()); return ColorProperty.getInstance(ua, sb.toString()); }
// in src/java/org/apache/fop/fo/expr/SystemColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { FOUserAgent ua = (pInfo == null) ? null : (pInfo.getFO() == null ? null : pInfo.getFO().getUserAgent()); return ColorProperty.getInstance(ua, "system-color(" + args[0] + ")"); }
// in src/java/org/apache/fop/fo/expr/RGBICCColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { // Map color profile NCNAME to src from declarations/color-profile element String colorProfileName = args[3].getString(); Declarations decls = (pInfo.getFO() != null ? pInfo.getFO().getRoot().getDeclarations() : null); ColorProfile cp = null; if (decls == null) { //function used in a color-specification //on a FO occurring: //a) before the fo:declarations, //b) or in a document without fo:declarations? //=> return the sRGB fallback if (!ColorUtil.isPseudoProfile(colorProfileName)) { Property[] rgbArgs = new Property[3]; System.arraycopy(args, 0, rgbArgs, 0, 3); return new RGBColorFunction().eval(rgbArgs, pInfo); } } else { cp = decls.getColorProfile(colorProfileName); if (cp == null) { if (!ColorUtil.isPseudoProfile(colorProfileName)) { PropertyException pe = new PropertyException("The " + colorProfileName + " color profile was not declared"); pe.setPropertyInfo(pInfo); throw pe; } } } String src = (cp != null ? cp.getSrc() : ""); float red = 0; float green = 0; float blue = 0; red = args[0].getNumber().floatValue(); green = args[1].getNumber().floatValue(); blue = args[2].getNumber().floatValue(); /* Verify rgb replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("Color values out of range. " + "Arguments to rgb-icc() must be [0..255] or [0%..100%]"); } // rgb-icc is replaced with fop-rgb-icc which has an extra fifth argument containing the // color profile src attribute as it is defined in the color-profile declarations element. StringBuffer sb = new StringBuffer(); sb.append("fop-rgb-icc("); sb.append(red / 255f); sb.append(',').append(green / 255f); sb.append(',').append(blue / 255f); for (int ix = 3; ix < args.length; ix++) { if (ix == 3) { sb.append(',').append(colorProfileName); sb.append(',').append(src); } else { sb.append(',').append(args[ix]); } } sb.append(")"); return ColorProperty.getInstance(pInfo.getUserAgent(), sb.toString()); }
// in src/java/org/apache/fop/fo/expr/RGBICCColorFunction.java
public int getBaseLength(PercentBaseContext context) throws PropertyException { return 0; }
// in src/java/org/apache/fop/fo/expr/RGBNamedColorFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { // Map color profile NCNAME to src from declarations/color-profile element String colorProfileName = args[3].getString(); String colorName = args[4].getString(); Declarations decls = (pInfo.getFO() != null ? pInfo.getFO().getRoot().getDeclarations() : null); ColorProfile cp = null; if (decls != null) { cp = decls.getColorProfile(colorProfileName); } if (cp == null) { PropertyException pe = new PropertyException("The " + colorProfileName + " color profile was not declared"); pe.setPropertyInfo(pInfo); throw pe; } float red = 0; float green = 0; float blue = 0; red = args[0].getNumber().floatValue(); green = args[1].getNumber().floatValue(); blue = args[2].getNumber().floatValue(); /* Verify rgb replacement arguments */ if ((red < 0 || red > 255) || (green < 0 || green > 255) || (blue < 0 || blue > 255)) { throw new PropertyException("sRGB color values out of range. " + "Arguments to rgb-named-color() must be [0..255] or [0%..100%]"); } // rgb-named-color is replaced with fop-rgb-named-color which has an extra argument // containing the color profile src attribute as it is defined in the color-profile // declarations element. StringBuffer sb = new StringBuffer(); sb.append("fop-rgb-named-color("); sb.append(red / 255f); sb.append(',').append(green / 255f); sb.append(',').append(blue / 255f); sb.append(',').append(colorProfileName); sb.append(',').append(cp.getSrc()); sb.append(", '").append(colorName).append('\''); sb.append(")"); return ColorProperty.getInstance(pInfo.getUserAgent(), sb.toString()); }
// in src/java/org/apache/fop/fo/expr/RGBNamedColorFunction.java
public int getBaseLength(PercentBaseContext context) throws PropertyException { return 0; }
// in src/java/org/apache/fop/fo/expr/CeilingFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number dbl = args[0].getNumber(); if (dbl == null) { throw new PropertyException("Non number operand to ceiling function"); } return NumberProperty.getInstance(Math.ceil(dbl.doubleValue())); }
// in src/java/org/apache/fop/fo/expr/ProportionalColumnWidthFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { Number d = args[0].getNumber(); if (d == null) { throw new PropertyException("Non numeric operand to " + "proportional-column-width() function."); } PropertyList pList = pInfo.getPropertyList(); if (!"fo:table-column".equals(pList.getFObj().getName())) { throw new PropertyException("proportional-column-width() function " + "may only be used on fo:table-column."); } Table t = (Table) pList.getParentFObj(); if (t.isAutoLayout()) { throw new PropertyException("proportional-column-width() function " + "may only be used when fo:table has " + "table-layout=\"fixed\"."); } return new TableColLength(d.doubleValue(), pInfo.getFO()); }
// in src/java/org/apache/fop/fo/expr/ProportionalColumnWidthFunction.java
public int getBaseLength(PercentBaseContext context) throws PropertyException { return 0; }
// in src/java/org/apache/fop/fo/expr/InheritedPropFunction.java
public Property eval(Property[] args, PropertyInfo pInfo) throws PropertyException { String propName = args[0].getString(); if (propName == null) { throw new PropertyException("Incorrect parameter to inherited-property-value function"); } int propId = FOPropertyMapping.getPropertyId(propName); if (propId < 0) { throw new PropertyException( "Unknown property name used with inherited-property-value function: " + propName); } return pInfo.getPropertyList().getInherited(propId); }
// in src/java/org/apache/fop/fo/flow/table/TableColumn.java
public Property getProperty(int propId) throws PropertyException { return this.pList.get(propId); }
// in src/java/org/apache/fop/fo/flow/table/TableFObj.java
public Property make(PropertyList propertyList) throws PropertyException { FObj fo = propertyList.getFObj(); return NumberProperty.getInstance(((ColumnNumberManagerHolder) fo.getParent()) .getColumnNumberManager().getCurrentColumnNumber()); }
// in src/java/org/apache/fop/fo/flow/table/TableFObj.java
public Property make(PropertyList propertyList, String value, FObj fo) throws PropertyException { Property p = super.make(propertyList, value, fo); int columnIndex = p.getNumeric().getValue(); int colSpan = propertyList.get(Constants.PR_NUMBER_COLUMNS_SPANNED) .getNumeric().getValue(); // only check whether the column-number is occupied in case it was // specified on a fo:table-cell or fo:table-column int foId = propertyList.getFObj().getNameId(); if (foId == FO_TABLE_COLUMN || foId == FO_TABLE_CELL) { ColumnNumberManagerHolder parent = (ColumnNumberManagerHolder) propertyList.getParentFObj(); ColumnNumberManager columnIndexManager = parent.getColumnNumberManager(); int lastIndex = columnIndex - 1 + colSpan; for (int i = columnIndex; i <= lastIndex; ++i) { if (columnIndexManager.isColumnNumberUsed(i)) { /* if column-number is already in use by another * cell/column => error! */ TableEventProducer eventProducer = TableEventProducer.Provider.get( fo.getUserAgent().getEventBroadcaster()); eventProducer.cellOverlap( this, propertyList.getFObj().getName(), i, propertyList.getFObj().getLocator()); } } } return p; }
// in src/java/org/apache/fop/fo/flow/table/TableFObj.java
public Property convertProperty(Property p, PropertyList propertyList, FObj fo) throws PropertyException { if (p instanceof EnumProperty) { return EnumNumber.getInstance(p); } Number val = p.getNumber(); if (val != null) { int i = Math.round(val.floatValue()); int foId = propertyList.getFObj().getNameId(); if (i <= 0) { if (foId == FO_TABLE_CELL || foId == FO_TABLE_COLUMN) { ColumnNumberManagerHolder parent = (ColumnNumberManagerHolder) propertyList.getParentFObj(); ColumnNumberManager columnIndexManager = parent.getColumnNumberManager(); i = columnIndexManager.getCurrentColumnNumber(); } else { /* very exceptional case: * negative column-number specified on * a FO that is not a fo:table-cell or fo:table-column */ i = 1; } TableEventProducer eventProducer = TableEventProducer.Provider.get( fo.getUserAgent().getEventBroadcaster()); eventProducer.forceNextColumnNumber(this, propertyList.getFObj().getName(), val, i, propertyList.getFObj().getLocator()); } return NumberProperty.getInstance(i); } return convertPropertyDatatype(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/FOPropertyMapping.java
private void createBorderPaddingBackgroundProperties() { // CSOK: MethodLength PropertyMaker m; BorderWidthPropertyMaker bwm; CorrespondingPropertyMaker corr; // background-attachment m = new EnumProperty.Maker(PR_BACKGROUND_ATTACHMENT); m.setInherited(false); m.addEnum("scroll", getEnumProperty(EN_SCROLL, "SCROLL")); m.addEnum("fixed", getEnumProperty(EN_FIXED, "FIXED")); m.setDefault("scroll"); addPropertyMaker("background-attachment", m); // background-color m = new ColorProperty.Maker(PR_BACKGROUND_COLOR) { protected Property convertPropertyDatatype( Property p, PropertyList propertyList, FObj fo) throws PropertyException { String nameval = p.getNCname(); if (nameval != null) { FObj fobj = (fo == null ? propertyList.getFObj() : fo); FOUserAgent ua = (fobj == null ? null : fobj.getUserAgent()); return ColorProperty.getInstance(ua, nameval); } return super.convertPropertyDatatype(p, propertyList, fo); } }; m.useGeneric(genericColor); m.setInherited(false); m.setDefault("transparent"); addPropertyMaker("background-color", m); // background-image m = new StringProperty.Maker(PR_BACKGROUND_IMAGE); m.setInherited(false); m.setDefault("none"); addPropertyMaker("background-image", m); // background-repeat m = new EnumProperty.Maker(PR_BACKGROUND_REPEAT); m.setInherited(false); m.addEnum("repeat", getEnumProperty(EN_REPEAT, "REPEAT")); m.addEnum("repeat-x", getEnumProperty(EN_REPEATX, "REPEATX")); m.addEnum("repeat-y", getEnumProperty(EN_REPEATY, "REPEATY")); m.addEnum("no-repeat", getEnumProperty(EN_NOREPEAT, "NOREPEAT")); m.setDefault("repeat"); addPropertyMaker("background-repeat", m); // background-position-horizontal m = new LengthProperty.Maker(PR_BACKGROUND_POSITION_HORIZONTAL); m.setInherited(false); m.setDefault("0pt"); m.addKeyword("left", "0pt"); m.addKeyword("center", "50%"); m.addKeyword("right", "100%"); m.setPercentBase(LengthBase.IMAGE_BACKGROUND_POSITION_HORIZONTAL); m.addShorthand(generics[PR_BACKGROUND_POSITION]); addPropertyMaker("background-position-horizontal", m); // background-position-vertical m = new LengthProperty.Maker(PR_BACKGROUND_POSITION_VERTICAL); m.setInherited(false); m.setDefault("0pt"); m.addKeyword("top", "0pt"); m.addKeyword("center", "50%"); m.addKeyword("bottom", "100%"); m.setPercentBase(LengthBase.IMAGE_BACKGROUND_POSITION_VERTICAL); m.addShorthand(generics[PR_BACKGROUND_POSITION]); addPropertyMaker("background-position-vertical", m); // border-before-color m = new ColorProperty.Maker(PR_BORDER_BEFORE_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_TOP_COLOR, PR_BORDER_TOP_COLOR, PR_BORDER_RIGHT_COLOR, PR_BORDER_LEFT_COLOR); corr.setRelative(true); addPropertyMaker("border-before-color", m); // border-before-style m = new EnumProperty.Maker(PR_BORDER_BEFORE_STYLE); m.useGeneric(genericBorderStyle); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_TOP_STYLE, PR_BORDER_TOP_STYLE, PR_BORDER_RIGHT_STYLE, PR_BORDER_LEFT_STYLE); corr.setRelative(true); addPropertyMaker("border-before-style", m); // border-before-width m = new CondLengthProperty.Maker(PR_BORDER_BEFORE_WIDTH); m.useGeneric(genericCondBorderWidth); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_TOP_WIDTH, PR_BORDER_TOP_WIDTH, PR_BORDER_RIGHT_WIDTH, PR_BORDER_LEFT_WIDTH); corr.setRelative(true); addPropertyMaker("border-before-width", m); // border-after-color m = new ColorProperty.Maker(PR_BORDER_AFTER_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_BOTTOM_COLOR, PR_BORDER_BOTTOM_COLOR, PR_BORDER_LEFT_COLOR, PR_BORDER_RIGHT_COLOR); corr.setRelative(true); addPropertyMaker("border-after-color", m); // border-after-style m = new EnumProperty.Maker(PR_BORDER_AFTER_STYLE); m.useGeneric(genericBorderStyle); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_BOTTOM_STYLE, PR_BORDER_BOTTOM_STYLE, PR_BORDER_LEFT_STYLE, PR_BORDER_RIGHT_STYLE); corr.setRelative(true); addPropertyMaker("border-after-style", m); // border-after-width m = new CondLengthProperty.Maker(PR_BORDER_AFTER_WIDTH); m.useGeneric(genericCondBorderWidth); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_BOTTOM_WIDTH, PR_BORDER_BOTTOM_WIDTH, PR_BORDER_LEFT_WIDTH, PR_BORDER_LEFT_WIDTH); corr.setRelative(true); addPropertyMaker("border-after-width", m); // border-start-color m = new ColorProperty.Maker(PR_BORDER_START_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_LEFT_COLOR, PR_BORDER_RIGHT_COLOR, PR_BORDER_TOP_COLOR, PR_BORDER_TOP_COLOR); corr.setRelative(true); addPropertyMaker("border-start-color", m); // border-start-style m = new EnumProperty.Maker(PR_BORDER_START_STYLE); m.useGeneric(genericBorderStyle); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_LEFT_STYLE, PR_BORDER_RIGHT_STYLE, PR_BORDER_TOP_STYLE, PR_BORDER_TOP_STYLE); corr.setRelative(true); addPropertyMaker("border-start-style", m); // border-start-width m = new CondLengthProperty.Maker(PR_BORDER_START_WIDTH); m.useGeneric(genericCondBorderWidth); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_LEFT_WIDTH, PR_BORDER_RIGHT_WIDTH, PR_BORDER_TOP_WIDTH, PR_BORDER_TOP_WIDTH); corr.setRelative(true); addPropertyMaker("border-start-width", m); // border-end-color m = new ColorProperty.Maker(PR_BORDER_END_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_RIGHT_COLOR, PR_BORDER_LEFT_COLOR, PR_BORDER_BOTTOM_COLOR, PR_BORDER_BOTTOM_COLOR); corr.setRelative(true); addPropertyMaker("border-end-color", m); // border-end-style m = new EnumProperty.Maker(PR_BORDER_END_STYLE); m.useGeneric(genericBorderStyle); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_RIGHT_STYLE, PR_BORDER_LEFT_STYLE, PR_BORDER_BOTTOM_STYLE, PR_BORDER_BOTTOM_STYLE); corr.setRelative(true); addPropertyMaker("border-end-style", m); // border-end-width m = new CondLengthProperty.Maker(PR_BORDER_END_WIDTH); m.useGeneric(genericCondBorderWidth); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_RIGHT_WIDTH, PR_BORDER_LEFT_WIDTH, PR_BORDER_BOTTOM_WIDTH, PR_BORDER_BOTTOM_WIDTH); corr.setRelative(true); addPropertyMaker("border-end-width", m); // border-top-color m = new ColorProperty.Maker(PR_BORDER_TOP_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); m.addShorthand(generics[PR_BORDER_TOP]); m.addShorthand(generics[PR_BORDER_COLOR]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_BEFORE_COLOR, PR_BORDER_BEFORE_COLOR, PR_BORDER_START_COLOR, PR_BORDER_START_COLOR); addPropertyMaker("border-top-color", m); // border-top-style m = new EnumProperty.Maker(PR_BORDER_TOP_STYLE); m.useGeneric(genericBorderStyle); m.addShorthand(generics[PR_BORDER_TOP]); m.addShorthand(generics[PR_BORDER_STYLE]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_BEFORE_STYLE, PR_BORDER_BEFORE_STYLE, PR_BORDER_START_STYLE, PR_BORDER_START_STYLE); addPropertyMaker("border-top-style", m); // border-top-width bwm = new BorderWidthPropertyMaker(PR_BORDER_TOP_WIDTH); bwm.useGeneric(genericBorderWidth); bwm.setBorderStyleId(PR_BORDER_TOP_STYLE); bwm.addShorthand(generics[PR_BORDER_TOP]); bwm.addShorthand(generics[PR_BORDER_WIDTH]); bwm.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(bwm); corr.setCorresponding(PR_BORDER_BEFORE_WIDTH, PR_BORDER_BEFORE_WIDTH, PR_BORDER_START_WIDTH, PR_BORDER_START_WIDTH); addPropertyMaker("border-top-width", bwm); // border-bottom-color m = new ColorProperty.Maker(PR_BORDER_BOTTOM_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); m.addShorthand(generics[PR_BORDER_BOTTOM]); m.addShorthand(generics[PR_BORDER_COLOR]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_AFTER_COLOR, PR_BORDER_AFTER_COLOR, PR_BORDER_END_COLOR, PR_BORDER_END_COLOR); addPropertyMaker("border-bottom-color", m); // border-bottom-style m = new EnumProperty.Maker(PR_BORDER_BOTTOM_STYLE); m.useGeneric(genericBorderStyle); m.addShorthand(generics[PR_BORDER_BOTTOM]); m.addShorthand(generics[PR_BORDER_STYLE]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_AFTER_STYLE, PR_BORDER_AFTER_STYLE, PR_BORDER_END_STYLE, PR_BORDER_END_STYLE); addPropertyMaker("border-bottom-style", m); // border-bottom-width bwm = new BorderWidthPropertyMaker(PR_BORDER_BOTTOM_WIDTH); bwm.useGeneric(genericBorderWidth); bwm.setBorderStyleId(PR_BORDER_BOTTOM_STYLE); bwm.addShorthand(generics[PR_BORDER_BOTTOM]); bwm.addShorthand(generics[PR_BORDER_WIDTH]); bwm.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(bwm); corr.setCorresponding(PR_BORDER_AFTER_WIDTH, PR_BORDER_AFTER_WIDTH, PR_BORDER_END_WIDTH, PR_BORDER_END_WIDTH); addPropertyMaker("border-bottom-width", bwm); // border-left-color m = new ColorProperty.Maker(PR_BORDER_LEFT_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); m.addShorthand(generics[PR_BORDER_LEFT]); m.addShorthand(generics[PR_BORDER_COLOR]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_START_COLOR, PR_BORDER_END_COLOR, PR_BORDER_AFTER_COLOR, PR_BORDER_BEFORE_COLOR); addPropertyMaker("border-left-color", m); // border-left-style m = new EnumProperty.Maker(PR_BORDER_LEFT_STYLE); m.useGeneric(genericBorderStyle); m.addShorthand(generics[PR_BORDER_LEFT]); m.addShorthand(generics[PR_BORDER_STYLE]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_START_STYLE, PR_BORDER_END_STYLE, PR_BORDER_AFTER_STYLE, PR_BORDER_BEFORE_STYLE); addPropertyMaker("border-left-style", m); // border-left-width bwm = new BorderWidthPropertyMaker(PR_BORDER_LEFT_WIDTH); bwm.useGeneric(genericBorderWidth); bwm.setBorderStyleId(PR_BORDER_LEFT_STYLE); bwm.addShorthand(generics[PR_BORDER_LEFT]); bwm.addShorthand(generics[PR_BORDER_WIDTH]); bwm.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(bwm); corr.setCorresponding(PR_BORDER_START_WIDTH, PR_BORDER_END_WIDTH, PR_BORDER_AFTER_WIDTH, PR_BORDER_BEFORE_WIDTH); addPropertyMaker("border-left-width", bwm); // border-right-color m = new ColorProperty.Maker(PR_BORDER_RIGHT_COLOR); m.useGeneric(genericColor); m.setInherited(false); m.setDefault("black"); m.addShorthand(generics[PR_BORDER_RIGHT]); m.addShorthand(generics[PR_BORDER_COLOR]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_END_COLOR, PR_BORDER_START_COLOR, PR_BORDER_BEFORE_COLOR, PR_BORDER_AFTER_COLOR); addPropertyMaker("border-right-color", m); // border-right-style m = new EnumProperty.Maker(PR_BORDER_RIGHT_STYLE); m.useGeneric(genericBorderStyle); m.addShorthand(generics[PR_BORDER_RIGHT]); m.addShorthand(generics[PR_BORDER_STYLE]); m.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_BORDER_END_STYLE, PR_BORDER_START_STYLE, PR_BORDER_BEFORE_STYLE, PR_BORDER_AFTER_STYLE); addPropertyMaker("border-right-style", m); // border-right-width bwm = new BorderWidthPropertyMaker(PR_BORDER_RIGHT_WIDTH); bwm.useGeneric(genericBorderWidth); bwm.setBorderStyleId(PR_BORDER_RIGHT_STYLE); bwm.addShorthand(generics[PR_BORDER_RIGHT]); bwm.addShorthand(generics[PR_BORDER_WIDTH]); bwm.addShorthand(generics[PR_BORDER]); corr = new CorrespondingPropertyMaker(bwm); corr.setCorresponding(PR_BORDER_END_WIDTH, PR_BORDER_START_WIDTH, PR_BORDER_BEFORE_WIDTH, PR_BORDER_AFTER_WIDTH); addPropertyMaker("border-right-width", bwm); // padding-before m = new CondLengthProperty.Maker(PR_PADDING_BEFORE); m.useGeneric(genericCondPadding); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_TOP, PR_PADDING_TOP, PR_PADDING_RIGHT, PR_PADDING_LEFT); corr.setRelative(true); addPropertyMaker("padding-before", m); // padding-after m = new CondLengthProperty.Maker(PR_PADDING_AFTER); m.useGeneric(genericCondPadding); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_BOTTOM, PR_PADDING_BOTTOM, PR_PADDING_LEFT, PR_PADDING_RIGHT); corr.setRelative(true); addPropertyMaker("padding-after", m); // padding-start m = new CondLengthProperty.Maker(PR_PADDING_START); m.useGeneric(genericCondPadding); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_LEFT, PR_PADDING_RIGHT, PR_PADDING_TOP, PR_PADDING_TOP); corr.setRelative(true); addPropertyMaker("padding-start", m); // padding-end m = new CondLengthProperty.Maker(PR_PADDING_END); m.useGeneric(genericCondPadding); m.getSubpropMaker(CP_CONDITIONALITY).setDefault("discard"); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_RIGHT, PR_PADDING_LEFT, PR_PADDING_BOTTOM, PR_PADDING_BOTTOM); corr.setRelative(true); addPropertyMaker("padding-end", m); // padding-top m = new LengthProperty.Maker(PR_PADDING_TOP); m.useGeneric(genericPadding); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_BEFORE, PR_PADDING_BEFORE, PR_PADDING_START, PR_PADDING_START); addPropertyMaker("padding-top", m); // padding-bottom m = new LengthProperty.Maker(PR_PADDING_BOTTOM); m.useGeneric(genericPadding); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_AFTER, PR_PADDING_AFTER, PR_PADDING_END, PR_PADDING_END); addPropertyMaker("padding-bottom", m); // padding-left m = new LengthProperty.Maker(PR_PADDING_LEFT); m.useGeneric(genericPadding); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_START, PR_PADDING_END, PR_PADDING_AFTER, PR_PADDING_BEFORE); addPropertyMaker("padding-left", m); // padding-right m = new LengthProperty.Maker(PR_PADDING_RIGHT); m.useGeneric(genericPadding); corr = new CorrespondingPropertyMaker(m); corr.setCorresponding(PR_PADDING_END, PR_PADDING_START, PR_PADDING_BEFORE, PR_PADDING_AFTER); addPropertyMaker("padding-right", m); }
// in src/java/org/apache/fop/fo/FOPropertyMapping.java
protected Property convertPropertyDatatype( Property p, PropertyList propertyList, FObj fo) throws PropertyException { String nameval = p.getNCname(); if (nameval != null) { FObj fobj = (fo == null ? propertyList.getFObj() : fo); FOUserAgent ua = (fobj == null ? null : fobj.getUserAgent()); return ColorProperty.getInstance(ua, nameval); } return super.convertPropertyDatatype(p, propertyList, fo); }
// in src/java/org/apache/fop/fo/FOPropertyMapping.java
private void createBlockAndLineProperties() { // CSOK: MethodLength PropertyMaker m; // hyphenation-keep m = new EnumProperty.Maker(PR_HYPHENATION_KEEP); m.setInherited(true); m.addEnum("auto", getEnumProperty(EN_AUTO, "AUTO")); m.addEnum("column", getEnumProperty(EN_COLUMN, "COLUMN")); m.addEnum("page", getEnumProperty(EN_PAGE, "PAGE")); m.setDefault("auto"); addPropertyMaker("hyphenation-keep", m); // hyphenation-ladder-count m = new NumberProperty.Maker(PR_HYPHENATION_LADDER_COUNT); m.setInherited(true); m.addEnum("no-limit", getEnumProperty(EN_NO_LIMIT, "NO_LIMIT")); m.setDefault("no-limit"); addPropertyMaker("hyphenation-ladder-count", m); // last-line-end-indent m = new LengthProperty.Maker(PR_LAST_LINE_END_INDENT); m.setInherited(true); m.setDefault("0pt"); m.setPercentBase(LengthBase.CONTAINING_BLOCK_WIDTH); addPropertyMaker("last-line-end-indent", m); // line-height m = new LineHeightPropertyMaker(PR_LINE_HEIGHT); m.useGeneric(genericSpace); m.setInherited(true); m.addKeyword("normal", "1.2"); m.setPercentBase(LengthBase.FONTSIZE); m.setDefault("normal", true); m.addShorthand(generics[PR_FONT]); addPropertyMaker("line-height", m); // line-height-shift-adjustment m = new EnumProperty.Maker(PR_LINE_HEIGHT_SHIFT_ADJUSTMENT); m.setInherited(true); m.addEnum("consider-shifts", getEnumProperty(EN_CONSIDER_SHIFTS, "CONSIDER_SHIFTS")); m.addEnum("disregard-shifts", getEnumProperty(EN_DISREGARD_SHIFTS, "DISREGARD_SHIFTS")); m.setDefault("consider-shifts"); addPropertyMaker("line-height-shift-adjustment", m); // line-stacking-strategy m = new EnumProperty.Maker(PR_LINE_STACKING_STRATEGY); m.setInherited(true); m.addEnum("line-height", getEnumProperty(EN_LINE_HEIGHT, "LINE_HEIGHT")); m.addEnum("font-height", getEnumProperty(EN_FONT_HEIGHT, "FONT_HEIGHT")); m.addEnum("max-height", getEnumProperty(EN_MAX_HEIGHT, "MAX_HEIGHT")); m.setDefault("max-height"); addPropertyMaker("line-stacking-strategy", m); // linefeed-treatment m = new EnumProperty.Maker(PR_LINEFEED_TREATMENT); m.setInherited(true); m.addEnum("ignore", getEnumProperty(EN_IGNORE, "IGNORE")); m.addEnum("preserve", getEnumProperty(EN_PRESERVE, "PRESERVE")); m.addEnum("treat-as-space", getEnumProperty(EN_TREAT_AS_SPACE, "TREAT_AS_SPACE")); m.addEnum("treat-as-zero-width-space", getEnumProperty(EN_TREAT_AS_ZERO_WIDTH_SPACE, "TREAT_AS_ZERO_WIDTH_SPACE")); m.setDefault("treat-as-space"); m.addShorthand(generics[PR_WHITE_SPACE]); addPropertyMaker("linefeed-treatment", m); // white-space-treatment m = new EnumProperty.Maker(PR_WHITE_SPACE_TREATMENT); m.setInherited(true); m.addEnum("ignore", getEnumProperty(EN_IGNORE, "IGNORE")); m.addEnum("preserve", getEnumProperty(EN_PRESERVE, "PRESERVE")); m.addEnum("ignore-if-before-linefeed", getEnumProperty(EN_IGNORE_IF_BEFORE_LINEFEED, "IGNORE_IF_BEFORE_LINEFEED")); m.addEnum("ignore-if-after-linefeed", getEnumProperty(EN_IGNORE_IF_AFTER_LINEFEED, "IGNORE_IF_AFTER_LINEFEED")); m.addEnum("ignore-if-surrounding-linefeed", getEnumProperty(EN_IGNORE_IF_SURROUNDING_LINEFEED, "IGNORE_IF_SURROUNDING_LINEFEED")); m.setDefault("ignore-if-surrounding-linefeed"); m.addShorthand(generics[PR_WHITE_SPACE]); addPropertyMaker("white-space-treatment", m); // text-align TODO: make it a StringProperty with enums. m = new EnumProperty.Maker(PR_TEXT_ALIGN) { public Property get(int subpropId, PropertyList propertyList, boolean bTryInherit, boolean bTryDefault) throws PropertyException { Property p = super.get(subpropId, propertyList, bTryInherit, bTryDefault); if ( p != null ) { int pv = p.getEnum(); if ( ( pv == EN_LEFT ) || ( pv == EN_RIGHT ) ) { p = calcWritingModeDependent ( pv, propertyList.get(Constants.PR_WRITING_MODE).getEnum() ); } } return p; } }; m.setInherited(true); m.addEnum("center", getEnumProperty(EN_CENTER, "CENTER")); m.addEnum("end", getEnumProperty(EN_END, "END")); m.addEnum("start", getEnumProperty(EN_START, "START")); m.addEnum("justify", getEnumProperty(EN_JUSTIFY, "JUSTIFY")); // [GA] must defer writing-mode relative mapping of left/right m.addEnum("left", getEnumProperty(EN_LEFT, "LEFT")); m.addEnum("right", getEnumProperty(EN_RIGHT, "RIGHT")); // [GA] inside and outside are not correctly implemented by the following mapping m.addEnum("inside", getEnumProperty(EN_START, "START")); m.addEnum("outside", getEnumProperty(EN_END, "END")); m.setDefault("start"); addPropertyMaker("text-align", m); // text-align-last m = new EnumProperty.Maker(PR_TEXT_ALIGN_LAST) { public Property get(int subpropId, PropertyList propertyList, boolean bTryInherit, boolean bTryDefault) throws PropertyException { Property p = super.get(subpropId, propertyList, bTryInherit, bTryDefault); if (p != null && p.getEnum() == EN_RELATIVE) { //The default may have been returned, so check inherited value p = propertyList.getNearestSpecified(PR_TEXT_ALIGN_LAST); if (p.getEnum() == EN_RELATIVE) { return calcRelative(propertyList); } } return p; } private Property calcRelative(PropertyList propertyList) throws PropertyException { Property corresponding = propertyList.get(PR_TEXT_ALIGN); if (corresponding == null) { return null; } int correspondingValue = corresponding.getEnum(); if (correspondingValue == EN_JUSTIFY) { return getEnumProperty(EN_START, "START"); } else if (correspondingValue == EN_END) { return getEnumProperty(EN_END, "END"); } else if (correspondingValue == EN_START) { return getEnumProperty(EN_START, "START"); } else if (correspondingValue == EN_CENTER) { return getEnumProperty(EN_CENTER, "CENTER"); } else if (correspondingValue == EN_LEFT) { return calcWritingModeDependent ( EN_LEFT, propertyList.get(Constants.PR_WRITING_MODE).getEnum() ); } else if (correspondingValue == EN_RIGHT) { return calcWritingModeDependent ( EN_RIGHT, propertyList.get(Constants.PR_WRITING_MODE).getEnum() ); } else { return null; } } }; m.setInherited(false); //Actually it's "true" but the special PropertyMaker compensates // Note: both 'end', 'right' and 'outside' are mapped to END // both 'start', 'left' and 'inside' are mapped to START m.addEnum("relative", getEnumProperty(EN_RELATIVE, "RELATIVE")); m.addEnum("center", getEnumProperty(EN_CENTER, "CENTER")); m.addEnum("end", getEnumProperty(EN_END, "END")); m.addEnum("right", getEnumProperty(EN_END, "END")); m.addEnum("start", getEnumProperty(EN_START, "START")); m.addEnum("left", getEnumProperty(EN_START, "START")); m.addEnum("justify", getEnumProperty(EN_JUSTIFY, "JUSTIFY")); m.addEnum("inside", getEnumProperty(EN_START, "START")); m.addEnum("outside", getEnumProperty(EN_END, "END")); m.setDefault("relative", true); addPropertyMaker("text-align-last", m); // text-indent m = new LengthProperty.Maker(PR_TEXT_INDENT); m.setInherited(true); m.setDefault("0pt"); m.setPercentBase(LengthBase.CONTAINING_BLOCK_WIDTH); addPropertyMaker("text-indent", m); // white-space-collapse m = new EnumProperty.Maker(PR_WHITE_SPACE_COLLAPSE); m.useGeneric(genericBoolean); m.setInherited(true); m.setDefault("true"); m.addShorthand(generics[PR_WHITE_SPACE]); addPropertyMaker("white-space-collapse", m); // wrap-option m = new EnumProperty.Maker(PR_WRAP_OPTION); m.setInherited(true); m.addEnum("wrap", getEnumProperty(EN_WRAP, "WRAP")); m.addEnum("no-wrap", getEnumProperty(EN_NO_WRAP, "NO_WRAP")); m.setDefault("wrap"); m.addShorthand(generics[PR_WHITE_SPACE]); addPropertyMaker("wrap-option", m); }
// in src/java/org/apache/fop/fo/FOPropertyMapping.java
public Property get(int subpropId, PropertyList propertyList, boolean bTryInherit, boolean bTryDefault) throws PropertyException { Property p = super.get(subpropId, propertyList, bTryInherit, bTryDefault); if ( p != null ) { int pv = p.getEnum(); if ( ( pv == EN_LEFT ) || ( pv == EN_RIGHT ) ) { p = calcWritingModeDependent ( pv, propertyList.get(Constants.PR_WRITING_MODE).getEnum() ); } } return p; }
// in src/java/org/apache/fop/fo/FOPropertyMapping.java
public Property get(int subpropId, PropertyList propertyList, boolean bTryInherit, boolean bTryDefault) throws PropertyException { Property p = super.get(subpropId, propertyList, bTryInherit, bTryDefault); if (p != null && p.getEnum() == EN_RELATIVE) { //The default may have been returned, so check inherited value p = propertyList.getNearestSpecified(PR_TEXT_ALIGN_LAST); if (p.getEnum() == EN_RELATIVE) { return calcRelative(propertyList); } } return p; }
// in src/java/org/apache/fop/fo/FOPropertyMapping.java
private Property calcRelative(PropertyList propertyList) throws PropertyException { Property corresponding = propertyList.get(PR_TEXT_ALIGN); if (corresponding == null) { return null; } int correspondingValue = corresponding.getEnum(); if (correspondingValue == EN_JUSTIFY) { return getEnumProperty(EN_START, "START"); } else if (correspondingValue == EN_END) { return getEnumProperty(EN_END, "END"); } else if (correspondingValue == EN_START) { return getEnumProperty(EN_START, "START"); } else if (correspondingValue == EN_CENTER) { return getEnumProperty(EN_CENTER, "CENTER"); } else if (correspondingValue == EN_LEFT) { return calcWritingModeDependent ( EN_LEFT, propertyList.get(Constants.PR_WRITING_MODE).getEnum() ); } else if (correspondingValue == EN_RIGHT) { return calcWritingModeDependent ( EN_RIGHT, propertyList.get(Constants.PR_WRITING_MODE).getEnum() ); } else { return null; } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
private Color getAttributeAsColor(Attributes attributes, String name) throws PropertyException { String s = attributes.getValue(name); if (s == null) { return null; } else { return ColorUtil.parseColorString(userAgent, s); } }
// in src/java/org/apache/fop/datatypes/LengthBase.java
public int getBaseLength(PercentBaseContext context) throws PropertyException { int baseLen = 0; if (context != null) { if (baseType == FONTSIZE || baseType == INH_FONTSIZE) { return baseLength.getValue(context); } baseLen = context.getBaseLength(baseType, fobj); } else { log.error("getBaseLength called without context"); } return baseLen; }
// in src/java/org/apache/fop/util/ColorUtil.java
public static Color parseColorString(FOUserAgent foUserAgent, String value) throws PropertyException { if (value == null) { return null; } Color parsedColor = colorMap.get(value.toLowerCase()); if (parsedColor == null) { if (value.startsWith("#")) { parsedColor = parseWithHash(value); } else if (value.startsWith("rgb(")) { parsedColor = parseAsRGB(value); } else if (value.startsWith("url(")) { throw new PropertyException( "Colors starting with url( are not yet supported!"); } else if (value.startsWith("java.awt.Color")) { parsedColor = parseAsJavaAWTColor(value); } else if (value.startsWith("system-color(")) { parsedColor = parseAsSystemColor(value); } else if (value.startsWith("fop-rgb-icc")) { parsedColor = parseAsFopRgbIcc(foUserAgent, value); } else if (value.startsWith("fop-rgb-named-color")) { parsedColor = parseAsFopRgbNamedColor(foUserAgent, value); } else if (value.startsWith("cie-lab-color")) { parsedColor = parseAsCIELabColor(foUserAgent, value); } else if (value.startsWith("cmyk")) { parsedColor = parseAsCMYK(value); } if (parsedColor == null) { throw new PropertyException("Unknown Color: " + value); } colorMap.put(value, parsedColor); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsSystemColor(String value) throws PropertyException { int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); } else { throw new PropertyException("Unknown color format: " + value + ". Must be system-color(x)"); } return colorMap.get(value); }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsJavaAWTColor(String value) throws PropertyException { float red = 0.0f; float green = 0.0f; float blue = 0.0f; int poss = value.indexOf("["); int pose = value.indexOf("]"); try { if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); String[] args = value.split(","); if (args.length != 3) { throw new PropertyException( "Invalid number of arguments for a java.awt.Color: " + value); } red = Float.parseFloat(args[0].trim().substring(2)) / 255f; green = Float.parseFloat(args[1].trim().substring(2)) / 255f; blue = Float.parseFloat(args[2].trim().substring(2)) / 255f; if ((red < 0.0 || red > 1.0) || (green < 0.0 || green > 1.0) || (blue < 0.0 || blue > 1.0)) { throw new PropertyException("Color values out of range"); } } else { throw new IllegalArgumentException( "Invalid format for a java.awt.Color: " + value); } } catch (RuntimeException re) { throw new PropertyException(re); } return new Color(red, green, blue); }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsRGB(String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); try { String[] args = value.split(","); if (args.length != 3) { throw new PropertyException( "Invalid number of arguments: rgb(" + value + ")"); } float red = parseComponent255(args[0], value); float green = parseComponent255(args[1], value); float blue = parseComponent255(args[2], value); //Convert to ints to synchronize the behaviour with toRGBFunctionCall() int r = (int)(red * 255 + 0.5); int g = (int)(green * 255 + 0.5); int b = (int)(blue * 255 + 0.5); parsedColor = new Color(r, g, b); } catch (RuntimeException re) { //wrap in a PropertyException throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be rgb(r,g,b)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static float parseComponent255(String str, String function) throws PropertyException { float component; str = str.trim(); if (str.endsWith("%")) { component = Float.parseFloat(str.substring(0, str.length() - 1)) / 100f; } else { component = Float.parseFloat(str) / 255f; } if ((component < 0.0 || component > 1.0)) { throw new PropertyException("Color value out of range for " + function + ": " + str + ". Valid range: [0..255] or [0%..100%]"); } return component; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static float parseComponent1(String argument, String function) throws PropertyException { return parseComponent(argument, 0f, 1f, function); }
// in src/java/org/apache/fop/util/ColorUtil.java
private static float parseComponent(String argument, float min, float max, String function) throws PropertyException { float component = Float.parseFloat(argument.trim()); if ((component < min || component > max)) { throw new PropertyException("Color value out of range for " + function + ": " + argument + ". Valid range: [" + min + ".." + max + "]"); } return component; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseFallback(String[] args, String value) throws PropertyException { float red = parseComponent1(args[0], value); float green = parseComponent1(args[1], value); float blue = parseComponent1(args[2], value); //Sun's classlib rounds differently with this constructor than when converting to sRGB //via CIE XYZ. Color sRGB = new Color(red, green, blue); return sRGB; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseWithHash(String value) throws PropertyException { Color parsedColor; try { int len = value.length(); int alpha; if (len == 5 || len == 9) { alpha = Integer.parseInt( value.substring((len == 5) ? 3 : 7), 16); } else { alpha = 0xFF; } int red = 0; int green = 0; int blue = 0; if ((len == 4) || (len == 5)) { //multiply by 0x11 = 17 = 255/15 red = Integer.parseInt(value.substring(1, 2), 16) * 0x11; green = Integer.parseInt(value.substring(2, 3), 16) * 0x11; blue = Integer.parseInt(value.substring(3, 4), 16) * 0X11; } else if ((len == 7) || (len == 9)) { red = Integer.parseInt(value.substring(1, 3), 16); green = Integer.parseInt(value.substring(3, 5), 16); blue = Integer.parseInt(value.substring(5, 7), 16); } else { throw new NumberFormatException(); } parsedColor = new Color(red, green, blue, alpha); } catch (RuntimeException re) { throw new PropertyException("Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsFopRgbIcc(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { String[] args = value.substring(poss + 1, pose).split(","); try { if (args.length < 5) { throw new PropertyException("Too few arguments for rgb-icc() function"); } //Set up fallback sRGB value Color sRGB = parseFallback(args, value); /* Get and verify ICC profile name */ String iccProfileName = args[3].trim(); if (iccProfileName == null || "".equals(iccProfileName)) { throw new PropertyException("ICC profile name missing"); } ColorSpace colorSpace = null; String iccProfileSrc = null; if (isPseudoProfile(iccProfileName)) { if (CMYK_PSEUDO_PROFILE.equalsIgnoreCase(iccProfileName)) { colorSpace = ColorSpaces.getDeviceCMYKColorSpace(); } else if (SEPARATION_PSEUDO_PROFILE.equalsIgnoreCase(iccProfileName)) { colorSpace = new NamedColorSpace(args[5], sRGB, SEPARATION_PSEUDO_PROFILE, null); } else { assert false : "Incomplete implementation"; } } else { /* Get and verify ICC profile source */ iccProfileSrc = args[4].trim(); if (iccProfileSrc == null || "".equals(iccProfileSrc)) { throw new PropertyException("ICC profile source missing"); } iccProfileSrc = unescapeString(iccProfileSrc); } /* ICC profile arguments */ int componentStart = 4; if (colorSpace instanceof NamedColorSpace) { componentStart++; } float[] iccComponents = new float[args.length - componentStart - 1]; for (int ix = componentStart; ++ix < args.length;) { iccComponents[ix - componentStart - 1] = Float.parseFloat(args[ix].trim()); } if (colorSpace instanceof NamedColorSpace && iccComponents.length == 0) { iccComponents = new float[] {1.0f}; //full tint if not specified } /* Ask FOP factory to get ColorSpace for the specified ICC profile source */ if (foUserAgent != null && iccProfileSrc != null) { RenderingIntent renderingIntent = RenderingIntent.AUTO; //TODO connect to fo:color-profile/@rendering-intent colorSpace = foUserAgent.getFactory().getColorSpaceCache().get( iccProfileName, foUserAgent.getBaseURL(), iccProfileSrc, renderingIntent); } if (colorSpace != null) { // ColorSpace is available if (ColorSpaces.isDeviceColorSpace(colorSpace)) { //Device-specific colors are handled differently: //sRGB is the primary color with the CMYK as the alternative Color deviceColor = new Color(colorSpace, iccComponents, 1.0f); float[] rgbComps = sRGB.getRGBColorComponents(null); parsedColor = new ColorWithAlternatives( rgbComps[0], rgbComps[1], rgbComps[2], new Color[] {deviceColor}); } else { parsedColor = new ColorWithFallback( colorSpace, iccComponents, 1.0f, null, sRGB); } } else { // ICC profile could not be loaded - use rgb replacement values */ log.warn("Color profile '" + iccProfileSrc + "' not found. Using sRGB replacement values."); parsedColor = sRGB; } } catch (RuntimeException re) { throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be fop-rgb-icc(r,g,b,NCNAME,src,....)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsFopRgbNamedColor(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { String[] args = value.substring(poss + 1, pose).split(","); try { if (args.length != 6) { throw new PropertyException("rgb-named-color() function must have 6 arguments"); } //Set up fallback sRGB value Color sRGB = parseFallback(args, value); /* Get and verify ICC profile name */ String iccProfileName = args[3].trim(); if (iccProfileName == null || "".equals(iccProfileName)) { throw new PropertyException("ICC profile name missing"); } ICC_ColorSpace colorSpace = null; String iccProfileSrc; if (isPseudoProfile(iccProfileName)) { throw new IllegalArgumentException( "Pseudo-profiles are not allowed with fop-rgb-named-color()"); } else { /* Get and verify ICC profile source */ iccProfileSrc = args[4].trim(); if (iccProfileSrc == null || "".equals(iccProfileSrc)) { throw new PropertyException("ICC profile source missing"); } iccProfileSrc = unescapeString(iccProfileSrc); } // color name String colorName = unescapeString(args[5].trim()); /* Ask FOP factory to get ColorSpace for the specified ICC profile source */ if (foUserAgent != null && iccProfileSrc != null) { RenderingIntent renderingIntent = RenderingIntent.AUTO; //TODO connect to fo:color-profile/@rendering-intent colorSpace = (ICC_ColorSpace)foUserAgent.getFactory().getColorSpaceCache().get( iccProfileName, foUserAgent.getBaseURL(), iccProfileSrc, renderingIntent); } if (colorSpace != null) { ICC_Profile profile = colorSpace.getProfile(); if (NamedColorProfileParser.isNamedColorProfile(profile)) { NamedColorProfileParser parser = new NamedColorProfileParser(); NamedColorProfile ncp = parser.parseProfile(profile, iccProfileName, iccProfileSrc); NamedColorSpace ncs = ncp.getNamedColor(colorName); if (ncs != null) { parsedColor = new ColorWithFallback(ncs, new float[] {1.0f}, 1.0f, null, sRGB); } else { log.warn("Color '" + colorName + "' does not exist in named color profile: " + iccProfileSrc); parsedColor = sRGB; } } else { log.warn("ICC profile is no named color profile: " + iccProfileSrc); parsedColor = sRGB; } } else { // ICC profile could not be loaded - use rgb replacement values */ log.warn("Color profile '" + iccProfileSrc + "' not found. Using sRGB replacement values."); parsedColor = sRGB; } } catch (IOException ioe) { //wrap in a PropertyException throw new PropertyException(ioe); } catch (RuntimeException re) { throw new PropertyException(re); //wrap in a PropertyException } } else { throw new PropertyException("Unknown color format: " + value + ". Must be fop-rgb-named-color(r,g,b,NCNAME,src,color-name)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsCIELabColor(FOUserAgent foUserAgent, String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { try { String[] args = value.substring(poss + 1, pose).split(","); if (args.length != 6) { throw new PropertyException("cie-lab-color() function must have 6 arguments"); } //Set up fallback sRGB value float red = parseComponent255(args[0], value); float green = parseComponent255(args[1], value); float blue = parseComponent255(args[2], value); Color sRGB = new Color(red, green, blue); float l = parseComponent(args[3], 0f, 100f, value); float a = parseComponent(args[4], -127f, 127f, value); float b = parseComponent(args[5], -127f, 127f, value); //Assuming the XSL-FO spec uses the D50 white point CIELabColorSpace cs = ColorSpaces.getCIELabColorSpaceD50(); //use toColor() to have components normalized Color labColor = cs.toColor(l, a, b, 1.0f); //Convert to ColorWithFallback parsedColor = new ColorWithFallback(labColor, sRGB); } catch (RuntimeException re) { throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be cie-lab-color(r,g,b,Lightness,a-value,b-value)"); } return parsedColor; }
// in src/java/org/apache/fop/util/ColorUtil.java
private static Color parseAsCMYK(String value) throws PropertyException { Color parsedColor; int poss = value.indexOf("("); int pose = value.indexOf(")"); if (poss != -1 && pose != -1) { value = value.substring(poss + 1, pose); String[] args = value.split(","); try { if (args.length != 4) { throw new PropertyException( "Invalid number of arguments: cmyk(" + value + ")"); } float cyan = parseComponent1(args[0], value); float magenta = parseComponent1(args[1], value); float yellow = parseComponent1(args[2], value); float black = parseComponent1(args[3], value); float[] comps = new float[] {cyan, magenta, yellow, black}; Color cmykColor = DeviceCMYKColorSpace.createCMYKColor(comps); float[] rgbComps = cmykColor.getRGBColorComponents(null); parsedColor = new ColorWithAlternatives(rgbComps[0], rgbComps[1], rgbComps[2], new Color[] {cmykColor}); } catch (RuntimeException re) { throw new PropertyException(re); } } else { throw new PropertyException("Unknown color format: " + value + ". Must be cmyk(c,m,y,k)"); } return parsedColor; }
15
            
// in src/java/org/apache/fop/fo/properties/PercentLength.java
catch (PropertyException exc) { log.error(exc); return 0; }
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
catch (PropertyException propEx) { if (fo != null) { propEx.setLocator(fo.getLocator()); } propEx.setPropertyName(getName()); throw propEx; }
// in src/java/org/apache/fop/fo/PropertyList.java
catch ( PropertyException e ) { propID = -1; }
// in src/java/org/apache/fop/fo/PropertyList.java
catch (PropertyException e) { fobj.getFOValidationEventProducer().invalidPropertyValue(this, fobj.getName(), attributeName, attributeValue, e, fobj.locator); }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
catch (PropertyException exc) { log.error(exc); }
// in src/java/org/apache/fop/fo/expr/RelativeNumericProperty.java
catch (PropertyException exc) { log.error(exc); }
// in src/java/org/apache/fop/fo/expr/NCnameProperty.java
catch (PropertyException e) { //Not logging this error since for properties like "border" you would get an awful //lot of error messages for things like "solid" not being valid colors. //log.error("Can't create color value: " + e.getMessage()); return null; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
catch (PropertyException exc) { exc.setPropertyInfo(propInfo); throw exc; }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the color attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/traits/BorderProps.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
9
            
// in src/java/org/apache/fop/fo/properties/FontShorthandProperty.java
catch (PropertyException pe) { pe.setLocator(propertyList.getFObj().getLocator()); pe.setPropertyName(getName()); throw pe; }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
catch (PropertyException propEx) { if (fo != null) { propEx.setLocator(fo.getLocator()); } propEx.setPropertyName(getName()); throw propEx; }
// in src/java/org/apache/fop/fo/expr/PropertyParser.java
catch (PropertyException exc) { exc.setPropertyInfo(propInfo); throw exc; }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the color attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (PropertyException pe) { throw new IFException("Error parsing the fill attribute", pe); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
// in src/java/org/apache/fop/traits/BorderProps.java
catch (PropertyException e) { throw new IllegalArgumentException(e.getMessage()); }
3
runtime (Domain) RendererRuntimeException
public class RendererRuntimeException extends NestedRuntimeException {

    /**
     * Constructs a RendererRuntimeException with the specified message.
     * @param msg the exception mesaage
     */
    public RendererRuntimeException(String msg) {
        super(msg);
    }

    /**
     * Constructs a RendererRuntimeException with the specified message
     * wrapping the underlying exception.
     * @param msg the exception mesaage
     * @param t the underlying exception
     */
    public RendererRuntimeException(String msg, Throwable t) {
        super(msg, t);
    }

}
0 0 0 0 0 0
checked (Domain) RtfException
public class RtfException extends java.io.IOException {
    /**
     * @param reason Description of reason for Exception.
     */
    public RtfException(String reason) {
        super(reason);
    }
}
1
            
// in src/java/org/apache/fop/render/rtf/rtflib/tools/BuilderContext.java
public RtfContainer getContainer(Class containerClass, boolean required, Object /*IBuilder*/ forWhichBuilder) throws RtfException { // TODO what to do if the desired container is not at the top of the stack? // close top-of-stack container? final RtfContainer result = (RtfContainer)getObjectFromStack(containers, containerClass); if (result == null && required) { throw new RtfException( "No RtfContainer of class '" + containerClass.getName() + "' available for '" + forWhichBuilder.getClass().getName() + "' builder" ); } return result; }
0 1
            
// in src/java/org/apache/fop/render/rtf/rtflib/tools/BuilderContext.java
public RtfContainer getContainer(Class containerClass, boolean required, Object /*IBuilder*/ forWhichBuilder) throws RtfException { // TODO what to do if the desired container is not at the top of the stack? // close top-of-stack container? final RtfContainer result = (RtfContainer)getObjectFromStack(containers, containerClass); if (result == null && required) { throw new RtfException( "No RtfContainer of class '" + containerClass.getName() + "' available for '" + forWhichBuilder.getClass().getName() + "' builder" ); } return result; }
1
            
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (RtfException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
1
            
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (RtfException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
1
checked (Domain) RtfStructureException
public class RtfStructureException
extends RtfException {
    /**
     * @param reason Description of reason for exception.
     */
    public RtfStructureException(String reason) {
        super(reason);
    }
}
3
            
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfHeader startHeader() throws IOException, RtfStructureException { if (header != null) { throw new RtfStructureException("startHeader called more than once"); } header = new RtfHeader(this, writer); listTableContainer = new RtfContainer(this, writer); return header; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfPageArea startPageArea() throws IOException, RtfStructureException { if (pageArea != null) { throw new RtfStructureException("startPageArea called more than once"); } // create an empty header if there was none if (header == null) { startHeader(); } header.close(); pageArea = new RtfPageArea(this, writer); addChild(pageArea); return pageArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfDocumentArea startDocumentArea() throws IOException, RtfStructureException { if (docArea != null) { throw new RtfStructureException("startDocumentArea called more than once"); } // create an empty header if there was none if (header == null) { startHeader(); } header.close(); docArea = new RtfDocumentArea(this, writer); addChild(docArea); return docArea; }
0 6
            
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfHeader startHeader() throws IOException, RtfStructureException { if (header != null) { throw new RtfStructureException("startHeader called more than once"); } header = new RtfHeader(this, writer); listTableContainer = new RtfContainer(this, writer); return header; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfPageArea startPageArea() throws IOException, RtfStructureException { if (pageArea != null) { throw new RtfStructureException("startPageArea called more than once"); } // create an empty header if there was none if (header == null) { startHeader(); } header.close(); pageArea = new RtfPageArea(this, writer); addChild(pageArea); return pageArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfPageArea getPageArea() throws IOException, RtfStructureException { if (pageArea == null) { return startPageArea(); } return pageArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfDocumentArea startDocumentArea() throws IOException, RtfStructureException { if (docArea != null) { throw new RtfStructureException("startDocumentArea called more than once"); } // create an empty header if there was none if (header == null) { startHeader(); } header.close(); docArea = new RtfDocumentArea(this, writer); addChild(docArea); return docArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfFile.java
public RtfDocumentArea getDocumentArea() throws IOException, RtfStructureException { if (docArea == null) { return startDocumentArea(); } return docArea; }
// in src/java/org/apache/fop/render/rtf/rtflib/rtfdoc/RtfContainer.java
protected void addChild(RtfElement e) throws RtfStructureException { if (isClosed()) { // No childs should be added to a container that has been closed final StringBuffer sb = new StringBuffer(); sb.append("addChild: container already closed (parent="); sb.append(this.getClass().getName()); sb.append(" child="); sb.append(e.getClass().getName()); sb.append(")"); final String msg = sb.toString(); // warn of this problem final RtfFile rf = getRtfFile(); // if(rf.getLog() != null) { // rf.getLog().logWarning(msg); // } // TODO this should be activated to help detect XSL-FO constructs // that we do not handle properly. /* throw new RtfStructureException(msg); */ } children.add(e); lastChild = e; }
0 0 0
runtime (Lib) RuntimeException 85
            
// in src/java/org/apache/fop/apps/FOURIResolver.java
protected void applyHttpBasicAuthentication(URLConnection connection, String username, String password) { String combined = username + ":" + password; try { ByteArrayOutputStream baout = new ByteArrayOutputStream(combined .length() * 2); Base64EncodeStream base64 = new Base64EncodeStream(baout); // TODO Not sure what charset/encoding can be used with basic // authentication base64.write(combined.getBytes("UTF-8")); base64.close(); connection.setRequestProperty("Authorization", "Basic " + new String(baout.toByteArray(), "UTF-8")); } catch (IOException e) { // won't happen. We're operating in-memory. throw new RuntimeException( "Error during base64 encodation of username/password"); } }
// in src/java/org/apache/fop/pdf/PDFStream.java
private void setUp() { try { data = StreamCacheFactory.getInstance().createStreamCache(); this.streamWriter = new OutputStreamWriter( getBufferOutputStream(), PDFDocument.ENCODING); //Buffer to minimize calls to the converter this.streamWriter = new java.io.BufferedWriter(this.streamWriter); } catch (IOException e) { throw new RuntimeException(e); } }
// in src/java/org/apache/fop/pdf/PDFICCBasedColorSpace.java
public static PDFICCStream setupsRGBColorProfile(PDFDocument pdfDoc) { ICC_Profile profile; PDFICCStream sRGBProfile = pdfDoc.getFactory().makePDFICCStream(); InputStream in = PDFDocument.class.getResourceAsStream("sRGB Color Space Profile.icm"); if (in != null) { try { profile = ColorProfileUtil.getICC_Profile(in); } catch (IOException ioe) { throw new RuntimeException( "Unexpected IOException loading the sRGB profile: " + ioe.getMessage()); } finally { IOUtils.closeQuietly(in); } } else { // Fallback: Use the sRGB profile from the JRE (about 140KB) profile = ColorProfileUtil.getICC_Profile(ColorSpace.CS_sRGB); } sRGBProfile.setColorSpace(profile, null); return sRGBProfile; }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
private String determineExtension(String outputFormat) { for (int i = 0; i < EXTENSIONS.length; i++) { if (EXTENSIONS[i][0].equals(outputFormat)) { String ext = EXTENSIONS[i][1]; if (ext == null) { throw new RuntimeException("Output format '" + outputFormat + "' does not produce a file."); } else { return ext; } } } return ".unk"; //unknown }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public void addSubpropMaker(PropertyMaker subproperty) { throw new RuntimeException("Unable to add subproperties " + getClass()); }
// in src/java/org/apache/fop/fo/properties/PropertyMaker.java
public PropertyMaker getSubpropMaker(int subpropertyId) { throw new RuntimeException("Unable to add subproperties"); }
// in src/java/org/apache/fop/fo/flow/Leader.java
public void bind(PropertyList pList) throws FOPException { super.bind(pList); alignmentAdjust = pList.get(PR_ALIGNMENT_ADJUST).getLength(); alignmentBaseline = pList.get(PR_ALIGNMENT_BASELINE).getEnum(); baselineShift = pList.get(PR_BASELINE_SHIFT).getLength(); dominantBaseline = pList.get(PR_DOMINANT_BASELINE).getEnum(); leaderAlignment = pList.get(PR_LEADER_ALIGNMENT).getEnum(); leaderLength = pList.get(PR_LEADER_LENGTH).getLengthRange(); leaderPattern = pList.get(PR_LEADER_PATTERN).getEnum(); leaderPatternWidth = pList.get(PR_LEADER_PATTERN_WIDTH).getLength(); // use default rule thickness as a default ruleThickness = getPropertyMakerFor(PR_RULE_THICKNESS).make(pList).getLength(); switch(leaderPattern) { case EN_SPACE: // use Space break; case EN_RULE: // the following properties only apply // for leader-pattern = "rule" ruleStyle = pList.get(PR_RULE_STYLE).getEnum(); // use specified rule thickness to override default (established above) ruleThickness = pList.get(PR_RULE_THICKNESS).getLength(); break; case EN_DOTS: break; case EN_USECONTENT: // use inline layout manager to create inline areas // add the inline parent multiple times until leader full break; default: throw new RuntimeException("Invalid leader pattern: " + leaderPattern); } // letterSpacing = pList.get(PR_LETTER_SPACING); // textShadow = pList.get(PR_TEXT_SHADOW); }
// in src/java/org/apache/fop/fo/ElementMapping.java
public static DOMImplementation getDefaultDOMImplementation() { DocumentBuilderFactory fact = DocumentBuilderFactory.newInstance(); fact.setNamespaceAware(true); fact.setValidating(false); try { return fact.newDocumentBuilder().getDOMImplementation(); } catch (ParserConfigurationException e) { throw new RuntimeException( "Cannot return default DOM implementation: " + e.getMessage()); } }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
private DOMImplementation getDOMImplementation(String ver) { //TODO It would be great if Batik provided this method as static helper method. if (ver == null || ver.length() == 0 || ver.equals("1.0") || ver.equals("1.1")) { return SVGDOMImplementation.getDOMImplementation(); } else if (ver.equals("1.2")) { try { Class clazz = Class.forName( "org.apache.batik.dom.svg12.SVG12DOMImplementation"); return (DOMImplementation)clazz.getMethod( "getDOMImplementation", (Class[])null).invoke(null, (Object[])null); } catch (Exception e) { return SVGDOMImplementation.getDOMImplementation(); } } throw new RuntimeException("Unsupport SVG version '" + ver + "'"); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
static XMLReader createParser() { try { SAXParserFactory factory = SAXParserFactory.newInstance(); factory.setNamespaceAware(true); return factory.newSAXParser().getXMLReader(); } catch (Exception e) { throw new RuntimeException("Couldn't create XMLReader: " + e.getMessage()); } }
// in src/java/org/apache/fop/svg/NativeTextPainter.java
Override protected void paintTextRuns(List textRuns, Graphics2D g2d) { if (log.isTraceEnabled()) { log.trace("paintTextRuns: count = " + textRuns.size()); } if (!isSupported(g2d)) { super.paintTextRuns(textRuns, g2d); return; } for (int i = 0; i < textRuns.size(); i++) { TextRun textRun = (TextRun)textRuns.get(i); try { paintTextRun(textRun, g2d); } catch (IOException ioe) { //No other possibility than to use a RuntimeException throw new RuntimeException(ioe); } } }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
public void displayError(String message) { try { getErrorHandler().error(new TranscoderException(message)); } catch (TranscoderException ex) { throw new RuntimeException(); } }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
public void displayError(Exception e) { try { getErrorHandler().error(new TranscoderException(e)); } catch (TranscoderException ex) { throw new RuntimeException(); } }
// in src/java/org/apache/fop/fonts/LazyFont.java
private void load(boolean fail) { if (!isMetricsLoaded) { try { if (metricsFileName != null) { /**@todo Possible thread problem here */ FontReader reader = null; if (resolver != null) { Source source = resolver.resolve(metricsFileName); if (source == null) { String err = "Cannot load font: failed to create Source from metrics file " + metricsFileName; if (fail) { throw new RuntimeException(err); } else { log.error(err); } return; } InputStream in = null; if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null && source.getSystemId() != null) { in = new java.net.URL(source.getSystemId()).openStream(); } if (in == null) { String err = "Cannot load font: After URI resolution, the returned" + " Source object does not contain an InputStream" + " or a valid URL (system identifier) for metrics file: " + metricsFileName; if (fail) { throw new RuntimeException(err); } else { log.error(err); } return; } InputSource src = new InputSource(in); src.setSystemId(source.getSystemId()); reader = new FontReader(src); } else { reader = new FontReader(new InputSource( new URL(metricsFileName).openStream())); } reader.setKerningEnabled(useKerning); reader.setAdvancedEnabled(useAdvanced); if (this.embedded) { reader.setFontEmbedPath(fontEmbedPath); } reader.setResolver(resolver); realFont = reader.getFont(); } else { if (fontEmbedPath == null) { throw new RuntimeException("Cannot load font. No font URIs available."); } realFont = FontLoader.loadFont(fontEmbedPath, this.subFontName, this.embedded, this.encodingMode, useKerning, useAdvanced, resolver); } if (realFont instanceof FontDescriptor) { realFontDescriptor = (FontDescriptor) realFont; } } catch (FOPException fopex) { log.error("Failed to read font metrics file " + metricsFileName, fopex); if (fail) { throw new RuntimeException(fopex.getMessage()); } } catch (IOException ioex) { log.error("Failed to read font metrics file " + metricsFileName, ioex); if (fail) { throw new RuntimeException(ioex.getMessage()); } } realFont.setEventListener(this.eventListener); isMetricsLoaded = true; } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
protected void setValue(Object target, Class<?> argType, Object value) { Class<?> c = target.getClass(); try { Method mth = c.getMethod(method, argType); mth.invoke(target, value); } catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
public void parse(String line, int startpos, Stack<Object> stack) throws IOException { Boolean b = getBooleanValue(line, startpos); Object target = getContextObject(stack); Class<?> c = target.getClass(); try { Method mth = c.getMethod(method, boolean.class); mth.invoke(target, b); } catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); } }
// in src/java/org/apache/fop/fonts/truetype/TTFFontLoader.java
private void buildFont(TTFFile ttf, String ttcFontName) { if (ttf.isCFF()) { throw new UnsupportedOperationException( "OpenType fonts with CFF data are not supported, yet"); } boolean isCid = this.embedded; if (this.encodingMode == EncodingMode.SINGLE_BYTE) { isCid = false; } if (isCid) { multiFont = new MultiByteFont(); returnFont = multiFont; multiFont.setTTCName(ttcFontName); } else { singleFont = new SingleByteFont(); returnFont = singleFont; } returnFont.setResolver(resolver); returnFont.setFontName(ttf.getPostScriptName()); returnFont.setFullName(ttf.getFullName()); returnFont.setFamilyNames(ttf.getFamilyNames()); returnFont.setFontSubFamilyName(ttf.getSubFamilyName()); returnFont.setCapHeight(ttf.getCapHeight()); returnFont.setXHeight(ttf.getXHeight()); returnFont.setAscender(ttf.getLowerCaseAscent()); returnFont.setDescender(ttf.getLowerCaseDescent()); returnFont.setFontBBox(ttf.getFontBBox()); returnFont.setFlags(ttf.getFlags()); returnFont.setStemV(Integer.parseInt(ttf.getStemV())); //not used for TTF returnFont.setItalicAngle(Integer.parseInt(ttf.getItalicAngle())); returnFont.setMissingWidth(0); returnFont.setWeight(ttf.getWeightClass()); if (isCid) { multiFont.setCIDType(CIDFontType.CIDTYPE2); int[] wx = ttf.getWidths(); multiFont.setWidthArray(wx); List entries = ttf.getCMaps(); BFEntry[] bfentries = new BFEntry[entries.size()]; int pos = 0; Iterator iter = ttf.getCMaps().listIterator(); while (iter.hasNext()) { TTFCmapEntry ce = (TTFCmapEntry)iter.next(); bfentries[pos] = new BFEntry(ce.getUnicodeStart(), ce.getUnicodeEnd(), ce.getGlyphStartIndex()); pos++; } multiFont.setBFEntries(bfentries); } else { singleFont.setFontType(FontType.TRUETYPE); singleFont.setEncoding(ttf.getCharSetName()); returnFont.setFirstChar(ttf.getFirstChar()); returnFont.setLastChar(ttf.getLastChar()); copyWidthsSingleByte(ttf); } if (useKerning) { copyKerning(ttf, isCid); } if (useAdvanced) { copyAdvanced(ttf); } if (this.embedded) { if (ttf.isEmbeddable()) { returnFont.setEmbedFileName(this.fontFileURI); } else { String msg = "The font " + this.fontFileURI + " is not embeddable due to a" + " licensing restriction."; throw new RuntimeException(msg); } } }
// in src/java/org/apache/fop/render/print/PrintRenderer.java
private void initializePrinterJob() { if (this.printerJob == null) { printerJob = PrinterJob.getPrinterJob(); printerJob.setJobName("FOP Document"); printerJob.setCopies(copies); if (System.getProperty("dialog") != null) { if (!printerJob.printDialog()) { throw new RuntimeException( "Printing cancelled by operator"); } } printerJob.setPageable(this); } }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
protected void handleSAXException(SAXException saxe) { throw new RuntimeException(saxe.getMessage()); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
public void startRenderer(OutputStream outputStream) throws IOException { if (this.handler == null) { SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); try { TransformerHandler transformerHandler = factory.newTransformerHandler(); setContentHandler(transformerHandler); StreamResult res = new StreamResult(outputStream); transformerHandler.setResult(res); } catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); } this.out = outputStream; } try { handler.startDocument(); } catch (SAXException saxe) { handleSAXException(saxe); } }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
Override public void startRenderer(OutputStream outputStream) throws IOException { log.debug("Rendering areas to Area Tree XML"); if (this.handler == null) { SAXTransformerFactory factory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); try { TransformerHandler transformerHandler = factory.newTransformerHandler(); this.handler = transformerHandler; StreamResult res = new StreamResult(outputStream); transformerHandler.setResult(res); } catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); } this.out = outputStream; } try { handler.startDocument(); } catch (SAXException saxe) { handleSAXException(saxe); } if (userAgent.getProducer() != null) { comment("Produced by " + userAgent.getProducer()); } atts.clear(); addAttribute("version", VERSION); startElement("areaTree", atts); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
Override public void setDocumentLocale(Locale locale) { AttributesImpl atts = new AttributesImpl(); atts.addAttribute(XML_NAMESPACE, "lang", "xml:lang", XMLUtil.CDATA, LanguageTags.toLanguageTag(locale)); try { handler.startElement(EL_LOCALE, atts); handler.endElement(EL_LOCALE); } catch (SAXException e) { throw new RuntimeException("Unable to create the " + EL_LOCALE + " element.", e); } }
// in src/java/org/apache/fop/render/intermediate/IFRenderer.java
private void handleIFException(IFException ife) { if (ife.getCause() instanceof SAXException) { throw new RuntimeException(ife.getCause()); } else { throw new RuntimeException(ife); } }
// in src/java/org/apache/fop/render/txt/TXTStream.java
public void add(String str) { if (!doOutput) { return; } try { byte[] buff = str.getBytes(encoding); out.write(buff); } catch (IOException e) { throw new RuntimeException(e.toString()); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void paint(Graphics2D g2d, Rectangle2D area) { g2d.translate(-rect.x, -rect.y); Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state); try { painter.drawBorderRect(rect, top, bottom, left, right); } catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting borders", e); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void paint(Graphics2D g2d, Rectangle2D area) { g2d.translate(-boundingBox.x, -boundingBox.y); Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state); try { painter.drawLine(start, end, width, color, style); } catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting a line", e); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void paint(Graphics2D g2d, Rectangle2D area) { if (DEBUG) { g2d.setBackground(Color.LIGHT_GRAY); g2d.clearRect(0, 0, (int)area.getWidth(), (int)area.getHeight()); } g2d.translate(-x, -y + baselineOffset); if (DEBUG) { Rectangle rect = new Rectangle(x, y - maxAscent, 3000, maxAscent); g2d.draw(rect); rect = new Rectangle(x, y - ascent, 2000, ascent); g2d.draw(rect); rect = new Rectangle(x, y, 1000, -descent); g2d.draw(rect); } Java2DPainter painter = new Java2DPainter(g2d, getContext(), parent.getFontInfo(), state); try { painter.drawText(x, y, letterSpacing, wordSpacing, dp, text); } catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting text", e); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startFlow(Flow fl) { if (bDefer) { return; } try { log.debug("starting flow: " + fl.getFlowName()); boolean handled = false; Region regionBody = pagemaster.getRegion(Constants.FO_REGION_BODY); Region regionBefore = pagemaster.getRegion(Constants.FO_REGION_BEFORE); Region regionAfter = pagemaster.getRegion(Constants.FO_REGION_AFTER); if (fl.getFlowName().equals(regionBody.getRegionName())) { // if there is no header in current page-sequence but there has been // a header in a previous page-sequence, insert an empty header. if (bPrevHeaderSpecified && !bHeaderSpecified) { RtfAttributes attr = new RtfAttributes(); attr.set(RtfBefore.HEADER); final IRtfBeforeContainer contBefore = (IRtfBeforeContainer)builderContext.getContainer (IRtfBeforeContainer.class, true, this); contBefore.newBefore(attr); } // if there is no footer in current page-sequence but there has been // a footer in a previous page-sequence, insert an empty footer. if (bPrevFooterSpecified && !bFooterSpecified) { RtfAttributes attr = new RtfAttributes(); attr.set(RtfAfter.FOOTER); final IRtfAfterContainer contAfter = (IRtfAfterContainer)builderContext.getContainer (IRtfAfterContainer.class, true, this); contAfter.newAfter(attr); } handled = true; } else if (regionBefore != null && fl.getFlowName().equals(regionBefore.getRegionName())) { bHeaderSpecified = true; bPrevHeaderSpecified = true; final IRtfBeforeContainer c = (IRtfBeforeContainer)builderContext.getContainer( IRtfBeforeContainer.class, true, this); RtfAttributes beforeAttributes = ((RtfElement)c).getRtfAttributes(); if (beforeAttributes == null) { beforeAttributes = new RtfAttributes(); } beforeAttributes.set(RtfBefore.HEADER); RtfBefore before = c.newBefore(beforeAttributes); builderContext.pushContainer(before); handled = true; } else if (regionAfter != null && fl.getFlowName().equals(regionAfter.getRegionName())) { bFooterSpecified = true; bPrevFooterSpecified = true; final IRtfAfterContainer c = (IRtfAfterContainer)builderContext.getContainer( IRtfAfterContainer.class, true, this); RtfAttributes afterAttributes = ((RtfElement)c).getRtfAttributes(); if (afterAttributes == null) { afterAttributes = new RtfAttributes(); } afterAttributes.set(RtfAfter.FOOTER); RtfAfter after = c.newAfter(afterAttributes); builderContext.pushContainer(after); handled = true; } if (!handled) { log.warn("A " + fl.getLocalName() + " has been skipped: " + fl.getFlowName()); } } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endFlow(Flow fl) { if (bDefer) { return; } try { Region regionBody = pagemaster.getRegion(Constants.FO_REGION_BODY); Region regionBefore = pagemaster.getRegion(Constants.FO_REGION_BEFORE); Region regionAfter = pagemaster.getRegion(Constants.FO_REGION_AFTER); if (fl.getFlowName().equals(regionBody.getRegionName())) { //just do nothing } else if (regionBefore != null && fl.getFlowName().equals(regionBefore.getRegionName())) { builderContext.popContainer(); } else if (regionAfter != null && fl.getFlowName().equals(regionAfter.getRegionName())) { builderContext.popContainer(); } } catch (Exception e) { log.error("endFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startBlock(Block bl) { if (bDefer) { return; } try { RtfAttributes rtfAttr = TextAttributesConverter.convertAttributes(bl); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addParagraphBreak(); textrun.pushBlockAttributes(rtfAttr); textrun.addBookmark(bl.getId()); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endBlock(Block bl) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); RtfParagraphBreak par = textrun.addParagraphBreak(); RtfTableCell cellParent = (RtfTableCell)textrun.getParentOfClass(RtfTableCell.class); if (cellParent != null && par != null) { int iDepth = cellParent.findChildren(textrun); cellParent.setLastParagraph(par, iDepth); } int breakValue = toRtfBreakValue(bl.getBreakAfter()); textrun.popBlockAttributes(breakValue); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startBlockContainer(BlockContainer blc) { if (bDefer) { return; } try { RtfAttributes rtfAttr = TextAttributesConverter.convertBlockContainerAttributes(blc); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addParagraphBreak(); textrun.pushBlockAttributes(rtfAttr); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endBlockContainer(BlockContainer bl) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addParagraphBreak(); int breakValue = toRtfBreakValue(bl.getBreakAfter()); textrun.popBlockAttributes(breakValue); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startTable(Table tbl) { if (bDefer) { return; } // create an RtfTable in the current table container TableContext tableContext = new TableContext(builderContext); try { final IRtfTableContainer tc = (IRtfTableContainer)builderContext.getContainer( IRtfTableContainer.class, true, null); RtfAttributes atts = TableAttributesConverter.convertTableAttributes(tbl); RtfTable table = tc.newTable(atts, tableContext); table.setNestedTableDepth(nestedTableDepth); nestedTableDepth++; CommonBorderPaddingBackground border = tbl.getCommonBorderPaddingBackground(); RtfAttributes borderAttributes = new RtfAttributes(); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.BEFORE, borderAttributes, ITableAttributes.CELL_BORDER_TOP); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.AFTER, borderAttributes, ITableAttributes.CELL_BORDER_BOTTOM); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.START, borderAttributes, ITableAttributes.CELL_BORDER_LEFT); BorderAttributesConverter.makeBorder(border, CommonBorderPaddingBackground.END, borderAttributes, ITableAttributes.CELL_BORDER_RIGHT); table.setBorderAttributes(borderAttributes); builderContext.pushContainer(table); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startTable:" + e.getMessage()); throw new RuntimeException(e.getMessage()); } builderContext.pushTableContext(tableContext); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startColumn(TableColumn tc) { if (bDefer) { return; } try { int iWidth = tc.getColumnWidth().getValue(percentManager); percentManager.setDimension(tc, iWidth); //convert to twips Float width = new Float(FoUnitsConverter.getInstance().convertMptToTwips(iWidth)); builderContext.getTableContext().setNextColumnWidth(width); builderContext.getTableContext().setNextColumnRowSpanning( new Integer(0), null); builderContext.getTableContext().setNextFirstSpanningCol(false); } catch (Exception e) { log.error("startColumn: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startInline(Inline inl) { if (bDefer) { return; } try { RtfAttributes rtfAttr = TextAttributesConverter.convertCharacterAttributes(inl); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.pushInlineAttributes(rtfAttr); textrun.addBookmark(inl.getId()); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (FOPException fe) { log.error("startInline:" + fe.getMessage()); throw new RuntimeException(fe.getMessage()); } catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endInline(Inline inl) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.popInlineAttributes(); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
private void startPart(TablePart part) { if (bDefer) { return; } try { RtfAttributes atts = TableAttributesConverter.convertTablePartAttributes(part); RtfTable tbl = (RtfTable)builderContext.getContainer(RtfTable.class, true, this); tbl.setHeaderAttribs(atts); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
private void endPart(TablePart tb) { if (bDefer) { return; } try { RtfTable tbl = (RtfTable)builderContext.getContainer(RtfTable.class, true, this); tbl.setHeaderAttribs(null); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("endPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startRow(TableRow tr) { if (bDefer) { return; } try { // create an RtfTableRow in the current RtfTable final RtfTable tbl = (RtfTable)builderContext.getContainer(RtfTable.class, true, null); RtfAttributes atts = TableAttributesConverter.convertRowAttributes(tr, tbl.getHeaderAttribs()); if (tr.getParent() instanceof TableHeader) { atts.set(ITableAttributes.ATTR_HEADER); } builderContext.pushContainer(tbl.newTableRow(atts)); // reset column iteration index to correctly access column widths builderContext.getTableContext().selectFirstColumn(); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endRow(TableRow tr) { if (bDefer) { return; } try { TableContext tctx = builderContext.getTableContext(); final RtfTableRow row = (RtfTableRow)builderContext.getContainer(RtfTableRow.class, true, null); //while the current column is in row-spanning, act as if //a vertical merged cell would have been specified. while (tctx.getNumberOfColumns() > tctx.getColumnIndex() && tctx.getColumnRowSpanningNumber().intValue() > 0) { RtfTableCell vCell = row.newTableCellMergedVertically( (int)tctx.getColumnWidth(), tctx.getColumnRowSpanningAttrs()); if (!tctx.getFirstSpanningCol()) { vCell.setHMerge(RtfTableCell.MERGE_WITH_PREVIOUS); } tctx.selectNextColumn(); } } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("endRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } builderContext.popContainer(); builderContext.getTableContext().decreaseRowSpannings(); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startCell(TableCell tc) { if (bDefer) { return; } try { TableContext tctx = builderContext.getTableContext(); final RtfTableRow row = (RtfTableRow)builderContext.getContainer(RtfTableRow.class, true, null); int numberRowsSpanned = tc.getNumberRowsSpanned(); int numberColumnsSpanned = tc.getNumberColumnsSpanned(); //while the current column is in row-spanning, act as if //a vertical merged cell would have been specified. while (tctx.getNumberOfColumns() > tctx.getColumnIndex() && tctx.getColumnRowSpanningNumber().intValue() > 0) { RtfTableCell vCell = row.newTableCellMergedVertically( (int)tctx.getColumnWidth(), tctx.getColumnRowSpanningAttrs()); if (!tctx.getFirstSpanningCol()) { vCell.setHMerge(RtfTableCell.MERGE_WITH_PREVIOUS); } tctx.selectNextColumn(); } //get the width of the currently started cell float width = tctx.getColumnWidth(); // create an RtfTableCell in the current RtfTableRow RtfAttributes atts = TableAttributesConverter.convertCellAttributes(tc); RtfTableCell cell = row.newTableCell((int)width, atts); //process number-rows-spanned attribute if (numberRowsSpanned > 1) { // Start vertical merge cell.setVMerge(RtfTableCell.MERGE_START); // set the number of rows spanned tctx.setCurrentColumnRowSpanning(new Integer(numberRowsSpanned), cell.getRtfAttributes()); } else { tctx.setCurrentColumnRowSpanning( new Integer(numberRowsSpanned), null); } //process number-columns-spanned attribute if (numberColumnsSpanned > 0) { // Get the number of columns spanned tctx.setCurrentFirstSpanningCol(true); // We widthdraw one cell because the first cell is already created // (it's the current cell) ! for (int i = 0; i < numberColumnsSpanned - 1; ++i) { tctx.selectNextColumn(); //aggregate width for further elements width += tctx.getColumnWidth(); tctx.setCurrentFirstSpanningCol(false); RtfTableCell hCell = row.newTableCellMergedHorizontally( 0, null); if (numberRowsSpanned > 1) { // Start vertical merge hCell.setVMerge(RtfTableCell.MERGE_START); // set the number of rows spanned tctx.setCurrentColumnRowSpanning( new Integer(numberRowsSpanned), cell.getRtfAttributes()); } else { tctx.setCurrentColumnRowSpanning( new Integer(numberRowsSpanned), cell.getRtfAttributes()); } } } //save width of the cell, convert from twips to mpt percentManager.setDimension(tc, (int)width * 50); builderContext.pushContainer(cell); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endCell(TableCell tc) { if (bDefer) { return; } try { RtfTableCell cell = (RtfTableCell)builderContext.getContainer(RtfTableCell.class, false, this); cell.finish(); } catch (Exception e) { log.error("endCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } builderContext.popContainer(); builderContext.getTableContext().selectNextColumn(); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startList(ListBlock lb) { if (bDefer) { return; } try { // create an RtfList in the current list container final IRtfListContainer c = (IRtfListContainer)builderContext.getContainer( IRtfListContainer.class, true, this); final RtfList newList = c.newList( ListAttributesConverter.convertAttributes(lb)); builderContext.pushContainer(newList); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (FOPException fe) { log.error("startList: " + fe.getMessage()); throw new RuntimeException(fe.getMessage()); } catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startListItem(ListItem li) { if (bDefer) { return; } // create an RtfListItem in the current RtfList try { RtfList list = (RtfList)builderContext.getContainer( RtfList.class, true, this); /** * If the current list already contains a list item, then close the * list and open a new one, so every single list item gets its own * list. This allows every item to have a different list label. * If all the items would be in the same list, they had all the * same label. */ //TODO: do this only, if the labels content <> previous labels content if (list.getChildCount() > 0) { this.endListBody(null); this.endList((ListBlock) li.getParent()); this.startList((ListBlock) li.getParent()); this.startListBody(null); list = (RtfList)builderContext.getContainer( RtfList.class, true, this); } builderContext.pushContainer(list.newListItem()); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startListLabel(ListItemLabel listItemLabel) { if (bDefer) { return; } try { RtfListItem item = (RtfListItem)builderContext.getContainer(RtfListItem.class, true, this); RtfListItemLabel label = item.new RtfListItemLabel(item); builderContext.pushContainer(label); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startLink(BasicLink basicLink) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); RtfHyperLink link = textrun.addHyperlink(new RtfAttributes()); if (basicLink.hasExternalDestination()) { link.setExternalURL(basicLink.getExternalDestination()); } else { link.setInternalURL(basicLink.getInternalDestination()); } builderContext.pushContainer(link); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startLink: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startFootnote(Footnote footnote) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); RtfFootnote rtfFootnote = textrun.addFootnote(); builderContext.pushContainer(rtfFootnote); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startFootnote: " + e.getMessage()); throw new RuntimeException("Exception: " + e); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startFootnoteBody(FootnoteBody body) { if (bDefer) { return; } try { RtfFootnote rtfFootnote = (RtfFootnote)builderContext.getContainer( RtfFootnote.class, true, this); rtfFootnote.startBody(); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endFootnoteBody(FootnoteBody body) { if (bDefer) { return; } try { RtfFootnote rtfFootnote = (RtfFootnote)builderContext.getContainer( RtfFootnote.class, true, this); rtfFootnote.endBody(); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("endFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startLeader(Leader l) { if (bDefer) { return; } try { percentManager.setDimension(l); RtfAttributes rtfAttr = TextAttributesConverter.convertLeaderAttributes( l, percentManager); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addLeader(rtfAttr); } catch (IOException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } catch (FOPException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void text(FOText text, CharSequence characters) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); RtfAttributes rtfAttr = TextAttributesConverter.convertCharacterAttributes(text); textrun.pushInlineAttributes(rtfAttr); textrun.addString(characters.toString()); textrun.popInlineAttributes(); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("characters:" + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startPageNumber(PageNumber pagenum) { if (bDefer) { return; } try { RtfAttributes rtfAttr = TextAttributesConverter.convertCharacterAttributes( pagenum); IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addPageNumber(rtfAttr); } catch (IOException ioe) { handleIOTrouble(ioe); } catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startPageNumberCitation(PageNumberCitation l) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addPageNumberCitation(l.getRefId()); } catch (Exception e) { log.error("startPageNumberCitation: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startPageNumberCitationLast(PageNumberCitationLast l) { if (bDefer) { return; } try { IRtfTextrunContainer container = (IRtfTextrunContainer)builderContext.getContainer( IRtfTextrunContainer.class, true, this); RtfTextrun textrun = container.getTextrun(); textrun.addPageNumberCitation(l.getRefId()); } catch (RtfException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } catch (IOException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); } }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
private void rewritePostScriptFile() throws IOException { log.debug("Processing PostScript resources..."); long startTime = System.currentTimeMillis(); ResourceTracker resTracker = gen.getResourceTracker(); InputStream in = new java.io.FileInputStream(this.tempFile); in = new java.io.BufferedInputStream(in); try { try { ResourceHandler handler = new ResourceHandler(getUserAgent(), this.fontInfo, resTracker, this.formResources); handler.process(in, this.outputStream, this.currentPageNumber, this.documentBoundingBox); this.outputStream.flush(); } catch (DSCException e) { throw new RuntimeException(e.getMessage()); } } finally { IOUtils.closeQuietly(in); if (!this.tempFile.delete()) { this.tempFile.deleteOnExit(); log.warn("Could not delete temporary file: " + this.tempFile); } } if (log.isDebugEnabled()) { long duration = System.currentTimeMillis() - startTime; log.debug("Resource Processing complete in " + duration + " ms."); } }
// in src/java/org/apache/fop/afp/svg/AFPTextHandler.java
private int registerPageFont(AFPPageFonts pageFonts, String internalFontName, int fontSize) { AFPFont afpFont = (AFPFont)fontInfo.getFonts().get(internalFontName); // register if necessary AFPFontAttributes afpFontAttributes = pageFonts.registerFont( internalFontName, afpFont, fontSize ); if (afpFont.isEmbeddable()) { try { final CharacterSet charSet = afpFont.getCharacterSet(fontSize); this.resourceManager.embedFont(afpFont, charSet); } catch (IOException ioe) { throw new RuntimeException("Error while embedding font resources", ioe); } } return afpFontAttributes.getFontReference(); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
private void handleUnexpectedIOError(IOException ioe) { //"Unexpected" since we're currently dealing with ByteArrayOutputStreams here. throw new RuntimeException("Unexpected I/O error: " + ioe.getMessage(), ioe); }
// in src/java/org/apache/fop/events/EventExceptionManager.java
public static void throwException(Event event, String exceptionClass) throws Throwable { if (exceptionClass != null) { ExceptionFactory factory = (ExceptionFactory)EXCEPTION_FACTORIES.get(exceptionClass); if (factory != null) { throw factory.createException(event); } else { throw new IllegalArgumentException( "No such ExceptionFactory available: " + exceptionClass); } } else { String msg = EventFormatter.format(event); //Get original exception as cause if it is given as one of the parameters Throwable t = null; Iterator<Object> iter = event.getParams().values().iterator(); while (iter.hasNext()) { Object o = iter.next(); if (o instanceof Throwable) { t = (Throwable)o; break; } } if (t != null) { throw new RuntimeException(msg, t); } else { throw new RuntimeException(msg); } } }
// in src/java/org/apache/fop/area/CTM.java
public static CTM getCTMandRelDims(int absRefOrient, WritingMode writingMode, Rectangle2D absVPrect, FODimension reldims) { int width; int height; // We will use the absolute reference-orientation to set up the CTM. // The value here is relative to its ancestor reference area. if (absRefOrient % 180 == 0) { width = (int) absVPrect.getWidth(); height = (int) absVPrect.getHeight(); } else { // invert width and height since top left are rotated by 90 (cl or ccl) height = (int) absVPrect.getWidth(); width = (int) absVPrect.getHeight(); } /* Set up the CTM for the content of this reference area. * This will transform region content coordinates in * writing-mode relative into absolute page-relative * which will then be translated based on the position of * the region viewport. * (Note: scrolling between region vp and ref area when * doing online content!) */ CTM ctm = new CTM(absVPrect.getX(), absVPrect.getY()); // First transform for rotation if (absRefOrient != 0) { // Rotation implies translation to keep the drawing area in the // first quadrant. Note: rotation is counter-clockwise switch (absRefOrient) { case 90: case -270: ctm = ctm.translate(0, width); // width = absVPrect.height break; case 180: case -180: ctm = ctm.translate(width, height); break; case 270: case -90: ctm = ctm.translate(height, 0); // height = absVPrect.width break; default: throw new RuntimeException(); } ctm = ctm.rotate(absRefOrient); } /* Since we've already put adjusted width and height values for the * top and left positions implied by the reference-orientation, we * can set ipd and bpd appropriately based on the writing mode. */ switch ( writingMode.getEnumValue() ) { case EN_TB_LR: case EN_TB_RL: reldims.ipd = height; reldims.bpd = width; break; case EN_LR_TB: case EN_RL_TB: default: reldims.ipd = width; reldims.bpd = height; break; } // Set a rectangle to be the writing-mode relative version??? // Now transform for writing mode return ctm.multiply(CTM.getWMctm(writingMode, reldims.ipd, reldims.bpd)); }
// in src/java/org/apache/fop/area/LineArea.java
public void handleIPDVariation(int ipdVariation) { int si = getStartIndent(); int ei = getEndIndent(); switch (adjustingInfo.lineAlignment) { case EN_START: // adjust end indent addTrait(Trait.END_INDENT, ei - ipdVariation); break; case EN_CENTER: // adjust start and end indents addTrait(Trait.START_INDENT, si - ipdVariation / 2); addTrait(Trait.END_INDENT, ei - ipdVariation / 2); break; case EN_END: // adjust start indent addTrait(Trait.START_INDENT, si - ipdVariation); break; case EN_JUSTIFY: // compute variation factor adjustingInfo.variationFactor *= (float) (adjustingInfo.difference - ipdVariation) / adjustingInfo.difference; adjustingInfo.difference -= ipdVariation; // if the LineArea has already been added to the area tree, // call finalize(); otherwise, wait for the LineLM to call it if (adjustingInfo.bAddedToAreaTree) { finish(); } break; default: throw new RuntimeException(); } }
// in src/java/org/apache/fop/area/RenderPagesModel.java
Override public void handleOffDocumentItem(OffDocumentItem oDI) { switch(oDI.getWhenToProcess()) { case OffDocumentItem.IMMEDIATELY: renderer.processOffDocumentItem(oDI); break; case OffDocumentItem.AFTER_PAGE: pendingODI.add(oDI); break; case OffDocumentItem.END_OF_DOC: endDocODI.add(oDI); break; default: throw new RuntimeException(); } }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
public void startPageSequence(Locale locale, String role) { try { AttributesImpl attributes = new AttributesImpl(); if (role != null) { attributes.addAttribute("", "type", "type", XMLConstants.CDATA, role); } contentHandler.startPrefixMapping( InternalElementMapping.STANDARD_PREFIX, InternalElementMapping.URI); contentHandler.startPrefixMapping( ExtensionElementMapping.STANDARD_PREFIX, ExtensionElementMapping.URI); contentHandler.startElement(IFConstants.NAMESPACE, IFConstants.EL_STRUCTURE_TREE, IFConstants.EL_STRUCTURE_TREE, attributes); } catch (SAXException e) { throw new RuntimeException(e); } }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
public void endPageSequence() { try { contentHandler.endElement(IFConstants.NAMESPACE, IFConstants.EL_STRUCTURE_TREE, IFConstants.EL_STRUCTURE_TREE); contentHandler.endPrefixMapping( ExtensionElementMapping.STANDARD_PREFIX); contentHandler.endPrefixMapping( InternalElementMapping.STANDARD_PREFIX); } catch (SAXException e) { throw new RuntimeException(e); } }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
public StructureTreeElement startNode(String name, Attributes attributes) { try { if (name.equals("#PCDATA")) { name = "marked-content"; contentHandler.startElement(IFConstants.NAMESPACE, name, name, attributes); } else { contentHandler.startElement(FOElementMapping.URI, name, FOElementMapping.STANDARD_PREFIX + ":" + name, attributes); } return null; } catch (SAXException e) { throw new RuntimeException(e); } }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
public void endNode(String name) { try { contentHandler.endElement(FOElementMapping.URI, name, FOElementMapping.STANDARD_PREFIX + ":" + name); } catch (SAXException e) { throw new RuntimeException(e); } }
// in src/java/org/apache/fop/layoutmgr/KnuthElement.java
public int getPenalty() { throw new RuntimeException("Element is not a penalty"); }
// in src/java/org/apache/fop/layoutmgr/KnuthElement.java
public int getStretch() { throw new RuntimeException("Element is not a glue"); }
// in src/java/org/apache/fop/layoutmgr/KnuthElement.java
public int getShrink() { throw new RuntimeException("Element is not a glue"); }
// in src/java/org/apache/fop/cli/Main.java
public static URL[] getJARList() throws MalformedURLException { String fopHome = System.getProperty("fop.home"); File baseDir; if (fopHome != null) { baseDir = new File(fopHome).getAbsoluteFile(); } else { baseDir = new File(".").getAbsoluteFile().getParentFile(); } File buildDir; if ("build".equals(baseDir.getName())) { buildDir = baseDir; baseDir = baseDir.getParentFile(); } else { buildDir = new File(baseDir, "build"); } File fopJar = new File(buildDir, "fop.jar"); if (!fopJar.exists()) { fopJar = new File(baseDir, "fop.jar"); } if (!fopJar.exists()) { throw new RuntimeException("fop.jar not found in directory: " + baseDir.getAbsolutePath() + " (or below)"); } List jars = new java.util.ArrayList(); jars.add(fopJar.toURI().toURL()); File[] files; FileFilter filter = new FileFilter() { public boolean accept(File pathname) { return pathname.getName().endsWith(".jar"); } }; File libDir = new File(baseDir, "lib"); if (!libDir.exists()) { libDir = baseDir; } files = libDir.listFiles(filter); if (files != null) { for (int i = 0, size = files.length; i < size; i++) { jars.add(files[i].toURI().toURL()); } } String optionalLib = System.getProperty("fop.optional.lib"); if (optionalLib != null) { files = new File(optionalLib).listFiles(filter); if (files != null) { for (int i = 0, size = files.length; i < size; i++) { jars.add(files[i].toURI().toURL()); } } } URL[] urls = (URL[])jars.toArray(new URL[jars.size()]); /* for (int i = 0, c = urls.length; i < c; i++) { System.out.println(urls[i]); }*/ return urls; }
62
            
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (IOException e) { // won't happen. We're operating in-memory. throw new RuntimeException( "Error during base64 encodation of username/password"); }
// in src/java/org/apache/fop/pdf/PDFStream.java
catch (IOException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/pdf/PDFICCBasedColorSpace.java
catch (IOException ioe) { throw new RuntimeException( "Unexpected IOException loading the sRGB profile: " + ioe.getMessage()); }
// in src/java/org/apache/fop/fo/ElementMapping.java
catch (ParserConfigurationException e) { throw new RuntimeException( "Cannot return default DOM implementation: " + e.getMessage()); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (Exception e) { throw new RuntimeException("Couldn't create XMLReader: " + e.getMessage()); }
// in src/java/org/apache/fop/svg/NativeTextPainter.java
catch (IOException ioe) { //No other possibility than to use a RuntimeException throw new RuntimeException(ioe); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (FOPException fopex) { log.error("Failed to read font metrics file " + metricsFileName, fopex); if (fail) { throw new RuntimeException(fopex.getMessage()); } }
// in src/java/org/apache/fop/fonts/LazyFont.java
catch (IOException ioex) { log.error("Failed to read font metrics file " + metricsFileName, ioex); if (fail) { throw new RuntimeException(ioex.getMessage()); } }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
catch (java.io.UnsupportedEncodingException e) { throw new RuntimeException("Incompatible VM. It doesn't support the US-ASCII encoding"); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( NoSuchMethodException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( IllegalAccessException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/fonts/type1/AFMParser.java
catch ( InvocationTargetException e ) { throw new RuntimeException("Bean error: " + e.getMessage(), e); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new RuntimeException("Unable to create the " + EL_LOCALE + " element.", e); }
// in src/java/org/apache/fop/render/txt/TXTStream.java
catch (IOException e) { throw new RuntimeException(e.toString()); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting borders", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting a line", e); }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
catch (IFException e) { //This should never happen with the Java2DPainter throw new RuntimeException("Unexpected error while painting text", e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFlow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startBlock:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startTable:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startColumn: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startInline:" + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startInline:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endPart: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endRow: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endCell: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException fe) { log.error("startList: " + fe.getMessage()); throw new RuntimeException(fe.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startList: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startLink: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnote: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("endFootnoteBody: " + e.getMessage()); throw new RuntimeException("Exception: " + e); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (FOPException e) { log.error("startLeader: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("characters:" + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumber: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (Exception e) { log.error("startPageNumberCitation: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (RtfException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException e) { log.error("startPageNumberCitationLast: " + e.getMessage()); throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/render/ps/PSDocumentHandler.java
catch (DSCException e) { throw new RuntimeException(e.getMessage()); }
// in src/java/org/apache/fop/afp/svg/AFPTextHandler.java
catch (IOException ioe) { throw new RuntimeException("Error while embedding font resources", ioe); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
0 8
            
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (RuntimeException re) { String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, re); throw re; }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { //wrap in a PropertyException throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException("Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA"); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); //wrap in a PropertyException }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
8
            
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (RuntimeException re) { String err = "Error while rendering page " + page.getPageNumberString(); log.error(err, re); throw re; }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { //wrap in a PropertyException throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException("Unknown color format: " + value + ". Must be #RGB. #RGBA, #RRGGBB, or #RRGGBBAA"); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); //wrap in a PropertyException }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
// in src/java/org/apache/fop/util/ColorUtil.java
catch (RuntimeException re) { throw new PropertyException(re); }
0
unknown (Lib) SAXException 38
            
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
public void startDocument() throws SAXException { log.fatal("The MIF Handler is non-functional at this time. Please help resurrect it!"); mifFile = new MIFFile(); try { mifFile.output(outStream); } catch (IOException ioe) { throw new SAXException(ioe); } }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
public void endDocument() throws SAXException { // finish all open elements mifFile.finish(true); try { mifFile.output(outStream); outStream.flush(); } catch (IOException ioe) { throw new SAXException(ioe); } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void startElement(String namespaceURI, String localName, String rawName, Attributes attlist) throws SAXException { /* the node found in the FO document */ FONode foNode; PropertyList propertyList = null; // Check to ensure first node encountered is an fo:root if (rootFObj == null) { empty = false; if (!namespaceURI.equals(FOElementMapping.URI) || !localName.equals("root")) { FOValidationEventProducer eventProducer = FOValidationEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.invalidFORoot(this, FONode.getNodeString(namespaceURI, localName), getEffectiveLocator()); } } else { // check that incoming node is valid for currentFObj if (currentFObj.getNamespaceURI().equals(FOElementMapping.URI) || currentFObj.getNamespaceURI().equals(ExtensionElementMapping.URI)) { currentFObj.validateChildNode(locator, namespaceURI, localName); } } ElementMapping.Maker fobjMaker = findFOMaker(namespaceURI, localName); try { foNode = fobjMaker.make(currentFObj); if (rootFObj == null) { rootFObj = (Root) foNode; rootFObj.setBuilderContext(builderContext); rootFObj.setFOEventHandler(foEventHandler); } propertyList = foNode.createPropertyList( currentPropertyList, foEventHandler); foNode.processNode(localName, getEffectiveLocator(), attlist, propertyList); if (foNode.getNameId() == Constants.FO_MARKER) { if (builderContext.inMarker()) { nestedMarkerDepth++; } else { builderContext.switchMarkerContext(true); } } if (foNode.getNameId() == Constants.FO_PAGE_SEQUENCE) { builderContext.getXMLWhiteSpaceHandler().reset(); } } catch (IllegalArgumentException e) { throw new SAXException(e); } ContentHandlerFactory chFactory = foNode.getContentHandlerFactory(); if (chFactory != null) { ContentHandler subHandler = chFactory.createContentHandler(); if (subHandler instanceof ObjectSource && foNode instanceof ObjectBuiltListener) { ((ObjectSource) subHandler).setObjectBuiltListener( (ObjectBuiltListener) foNode); } subHandler.startDocument(); subHandler.startElement(namespaceURI, localName, rawName, attlist); depth = 1; delegate = subHandler; } if (currentFObj != null) { currentFObj.addChildNode(foNode); } currentFObj = foNode; if (propertyList != null && !builderContext.inMarker()) { currentPropertyList = propertyList; } // fo:characters can potentially be removed during // white-space handling. // Do not notify the FOEventHandler. if (currentFObj.getNameId() != Constants.FO_CHARACTER) { currentFObj.startOfNode(); } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void endElement(String uri, String localName, String rawName) throws SAXException { if (currentFObj == null) { throw new SAXException( "endElement() called for " + rawName + " where there is no current element."); } else if (!currentFObj.getLocalName().equals(localName) || !currentFObj.getNamespaceURI().equals(uri)) { throw new SAXException("Mismatch: " + currentFObj.getLocalName() + " (" + currentFObj.getNamespaceURI() + ") vs. " + localName + " (" + uri + ")"); } // fo:characters can potentially be removed during // white-space handling. // Do not notify the FOEventHandler. if (currentFObj.getNameId() != Constants.FO_CHARACTER) { currentFObj.endOfNode(); } if (currentPropertyList != null && currentPropertyList.getFObj() == currentFObj && !builderContext.inMarker()) { currentPropertyList = currentPropertyList.getParentPropertyList(); } if (currentFObj.getNameId() == Constants.FO_MARKER) { if (nestedMarkerDepth == 0) { builderContext.switchMarkerContext(false); } else { nestedMarkerDepth--; } } if (currentFObj.getParent() == null) { LOG.debug("endElement for top-level " + currentFObj.getName()); } currentFObj = currentFObj.getParent(); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (doc == null) { TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } String version = atts.getValue("version"); DOMImplementation domImplementation = getDOMImplementation(version); doc = domImplementation.createDocument(uri, qName, null); // It's easier to work with an empty document, so remove the // root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); setDelegateContentHandler(handler); setDelegateLexicalHandler(handler); setDelegateDTDHandler(handler); handler.startDocument(); } super.startElement(uri, localName, qName, atts); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
protected void getExternalClasses() throws SAXException { XMLReader mainParser = parser; parser = createParser(); parser.setContentHandler(this); parser.setErrorHandler(this); InputStream stream = this.getClass().getResourceAsStream("classes.xml"); InputSource source = new InputSource(stream); try { parser.parse(source); } catch (IOException ioe) { throw new SAXException(ioe.getMessage()); } finally { parser = mainParser; } }
// in src/java/org/apache/fop/svg/FOPSAXSVGDocumentFactory.java
public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (this.additionalResolver != null) { try { InputSource result = this.additionalResolver.resolveEntity(publicId, systemId); if (result != null) { return result; } } catch (IOException ioe) { /**@todo Batik's SAXSVGDocumentFactory should throw IOException, * so we don't have to handle it here. */ throw new SAXException(ioe); } } return super.resolveEntity(publicId, systemId); }
// in src/java/org/apache/fop/fonts/FontReader.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("font-metrics")) { if ("TYPE0".equals(attributes.getValue("type"))) { multiFont = new MultiByteFont(); returnFont = multiFont; isCID = true; TTFReader.checkMetricsVersion(attributes); } else if ("TRUETYPE".equals(attributes.getValue("type"))) { singleFont = new SingleByteFont(); singleFont.setFontType(FontType.TRUETYPE); returnFont = singleFont; isCID = false; TTFReader.checkMetricsVersion(attributes); } else { singleFont = new SingleByteFont(); singleFont.setFontType(FontType.TYPE1); returnFont = singleFont; isCID = false; } } else if ("embed".equals(localName)) { returnFont.setEmbedFileName(attributes.getValue("file")); returnFont.setEmbedResourceName(attributes.getValue("class")); } else if ("cid-widths".equals(localName)) { cidWidthIndex = getInt(attributes.getValue("start-index")); cidWidths = new ArrayList<Integer>(); } else if ("kerning".equals(localName)) { currentKerning = new HashMap<Integer, Integer>(); returnFont.putKerningEntry(new Integer(attributes.getValue("kpx1")), currentKerning); } else if ("bfranges".equals(localName)) { bfranges = new ArrayList<BFEntry>(); } else if ("bf".equals(localName)) { BFEntry entry = new BFEntry(getInt(attributes.getValue("us")), getInt(attributes.getValue("ue")), getInt(attributes.getValue("gi"))); bfranges.add(entry); } else if ("wx".equals(localName)) { cidWidths.add(new Integer(attributes.getValue("w"))); } else if ("widths".equals(localName)) { //singleFont.width = new int[256]; } else if ("char".equals(localName)) { try { singleFont.setWidth(Integer.parseInt(attributes.getValue("idx")), Integer.parseInt(attributes.getValue("wdt"))); } catch (NumberFormatException ne) { throw new SAXException("Malformed width in metric file: " + ne.getMessage(), ne); } } else if ("pair".equals(localName)) { currentKerning.put(new Integer(attributes.getValue("kpx2")), new Integer(attributes.getValue("kern"))); } }
// in src/java/org/apache/fop/fonts/FontReader.java
private int getInt(String str) throws SAXException { int ret = 0; try { ret = Integer.parseInt(str); } catch (Exception e) { throw new SAXException("Error while parsing integer value: " + str, e); } return ret; }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
public static void checkMetricsVersion(Attributes attr) throws SAXException { String err = null; final String str = attr.getValue(METRICS_VERSION_ATTR); if (str == null) { err = "Missing " + METRICS_VERSION_ATTR + " attribute"; } else { int version = 0; try { version = Integer.parseInt(str); if (version < METRICS_VERSION) { err = "Incompatible " + METRICS_VERSION_ATTR + " value (" + version + ", should be " + METRICS_VERSION + ")"; } } catch (NumberFormatException e) { err = "Invalid " + METRICS_VERSION_ATTR + " attribute value (" + str + ")"; } } if (err != null) { throw new SAXException( err + " - please regenerate the font metrics file with " + "a more recent version of FOP." ); } }
// in src/java/org/apache/fop/render/pdf/extensions/PDFExtensionHandler.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (PDFExtensionAttachment.CATEGORY.equals(uri)) { lastAttributes = new AttributesImpl(attributes); handled = false; if (localName.equals(PDFEmbeddedFileExtensionAttachment.ELEMENT)) { //handled in endElement handled = true; } } if (!handled) { if (PDFExtensionAttachment.CATEGORY.equals(uri)) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateDepth++; delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if (NAMESPACE.equals(uri)) { if (localName.equals(EL_PAGE_SEQUENCE) && userAgent.isAccessibilityEnabled()) { pageSequenceAttributes = new AttributesImpl(attributes); Locale language = getLanguage(attributes); structureTreeHandler = new StructureTreeHandler( userAgent.getStructureTreeEventHandler(), language); } else if (localName.equals(EL_STRUCTURE_TREE)) { if (userAgent.isAccessibilityEnabled()) { String type = attributes.getValue("type"); structureTreeHandler.startStructureTree(type); delegate = structureTreeHandler; } else { /* Delegate to a handler that does nothing */ delegate = new DefaultHandler(); } delegateDepth++; delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { if (pageSequenceAttributes != null) { /* * This means that no structure-element tag was * found in the XML, otherwise a * StructureTreeBuilderWrapper object would have * been created, which would have reset the * pageSequenceAttributes field. */ AccessibilityEventProducer.Provider .get(userAgent.getEventBroadcaster()) .noStructureTreeInXML(this); } handled = startIFElement(localName, attributes); } } else if (DocumentNavigationExtensionConstants.NAMESPACE.equals(uri)) { if (this.navParser == null) { this.navParser = new DocumentNavigationHandler( this.documentHandler.getDocumentNavigationHandler(), structureTreeElements); } delegate = this.navParser; delegateDepth++; delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { ContentHandlerFactoryRegistry registry = userAgent.getFactory().getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory == null) { DOMImplementation domImplementation = elementMappingRegistry.getDOMImplementationForNamespace(uri); if (domImplementation == null) { domImplementation = ElementMapping.getDefaultDOMImplementation(); /* throw new SAXException("No DOMImplementation could be" + " identified to handle namespace: " + uri); */ } factory = new DOMBuilderContentHandlerFactory(uri, domImplementation); } delegate = factory.createContentHandler(); delegateDepth++; delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
private void handleIFException(IFException ife) throws SAXException { if (ife.getCause() instanceof SAXException) { //unwrap throw (SAXException)ife.getCause(); } else { //wrap throw new SAXException(ife); } }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (NAMESPACE.equals(uri)) { if (BOOKMARK_TREE.getLocalName().equals(localName)) { if (!objectStack.isEmpty()) { throw new SAXException(localName + " must be the root element!"); } BookmarkTree bookmarkTree = new BookmarkTree(); objectStack.push(bookmarkTree); } else if (BOOKMARK.getLocalName().equals(localName)) { String title = attributes.getValue("title"); String s = attributes.getValue("starting-state"); boolean show = !"hide".equals(s); Bookmark b = new Bookmark(title, show, null); Object o = objectStack.peek(); if (o instanceof AbstractAction) { AbstractAction action = (AbstractAction)objectStack.pop(); o = objectStack.peek(); ((Bookmark)o).setAction(action); } if (o instanceof BookmarkTree) { ((BookmarkTree)o).addBookmark(b); } else { ((Bookmark)o).addChildBookmark(b); } objectStack.push(b); } else if (NAMED_DESTINATION.getLocalName().equals(localName)) { if (!objectStack.isEmpty()) { throw new SAXException(localName + " must be the root element!"); } String name = attributes.getValue("name"); NamedDestination dest = new NamedDestination(name, null); objectStack.push(dest); } else if (LINK.getLocalName().equals(localName)) { if (!objectStack.isEmpty()) { throw new SAXException(localName + " must be the root element!"); } Rectangle targetRect = XMLUtil.getAttributeAsRectangle(attributes, "rect"); structureTreeElement = structureTreeElements.get(attributes.getValue( InternalElementMapping.URI, InternalElementMapping.STRUCT_REF)); Link link = new Link(null, targetRect); objectStack.push(link); } else if (GOTO_XY.getLocalName().equals(localName)) { String idref = attributes.getValue("idref"); GoToXYAction action; if (idref != null) { action = new GoToXYAction(idref); } else { String id = attributes.getValue("id"); int pageIndex = XMLUtil.getAttributeAsInt(attributes, "page-index"); final Point location; if (pageIndex < 0) { location = null; } else { final int x = XMLUtil .getAttributeAsInt(attributes, "x"); final int y = XMLUtil .getAttributeAsInt(attributes, "y"); location = new Point(x, y); } action = new GoToXYAction(id, pageIndex, location); } if (structureTreeElement != null) { action.setStructureTreeElement(structureTreeElement); } objectStack.push(action); } else if (GOTO_URI.getLocalName().equals(localName)) { String id = attributes.getValue("id"); String gotoURI = attributes.getValue("uri"); String showDestination = attributes.getValue("show-destination"); boolean newWindow = "new".equals(showDestination); URIAction action = new URIAction(gotoURI, newWindow); if (id != null) { action.setID(id); } if (structureTreeElement != null) { action.setStructureTreeElement(structureTreeElement); } objectStack.push(action); } else { throw new SAXException( "Invalid element '" + localName + "' in namespace: " + uri); } handled = true; } if (!handled) { if (NAMESPACE.equals(uri)) { throw new SAXException("Unhandled element '" + localName + "' in namespace: " + uri); } else { log.warn("Unhandled element '" + localName + "' in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
public void endElement(String uri, String localName, String qName) throws SAXException { if (NAMESPACE.equals(uri)) { try { if (BOOKMARK_TREE.getLocalName().equals(localName)) { BookmarkTree tree = (BookmarkTree)objectStack.pop(); if (hasNavigation()) { this.navHandler.renderBookmarkTree(tree); } } else if (BOOKMARK.getLocalName().equals(localName)) { if (objectStack.peek() instanceof AbstractAction) { AbstractAction action = (AbstractAction)objectStack.pop(); Bookmark b = (Bookmark)objectStack.pop(); b.setAction(action); } else { objectStack.pop(); } } else if (NAMED_DESTINATION.getLocalName().equals(localName)) { AbstractAction action = (AbstractAction)objectStack.pop(); NamedDestination dest = (NamedDestination)objectStack.pop(); dest.setAction(action); if (hasNavigation()) { this.navHandler.renderNamedDestination(dest); } } else if (LINK.getLocalName().equals(localName)) { AbstractAction action = (AbstractAction)objectStack.pop(); Link link = (Link)objectStack.pop(); link.setAction(action); if (hasNavigation()) { this.navHandler.renderLink(link); } } else if (localName.startsWith("goto-")) { if (objectStack.size() == 1) { //Stand-alone action AbstractAction action = (AbstractAction)objectStack.pop(); if (hasNavigation()) { this.navHandler.addResolvedAction(action); } } } } catch (IFException ife) { throw new SAXException(ife); } } content.setLength(0); // Reset text buffer (see characters()) }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startDocument() throws SAXException { // TODO sections should be created try { rtfFile = new RtfFile(new OutputStreamWriter(os)); docArea = rtfFile.startDocumentArea(); } catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endDocument() throws SAXException { try { rtfFile.flush(); } catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (AFPExtensionAttachment.CATEGORY.equals(uri)) { lastAttributes = new AttributesImpl(attributes); handled = true; if (localName.equals(AFPElementMapping.NO_OPERATION) || localName.equals(AFPElementMapping.TAG_LOGICAL_ELEMENT) || localName.equals(AFPElementMapping.INCLUDE_PAGE_OVERLAY) || localName.equals(AFPElementMapping.INCLUDE_PAGE_SEGMENT) || localName.equals(AFPElementMapping.INCLUDE_FORM_MAP) || localName.equals(AFPElementMapping.INVOKE_MEDIUM_MAP)) { //handled in endElement } else { handled = false; } } if (!handled) { if (AFPExtensionAttachment.CATEGORY.equals(uri)) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
Override public void endElement(String uri, String localName, String qName) throws SAXException { if (AFPExtensionAttachment.CATEGORY.equals(uri)) { if (AFPElementMapping.INCLUDE_FORM_MAP.equals(localName)) { AFPIncludeFormMap formMap = new AFPIncludeFormMap(); String name = lastAttributes.getValue("name"); formMap.setName(name); String src = lastAttributes.getValue("src"); try { formMap.setSrc(new URI(src)); } catch (URISyntaxException e) { throw new SAXException("Invalid URI: " + src, e); } this.returnedObject = formMap; } else if (AFPElementMapping.INCLUDE_PAGE_OVERLAY.equals(localName)) { this.returnedObject = new AFPPageOverlay(); String name = lastAttributes.getValue("name"); if (name != null) { returnedObject.setName(name); } } else if (AFPElementMapping.INCLUDE_PAGE_SEGMENT.equals(localName)) { AFPPageSegmentSetup pageSetupExtn = null; pageSetupExtn = new AFPPageSegmentSetup(localName); this.returnedObject = pageSetupExtn; String name = lastAttributes.getValue("name"); if (name != null) { returnedObject.setName(name); } String value = lastAttributes.getValue("value"); if (value != null && pageSetupExtn != null) { pageSetupExtn.setValue(value); } String resourceSrc = lastAttributes.getValue("resource-file"); if (resourceSrc != null && pageSetupExtn != null) { pageSetupExtn.setResourceSrc(resourceSrc); } if (content.length() > 0 && pageSetupExtn != null) { pageSetupExtn.setContent(content.toString()); content.setLength(0); //Reset text buffer (see characters()) } } else { AFPPageSetup pageSetupExtn = null; if (AFPElementMapping.INVOKE_MEDIUM_MAP.equals(localName)) { this.returnedObject = new AFPInvokeMediumMap(); } else { pageSetupExtn = new AFPPageSetup(localName); this.returnedObject = pageSetupExtn; } String name = lastAttributes.getValue(AFPPageSetup.ATT_NAME); if (name != null) { returnedObject.setName(name); } String value = lastAttributes.getValue(AFPPageSetup.ATT_VALUE); if (value != null && pageSetupExtn != null) { pageSetupExtn.setValue(value); } String placement = lastAttributes.getValue(AFPPageSetup.ATT_PLACEMENT); if (placement != null && placement.length() > 0) { pageSetupExtn.setPlacement(ExtensionPlacement.fromXMLValue(placement)); } if (content.length() > 0 && pageSetupExtn != null) { pageSetupExtn.setContent(content.toString()); content.setLength(0); //Reset text buffer (see characters()) } } } }
// in src/java/org/apache/fop/render/ps/extensions/PSExtensionHandler.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (PSExtensionAttachment.CATEGORY.equals(uri)) { lastAttributes = new AttributesImpl(attributes); handled = false; if (localName.equals(PSSetupCode.ELEMENT) || localName.equals(PSPageTrailerCodeBefore.ELEMENT) || localName.equals(PSSetPageDevice.ELEMENT) || localName.equals(PSCommentBefore.ELEMENT) || localName.equals(PSCommentAfter.ELEMENT)) { //handled in endElement handled = true; } } if (!handled) { if (PSExtensionAttachment.CATEGORY.equals(uri)) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/events/model/EventModelParser.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { try { if ("event-model".equals(localName)) { if (objectStack.size() > 0) { throw new SAXException("event-model must be the root element"); } objectStack.push(model); } else if ("producer".equals(localName)) { EventProducerModel producer = new EventProducerModel( attributes.getValue("name")); EventModel parent = (EventModel)objectStack.peek(); parent.addProducer(producer); objectStack.push(producer); } else if ("method".equals(localName)) { EventSeverity severity = EventSeverity.valueOf(attributes.getValue("severity")); String ex = attributes.getValue("exception"); EventMethodModel method = new EventMethodModel( attributes.getValue("name"), severity); if (ex != null && ex.length() > 0) { method.setExceptionClass(ex); } EventProducerModel parent = (EventProducerModel)objectStack.peek(); parent.addMethod(method); objectStack.push(method); } else if ("parameter".equals(localName)) { String className = attributes.getValue("type"); Class type; try { type = Class.forName(className); } catch (ClassNotFoundException e) { throw new SAXException("Could not find Class for: " + className, e); } String name = attributes.getValue("name"); EventMethodModel parent = (EventMethodModel)objectStack.peek(); objectStack.push(parent.addParameter(type, name)); } else { throw new SAXException("Invalid element: " + qName); } } catch (ClassCastException cce) { throw new SAXException("XML format error: " + qName, cce); } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getFactory().getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) throws SAXException { String ns = attributes.getValue("ns"); domImplementation = elementMappingRegistry.getDOMImplementationForNamespace(ns); if (domImplementation == null) { throw new SAXException("No DOMImplementation could be" + " identified to handle namespace: " + ns); } ForeignObject foreign = new ForeignObject(ns); transferForeignObjects(attributes, foreign); setAreaAttributes(attributes, foreign); setTraits(attributes, foreign, SUBSET_COMMON); getCurrentViewport().setContent(foreign); areaStack.push(foreign); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
Override public void endDocument() throws SAXException { // render any pages that had unresolved ids checkPreparedPages(null, true); processOffDocumentItems(pendingODI); pendingODI.clear(); processOffDocumentItems(endDocODI); try { renderer.stopRenderer(); } catch (IOException ex) { throw new SAXException(ex); } }
// in src/java/org/apache/fop/util/XMLUtil.java
public static int getAttributeAsInt(Attributes attributes, String name) throws SAXException { String s = attributes.getValue(name); if (s == null) { throw new SAXException("Attribute '" + name + "' is missing"); } else { return Integer.parseInt(s); } }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { super.startElement(uri, localName, qName, atts); QName elementName = new QName(uri, qName); if (isOwnNamespace(uri)) { if (CATALOGUE.equals(localName)) { //nop } else if (MESSAGE.equals(localName)) { if (!CATALOGUE.equals(getParentElementName().getLocalName())) { throw new SAXException(MESSAGE + " must be a child of " + CATALOGUE); } this.currentKey = atts.getValue("key"); } else { throw new SAXException("Invalid element name: " + elementName); } } else { //ignore } this.valueBuffer.setLength(0); elementStack.push(elementName); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); elementStack.pop(); if (isOwnNamespace(uri)) { if (CATALOGUE.equals(localName)) { //nop } else if (MESSAGE.equals(localName)) { if (this.currentKey == null) { throw new SAXException( "current key is null (attribute 'key' might be mistyped)"); } resources.put(this.currentKey, this.valueBuffer.toString()); this.currentKey = null; } } else { //ignore } this.valueBuffer.setLength(0); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (doc == null) { TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } doc = domImplementation.createDocument(namespaceURI, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); setDelegateContentHandler(handler); setDelegateLexicalHandler(handler); setDelegateDTDHandler(handler); handler.startDocument(); } super.startElement(uri, localName, qName, atts); }
17
            
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
catch (IOException ioe) { throw new SAXException(ioe); }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
catch (IllegalArgumentException e) { throw new SAXException(e); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (IOException ioe) { throw new SAXException(ioe.getMessage()); }
// in src/java/org/apache/fop/svg/FOPSAXSVGDocumentFactory.java
catch (IOException ioe) { /**@todo Batik's SAXSVGDocumentFactory should throw IOException, * so we don't have to handle it here. */ throw new SAXException(ioe); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (NumberFormatException ne) { throw new SAXException("Malformed width in metric file: " + ne.getMessage(), ne); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (Exception e) { throw new SAXException("Error while parsing integer value: " + str, e); }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
catch (IFException ife) { throw new SAXException(ife); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
catch (URISyntaxException e) { throw new SAXException("Invalid URI: " + src, e); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassNotFoundException e) { throw new SAXException("Could not find Class for: " + className, e); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
catch (ClassCastException cce) { throw new SAXException("XML format error: " + qName, cce); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/area/RenderPagesModel.java
catch (IOException ex) { throw new SAXException(ex); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
202
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void leaveTextMode() throws SAXException { assert this.mode == MODE_TEXT; handler.endElement("g"); this.mode = MODE_NORMAL; }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void establish(int newMode) throws SAXException { switch (newMode) { case MODE_TEXT: enterTextMode(); break; default: if (this.mode == MODE_TEXT) { leaveTextMode(); } } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void enterTextMode() throws SAXException { if (state.isFontChanged() && this.mode == MODE_TEXT) { leaveTextMode(); } if (this.mode != MODE_TEXT) { startTextGroup(); this.mode = MODE_TEXT; } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private void startTextGroup() throws SAXException { AttributesImpl atts = new AttributesImpl(); XMLUtil.addAttribute(atts, "font-family", "'" + state.getFontFamily() + "'"); XMLUtil.addAttribute(atts, "font-style", state.getFontStyle()); XMLUtil.addAttribute(atts, "font-weight", Integer.toString(state.getFontWeight())); XMLUtil.addAttribute(atts, "font-variant", state.getFontVariant()); XMLUtil.addAttribute(atts, "font-size", SVGUtil.formatMptToPt(state.getFontSize())); XMLUtil.addAttribute(atts, "fill", toString(state.getTextColor())); handler.startElement("g", atts); state.resetFontChanged(); }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
public void handleImage(RenderingContext context, Image image, final Rectangle pos) throws IOException { SVGRenderingContext svgContext = (SVGRenderingContext)context; ImageXMLDOM svg = (ImageXMLDOM)image; ContentHandler handler = svgContext.getContentHandler(); AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "x", "x", CDATA, SVGUtil.formatMptToPt(pos.x)); atts.addAttribute("", "y", "y", CDATA, SVGUtil.formatMptToPt(pos.y)); atts.addAttribute("", "width", "width", CDATA, SVGUtil.formatMptToPt(pos.width)); atts.addAttribute("", "height", "height", CDATA, SVGUtil.formatMptToPt(pos.height)); try { Document doc = (Document)svg.getDocument(); Element svgEl = (Element)doc.getDocumentElement(); if (svgEl.getAttribute("viewBox").length() == 0) { log.warn("SVG doesn't have a viewBox. The result might not be scaled correctly!"); } TransformerFactory tFactory = TransformerFactory.newInstance(); Transformer transformer = tFactory.newTransformer(); DOMSource src = new DOMSource(svg.getDocument()); SAXResult res = new SAXResult(new DelegatingFragmentContentHandler(handler) { private boolean topLevelSVGFound = false; private void setAttribute(AttributesImpl atts, String localName, String value) { int index; index = atts.getIndex("", localName); if (index < 0) { atts.addAttribute("", localName, localName, CDATA, value); } else { atts.setAttribute(index, "", localName, localName, CDATA, value); } } public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { if (!topLevelSVGFound && SVG_ELEMENT.getNamespaceURI().equals(uri) && SVG_ELEMENT.getLocalName().equals(localName)) { topLevelSVGFound = true; AttributesImpl modAtts = new AttributesImpl(atts); setAttribute(modAtts, "x", SVGUtil.formatMptToPt(pos.x)); setAttribute(modAtts, "y", SVGUtil.formatMptToPt(pos.y)); setAttribute(modAtts, "width", SVGUtil.formatMptToPt(pos.width)); setAttribute(modAtts, "height", SVGUtil.formatMptToPt(pos.height)); super.startElement(uri, localName, name, modAtts); } else { super.startElement(uri, localName, name, atts); } } }); transformer.transform(src, res); } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
public void startElement(String uri, String localName, String name, Attributes atts) throws SAXException { if (!topLevelSVGFound && SVG_ELEMENT.getNamespaceURI().equals(uri) && SVG_ELEMENT.getLocalName().equals(localName)) { topLevelSVGFound = true; AttributesImpl modAtts = new AttributesImpl(atts); setAttribute(modAtts, "x", SVGUtil.formatMptToPt(pos.x)); setAttribute(modAtts, "y", SVGUtil.formatMptToPt(pos.y)); setAttribute(modAtts, "width", SVGUtil.formatMptToPt(pos.width)); setAttribute(modAtts, "height", SVGUtil.formatMptToPt(pos.height)); super.startElement(uri, localName, name, modAtts); } else { super.startElement(uri, localName, name, atts); } }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
public void startDocument() throws SAXException { log.fatal("The MIF Handler is non-functional at this time. Please help resurrect it!"); mifFile = new MIFFile(); try { mifFile.output(outStream); } catch (IOException ioe) { throw new SAXException(ioe); } }
// in src/sandbox/org/apache/fop/render/mif/MIFHandler.java
public void endDocument() throws SAXException { // finish all open elements mifFile.finish(true); try { mifFile.output(outStream); outStream.flush(); } catch (IOException ioe) { throw new SAXException(ioe); } }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setUserConfig(File userConfigFile) throws SAXException, IOException { config.setUserConfig(userConfigFile); }
// in src/java/org/apache/fop/apps/FopFactory.java
public void setUserConfig(String uri) throws SAXException, IOException { config.setUserConfig(uri); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(File userConfigFile) throws SAXException, IOException { try { DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); setUserConfig(cfgBuilder.buildFromFile(userConfigFile)); } catch (ConfigurationException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
public void setUserConfig(String uri) throws SAXException, IOException { try { DefaultConfigurationBuilder cfgBuilder = new DefaultConfigurationBuilder(); setUserConfig(cfgBuilder.build(uri)); } catch (ConfigurationException e) { throw new FOPException(e); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void prepare() throws SAXException, IOException { if (this.configFile != null) { fopFactory.setUserConfig(this.configFile); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void generateXML(SortedMap fontFamilies, File outFile, String singleFamily) throws TransformerConfigurationException, SAXException, IOException { SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler handler; if (this.mode == GENERATE_XML) { handler = tFactory.newTransformerHandler(); } else { URL url = getClass().getResource("fonts2fo.xsl"); if (url == null) { throw new FileNotFoundException("Did not find resource: fonts2fo.xsl"); } handler = tFactory.newTransformerHandler(new StreamSource(url.toExternalForm())); } if (singleFamily != null) { Transformer transformer = handler.getTransformer(); transformer.setParameter("single-family", singleFamily); } OutputStream out = new java.io.FileOutputStream(outFile); out = new java.io.BufferedOutputStream(out); if (this.mode == GENERATE_RENDERED) { handler.setResult(new SAXResult(getFOPContentHandler(out))); } else { handler.setResult(new StreamResult(out)); } try { GenerationHelperContentHandler helper = new GenerationHelperContentHandler( handler, null); FontListSerializer serializer = new FontListSerializer(); serializer.generateSAX(fontFamilies, singleFamily, helper); } finally { IOUtils.closeQuietly(out); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void writeToConsole(SortedMap fontFamilies) throws TransformerConfigurationException, SAXException, IOException { Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String firstFamilyName = (String)entry.getKey(); System.out.println(firstFamilyName + ":"); List list = (List)entry.getValue(); Iterator fonts = list.iterator(); while (fonts.hasNext()) { FontSpec f = (FontSpec)fonts.next(); System.out.println(" " + f.getKey() + " " + f.getFamilyNames()); Iterator triplets = f.getTriplets().iterator(); while (triplets.hasNext()) { FontTriplet triplet = (FontTriplet)triplets.next(); System.out.println(" " + triplet.toString()); } } } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void writeOutput(SortedMap fontFamilies) throws TransformerConfigurationException, SAXException, IOException { if (this.outputFile.isDirectory()) { System.out.println("Creating one file for each family..."); Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String familyName = (String)entry.getKey(); System.out.println("Creating output file for " + familyName + "..."); String filename; switch(this.mode) { case GENERATE_RENDERED: filename = familyName + ".pdf"; break; case GENERATE_FO: filename = familyName + ".fo"; break; case GENERATE_XML: filename = familyName + ".xml"; break; default: throw new IllegalStateException("Unsupported mode"); } File outFile = new File(this.outputFile, filename); generateXML(fontFamilies, outFile, familyName); } } else { System.out.println("Creating output file..."); generateXML(fontFamilies, this.outputFile, this.singleFamilyFilter); } System.out.println(this.outputFile + " written."); }
// in src/java/org/apache/fop/tools/fontlist/FontListSerializer.java
public void generateSAX(SortedMap fontFamilies, GenerationHelperContentHandler handler) throws SAXException { generateSAX(fontFamilies, null, handler); }
// in src/java/org/apache/fop/tools/fontlist/FontListSerializer.java
public void generateSAX(SortedMap fontFamilies, String singleFamily, GenerationHelperContentHandler handler) throws SAXException { handler.startDocument(); AttributesImpl atts = new AttributesImpl(); handler.startElement(FONTS, atts); Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String familyName = (String)entry.getKey(); if (singleFamily != null && familyName != singleFamily) { continue; } atts.clear(); atts.addAttribute(null, NAME, NAME, CDATA, familyName); atts.addAttribute(null, STRIPPED_NAME, STRIPPED_NAME, CDATA, stripQuotes(familyName)); handler.startElement(FAMILY, atts); List containers = (List)entry.getValue(); generateXMLForFontContainers(handler, containers); handler.endElement(FAMILY); } handler.endElement(FONTS); handler.endDocument(); }
// in src/java/org/apache/fop/tools/fontlist/FontListSerializer.java
private void generateXMLForFontContainers(GenerationHelperContentHandler handler, List containers) throws SAXException { AttributesImpl atts = new AttributesImpl(); Iterator fontIter = containers.iterator(); while (fontIter.hasNext()) { FontSpec cont = (FontSpec)fontIter.next(); atts.clear(); atts.addAttribute(null, KEY, KEY, CDATA, cont.getKey()); atts.addAttribute(null, TYPE, TYPE, CDATA, cont.getFontMetrics().getFontType().getName()); handler.startElement(FONT, atts); generateXMLForTriplets(handler, cont.getTriplets()); handler.endElement(FONT); } }
// in src/java/org/apache/fop/tools/fontlist/FontListSerializer.java
private void generateXMLForTriplets(GenerationHelperContentHandler handler, Collection triplets) throws SAXException { AttributesImpl atts = new AttributesImpl(); atts.clear(); handler.startElement(TRIPLETS, atts); Iterator iter = triplets.iterator(); while (iter.hasNext()) { FontTriplet triplet = (FontTriplet)iter.next(); atts.clear(); atts.addAttribute(null, NAME, NAME, CDATA, triplet.getName()); atts.addAttribute(null, STYLE, STYLE, CDATA, triplet.getStyle()); atts.addAttribute(null, WEIGHT, WEIGHT, CDATA, Integer.toString(triplet.getWeight())); handler.element(TRIPLET, atts); } handler.endElement(TRIPLETS); }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void characters(char[] data, int start, int length) throws SAXException { delegate.characters(data, start, length); }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void startDocument() throws SAXException { if (used) { throw new IllegalStateException("FOTreeBuilder (and the Fop class) cannot be reused." + " Please instantiate a new instance."); } used = true; empty = true; rootFObj = null; // allows FOTreeBuilder to be reused if (LOG.isDebugEnabled()) { LOG.debug("Building formatting object tree"); } foEventHandler.startDocument(); this.mainFOHandler = new MainFOHandler(); this.mainFOHandler.startDocument(); this.delegate = this.mainFOHandler; }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void endDocument() throws SAXException { this.delegate.endDocument(); if (this.rootFObj == null && empty) { FOValidationEventProducer eventProducer = FOValidationEventProducer.Provider.get(userAgent.getEventBroadcaster()); eventProducer.emptyDocument(this); } rootFObj = null; if (LOG.isDebugEnabled()) { LOG.debug("Parsing of document complete"); } foEventHandler.endDocument(); }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void startElement(String namespaceURI, String localName, String rawName, Attributes attlist) throws SAXException { this.depth++; delegate.startElement(namespaceURI, localName, rawName, attlist); }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void endElement(String uri, String localName, String rawName) throws SAXException { this.delegate.endElement(uri, localName, rawName); this.depth--; if (depth == 0) { if (delegate != mainFOHandler) { //Return from sub-handler back to main handler delegate.endDocument(); delegate = mainFOHandler; delegate.endElement(uri, localName, rawName); } } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void fatalError(SAXParseException e) throws SAXException { LOG.error(e.toString()); throw e; }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void startElement(String namespaceURI, String localName, String rawName, Attributes attlist) throws SAXException { /* the node found in the FO document */ FONode foNode; PropertyList propertyList = null; // Check to ensure first node encountered is an fo:root if (rootFObj == null) { empty = false; if (!namespaceURI.equals(FOElementMapping.URI) || !localName.equals("root")) { FOValidationEventProducer eventProducer = FOValidationEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.invalidFORoot(this, FONode.getNodeString(namespaceURI, localName), getEffectiveLocator()); } } else { // check that incoming node is valid for currentFObj if (currentFObj.getNamespaceURI().equals(FOElementMapping.URI) || currentFObj.getNamespaceURI().equals(ExtensionElementMapping.URI)) { currentFObj.validateChildNode(locator, namespaceURI, localName); } } ElementMapping.Maker fobjMaker = findFOMaker(namespaceURI, localName); try { foNode = fobjMaker.make(currentFObj); if (rootFObj == null) { rootFObj = (Root) foNode; rootFObj.setBuilderContext(builderContext); rootFObj.setFOEventHandler(foEventHandler); } propertyList = foNode.createPropertyList( currentPropertyList, foEventHandler); foNode.processNode(localName, getEffectiveLocator(), attlist, propertyList); if (foNode.getNameId() == Constants.FO_MARKER) { if (builderContext.inMarker()) { nestedMarkerDepth++; } else { builderContext.switchMarkerContext(true); } } if (foNode.getNameId() == Constants.FO_PAGE_SEQUENCE) { builderContext.getXMLWhiteSpaceHandler().reset(); } } catch (IllegalArgumentException e) { throw new SAXException(e); } ContentHandlerFactory chFactory = foNode.getContentHandlerFactory(); if (chFactory != null) { ContentHandler subHandler = chFactory.createContentHandler(); if (subHandler instanceof ObjectSource && foNode instanceof ObjectBuiltListener) { ((ObjectSource) subHandler).setObjectBuiltListener( (ObjectBuiltListener) foNode); } subHandler.startDocument(); subHandler.startElement(namespaceURI, localName, rawName, attlist); depth = 1; delegate = subHandler; } if (currentFObj != null) { currentFObj.addChildNode(foNode); } currentFObj = foNode; if (propertyList != null && !builderContext.inMarker()) { currentPropertyList = propertyList; } // fo:characters can potentially be removed during // white-space handling. // Do not notify the FOEventHandler. if (currentFObj.getNameId() != Constants.FO_CHARACTER) { currentFObj.startOfNode(); } }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void endElement(String uri, String localName, String rawName) throws SAXException { if (currentFObj == null) { throw new SAXException( "endElement() called for " + rawName + " where there is no current element."); } else if (!currentFObj.getLocalName().equals(localName) || !currentFObj.getNamespaceURI().equals(uri)) { throw new SAXException("Mismatch: " + currentFObj.getLocalName() + " (" + currentFObj.getNamespaceURI() + ") vs. " + localName + " (" + uri + ")"); } // fo:characters can potentially be removed during // white-space handling. // Do not notify the FOEventHandler. if (currentFObj.getNameId() != Constants.FO_CHARACTER) { currentFObj.endOfNode(); } if (currentPropertyList != null && currentPropertyList.getFObj() == currentFObj && !builderContext.inMarker()) { currentPropertyList = currentPropertyList.getParentPropertyList(); } if (currentFObj.getNameId() == Constants.FO_MARKER) { if (nestedMarkerDepth == 0) { builderContext.switchMarkerContext(false); } else { nestedMarkerDepth--; } } if (currentFObj.getParent() == null) { LOG.debug("endElement for top-level " + currentFObj.getName()); } currentFObj = currentFObj.getParent(); }
// in src/java/org/apache/fop/fo/FOTreeBuilder.java
public void endDocument() throws SAXException { currentFObj = null; }
// in src/java/org/apache/fop/fo/DelegatingFOEventHandler.java
Override public void startDocument() throws SAXException { delegate.startDocument(); }
// in src/java/org/apache/fop/fo/DelegatingFOEventHandler.java
Override public void endDocument() throws SAXException { delegate.endDocument(); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
public ContentHandler createContentHandler() throws SAXException { return new Handler(); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
public void startDocument() throws SAXException { // Suppress startDocument() call if doc has not been set, yet. It // will be done later. if (doc != null) { super.startDocument(); } }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (doc == null) { TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } String version = atts.getValue("version"); DOMImplementation domImplementation = getDOMImplementation(version); doc = domImplementation.createDocument(uri, qName, null); // It's easier to work with an empty document, so remove the // root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); setDelegateContentHandler(handler); setDelegateLexicalHandler(handler); setDelegateDTDHandler(handler); handler.startDocument(); } super.startElement(uri, localName, qName, atts); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
public void endDocument() throws SAXException { super.endDocument(); if (obListener != null) { obListener.notifyObjectBuilt(getObject()); } }
// in src/java/org/apache/fop/fo/extensions/xmp/XMPMetadata.java
public void toSAX(ContentHandler handler) throws SAXException { getMetadata().toSAX(handler); }
// in src/java/org/apache/fop/fo/extensions/xmp/XMPContentHandlerFactory.java
public ContentHandler createContentHandler() throws SAXException { return new FOPXMPHandler(); }
// in src/java/org/apache/fop/fo/extensions/xmp/XMPContentHandlerFactory.java
public void endDocument() throws SAXException { if (obListener != null) { obListener.notifyObjectBuilt(getObject()); } }
// in src/java/org/apache/fop/fo/FOEventHandler.java
public void startDocument() throws SAXException { }
// in src/java/org/apache/fop/fo/FOEventHandler.java
public void endDocument() throws SAXException { }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
protected void getExternalClasses() throws SAXException { XMLReader mainParser = parser; parser = createParser(); parser.setContentHandler(this); parser.setErrorHandler(this); InputStream stream = this.getClass().getResourceAsStream("classes.xml"); InputSource source = new InputSource(stream); try { parser.parse(source); } catch (IOException ioe) { throw new SAXException(ioe.getMessage()); } finally { parser = mainParser; } }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void startElement(String uri, String local, String raw, Attributes attrs) throws SAXException { if (local.equals("hyphen-char")) { String h = attrs.getValue("value"); if (h != null && h.length() == 1) { hyphenChar = h.charAt(0); } } else if (local.equals("classes")) { currElement = ELEM_CLASSES; } else if (local.equals("patterns")) { if (!hasClasses) { getExternalClasses(); } currElement = ELEM_PATTERNS; } else if (local.equals("exceptions")) { if (!hasClasses) { getExternalClasses(); } currElement = ELEM_EXCEPTIONS; exception = new ArrayList(); } else if (local.equals("hyphen")) { if (token.length() > 0) { exception.add(token.toString()); } exception.add(new Hyphen(attrs.getValue("pre"), attrs.getValue("no"), attrs.getValue("post"))); currElement = ELEM_HYPHEN; } token.setLength(0); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
public void fatalError(SAXParseException ex) throws SAXException { errMsg = "[Fatal Error] " + getLocationString(ex) + ": " + ex.getMessage(); throw ex; }
// in src/java/org/apache/fop/svg/FOPSAXSVGDocumentFactory.java
public InputSource resolveEntity(String publicId, String systemId) throws SAXException { if (this.additionalResolver != null) { try { InputSource result = this.additionalResolver.resolveEntity(publicId, systemId); if (result != null) { return result; } } catch (IOException ioe) { /**@todo Batik's SAXSVGDocumentFactory should throw IOException, * so we don't have to handle it here. */ throw new SAXException(ioe); } } return super.resolveEntity(publicId, systemId); }
// in src/java/org/apache/fop/fonts/FontReader.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("font-metrics")) { if ("TYPE0".equals(attributes.getValue("type"))) { multiFont = new MultiByteFont(); returnFont = multiFont; isCID = true; TTFReader.checkMetricsVersion(attributes); } else if ("TRUETYPE".equals(attributes.getValue("type"))) { singleFont = new SingleByteFont(); singleFont.setFontType(FontType.TRUETYPE); returnFont = singleFont; isCID = false; TTFReader.checkMetricsVersion(attributes); } else { singleFont = new SingleByteFont(); singleFont.setFontType(FontType.TYPE1); returnFont = singleFont; isCID = false; } } else if ("embed".equals(localName)) { returnFont.setEmbedFileName(attributes.getValue("file")); returnFont.setEmbedResourceName(attributes.getValue("class")); } else if ("cid-widths".equals(localName)) { cidWidthIndex = getInt(attributes.getValue("start-index")); cidWidths = new ArrayList<Integer>(); } else if ("kerning".equals(localName)) { currentKerning = new HashMap<Integer, Integer>(); returnFont.putKerningEntry(new Integer(attributes.getValue("kpx1")), currentKerning); } else if ("bfranges".equals(localName)) { bfranges = new ArrayList<BFEntry>(); } else if ("bf".equals(localName)) { BFEntry entry = new BFEntry(getInt(attributes.getValue("us")), getInt(attributes.getValue("ue")), getInt(attributes.getValue("gi"))); bfranges.add(entry); } else if ("wx".equals(localName)) { cidWidths.add(new Integer(attributes.getValue("w"))); } else if ("widths".equals(localName)) { //singleFont.width = new int[256]; } else if ("char".equals(localName)) { try { singleFont.setWidth(Integer.parseInt(attributes.getValue("idx")), Integer.parseInt(attributes.getValue("wdt"))); } catch (NumberFormatException ne) { throw new SAXException("Malformed width in metric file: " + ne.getMessage(), ne); } } else if ("pair".equals(localName)) { currentKerning.put(new Integer(attributes.getValue("kpx2")), new Integer(attributes.getValue("kern"))); } }
// in src/java/org/apache/fop/fonts/FontReader.java
private int getInt(String str) throws SAXException { int ret = 0; try { ret = Integer.parseInt(str); } catch (Exception e) { throw new SAXException("Error while parsing integer value: " + str, e); } return ret; }
// in src/java/org/apache/fop/fonts/FontReader.java
public void endElement(String uri, String localName, String qName) throws SAXException { String content = text.toString().trim(); if ("font-name".equals(localName)) { returnFont.setFontName(content); } else if ("full-name".equals(localName)) { returnFont.setFullName(content); } else if ("family-name".equals(localName)) { Set<String> s = new HashSet<String>(); s.add(content); returnFont.setFamilyNames(s); } else if ("ttc-name".equals(localName) && isCID) { multiFont.setTTCName(content); } else if ("encoding".equals(localName)) { if (singleFont != null && singleFont.getFontType() == FontType.TYPE1) { singleFont.setEncoding(content); } } else if ("cap-height".equals(localName)) { returnFont.setCapHeight(getInt(content)); } else if ("x-height".equals(localName)) { returnFont.setXHeight(getInt(content)); } else if ("ascender".equals(localName)) { returnFont.setAscender(getInt(content)); } else if ("descender".equals(localName)) { returnFont.setDescender(getInt(content)); } else if ("left".equals(localName)) { int[] bbox = returnFont.getFontBBox(); bbox[0] = getInt(content); returnFont.setFontBBox(bbox); } else if ("bottom".equals(localName)) { int[] bbox = returnFont.getFontBBox(); bbox[1] = getInt(content); returnFont.setFontBBox(bbox); } else if ("right".equals(localName)) { int[] bbox = returnFont.getFontBBox(); bbox[2] = getInt(content); returnFont.setFontBBox(bbox); } else if ("top".equals(localName)) { int[] bbox = returnFont.getFontBBox(); bbox[3] = getInt(content); returnFont.setFontBBox(bbox); } else if ("first-char".equals(localName)) { returnFont.setFirstChar(getInt(content)); } else if ("last-char".equals(localName)) { returnFont.setLastChar(getInt(content)); } else if ("flags".equals(localName)) { returnFont.setFlags(getInt(content)); } else if ("stemv".equals(localName)) { returnFont.setStemV(getInt(content)); } else if ("italic-angle".equals(localName)) { returnFont.setItalicAngle(getInt(content)); } else if ("missing-width".equals(localName)) { returnFont.setMissingWidth(getInt(content)); } else if ("cid-type".equals(localName)) { multiFont.setCIDType(CIDFontType.byName(content)); } else if ("default-width".equals(localName)) { multiFont.setDefaultWidth(getInt(content)); } else if ("cid-widths".equals(localName)) { int[] wds = new int[cidWidths.size()]; int j = 0; for (int count = 0; count < cidWidths.size(); count++) { wds[j++] = cidWidths.get(count).intValue(); } //multiFont.addCIDWidthEntry(cidWidthIndex, wds); multiFont.setWidthArray(wds); } else if ("bfranges".equals(localName)) { multiFont.setBFEntries(bfranges.toArray(new BFEntry[0])); } text.setLength(0); //Reset text buffer (see characters()) }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
public static void checkMetricsVersion(Attributes attr) throws SAXException { String err = null; final String str = attr.getValue(METRICS_VERSION_ATTR); if (str == null) { err = "Missing " + METRICS_VERSION_ATTR + " attribute"; } else { int version = 0; try { version = Integer.parseInt(str); if (version < METRICS_VERSION) { err = "Incompatible " + METRICS_VERSION_ATTR + " value (" + version + ", should be " + METRICS_VERSION + ")"; } } catch (NumberFormatException e) { err = "Invalid " + METRICS_VERSION_ATTR + " attribute value (" + str + ")"; } } if (err != null) { throw new SAXException( err + " - please regenerate the font metrics file with " + "a more recent version of FOP." ); } }
// in src/java/org/apache/fop/render/pdf/extensions/PDFEmbeddedFileExtensionAttachment.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (filename != null && filename.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", filename); } if (src != null && src.length() > 0) { atts.addAttribute(null, ATT_SRC, ATT_SRC, "CDATA", src); } if (desc != null && desc.length() > 0) { atts.addAttribute(null, ATT_DESC, ATT_DESC, "CDATA", desc); } String element = getElement(); handler.startElement(CATEGORY, element, element, atts); handler.endElement(CATEGORY, element, element); }
// in src/java/org/apache/fop/render/pdf/extensions/PDFExtensionHandler.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (PDFExtensionAttachment.CATEGORY.equals(uri)) { lastAttributes = new AttributesImpl(attributes); handled = false; if (localName.equals(PDFEmbeddedFileExtensionAttachment.ELEMENT)) { //handled in endElement handled = true; } } if (!handled) { if (PDFExtensionAttachment.CATEGORY.equals(uri)) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/pdf/extensions/PDFExtensionHandler.java
public void endElement(String uri, String localName, String qName) throws SAXException { if (PDFExtensionAttachment.CATEGORY.equals(uri)) { if (PDFEmbeddedFileExtensionAttachment.ELEMENT.equals(localName)) { String name = lastAttributes.getValue("name"); String src = lastAttributes.getValue("src"); String desc = lastAttributes.getValue("description"); this.returnedObject = new PDFEmbeddedFileExtensionAttachment(name, src, desc); } } }
// in src/java/org/apache/fop/render/pdf/extensions/PDFExtensionHandler.java
public void endDocument() throws SAXException { if (listener != null) { listener.notifyObjectBuilt(getObject()); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endDocument() throws SAXException { startIFElement(EL_PAGE_SEQUENCE, pageSequenceAttributes); pageSequenceAttributes = null; }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (!"structure-tree".equals(localName)) { if (localName.equals("marked-content")) { localName = "#PCDATA"; } String structID = attributes.getValue(InternalElementMapping.URI, InternalElementMapping.STRUCT_ID); if (structID == null) { structureTreeEventHandler.startNode(localName, attributes); } else if (localName.equals("external-graphic") || localName.equals("instream-foreign-object")) { StructureTreeElement structureTreeElement = structureTreeEventHandler.startImageNode(localName, attributes); structureTreeElements.put(structID, structureTreeElement); } else { StructureTreeElement structureTreeElement = structureTreeEventHandler .startReferencedNode(localName, attributes); structureTreeElements.put(structID, structureTreeElement); } } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
Override public void endElement(String uri, String localName, String arqNameg2) throws SAXException { if (!"structure-tree".equals(localName)) { structureTreeEventHandler.endNode(localName); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateDepth++; delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if (NAMESPACE.equals(uri)) { if (localName.equals(EL_PAGE_SEQUENCE) && userAgent.isAccessibilityEnabled()) { pageSequenceAttributes = new AttributesImpl(attributes); Locale language = getLanguage(attributes); structureTreeHandler = new StructureTreeHandler( userAgent.getStructureTreeEventHandler(), language); } else if (localName.equals(EL_STRUCTURE_TREE)) { if (userAgent.isAccessibilityEnabled()) { String type = attributes.getValue("type"); structureTreeHandler.startStructureTree(type); delegate = structureTreeHandler; } else { /* Delegate to a handler that does nothing */ delegate = new DefaultHandler(); } delegateDepth++; delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { if (pageSequenceAttributes != null) { /* * This means that no structure-element tag was * found in the XML, otherwise a * StructureTreeBuilderWrapper object would have * been created, which would have reset the * pageSequenceAttributes field. */ AccessibilityEventProducer.Provider .get(userAgent.getEventBroadcaster()) .noStructureTreeInXML(this); } handled = startIFElement(localName, attributes); } } else if (DocumentNavigationExtensionConstants.NAMESPACE.equals(uri)) { if (this.navParser == null) { this.navParser = new DocumentNavigationHandler( this.documentHandler.getDocumentNavigationHandler(), structureTreeElements); } delegate = this.navParser; delegateDepth++; delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { ContentHandlerFactoryRegistry registry = userAgent.getFactory().getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory == null) { DOMImplementation domImplementation = elementMappingRegistry.getDOMImplementationForNamespace(uri); if (domImplementation == null) { domImplementation = ElementMapping.getDefaultDOMImplementation(); /* throw new SAXException("No DOMImplementation could be" + " identified to handle namespace: " + uri); */ } factory = new DOMBuilderContentHandlerFactory(uri, domImplementation); } delegate = factory.createContentHandler(); delegateDepth++; delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
private boolean startIFElement(String localName, Attributes attributes) throws SAXException { lastAttributes = new AttributesImpl(attributes); ElementHandler elementHandler = elementHandlers.get(localName); content.setLength(0); ignoreCharacters = true; if (elementHandler != null) { ignoreCharacters = elementHandler.ignoreCharacters(); try { elementHandler.startElement(attributes); } catch (IFException ife) { handleIFException(ife); } return true; } else { return false; } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
private void handleIFException(IFException ife) throws SAXException { if (ife.getCause() instanceof SAXException) { //unwrap throw (SAXException)ife.getCause(); } else { //wrap throw new SAXException(ife); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void endElement(String uri, String localName, String qName) throws SAXException { if (delegate != null) { delegate.endElement(uri, localName, qName); delegateDepth--; if (delegateDepth == 0) { delegate.endDocument(); if (delegate instanceof ContentHandlerFactory.ObjectSource) { Object obj = ((ContentHandlerFactory.ObjectSource)delegate).getObject(); if (inForeignObject) { this.foreignObject = (Document)obj; } else { handleExternallyGeneratedObject(obj); } } delegate = null; //Sub-document is processed, return to normal processing } } else { if (NAMESPACE.equals(uri)) { ElementHandler elementHandler = elementHandlers.get(localName); if (elementHandler != null) { try { elementHandler.endElement(); } catch (IFException ife) { handleIFException(ife); } content.setLength(0); } ignoreCharacters = true; } else { if (log.isTraceEnabled()) { log.trace("Ignoring " + localName + " in namespace: " + uri); } } } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void startElement(Attributes attributes) throws IFException, SAXException { //nop }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
Override public void startElement(Attributes attributes) throws IFException, SAXException { String id = attributes.getValue("name"); documentHandler.getContext().setID(id); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
protected void handleExternallyGeneratedObject(Object obj) throws SAXException { try { documentHandler.handleExtensionObject(obj); } catch (IFException ife) { handleIFException(ife); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void characters(char[] ch, int start, int length) throws SAXException { if (delegate != null) { delegate.characters(ch, start, length); } else if (!ignoreCharacters) { this.content.append(ch, start, length); } }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void characters(char[] arg0, int arg1, int arg2) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void endDocument() throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void endElement(String arg0, String arg1, String arg2) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void endPrefixMapping(String arg0) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void ignorableWhitespace(char[] arg0, int arg1, int arg2) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void processingInstruction(String arg0, String arg1) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void skippedEntity(String arg0) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void startDocument() throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void startElement(String arg0, String arg1, String arg2, Attributes arg3) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFContentHandler.java
public void startPrefixMapping(String arg0, String arg1) throws SAXException { // TODO Auto-generated method stub }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override void replay(ContentHandler handler) throws SAXException { handler.startElement(uri, localName, qName, attributes); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override void replay(ContentHandler handler) throws SAXException { handler.endElement(uri, localName, qName); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override void replay(ContentHandler handler) throws SAXException { handler.startPrefixMapping(prefix, uri); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override void replay(ContentHandler handler) throws SAXException { handler.endPrefixMapping(prefix); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { events.add(new StartElement(uri, localName, qName, attributes)); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override public void endElement(String uri, String localName, String qName) throws SAXException { events.add(new EndElement(uri, localName, qName)); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override public void startPrefixMapping(String prefix, String uri) throws SAXException { events.add(new StartPrefixMapping(prefix, uri)); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
Override public void endPrefixMapping(String prefix) throws SAXException { events.add(new EndPrefixMapping(prefix)); }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
public void replay(ContentHandler handler) throws SAXException { for (SAXEventRecorder.Event e : events) { e.replay(handler); } }
// in src/java/org/apache/fop/render/intermediate/IFStructureTreeBuilder.java
public void replayEventsForPageSequence(ContentHandler handler, int pageSequenceIndex) throws SAXException { pageSequenceEventRecorders.get(pageSequenceIndex).replay(handler); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void addForeignAttributes(AttributesImpl atts) throws SAXException { Map foreignAttributes = getContext().getForeignAttributes(); if (!foreignAttributes.isEmpty()) { Iterator iter = foreignAttributes.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); addAttribute(atts, (QName)entry.getKey(), entry.getValue().toString()); } } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void addAttribute(AttributesImpl atts, org.apache.xmlgraphics.util.QName attribute, String value) throws SAXException { handler.startPrefixMapping(attribute.getPrefix(), attribute.getNamespaceURI()); XMLUtil.addAttribute(atts, attribute, value); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void addID() throws SAXException { String id = getContext().getID(); if (!currentID.equals(id)) { AttributesImpl atts = new AttributesImpl(); addAttribute(atts, "name", id); handler.startElement(EL_ID, atts); handler.endElement(EL_ID); currentID = id; } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private void serializeBookmark(Bookmark bookmark) throws SAXException, IFException { noteAction(bookmark.getAction()); AttributesImpl atts = new AttributesImpl(); atts.addAttribute(null, "title", "title", XMLUtil.CDATA, bookmark.getTitle()); atts.addAttribute(null, "starting-state", "starting-state", XMLUtil.CDATA, bookmark.isShown() ? "show" : "hide"); handler.startElement(DocumentNavigationExtensionConstants.BOOKMARK, atts); serializeXMLizable(bookmark.getAction()); Iterator iter = bookmark.getChildBookmarks().iterator(); while (iter.hasNext()) { Bookmark b = (Bookmark)iter.next(); if (b.getAction() != null) { serializeBookmark(b); } } handler.endElement(DocumentNavigationExtensionConstants.BOOKMARK); }
// in src/java/org/apache/fop/render/intermediate/DelegatingFragmentContentHandler.java
public void startDocument() throws SAXException { //nop/ignore }
// in src/java/org/apache/fop/render/intermediate/DelegatingFragmentContentHandler.java
public void endDocument() throws SAXException { //nop/ignore }
// in src/java/org/apache/fop/render/intermediate/extensions/GoToXYAction.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (this.isCompleteExceptTargetLocation()) { final Point reportedTargetLocation = this.getTargetLocation(); atts.addAttribute(null, "id", "id", XMLUtil.CDATA, getID()); atts.addAttribute(null, "page-index", "page-index", XMLUtil.CDATA, Integer.toString(pageIndex)); atts.addAttribute(null, "x", "x", XMLUtil.CDATA, Integer.toString(reportedTargetLocation.x)); atts.addAttribute(null, "y", "y", XMLUtil.CDATA, Integer.toString(reportedTargetLocation.y)); } else { atts.addAttribute(null, "idref", "idref", XMLUtil.CDATA, getID()); } handler.startElement(GOTO_XY.getNamespaceURI(), GOTO_XY.getLocalName(), GOTO_XY.getQName(), atts); handler.endElement(GOTO_XY.getNamespaceURI(), GOTO_XY.getLocalName(), GOTO_XY.getQName()); }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (NAMESPACE.equals(uri)) { if (BOOKMARK_TREE.getLocalName().equals(localName)) { if (!objectStack.isEmpty()) { throw new SAXException(localName + " must be the root element!"); } BookmarkTree bookmarkTree = new BookmarkTree(); objectStack.push(bookmarkTree); } else if (BOOKMARK.getLocalName().equals(localName)) { String title = attributes.getValue("title"); String s = attributes.getValue("starting-state"); boolean show = !"hide".equals(s); Bookmark b = new Bookmark(title, show, null); Object o = objectStack.peek(); if (o instanceof AbstractAction) { AbstractAction action = (AbstractAction)objectStack.pop(); o = objectStack.peek(); ((Bookmark)o).setAction(action); } if (o instanceof BookmarkTree) { ((BookmarkTree)o).addBookmark(b); } else { ((Bookmark)o).addChildBookmark(b); } objectStack.push(b); } else if (NAMED_DESTINATION.getLocalName().equals(localName)) { if (!objectStack.isEmpty()) { throw new SAXException(localName + " must be the root element!"); } String name = attributes.getValue("name"); NamedDestination dest = new NamedDestination(name, null); objectStack.push(dest); } else if (LINK.getLocalName().equals(localName)) { if (!objectStack.isEmpty()) { throw new SAXException(localName + " must be the root element!"); } Rectangle targetRect = XMLUtil.getAttributeAsRectangle(attributes, "rect"); structureTreeElement = structureTreeElements.get(attributes.getValue( InternalElementMapping.URI, InternalElementMapping.STRUCT_REF)); Link link = new Link(null, targetRect); objectStack.push(link); } else if (GOTO_XY.getLocalName().equals(localName)) { String idref = attributes.getValue("idref"); GoToXYAction action; if (idref != null) { action = new GoToXYAction(idref); } else { String id = attributes.getValue("id"); int pageIndex = XMLUtil.getAttributeAsInt(attributes, "page-index"); final Point location; if (pageIndex < 0) { location = null; } else { final int x = XMLUtil .getAttributeAsInt(attributes, "x"); final int y = XMLUtil .getAttributeAsInt(attributes, "y"); location = new Point(x, y); } action = new GoToXYAction(id, pageIndex, location); } if (structureTreeElement != null) { action.setStructureTreeElement(structureTreeElement); } objectStack.push(action); } else if (GOTO_URI.getLocalName().equals(localName)) { String id = attributes.getValue("id"); String gotoURI = attributes.getValue("uri"); String showDestination = attributes.getValue("show-destination"); boolean newWindow = "new".equals(showDestination); URIAction action = new URIAction(gotoURI, newWindow); if (id != null) { action.setID(id); } if (structureTreeElement != null) { action.setStructureTreeElement(structureTreeElement); } objectStack.push(action); } else { throw new SAXException( "Invalid element '" + localName + "' in namespace: " + uri); } handled = true; } if (!handled) { if (NAMESPACE.equals(uri)) { throw new SAXException("Unhandled element '" + localName + "' in namespace: " + uri); } else { log.warn("Unhandled element '" + localName + "' in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
public void endElement(String uri, String localName, String qName) throws SAXException { if (NAMESPACE.equals(uri)) { try { if (BOOKMARK_TREE.getLocalName().equals(localName)) { BookmarkTree tree = (BookmarkTree)objectStack.pop(); if (hasNavigation()) { this.navHandler.renderBookmarkTree(tree); } } else if (BOOKMARK.getLocalName().equals(localName)) { if (objectStack.peek() instanceof AbstractAction) { AbstractAction action = (AbstractAction)objectStack.pop(); Bookmark b = (Bookmark)objectStack.pop(); b.setAction(action); } else { objectStack.pop(); } } else if (NAMED_DESTINATION.getLocalName().equals(localName)) { AbstractAction action = (AbstractAction)objectStack.pop(); NamedDestination dest = (NamedDestination)objectStack.pop(); dest.setAction(action); if (hasNavigation()) { this.navHandler.renderNamedDestination(dest); } } else if (LINK.getLocalName().equals(localName)) { AbstractAction action = (AbstractAction)objectStack.pop(); Link link = (Link)objectStack.pop(); link.setAction(action); if (hasNavigation()) { this.navHandler.renderLink(link); } } else if (localName.startsWith("goto-")) { if (objectStack.size() == 1) { //Stand-alone action AbstractAction action = (AbstractAction)objectStack.pop(); if (hasNavigation()) { this.navHandler.addResolvedAction(action); } } } } catch (IFException ife) { throw new SAXException(ife); } } content.setLength(0); // Reset text buffer (see characters()) }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
public void characters(char[] ch, int start, int length) throws SAXException { content.append(ch, start, length); }
// in src/java/org/apache/fop/render/intermediate/extensions/DocumentNavigationHandler.java
public void endDocument() throws SAXException { assert objectStack.isEmpty(); }
// in src/java/org/apache/fop/render/intermediate/extensions/URIAction.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (hasID()) { atts.addAttribute(null, "id", "id", XMLUtil.CDATA, getID()); } atts.addAttribute(null, "uri", "uri", XMLUtil.CDATA, getURI()); if (isNewWindow()) { atts.addAttribute(null, "show-destination", "show-destination", XMLUtil.CDATA, "new"); } handler.startElement(GOTO_URI.getNamespaceURI(), GOTO_URI.getLocalName(), GOTO_URI.getQName(), atts); handler.endElement(GOTO_URI.getNamespaceURI(), GOTO_URI.getLocalName(), GOTO_URI.getQName()); }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void startDocument() throws SAXException { // TODO sections should be created try { rtfFile = new RtfFile(new OutputStreamWriter(os)); docArea = rtfFile.startDocumentArea(); } catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); } }
// in src/java/org/apache/fop/render/rtf/RTFHandler.java
public void endDocument() throws SAXException { try { rtfFile.flush(); } catch (IOException ioe) { // TODO could we throw Exception in all FOEventHandler events? throw new SAXException(ioe); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageOverlay.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } handler.startElement(CATEGORY, elementName, elementName, atts); handler.endElement(CATEGORY, elementName, elementName); }
// in src/java/org/apache/fop/render/afp/extensions/AFPInvokeMediumMap.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } handler.startElement(CATEGORY, elementName, elementName, atts); handler.endElement(CATEGORY, elementName, elementName); }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSetup.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } if (value != null && value.length() > 0) { atts.addAttribute(null, ATT_VALUE, ATT_VALUE, "CDATA", value); } if (this.placement != ExtensionPlacement.DEFAULT) { atts.addAttribute(null, ATT_PLACEMENT, ATT_PLACEMENT, "CDATA", placement.getXMLValue()); } handler.startElement(CATEGORY, elementName, elementName, atts); if (content != null && content.length() > 0) { char[] chars = content.toCharArray(); handler.characters(chars, 0, chars.length); } handler.endElement(CATEGORY, elementName, elementName); }
// in src/java/org/apache/fop/render/afp/extensions/AFPIncludeFormMap.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } if (this.src != null) { atts.addAttribute(null, ATT_SRC, ATT_SRC, "CDATA", this.src.toASCIIString()); } handler.startElement(CATEGORY, elementName, elementName, atts); handler.endElement(CATEGORY, elementName, elementName); }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (AFPExtensionAttachment.CATEGORY.equals(uri)) { lastAttributes = new AttributesImpl(attributes); handled = true; if (localName.equals(AFPElementMapping.NO_OPERATION) || localName.equals(AFPElementMapping.TAG_LOGICAL_ELEMENT) || localName.equals(AFPElementMapping.INCLUDE_PAGE_OVERLAY) || localName.equals(AFPElementMapping.INCLUDE_PAGE_SEGMENT) || localName.equals(AFPElementMapping.INCLUDE_FORM_MAP) || localName.equals(AFPElementMapping.INVOKE_MEDIUM_MAP)) { //handled in endElement } else { handled = false; } } if (!handled) { if (AFPExtensionAttachment.CATEGORY.equals(uri)) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
Override public void endElement(String uri, String localName, String qName) throws SAXException { if (AFPExtensionAttachment.CATEGORY.equals(uri)) { if (AFPElementMapping.INCLUDE_FORM_MAP.equals(localName)) { AFPIncludeFormMap formMap = new AFPIncludeFormMap(); String name = lastAttributes.getValue("name"); formMap.setName(name); String src = lastAttributes.getValue("src"); try { formMap.setSrc(new URI(src)); } catch (URISyntaxException e) { throw new SAXException("Invalid URI: " + src, e); } this.returnedObject = formMap; } else if (AFPElementMapping.INCLUDE_PAGE_OVERLAY.equals(localName)) { this.returnedObject = new AFPPageOverlay(); String name = lastAttributes.getValue("name"); if (name != null) { returnedObject.setName(name); } } else if (AFPElementMapping.INCLUDE_PAGE_SEGMENT.equals(localName)) { AFPPageSegmentSetup pageSetupExtn = null; pageSetupExtn = new AFPPageSegmentSetup(localName); this.returnedObject = pageSetupExtn; String name = lastAttributes.getValue("name"); if (name != null) { returnedObject.setName(name); } String value = lastAttributes.getValue("value"); if (value != null && pageSetupExtn != null) { pageSetupExtn.setValue(value); } String resourceSrc = lastAttributes.getValue("resource-file"); if (resourceSrc != null && pageSetupExtn != null) { pageSetupExtn.setResourceSrc(resourceSrc); } if (content.length() > 0 && pageSetupExtn != null) { pageSetupExtn.setContent(content.toString()); content.setLength(0); //Reset text buffer (see characters()) } } else { AFPPageSetup pageSetupExtn = null; if (AFPElementMapping.INVOKE_MEDIUM_MAP.equals(localName)) { this.returnedObject = new AFPInvokeMediumMap(); } else { pageSetupExtn = new AFPPageSetup(localName); this.returnedObject = pageSetupExtn; } String name = lastAttributes.getValue(AFPPageSetup.ATT_NAME); if (name != null) { returnedObject.setName(name); } String value = lastAttributes.getValue(AFPPageSetup.ATT_VALUE); if (value != null && pageSetupExtn != null) { pageSetupExtn.setValue(value); } String placement = lastAttributes.getValue(AFPPageSetup.ATT_PLACEMENT); if (placement != null && placement.length() > 0) { pageSetupExtn.setPlacement(ExtensionPlacement.fromXMLValue(placement)); } if (content.length() > 0 && pageSetupExtn != null) { pageSetupExtn.setContent(content.toString()); content.setLength(0); //Reset text buffer (see characters()) } } } }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
Override public void characters(char[] ch, int start, int length) throws SAXException { content.append(ch, start, length); }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
Override public void endDocument() throws SAXException { if (listener != null) { listener.notifyObjectBuilt(getObject()); } }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSegmentElement.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } if (value != null && value.length() > 0) { atts.addAttribute(null, ATT_VALUE, ATT_VALUE, "CDATA", value); } if (resourceSrc != null && resourceSrc.length() > 0) { atts.addAttribute(null, ATT_RESOURCE_SRC, ATT_RESOURCE_SRC, "CDATA", resourceSrc); } handler.startElement(CATEGORY, elementName, elementName, atts); if (content != null && content.length() > 0) { char[] chars = content.toCharArray(); handler.characters(chars, 0, chars.length); } handler.endElement(CATEGORY, elementName, elementName); }
// in src/java/org/apache/fop/render/ps/extensions/PSSetupCode.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } String element = getElement(); handler.startElement(CATEGORY, element, element, atts); if (content != null && content.length() > 0) { char[] chars = content.toCharArray(); handler.characters(chars, 0, chars.length); } handler.endElement(CATEGORY, element, element); }
// in src/java/org/apache/fop/render/ps/extensions/PSExtensionAttachment.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); String element = getElement(); handler.startElement(CATEGORY, element, element, atts); if (content != null && content.length() > 0) { char[] chars = content.toCharArray(); handler.characters(chars, 0, chars.length); } handler.endElement(CATEGORY, element, element); }
// in src/java/org/apache/fop/render/ps/extensions/PSSetPageDevice.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); if (name != null && name.length() > 0) { atts.addAttribute(null, ATT_NAME, ATT_NAME, "CDATA", name); } String element = getElement(); handler.startElement(CATEGORY, element, element, atts); if (content != null && content.length() > 0) { char[] chars = content.toCharArray(); handler.characters(chars, 0, chars.length); } handler.endElement(CATEGORY, element, element); }
// in src/java/org/apache/fop/render/ps/extensions/PSExtensionHandler.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { boolean handled = false; if (PSExtensionAttachment.CATEGORY.equals(uri)) { lastAttributes = new AttributesImpl(attributes); handled = false; if (localName.equals(PSSetupCode.ELEMENT) || localName.equals(PSPageTrailerCodeBefore.ELEMENT) || localName.equals(PSSetPageDevice.ELEMENT) || localName.equals(PSCommentBefore.ELEMENT) || localName.equals(PSCommentAfter.ELEMENT)) { //handled in endElement handled = true; } } if (!handled) { if (PSExtensionAttachment.CATEGORY.equals(uri)) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/render/ps/extensions/PSExtensionHandler.java
public void endElement(String uri, String localName, String qName) throws SAXException { if (PSExtensionAttachment.CATEGORY.equals(uri)) { if (PSSetupCode.ELEMENT.equals(localName)) { String name = lastAttributes.getValue("name"); this.returnedObject = new PSSetupCode(name, content.toString()); } else if (PSSetPageDevice.ELEMENT.equals(localName)) { String name = lastAttributes.getValue("name"); this.returnedObject = new PSSetPageDevice(name, content.toString()); } else if (PSCommentBefore.ELEMENT.equals(localName)) { this.returnedObject = new PSCommentBefore(content.toString()); } else if (PSCommentAfter.ELEMENT.equals(localName)) { this.returnedObject = new PSCommentAfter(content.toString()); } else if (PSPageTrailerCodeBefore.ELEMENT.equals(localName)) { this.returnedObject = new PSPageTrailerCodeBefore(content.toString()); } } content.setLength(0); //Reset text buffer (see characters()) }
// in src/java/org/apache/fop/render/ps/extensions/PSExtensionHandler.java
public void characters(char[] ch, int start, int length) throws SAXException { content.append(ch, start, length); }
// in src/java/org/apache/fop/render/ps/extensions/PSExtensionHandler.java
public void endDocument() throws SAXException { if (listener != null) { listener.notifyObjectBuilt(getObject()); } }
// in src/java/org/apache/fop/events/model/EventModelParser.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { try { if ("event-model".equals(localName)) { if (objectStack.size() > 0) { throw new SAXException("event-model must be the root element"); } objectStack.push(model); } else if ("producer".equals(localName)) { EventProducerModel producer = new EventProducerModel( attributes.getValue("name")); EventModel parent = (EventModel)objectStack.peek(); parent.addProducer(producer); objectStack.push(producer); } else if ("method".equals(localName)) { EventSeverity severity = EventSeverity.valueOf(attributes.getValue("severity")); String ex = attributes.getValue("exception"); EventMethodModel method = new EventMethodModel( attributes.getValue("name"), severity); if (ex != null && ex.length() > 0) { method.setExceptionClass(ex); } EventProducerModel parent = (EventProducerModel)objectStack.peek(); parent.addMethod(method); objectStack.push(method); } else if ("parameter".equals(localName)) { String className = attributes.getValue("type"); Class type; try { type = Class.forName(className); } catch (ClassNotFoundException e) { throw new SAXException("Could not find Class for: " + className, e); } String name = attributes.getValue("name"); EventMethodModel parent = (EventMethodModel)objectStack.peek(); objectStack.push(parent.addParameter(type, name)); } else { throw new SAXException("Invalid element: " + qName); } } catch (ClassCastException cce) { throw new SAXException("XML format error: " + qName, cce); } }
// in src/java/org/apache/fop/events/model/EventModelParser.java
public void endElement(String uri, String localName, String qName) throws SAXException { objectStack.pop(); }
// in src/java/org/apache/fop/events/model/EventModel.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); String elName = "event-model"; handler.startElement("", elName, elName, atts); Iterator iter = getProducers(); while (iter.hasNext()) { ((XMLizable)iter.next()).toSAX(handler); } handler.endElement("", elName, elName); }
// in src/java/org/apache/fop/events/model/EventProducerModel.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "name", "name", "CDATA", getInterfaceName()); String elName = "producer"; handler.startElement("", elName, elName, atts); Iterator iter = getMethods(); while (iter.hasNext()) { ((XMLizable)iter.next()).toSAX(handler); } handler.endElement("", elName, elName); }
// in src/java/org/apache/fop/events/model/EventMethodModel.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "name", "name", "CDATA", getMethodName()); atts.addAttribute("", "severity", "severity", "CDATA", getSeverity().getName()); if (getExceptionClass() != null) { atts.addAttribute("", "exception", "exception", "CDATA", getExceptionClass()); } String elName = "method"; handler.startElement("", elName, elName, atts); Iterator iter = this.params.iterator(); while (iter.hasNext()) { ((XMLizable)iter.next()).toSAX(handler); } handler.endElement("", elName, elName); }
// in src/java/org/apache/fop/events/model/EventMethodModel.java
public void toSAX(ContentHandler handler) throws SAXException { AttributesImpl atts = new AttributesImpl(); atts.addAttribute("", "type", "type", "CDATA", getType().getName()); atts.addAttribute("", "name", "name", "CDATA", getName()); String elName = "parameter"; handler.startElement("", elName, elName, atts); handler.endElement("", elName, elName); }
// in src/java/org/apache/fop/area/AreaTreeHandler.java
Override public void startDocument() throws SAXException { // Initialize statistics if (statistics != null) { statistics.start(); } }
// in src/java/org/apache/fop/area/AreaTreeHandler.java
Override public void endDocument() throws SAXException { finishPrevPageSequence(null); // process fox:destination elements if (rootFObj != null) { List<Destination> destinationList = rootFObj.getDestinationList(); if (destinationList != null) { while (destinationList.size() > 0) { Destination destination = destinationList.remove(0); DestinationData destinationData = new DestinationData(destination); addOffDocumentItem(destinationData); } } // process fo:bookmark-tree BookmarkTree bookmarkTree = rootFObj.getBookmarkTree(); if (bookmarkTree != null) { BookmarkData data = new BookmarkData(bookmarkTree); addOffDocumentItem(data); if (!data.isResolved()) { // bookmarks did not fully resolve, add anyway. (hacky? yeah) model.handleOffDocumentItem(data); } } idTracker.signalIDProcessed(rootFObj.getId()); } model.endDocument(); if (statistics != null) { statistics.logResults(); } }
// in src/java/org/apache/fop/area/AreaTreeModel.java
public void endDocument() throws SAXException { }
// in src/java/org/apache/fop/area/CachedRenderPagesModel.java
Override public void endDocument() throws SAXException { super.endDocument(); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (delegate != null) { delegateStack.push(qName); delegate.startElement(uri, localName, qName, attributes); } else if (domImplementation != null) { //domImplementation is set so we need to start a new DOM building sub-process TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } Document doc = domImplementation.createDocument(uri, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); Area parent = (Area)areaStack.peek(); ((ForeignObject)parent).setDocument(doc); //activate delegate for nested foreign document domImplementation = null; //Not needed anymore now this.delegate = handler; delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { boolean handled = true; if ("".equals(uri)) { if (localName.equals("structureTree")) { /* The area tree parser no longer supports the structure tree. */ delegate = new DefaultHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = startAreaTreeElement(localName, attributes); } } else { ContentHandlerFactoryRegistry registry = userAgent.getFactory().getContentHandlerFactoryRegistry(); ContentHandlerFactory factory = registry.getFactory(uri); if (factory != null) { delegate = factory.createContentHandler(); delegateStack.push(qName); delegate.startDocument(); delegate.startElement(uri, localName, qName, attributes); } else { handled = false; } } if (!handled) { if (uri == null || uri.length() == 0) { throw new SAXException("Unhandled element " + localName + " in namespace: " + uri); } else { log.warn("Unhandled element " + localName + " in namespace: " + uri); } } } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
private boolean startAreaTreeElement(String localName, Attributes attributes) throws SAXException { lastAttributes = new AttributesImpl(attributes); Maker maker = makers.get(localName); content.clear(); ignoreCharacters = true; if (maker != null) { ignoreCharacters = maker.ignoreCharacters(); maker.startElement(attributes); } else if ("extension-attachments".equals(localName)) { //TODO implement me } else { return false; } return true; }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void endElement(String uri, String localName, String qName) throws SAXException { if (delegate != null) { delegate.endElement(uri, localName, qName); delegateStack.pop(); if (delegateStack.size() == 0) { delegate.endDocument(); if (delegate instanceof ContentHandlerFactory.ObjectSource) { Object obj = ((ContentHandlerFactory.ObjectSource)delegate).getObject(); handleExternallyGeneratedObject(obj); } delegate = null; //Sub-document is processed, return to normal processing } } else { if ("".equals(uri)) { Maker maker = makers.get(localName); if (maker != null) { maker.endElement(); content.clear(); } ignoreCharacters = true; } else { //log.debug("Ignoring " + localName + " in namespace: " + uri); } } }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) throws SAXException { //nop }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void startElement(Attributes attributes) throws SAXException { String ns = attributes.getValue("ns"); domImplementation = elementMappingRegistry.getDOMImplementationForNamespace(ns); if (domImplementation == null) { throw new SAXException("No DOMImplementation could be" + " identified to handle namespace: " + ns); } ForeignObject foreign = new ForeignObject(ns); transferForeignObjects(attributes, foreign); setAreaAttributes(attributes, foreign); setTraits(attributes, foreign, SUBSET_COMMON); getCurrentViewport().setContent(foreign); areaStack.push(foreign); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void characters(char[] ch, int start, int length) throws SAXException { if (delegate != null) { delegate.characters(ch, start, length); } else if (!ignoreCharacters) { int maxLength = this.content.capacity() - this.content.position(); if (maxLength < length) { // allocate a larger buffer and transfer content CharBuffer newContent = CharBuffer.allocate(this.content.position() + length); this.content.flip(); newContent.put(this.content); this.content = newContent; } // make sure the full capacity is used this.content.limit(this.content.capacity()); // add characters to the buffer this.content.put(ch, start, length); // decrease the limit, if necessary if (this.content.position() < this.content.limit()) { this.content.limit(this.content.position()); } } }
// in src/java/org/apache/fop/area/RenderPagesModel.java
Override public void endDocument() throws SAXException { // render any pages that had unresolved ids checkPreparedPages(null, true); processOffDocumentItems(pendingODI); pendingODI.clear(); processOffDocumentItems(endDocODI); try { renderer.stopRenderer(); } catch (IOException ex) { throw new SAXException(ex); } }
// in src/java/org/apache/fop/accessibility/fo/StructureTreeEventTrigger.java
Override public void startDocument() throws SAXException { }
// in src/java/org/apache/fop/accessibility/fo/StructureTreeEventTrigger.java
Override public void endDocument() throws SAXException { }
// in src/java/org/apache/fop/accessibility/fo/FO2StructureTreeConverter.java
Override public void startDocument() throws SAXException { converter.startDocument(); super.startDocument(); }
// in src/java/org/apache/fop/accessibility/fo/FO2StructureTreeConverter.java
Override public void endDocument() throws SAXException { converter.endDocument(); super.endDocument(); }
// in src/java/org/apache/fop/util/DOM2SAX.java
public void writeDocument(Document doc, boolean fragment) throws SAXException { if (!fragment) { contentHandler.startDocument(); } for (Node n = doc.getFirstChild(); n != null; n = n.getNextSibling()) { writeNode(n); } if (!fragment) { contentHandler.endDocument(); } }
// in src/java/org/apache/fop/util/DOM2SAX.java
public void writeFragment(Node node) throws SAXException { writeNode(node); }
// in src/java/org/apache/fop/util/DOM2SAX.java
private boolean startPrefixMapping(String prefix, String uri) throws SAXException { boolean pushed = true; Stack uriStack = (Stack)prefixes.get(prefix); if (uriStack != null) { if (uriStack.isEmpty()) { contentHandler.startPrefixMapping(prefix, uri); uriStack.push(uri); } else { final String lastUri = (String) uriStack.peek(); if (!lastUri.equals(uri)) { contentHandler.startPrefixMapping(prefix, uri); uriStack.push(uri); } else { pushed = false; } } } else { contentHandler.startPrefixMapping(prefix, uri); uriStack = new Stack(); prefixes.put(prefix, uriStack); uriStack.push(uri); } return pushed; }
// in src/java/org/apache/fop/util/DOM2SAX.java
private void endPrefixMapping(String prefix) throws SAXException { final Stack uriStack = (Stack)prefixes.get(prefix); if (uriStack != null) { contentHandler.endPrefixMapping(prefix); uriStack.pop(); } }
// in src/java/org/apache/fop/util/DOM2SAX.java
private void writeNode(Node node) throws SAXException { if (node == null) { return; } switch (node.getNodeType()) { case Node.ATTRIBUTE_NODE: // handled by ELEMENT_NODE case Node.DOCUMENT_FRAGMENT_NODE: case Node.DOCUMENT_TYPE_NODE: case Node.ENTITY_NODE: case Node.ENTITY_REFERENCE_NODE: case Node.NOTATION_NODE: // These node types are ignored!!! break; case Node.CDATA_SECTION_NODE: final String cdata = node.getNodeValue(); if (lexicalHandler != null) { lexicalHandler.startCDATA(); contentHandler.characters(cdata.toCharArray(), 0, cdata.length()); lexicalHandler.endCDATA(); } else { // in the case where there is no lex handler, we still // want the text of the cdate to make its way through. contentHandler.characters(cdata.toCharArray(), 0, cdata.length()); } break; case Node.COMMENT_NODE: // should be handled!!! if (lexicalHandler != null) { final String value = node.getNodeValue(); lexicalHandler.comment(value.toCharArray(), 0, value.length()); } break; case Node.DOCUMENT_NODE: contentHandler.startDocument(); Node next = node.getFirstChild(); while (next != null) { writeNode(next); next = next.getNextSibling(); } contentHandler.endDocument(); break; case Node.ELEMENT_NODE: String prefix; List pushedPrefixes = new java.util.ArrayList(); final AttributesImpl attrs = new AttributesImpl(); final NamedNodeMap map = node.getAttributes(); final int length = map.getLength(); // Process all namespace declarations for (int i = 0; i < length; i++) { final Node attr = map.item(i); final String qnameAttr = attr.getNodeName(); // Ignore everything but NS declarations here if (qnameAttr.startsWith(XMLNS_PREFIX)) { final String uriAttr = attr.getNodeValue(); final int colon = qnameAttr.lastIndexOf(':'); prefix = (colon > 0) ? qnameAttr.substring(colon + 1) : EMPTYSTRING; if (startPrefixMapping(prefix, uriAttr)) { pushedPrefixes.add(prefix); } } } // Process all other attributes for (int i = 0; i < length; i++) { final Node attr = map.item(i); final String qnameAttr = attr.getNodeName(); // Ignore NS declarations here if (!qnameAttr.startsWith(XMLNS_PREFIX)) { final String uriAttr = attr.getNamespaceURI(); // Uri may be implicitly declared if (uriAttr != null) { final int colon = qnameAttr.lastIndexOf(':'); prefix = (colon > 0) ? qnameAttr.substring(0, colon) : EMPTYSTRING; if (startPrefixMapping(prefix, uriAttr)) { pushedPrefixes.add(prefix); } } // Add attribute to list attrs.addAttribute(attr.getNamespaceURI(), getLocalName(attr), qnameAttr, XMLUtil.CDATA, attr .getNodeValue()); } } // Now process the element itself final String qname = node.getNodeName(); final String uri = node.getNamespaceURI(); final String localName = getLocalName(node); // Uri may be implicitly declared if (uri != null) { final int colon = qname.lastIndexOf(':'); prefix = (colon > 0) ? qname.substring(0, colon) : EMPTYSTRING; if (startPrefixMapping(prefix, uri)) { pushedPrefixes.add(prefix); } } // Generate SAX event to start element contentHandler.startElement(uri, localName, qname, attrs); // Traverse all child nodes of the element (if any) next = node.getFirstChild(); while (next != null) { writeNode(next); next = next.getNextSibling(); } // Generate SAX event to close element contentHandler.endElement(uri, localName, qname); // Generate endPrefixMapping() for all pushed prefixes final int nPushedPrefixes = pushedPrefixes.size(); for (int i = 0; i < nPushedPrefixes; i++) { endPrefixMapping((String)pushedPrefixes.get(i)); } break; case Node.PROCESSING_INSTRUCTION_NODE: contentHandler.processingInstruction(node.getNodeName(), node.getNodeValue()); break; case Node.TEXT_NODE: final String data = node.getNodeValue(); contentHandler.characters(data.toCharArray(), 0, data.length()); break; default: //nop } }
// in src/java/org/apache/fop/util/XMLUtil.java
public static int getAttributeAsInt(Attributes attributes, String name) throws SAXException { String s = attributes.getValue(name); if (s == null) { throw new SAXException("Attribute '" + name + "' is missing"); } else { return Integer.parseInt(s); } }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { super.startElement(uri, localName, qName, atts); QName elementName = new QName(uri, qName); if (isOwnNamespace(uri)) { if (CATALOGUE.equals(localName)) { //nop } else if (MESSAGE.equals(localName)) { if (!CATALOGUE.equals(getParentElementName().getLocalName())) { throw new SAXException(MESSAGE + " must be a child of " + CATALOGUE); } this.currentKey = atts.getValue("key"); } else { throw new SAXException("Invalid element name: " + elementName); } } else { //ignore } this.valueBuffer.setLength(0); elementStack.push(elementName); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public void endElement(String uri, String localName, String qName) throws SAXException { super.endElement(uri, localName, qName); elementStack.pop(); if (isOwnNamespace(uri)) { if (CATALOGUE.equals(localName)) { //nop } else if (MESSAGE.equals(localName)) { if (this.currentKey == null) { throw new SAXException( "current key is null (attribute 'key' might be mistyped)"); } resources.put(this.currentKey, this.valueBuffer.toString()); this.currentKey = null; } } else { //ignore } this.valueBuffer.setLength(0); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
public void characters(char[] ch, int start, int length) throws SAXException { super.characters(ch, start, length); valueBuffer.append(ch, start, length); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void startElement(String localName, Attributes atts) throws SAXException { getDelegateContentHandler().startElement(getMainNamespace(), localName, localName, atts); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void startElement(String localName) throws SAXException { startElement(localName, EMPTY_ATTS); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void startElement(QName qName, Attributes atts) throws SAXException { getDelegateContentHandler().startElement(qName.getNamespaceURI(), qName.getLocalName(), qName.getQName(), atts); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void startElement(QName qName) throws SAXException { startElement(qName, EMPTY_ATTS); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void endElement(String localName) throws SAXException { getDelegateContentHandler().endElement(getMainNamespace(), localName, localName); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void endElement(QName qName) throws SAXException { getDelegateContentHandler().endElement(qName.getNamespaceURI(), qName.getLocalName(), qName.getQName()); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void element(String localName, Attributes atts) throws SAXException { getDelegateContentHandler().startElement(getMainNamespace(), localName, localName, atts); getDelegateContentHandler().endElement(getMainNamespace(), localName, localName); }
// in src/java/org/apache/fop/util/GenerationHelperContentHandler.java
public void element(QName qName, Attributes atts) throws SAXException { getDelegateContentHandler().startElement(qName.getNamespaceURI(), qName.getLocalName(), qName.getQName(), atts); getDelegateContentHandler().endElement(qName.getNamespaceURI(), qName.getLocalName(), qName.getQName()); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
public ContentHandler createContentHandler() throws SAXException { return new Handler(); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
public void startDocument() throws SAXException { //Suppress startDocument() call if doc has not been set, yet. It will be done later. if (doc != null) { super.startDocument(); } }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { if (doc == null) { TransformerHandler handler; try { handler = tFactory.newTransformerHandler(); } catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); } doc = domImplementation.createDocument(namespaceURI, qName, null); //It's easier to work with an empty document, so remove the root element doc.removeChild(doc.getDocumentElement()); handler.setResult(new DOMResult(doc)); setDelegateContentHandler(handler); setDelegateLexicalHandler(handler); setDelegateDTDHandler(handler); handler.startDocument(); } super.startElement(uri, localName, qName, atts); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
public void endDocument() throws SAXException { super.endDocument(); if (obListener != null) { obListener.notifyObjectBuilt(getObject()); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException { if (entityResolver != null) { return entityResolver.resolveEntity(publicId, systemId); } else { return null; } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void notationDecl(String name, String publicId, String systemId) throws SAXException { if (dtdHandler != null) { dtdHandler.notationDecl(name, publicId, systemId); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { if (dtdHandler != null) { dtdHandler.unparsedEntityDecl(name, publicId, systemId, notationName); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void startDocument() throws SAXException { delegate.startDocument(); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void endDocument() throws SAXException { delegate.endDocument(); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void startPrefixMapping(String prefix, String uri) throws SAXException { delegate.startPrefixMapping(prefix, uri); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void endPrefixMapping(String prefix) throws SAXException { delegate.endPrefixMapping(prefix); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException { delegate.startElement(uri, localName, qName, atts); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void endElement(String uri, String localName, String qName) throws SAXException { delegate.endElement(uri, localName, qName); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void characters(char[] ch, int start, int length) throws SAXException { delegate.characters(ch, start, length); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { delegate.ignorableWhitespace(ch, start, length); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void processingInstruction(String target, String data) throws SAXException { delegate.processingInstruction(target, data); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void skippedEntity(String name) throws SAXException { delegate.skippedEntity(name); }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void startDTD(String name, String publicId, String systemId) throws SAXException { if (lexicalHandler != null) { lexicalHandler.startDTD(name, publicId, systemId); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void endDTD() throws SAXException { if (lexicalHandler != null) { lexicalHandler.endDTD(); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void startEntity(String name) throws SAXException { if (lexicalHandler != null) { lexicalHandler.startEntity(name); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void endEntity(String name) throws SAXException { if (lexicalHandler != null) { lexicalHandler.endEntity(name); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void startCDATA() throws SAXException { if (lexicalHandler != null) { lexicalHandler.startCDATA(); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void endCDATA() throws SAXException { if (lexicalHandler != null) { lexicalHandler.endCDATA(); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void comment(char[] ch, int start, int length) throws SAXException { if (lexicalHandler != null) { lexicalHandler.comment(ch, start, length); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void warning(SAXParseException exception) throws SAXException { if (errorHandler != null) { errorHandler.warning(exception); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void error(SAXParseException exception) throws SAXException { if (errorHandler != null) { errorHandler.error(exception); } }
// in src/java/org/apache/fop/util/DelegatingContentHandler.java
public void fatalError(SAXParseException exception) throws SAXException { if (errorHandler != null) { errorHandler.fatalError(exception); } }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void startDocument() throws SAXException { transformerHandler.startDocument(); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void endDocument() throws SAXException { transformerHandler.endDocument(); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void startPrefixMapping(String prefix, String uri) throws SAXException { transformerHandler.startPrefixMapping(prefix, uri); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void endPrefixMapping(String string) throws SAXException { transformerHandler.endPrefixMapping(string); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void startElement(String uri, String localName, String qName, Attributes attrs) throws SAXException { AttributesImpl ai = new AttributesImpl(attrs); transformerHandler.startElement(uri, localName, qName, ai); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void endElement(String uri, String localName, String qName) throws SAXException { transformerHandler.endElement(uri, localName, qName); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void characters(char[] ch, int start, int length) throws SAXException { transformerHandler.characters(ch, start, length); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException { transformerHandler.ignorableWhitespace(ch, start, length); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void processingInstruction(String target, String data) throws SAXException { transformerHandler.processingInstruction(target, data); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void skippedEntity(String name) throws SAXException { transformerHandler.skippedEntity(name); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void notationDecl(String name, String publicId, String systemId) throws SAXException { transformerHandler.notationDecl(name, publicId, systemId); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void unparsedEntityDecl(String name, String publicId, String systemId, String notationName) throws SAXException { transformerHandler.unparsedEntityDecl(name, publicId, systemId, notationName); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void startDTD(String name, String pid, String lid) throws SAXException { transformerHandler.startDTD(name, pid, lid); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void endDTD() throws SAXException { transformerHandler.endDTD(); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void startEntity(String name) throws SAXException { transformerHandler.startEntity(name); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void endEntity(String name) throws SAXException { transformerHandler.endEntity(name); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void startCDATA() throws SAXException { transformerHandler.startCDATA(); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void endCDATA() throws SAXException { transformerHandler.endCDATA(); }
// in src/java/org/apache/fop/util/TransformerDefaultHandler.java
public void comment(char[] charArray, int start, int length) throws SAXException { transformerHandler.comment(charArray, start, length); }
// in src/java/org/apache/fop/cli/InputHandler.java
private XMLReader getXMLReader() throws ParserConfigurationException, SAXException { SAXParserFactory spf = SAXParserFactory.newInstance(); spf.setFeature("http://xml.org/sax/features/namespaces", true); spf.setFeature("http://apache.org/xml/features/xinclude", true); XMLReader xr = spf.newSAXParser().getXMLReader(); return xr; }
85
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException se) { throw new IFException("SAX error in startDocument()", se); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDataUrlImageHandler.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (SAXException saxe) { throw new IOException("Error while serializing XMP stream: " + saxe.getMessage()); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (SAXException saxex) { throw new BuildException(saxex); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (SAXException e) { throw new HyphenationException(errMsg); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException("You need a SAX parser which supports SAX version 2", e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (SAXException saxe) { handleSAXException(saxe); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (SAXException e) { log.error("Error while serializing Extension Attachment", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new RuntimeException("Unable to create the " + EL_LOCALE + " element.", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in clipRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawBorderRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing named destination", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing bookmark tree", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing link", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing object", e); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/cli/AreaTreeInputHandler.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (SAXException e) { if (this.sourcefile != null) { source = new StreamSource(this.sourcefile); } else { source = new StreamSource(in, uri); } }
// in src/java/org/apache/fop/cli/InputHandler.java
catch (SAXException e) { // return StreamSource }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (SAXException e) { throw new FOPException(e); }
74
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endBox()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawImage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/AbstractSVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException se) { throw new IFException("SAX error in startDocument()", se); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentHeader()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGPrintDocumentHandler.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDataUrlImageHandler.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (SAXException saxe) { throw new IOException("Error while serializing XMP stream: " + saxe.getMessage()); }
// in src/java/org/apache/fop/tools/anttasks/Fop.java
catch (SAXException saxex) { throw new BuildException(saxex); }
// in src/java/org/apache/fop/hyphenation/PatternParser.java
catch (SAXException e) { throw new HyphenationException(errMsg); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException("You need a SAX parser which supports SAX version 2", e); }
// in src/java/org/apache/fop/fonts/FontReader.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new RuntimeException("Unable to create the " + EL_LOCALE + " element.", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocumentTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endDocument()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageSequence()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageHeader()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageContent()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPageTrailer()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endPage()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endViewport()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in endGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in startGroup()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in clipRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in fillRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawBorderRect()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in drawLine()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error in setFont()", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing named destination", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing bookmark tree", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing link", e); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
catch (SAXException e) { throw new IFException("SAX error serializing object", e); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (SAXException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/accessibility/StructureTree2SAXEventAdapter.java
catch (SAXException e) { throw new RuntimeException(e); }
// in src/java/org/apache/fop/cli/AreaTreeInputHandler.java
catch (SAXException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/cli/CommandLineOptions.java
catch (SAXException e) { throw new FOPException(e); }
5
unknown (Lib) SecurityException 0 0 0 5
            
// in src/java/org/apache/fop/fo/properties/PropertyCache.java
catch ( SecurityException e ) { useCache = true; LOG.info("Unable to access org.apache.fop.fo.properties.use-cache" + " due to security restriction; defaulting to 'true'."); }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (IOException ioe) { // We don't really care about the exception since it's just a // cache file log.warn("I/O exception while reading font cache (" + ioe.getMessage() + "). Discarding font cache file."); try { cacheFile.delete(); } catch (SecurityException ex) { log.warn("Failed to delete font cache file: " + cacheFile.getAbsolutePath()); } }
// in src/java/org/apache/fop/fonts/FontCache.java
catch (SecurityException ex) { log.warn("Failed to delete font cache file: " + cacheFile.getAbsolutePath()); }
// in src/java/org/apache/fop/fonts/autodetect/WindowsFontDirFinder.java
catch (SecurityException e) { // should continue if this fails }
// in src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java
catch (SecurityException ex) { String msg = "unable to gain write access to external resource file: " + resourceGroupFile; LOG.error(msg); }
// in src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java
catch (SecurityException ex) { String msg = "unable to gain read access to external resource file: " + resourceGroupFile; LOG.error(msg); }
0 0
unknown (Lib) ServletException 1
            
// in src/java/org/apache/fop/servlet/FopServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { //Get parameters String foParam = request.getParameter(FO_REQUEST_PARAM); String xmlParam = request.getParameter(XML_REQUEST_PARAM); String xsltParam = request.getParameter(XSLT_REQUEST_PARAM); //Analyze parameters and decide with method to use if (foParam != null) { renderFO(foParam, response); } else if ((xmlParam != null) && (xsltParam != null)) { renderXML(xmlParam, xsltParam, response); } else { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>Error</title></head>\n" + "<body><h1>FopServlet Error</h1><h3>No 'fo' " + "request param given.</body></html>"); } } catch (Exception ex) { throw new ServletException(ex); } }
1
            
// in src/java/org/apache/fop/servlet/FopServlet.java
catch (Exception ex) { throw new ServletException(ex); }
2
            
// in src/java/org/apache/fop/servlet/FopServlet.java
public void init() throws ServletException { this.uriResolver = new ServletContextURIResolver(getServletContext()); this.transFactory = TransformerFactory.newInstance(); this.transFactory.setURIResolver(this.uriResolver); //Configure FopFactory as desired this.fopFactory = FopFactory.newInstance(); this.fopFactory.setURIResolver(this.uriResolver); configureFopFactory(); }
// in src/java/org/apache/fop/servlet/FopServlet.java
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException { try { //Get parameters String foParam = request.getParameter(FO_REQUEST_PARAM); String xmlParam = request.getParameter(XML_REQUEST_PARAM); String xsltParam = request.getParameter(XSLT_REQUEST_PARAM); //Analyze parameters and decide with method to use if (foParam != null) { renderFO(foParam, response); } else if ((xmlParam != null) && (xsltParam != null)) { renderXML(xmlParam, xsltParam, response); } else { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>Error</title></head>\n" + "<body><h1>FopServlet Error</h1><h3>No 'fo' " + "request param given.</body></html>"); } } catch (Exception ex) { throw new ServletException(ex); } }
0 0 0
checked (Lib) Throwable 0 0 2
            
// in src/java/org/apache/fop/events/EventExceptionManager.java
public static void throwException(Event event, String exceptionClass) throws Throwable { if (exceptionClass != null) { ExceptionFactory factory = (ExceptionFactory)EXCEPTION_FACTORIES.get(exceptionClass); if (factory != null) { throw factory.createException(event); } else { throw new IllegalArgumentException( "No such ExceptionFactory available: " + exceptionClass); } } else { String msg = EventFormatter.format(event); //Get original exception as cause if it is given as one of the parameters Throwable t = null; Iterator<Object> iter = event.getParams().values().iterator(); while (iter.hasNext()) { Object o = iter.next(); if (o instanceof Throwable) { t = (Throwable)o; break; } } if (t != null) { throw new RuntimeException(msg, t); } else { throw new RuntimeException(msg); } } }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
protected EventProducer createProxyFor(Class clazz) { final EventProducerModel producerModel = getEventProducerModel(clazz); if (producerModel == null) { throw new IllegalStateException("Event model doesn't contain the definition for " + clazz.getName()); } return (EventProducer)Proxy.newProxyInstance(clazz.getClassLoader(), new Class[] {clazz}, new InvocationHandler() { public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); EventMethodModel methodModel = producerModel.getMethod(methodName); String eventID = producerModel.getInterfaceName() + "." + methodName; if (methodModel == null) { throw new IllegalStateException( "Event model isn't consistent" + " with the EventProducer interface. Please rebuild FOP!" + " Affected method: " + eventID); } Map params = new java.util.HashMap(); int i = 1; Iterator iter = methodModel.getParameters().iterator(); while (iter.hasNext()) { EventMethodModel.Parameter param = (EventMethodModel.Parameter)iter.next(); params.put(param.getName(), args[i]); i++; } Event ev = new Event(args[0], eventID, methodModel.getSeverity(), params); broadcastEvent(ev); if (ev.getSeverity() == EventSeverity.FATAL) { EventExceptionManager.throwException(ev, methodModel.getExceptionClass()); } return null; } }); }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { String methodName = method.getName(); EventMethodModel methodModel = producerModel.getMethod(methodName); String eventID = producerModel.getInterfaceName() + "." + methodName; if (methodModel == null) { throw new IllegalStateException( "Event model isn't consistent" + " with the EventProducer interface. Please rebuild FOP!" + " Affected method: " + eventID); } Map params = new java.util.HashMap(); int i = 1; Iterator iter = methodModel.getParameters().iterator(); while (iter.hasNext()) { EventMethodModel.Parameter param = (EventMethodModel.Parameter)iter.next(); params.put(param.getName(), args[i]); i++; } Event ev = new Event(args[0], eventID, methodModel.getSeverity(), params); broadcastEvent(ev); if (ev.getSeverity() == EventSeverity.FATAL) { EventExceptionManager.throwException(ev, methodModel.getExceptionClass()); } return null; }
4
            
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
catch (Throwable t) { printHelp(); t.printStackTrace(); System.exit(-1); }
// in src/java/org/apache/fop/fo/extensions/svg/BatikExtensionElementMapping.java
catch (Throwable t) { // if the classes are not available // the DISPLAY is not checked batikAvail = false; }
// in src/java/org/apache/fop/fo/extensions/svg/SVGElementMapping.java
catch (Throwable t) { log.error("Error while initializing the Batik SVG extensions", t); // if the classes are not available // the DISPLAY is not checked batikAvailable = false; }
// in src/java/org/apache/fop/svg/AbstractFOPBridgeContext.java
catch (Throwable t) { //simply ignore (bridges instantiated over this method are optional) }
0 0
unknown (Lib) TranscoderException 4
            
// in src/java/org/apache/fop/svg/PDFTranscoder.java
protected void transcode(Document document, String uri, TranscoderOutput output) throws TranscoderException { graphics = new PDFDocumentGraphics2D(isTextStroked()); graphics.getPDFDocument().getInfo().setProducer("Apache FOP Version " + Version.getVersion() + ": PDF Transcoder for Batik"); if (hints.containsKey(KEY_DEVICE_RESOLUTION)) { graphics.setDeviceDPI(getDeviceResolution()); } setupImageInfrastructure(uri); try { Configuration effCfg = getEffectiveConfiguration(); if (effCfg != null) { PDFDocumentGraphics2DConfigurator configurator = new PDFDocumentGraphics2DConfigurator(); boolean useComplexScriptFeatures = false; //TODO - FIX ME configurator.configure(graphics, effCfg, useComplexScriptFeatures); } else { graphics.setupDefaultFontInfo(); } } catch (Exception e) { throw new TranscoderException( "Error while setting up PDFDocumentGraphics2D", e); } super.transcode(document, uri, output); if (getLogger().isTraceEnabled()) { getLogger().trace("document size: " + width + " x " + height); } // prepare the image to be painted UnitProcessor.Context uctx = UnitProcessor.createContext(ctx, document.getDocumentElement()); float widthInPt = UnitProcessor.userSpaceToSVG(width, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int w = (int)(widthInPt + 0.5); float heightInPt = UnitProcessor.userSpaceToSVG(height, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int h = (int)(heightInPt + 0.5); if (getLogger().isTraceEnabled()) { getLogger().trace("document size: " + w + "pt x " + h + "pt"); } // prepare the image to be painted //int w = (int)(width + 0.5); //int h = (int)(height + 0.5); try { OutputStream out = output.getOutputStream(); if (!(out instanceof BufferedOutputStream)) { out = new BufferedOutputStream(out); } graphics.setupDocument(out, w, h); graphics.setSVGDimension(width, height); if (hints.containsKey(ImageTranscoder.KEY_BACKGROUND_COLOR)) { graphics.setBackgroundColor ((Color)hints.get(ImageTranscoder.KEY_BACKGROUND_COLOR)); } graphics.setGraphicContext (new org.apache.xmlgraphics.java2d.GraphicContext()); graphics.preparePainting(); graphics.transform(curTxf); graphics.setRenderingHint (RenderingHintsKeyExt.KEY_TRANSCODING, RenderingHintsKeyExt.VALUE_TRANSCODING_VECTOR); this.root.paint(graphics); graphics.finish(); } catch (IOException ex) { throw new TranscoderException(ex); } }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
protected void transcode(Document document, String uri, TranscoderOutput output) throws TranscoderException { graphics = createDocumentGraphics2D(); if (!isTextStroked()) { try { boolean useComplexScriptFeatures = false; //TODO - FIX ME this.fontInfo = PDFDocumentGraphics2DConfigurator.createFontInfo( getEffectiveConfiguration(), useComplexScriptFeatures); graphics.setCustomTextHandler(new NativeTextHandler(graphics, fontInfo)); } catch (FOPException fe) { throw new TranscoderException(fe); } } super.transcode(document, uri, output); getLogger().trace("document size: " + width + " x " + height); // prepare the image to be painted UnitProcessor.Context uctx = UnitProcessor.createContext(ctx, document.getDocumentElement()); float widthInPt = UnitProcessor.userSpaceToSVG(width, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int w = (int)(widthInPt + 0.5); float heightInPt = UnitProcessor.userSpaceToSVG(height, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int h = (int)(heightInPt + 0.5); getLogger().trace("document size: " + w + "pt x " + h + "pt"); try { OutputStream out = output.getOutputStream(); if (!(out instanceof BufferedOutputStream)) { out = new BufferedOutputStream(out); } graphics.setupDocument(out, w, h); graphics.setViewportDimension(width, height); if (hints.containsKey(ImageTranscoder.KEY_BACKGROUND_COLOR)) { graphics.setBackgroundColor ((Color)hints.get(ImageTranscoder.KEY_BACKGROUND_COLOR)); } graphics.setGraphicContext (new org.apache.xmlgraphics.java2d.GraphicContext()); graphics.setTransform(curTxf); this.root.paint(graphics); graphics.finish(); } catch (IOException ex) { throw new TranscoderException(ex); } }
4
            
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (Exception e) { throw new TranscoderException( "Error while setting up PDFDocumentGraphics2D", e); }
// in src/java/org/apache/fop/svg/PDFTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (FOPException fe) { throw new TranscoderException(fe); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
catch (IOException ex) { throw new TranscoderException(ex); }
5
            
// in src/java/org/apache/fop/svg/PDFTranscoder.java
protected void transcode(Document document, String uri, TranscoderOutput output) throws TranscoderException { graphics = new PDFDocumentGraphics2D(isTextStroked()); graphics.getPDFDocument().getInfo().setProducer("Apache FOP Version " + Version.getVersion() + ": PDF Transcoder for Batik"); if (hints.containsKey(KEY_DEVICE_RESOLUTION)) { graphics.setDeviceDPI(getDeviceResolution()); } setupImageInfrastructure(uri); try { Configuration effCfg = getEffectiveConfiguration(); if (effCfg != null) { PDFDocumentGraphics2DConfigurator configurator = new PDFDocumentGraphics2DConfigurator(); boolean useComplexScriptFeatures = false; //TODO - FIX ME configurator.configure(graphics, effCfg, useComplexScriptFeatures); } else { graphics.setupDefaultFontInfo(); } } catch (Exception e) { throw new TranscoderException( "Error while setting up PDFDocumentGraphics2D", e); } super.transcode(document, uri, output); if (getLogger().isTraceEnabled()) { getLogger().trace("document size: " + width + " x " + height); } // prepare the image to be painted UnitProcessor.Context uctx = UnitProcessor.createContext(ctx, document.getDocumentElement()); float widthInPt = UnitProcessor.userSpaceToSVG(width, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int w = (int)(widthInPt + 0.5); float heightInPt = UnitProcessor.userSpaceToSVG(height, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int h = (int)(heightInPt + 0.5); if (getLogger().isTraceEnabled()) { getLogger().trace("document size: " + w + "pt x " + h + "pt"); } // prepare the image to be painted //int w = (int)(width + 0.5); //int h = (int)(height + 0.5); try { OutputStream out = output.getOutputStream(); if (!(out instanceof BufferedOutputStream)) { out = new BufferedOutputStream(out); } graphics.setupDocument(out, w, h); graphics.setSVGDimension(width, height); if (hints.containsKey(ImageTranscoder.KEY_BACKGROUND_COLOR)) { graphics.setBackgroundColor ((Color)hints.get(ImageTranscoder.KEY_BACKGROUND_COLOR)); } graphics.setGraphicContext (new org.apache.xmlgraphics.java2d.GraphicContext()); graphics.preparePainting(); graphics.transform(curTxf); graphics.setRenderingHint (RenderingHintsKeyExt.KEY_TRANSCODING, RenderingHintsKeyExt.VALUE_TRANSCODING_VECTOR); this.root.paint(graphics); graphics.finish(); } catch (IOException ex) { throw new TranscoderException(ex); } }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
public void error(TranscoderException te) throws TranscoderException { getLogger().error(te.getMessage()); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
public void fatalError(TranscoderException te) throws TranscoderException { throw te; }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
public void warning(TranscoderException te) throws TranscoderException { getLogger().warn(te.getMessage()); }
// in src/java/org/apache/fop/render/ps/AbstractPSTranscoder.java
protected void transcode(Document document, String uri, TranscoderOutput output) throws TranscoderException { graphics = createDocumentGraphics2D(); if (!isTextStroked()) { try { boolean useComplexScriptFeatures = false; //TODO - FIX ME this.fontInfo = PDFDocumentGraphics2DConfigurator.createFontInfo( getEffectiveConfiguration(), useComplexScriptFeatures); graphics.setCustomTextHandler(new NativeTextHandler(graphics, fontInfo)); } catch (FOPException fe) { throw new TranscoderException(fe); } } super.transcode(document, uri, output); getLogger().trace("document size: " + width + " x " + height); // prepare the image to be painted UnitProcessor.Context uctx = UnitProcessor.createContext(ctx, document.getDocumentElement()); float widthInPt = UnitProcessor.userSpaceToSVG(width, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int w = (int)(widthInPt + 0.5); float heightInPt = UnitProcessor.userSpaceToSVG(height, SVGLength.SVG_LENGTHTYPE_PT, UnitProcessor.HORIZONTAL_LENGTH, uctx); int h = (int)(heightInPt + 0.5); getLogger().trace("document size: " + w + "pt x " + h + "pt"); try { OutputStream out = output.getOutputStream(); if (!(out instanceof BufferedOutputStream)) { out = new BufferedOutputStream(out); } graphics.setupDocument(out, w, h); graphics.setViewportDimension(width, height); if (hints.containsKey(ImageTranscoder.KEY_BACKGROUND_COLOR)) { graphics.setBackgroundColor ((Color)hints.get(ImageTranscoder.KEY_BACKGROUND_COLOR)); } graphics.setGraphicContext (new org.apache.xmlgraphics.java2d.GraphicContext()); graphics.setTransform(curTxf); this.root.paint(graphics); graphics.finish(); } catch (IOException ex) { throw new TranscoderException(ex); } }
2
            
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
2
            
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
// in src/java/org/apache/fop/svg/AbstractFOPTranscoder.java
catch (TranscoderException ex) { throw new RuntimeException(); }
2
unknown (Lib) TransformerConfigurationException 0 0 3
            
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void generateXML(SortedMap fontFamilies, File outFile, String singleFamily) throws TransformerConfigurationException, SAXException, IOException { SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); TransformerHandler handler; if (this.mode == GENERATE_XML) { handler = tFactory.newTransformerHandler(); } else { URL url = getClass().getResource("fonts2fo.xsl"); if (url == null) { throw new FileNotFoundException("Did not find resource: fonts2fo.xsl"); } handler = tFactory.newTransformerHandler(new StreamSource(url.toExternalForm())); } if (singleFamily != null) { Transformer transformer = handler.getTransformer(); transformer.setParameter("single-family", singleFamily); } OutputStream out = new java.io.FileOutputStream(outFile); out = new java.io.BufferedOutputStream(out); if (this.mode == GENERATE_RENDERED) { handler.setResult(new SAXResult(getFOPContentHandler(out))); } else { handler.setResult(new StreamResult(out)); } try { GenerationHelperContentHandler helper = new GenerationHelperContentHandler( handler, null); FontListSerializer serializer = new FontListSerializer(); serializer.generateSAX(fontFamilies, singleFamily, helper); } finally { IOUtils.closeQuietly(out); } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void writeToConsole(SortedMap fontFamilies) throws TransformerConfigurationException, SAXException, IOException { Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String firstFamilyName = (String)entry.getKey(); System.out.println(firstFamilyName + ":"); List list = (List)entry.getValue(); Iterator fonts = list.iterator(); while (fonts.hasNext()) { FontSpec f = (FontSpec)fonts.next(); System.out.println(" " + f.getKey() + " " + f.getFamilyNames()); Iterator triplets = f.getTriplets().iterator(); while (triplets.hasNext()) { FontTriplet triplet = (FontTriplet)triplets.next(); System.out.println(" " + triplet.toString()); } } } }
// in src/java/org/apache/fop/tools/fontlist/FontListMain.java
private void writeOutput(SortedMap fontFamilies) throws TransformerConfigurationException, SAXException, IOException { if (this.outputFile.isDirectory()) { System.out.println("Creating one file for each family..."); Iterator iter = fontFamilies.entrySet().iterator(); while (iter.hasNext()) { Map.Entry entry = (Map.Entry)iter.next(); String familyName = (String)entry.getKey(); System.out.println("Creating output file for " + familyName + "..."); String filename; switch(this.mode) { case GENERATE_RENDERED: filename = familyName + ".pdf"; break; case GENERATE_FO: filename = familyName + ".fo"; break; case GENERATE_XML: filename = familyName + ".xml"; break; default: throw new IllegalStateException("Unsupported mode"); } File outFile = new File(this.outputFile, filename); generateXML(fontFamilies, outFile, familyName); } } else { System.out.println("Creating output file..."); generateXML(fontFamilies, this.outputFile, this.singleFamilyFilter); } System.out.println(this.outputFile + " written."); }
10
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException e) { throw new IFException( "Error while setting up a TransformerHandler for SVG generation", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException("Error setting up a Transformer", tce); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (TransformerConfigurationException tce) { throw new IOException("Error setting up Transformer for XMP stream serialization: " + tce.getMessage()); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException( "Error while setting up the serializer for XML output", tce); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerConfigurationException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
10
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException e) { throw new IFException( "Error while setting up a TransformerHandler for SVG generation", e); }
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException("Error setting up a Transformer", tce); }
// in src/java/org/apache/fop/pdf/PDFMetadata.java
catch (TransformerConfigurationException tce) { throw new IOException("Error setting up Transformer for XMP stream serialization: " + tce.getMessage()); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGDOMContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/render/xml/AbstractXMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/xml/XMLRenderer.java
catch (TransformerConfigurationException tce) { throw new RuntimeException(tce.getMessage()); }
// in src/java/org/apache/fop/render/intermediate/AbstractXMLWritingIFDocumentHandler.java
catch (TransformerConfigurationException tce) { throw new IFException( "Error while setting up the serializer for XML output", tce); }
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerConfigurationException e) { throw new IOException(e.getMessage()); }
// in src/java/org/apache/fop/area/AreaTreeParser.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
// in src/java/org/apache/fop/util/DOMBuilderContentHandlerFactory.java
catch (TransformerConfigurationException e) { throw new SAXException("Error creating a new TransformerHandler", e); }
2
unknown (Lib) TransformerException 4
            
// in src/java/org/apache/fop/apps/FOURIResolver.java
private void handleException(Exception e, String errorStr, boolean strict) throws TransformerException { if (strict) { throw new TransformerException(errorStr, e); } log.error(e.getMessage()); }
// in src/java/org/apache/fop/servlet/ServletContextURIResolver.java
protected Source resolveServletContextURI(String path) throws TransformerException { while (path.startsWith("//")) { path = path.substring(1); } try { URL url = this.servletContext.getResource(path); InputStream in = this.servletContext.getResourceAsStream(path); if (in != null) { if (url != null) { return new StreamSource(in, url.toExternalForm()); } else { return new StreamSource(in); } } else { throw new TransformerException("Resource does not exist. \"" + path + "\" is not accessible through the servlet context."); } } catch (MalformedURLException mfue) { throw new TransformerException( "Error accessing resource using servlet context: " + path, mfue); } }
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
public void writeFontXML(org.w3c.dom.Document doc, File target) throws TransformerException { log.info("Writing xml font file " + target + "..."); try { OutputStream out = new java.io.FileOutputStream(target); out = new java.io.BufferedOutputStream(out); try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.transform( new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(out)); } finally { out.close(); } } catch (IOException ioe) { throw new TransformerException("Error writing the output file", ioe); } }
2
            
// in src/java/org/apache/fop/servlet/ServletContextURIResolver.java
catch (MalformedURLException mfue) { throw new TransformerException( "Error accessing resource using servlet context: " + path, mfue); }
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
catch (IOException ioe) { throw new TransformerException("Error writing the output file", ioe); }
19
            
// in src/java/org/apache/fop/apps/FOURIResolver.java
private void handleException(Exception e, String errorStr, boolean strict) throws TransformerException { if (strict) { throw new TransformerException(errorStr, e); } log.error(e.getMessage()); }
// in src/java/org/apache/fop/apps/FOURIResolver.java
public Source resolve(String href, String base) throws TransformerException { Source source = null; // data URLs can be quite long so evaluate early and don't try to build a File // (can lead to problems) source = commonURIResolver.resolve(href, base); // Custom uri resolution if (source == null && uriResolver != null) { source = uriResolver.resolve(href, base); } // Fallback to default resolution mechanism if (source == null) { URL absoluteURL = null; int hashPos = href.indexOf('#'); String fileURL; String fragment; if (hashPos >= 0) { fileURL = href.substring(0, hashPos); fragment = href.substring(hashPos); } else { fileURL = href; fragment = null; } File file = new File(fileURL); if (file.canRead() && file.isFile()) { try { if (fragment != null) { absoluteURL = new URL(file.toURI().toURL().toExternalForm() + fragment); } else { absoluteURL = file.toURI().toURL(); } } catch (MalformedURLException mfue) { handleException(mfue, "Could not convert filename '" + href + "' to URL", throwExceptions); } } else { // no base provided if (base == null) { // We don't have a valid file protocol based URL try { absoluteURL = new URL(href); } catch (MalformedURLException mue) { try { // the above failed, we give it another go in case // the href contains only a path then file: is // assumed absoluteURL = new URL("file:" + href); } catch (MalformedURLException mfue) { handleException(mfue, "Error with URL '" + href + "'", throwExceptions); } } // try and resolve from context of base } else { URL baseURL = null; try { baseURL = new URL(base); } catch (MalformedURLException mfue) { handleException(mfue, "Error with base URL '" + base + "'", throwExceptions); } /* * This piece of code is based on the following statement in * RFC2396 section 5.2: * * 3) If the scheme component is defined, indicating that * the reference starts with a scheme name, then the * reference is interpreted as an absolute URI and we are * done. Otherwise, the reference URI's scheme is inherited * from the base URI's scheme component. * * Due to a loophole in prior specifications [RFC1630], some * parsers allow the scheme name to be present in a relative * URI if it is the same as the base URI scheme. * Unfortunately, this can conflict with the correct parsing * of non-hierarchical URI. For backwards compatibility, an * implementation may work around such references by * removing the scheme if it matches that of the base URI * and the scheme is known to always use the <hier_part> * syntax. * * The URL class does not implement this work around, so we * do. */ assert (baseURL != null); String scheme = baseURL.getProtocol() + ":"; if (href.startsWith(scheme) && "file:".equals(scheme)) { href = href.substring(scheme.length()); int colonPos = href.indexOf(':'); int slashPos = href.indexOf('/'); if (slashPos >= 0 && colonPos >= 0 && colonPos < slashPos) { href = "/" + href; // Absolute file URL doesn't // have a leading slash } } try { absoluteURL = new URL(baseURL, href); } catch (MalformedURLException mfue) { handleException(mfue, "Error with URL; base '" + base + "' " + "href '" + href + "'", throwExceptions); } } } if (absoluteURL != null) { String effURL = absoluteURL.toExternalForm(); try { URLConnection connection = absoluteURL.openConnection(); connection.setAllowUserInteraction(false); connection.setDoInput(true); updateURLConnection(connection, href); connection.connect(); return new StreamSource(connection.getInputStream(), effURL); } catch (FileNotFoundException fnfe) { // Note: This is on "debug" level since the caller is // supposed to handle this log.debug("File not found: " + effURL); } catch (java.io.IOException ioe) { log.error("Error with opening URL '" + effURL + "': " + ioe.getMessage()); } } } return source; }
// in src/java/org/apache/fop/servlet/FopPrintServlet.java
protected void render(Source src, Transformer transformer, HttpServletResponse response) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_FOP_PRINT, foUserAgent); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer.transform(src, res); //Return the result reportOK(response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void renderFO(String fo, HttpServletResponse response) throws FOPException, TransformerException, IOException { //Setup source Source foSrc = convertString2Source(fo); //Setup the identity transformation Transformer transformer = this.transFactory.newTransformer(); transformer.setURIResolver(this.uriResolver); //Start transformation and rendering process render(foSrc, transformer, response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void renderXML(String xml, String xslt, HttpServletResponse response) throws FOPException, TransformerException, IOException { //Setup sources Source xmlSrc = convertString2Source(xml); Source xsltSrc = convertString2Source(xslt); //Setup the XSL transformation Transformer transformer = this.transFactory.newTransformer(xsltSrc); transformer.setURIResolver(this.uriResolver); //Start transformation and rendering process render(xmlSrc, transformer, response); }
// in src/java/org/apache/fop/servlet/FopServlet.java
protected void render(Source src, Transformer transformer, HttpServletResponse response) throws FOPException, TransformerException, IOException { FOUserAgent foUserAgent = getFOUserAgent(); //Setup output ByteArrayOutputStream out = new ByteArrayOutputStream(); //Setup FOP Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF, foUserAgent, out); //Make sure the XSL transformation's result is piped through to FOP Result res = new SAXResult(fop.getDefaultHandler()); //Start the transformation and rendering process transformer.transform(src, res); //Return the result sendPDF(out.toByteArray(), response); }
// in src/java/org/apache/fop/servlet/ServletContextURIResolver.java
public Source resolve(String href, String base) throws TransformerException { if (href.startsWith(SERVLET_CONTEXT_PROTOCOL)) { return resolveServletContextURI(href.substring(SERVLET_CONTEXT_PROTOCOL.length())); } else { if (base != null && base.startsWith(SERVLET_CONTEXT_PROTOCOL) && (href.indexOf(':') < 0)) { String abs = base + href; return resolveServletContextURI( abs.substring(SERVLET_CONTEXT_PROTOCOL.length())); } else { return null; } } }
// in src/java/org/apache/fop/servlet/ServletContextURIResolver.java
protected Source resolveServletContextURI(String path) throws TransformerException { while (path.startsWith("//")) { path = path.substring(1); } try { URL url = this.servletContext.getResource(path); InputStream in = this.servletContext.getResourceAsStream(path); if (in != null) { if (url != null) { return new StreamSource(in, url.toExternalForm()); } else { return new StreamSource(in); } } else { throw new TransformerException("Resource does not exist. \"" + path + "\" is not accessible through the servlet context."); } } catch (MalformedURLException mfue) { throw new TransformerException( "Error accessing resource using servlet context: " + path, mfue); } }
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
public void writeFontXML(org.w3c.dom.Document doc, String target) throws TransformerException { writeFontXML(doc, new File(target)); }
// in src/java/org/apache/fop/fonts/apps/AbstractFontReader.java
public void writeFontXML(org.w3c.dom.Document doc, File target) throws TransformerException { log.info("Writing xml font file " + target + "..."); try { OutputStream out = new java.io.FileOutputStream(target); out = new java.io.BufferedOutputStream(out); try { TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.transform( new javax.xml.transform.dom.DOMSource(doc), new javax.xml.transform.stream.StreamResult(out)); } finally { out.close(); } } catch (IOException ioe) { throw new TransformerException("Error writing the output file", ioe); } }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
public void parse(Source src, IFDocumentHandler documentHandler, FOUserAgent userAgent) throws TransformerException, IFException { try { Transformer transformer = tFactory.newTransformer(); transformer.setErrorListener(new DefaultErrorListener(log)); SAXResult res = new SAXResult(getContentHandler(documentHandler, userAgent)); transformer.transform(src, res); } catch (TransformerException te) { //Unpack original IFException if applicable if (te.getCause() instanceof SAXException) { SAXException se = (SAXException)te.getCause(); if (se.getCause() instanceof IFException) { throw (IFException)se.getCause(); } } else if (te.getCause() instanceof IFException) { throw (IFException)te.getCause(); } throw te; } }
// in src/java/org/apache/fop/render/intermediate/util/IFConcatenator.java
public void appendDocument(Source src) throws TransformerException, IFException { IFParser parser = new IFParser(); parser.parse(src, new IFPageSequenceFilter(getTargetHandler()), getTargetHandler().getContext().getUserAgent()); }
// in src/java/org/apache/fop/events/model/EventModelParser.java
public static EventModel parse(Source src) throws TransformerException { Transformer transformer = tFactory.newTransformer(); transformer.setErrorListener(new DefaultErrorListener(LOG)); EventModel model = new EventModel(); SAXResult res = new SAXResult(getContentHandler(model)); transformer.transform(src, res); return model; }
// in src/java/org/apache/fop/area/AreaTreeParser.java
public void parse(Source src, AreaTreeModel treeModel, FOUserAgent userAgent) throws TransformerException { Transformer transformer = tFactory.newTransformer(); transformer.setErrorListener(new DefaultErrorListener(log)); SAXResult res = new SAXResult(getContentHandler(treeModel, userAgent)); transformer.transform(src, res); }
// in src/java/org/apache/fop/util/DataURIResolver.java
public Source resolve(String href, String base) throws TransformerException { return newResolver.resolve(href, base); }
// in src/java/org/apache/fop/util/DefaultErrorListener.java
public void error(TransformerException exc) throws TransformerException { throw exc; }
// in src/java/org/apache/fop/util/DefaultErrorListener.java
public void fatalError(TransformerException exc) throws TransformerException { throw exc; }
// in src/java/org/apache/fop/cli/InputHandler.java
public void fatalError(TransformerException exc) throws TransformerException { throw exc; }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
protected void updateTranslationFile(File modelFile) throws IOException { try { boolean resultExists = getTranslationFile().exists(); SAXTransformerFactory tFactory = (SAXTransformerFactory)SAXTransformerFactory.newInstance(); //Generate fresh generated translation file as template Source src = new StreamSource(modelFile.toURI().toURL().toExternalForm()); StreamSource xslt1 = new StreamSource( getClass().getResourceAsStream(MODEL2TRANSLATION)); if (xslt1.getInputStream() == null) { throw new FileNotFoundException(MODEL2TRANSLATION + " not found"); } DOMResult domres = new DOMResult(); Transformer transformer = tFactory.newTransformer(xslt1); transformer.transform(src, domres); final Node generated = domres.getNode(); Node sourceDocument; if (resultExists) { //Load existing translation file into memory (because we overwrite it later) src = new StreamSource(getTranslationFile().toURI().toURL().toExternalForm()); domres = new DOMResult(); transformer = tFactory.newTransformer(); transformer.transform(src, domres); sourceDocument = domres.getNode(); } else { //Simply use generated as source document sourceDocument = generated; } //Generate translation file (with potentially new translations) src = new DOMSource(sourceDocument); //The following triggers a bug in older Xalan versions //Result res = new StreamResult(getTranslationFile()); OutputStream out = new java.io.FileOutputStream(getTranslationFile()); out = new java.io.BufferedOutputStream(out); Result res = new StreamResult(out); try { StreamSource xslt2 = new StreamSource( getClass().getResourceAsStream(MERGETRANSLATION)); if (xslt2.getInputStream() == null) { throw new FileNotFoundException(MERGETRANSLATION + " not found"); } transformer = tFactory.newTransformer(xslt2); transformer.setURIResolver(new URIResolver() { public Source resolve(String href, String base) throws TransformerException { if ("my:dom".equals(href)) { return new DOMSource(generated); } return null; } }); if (resultExists) { transformer.setParameter("generated-url", "my:dom"); } transformer.transform(src, res); if (resultExists) { log("Translation file updated: " + getTranslationFile()); } else { log("Translation file generated: " + getTranslationFile()); } } finally { IOUtils.closeQuietly(out); } } catch (TransformerException te) { throw new IOException(te.getMessage()); } }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
public Source resolve(String href, String base) throws TransformerException { if ("my:dom".equals(href)) { return new DOMSource(generated); } return null; }
9
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException)te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
// in src/java/org/apache/fop/apps/FopFactory.java
catch (TransformerException e) { log.error("Attempt to resolve URI '" + href + "' failed: ", e); }
// in src/java/org/apache/fop/apps/FOUserAgent.java
catch (TransformerException te) { log.error("Attempt to resolve URI '" + href + "' failed: ", te); }
// in src/java/org/apache/fop/servlet/FopServlet.java
catch (TransformerException e) { src = null; }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (TransformerException te) { //Unpack original IFException if applicable if (te.getCause() instanceof SAXException) { SAXException se = (SAXException)te.getCause(); if (se.getCause() instanceof IFException) { throw (IFException)se.getCause(); } } else if (te.getCause() instanceof IFException) { throw (IFException)te.getCause(); } throw te; }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
catch (TransformerException e) { throw new MissingResourceException( "Error reading " + resourceName + ": " + e.getMessage(), DefaultEventBroadcaster.class.getName(), ""); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (TransformerException e) { throw new IOException("Error while parsing XML resource bundle: " + e.getMessage()); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
9
            
// in src/sandbox/org/apache/fop/render/svg/SVGDocumentHandler.java
catch (TransformerException te) { if (te.getCause() instanceof SAXException) { throw (SAXException)te.getCause(); } else { throw new IFException("Error while serializing reused parts", te); } }
// in src/sandbox/org/apache/fop/render/svg/EmbeddedSVGImageHandler.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
// in src/java/org/apache/fop/render/intermediate/IFParser.java
catch (TransformerException te) { //Unpack original IFException if applicable if (te.getCause() instanceof SAXException) { SAXException se = (SAXException)te.getCause(); if (se.getCause() instanceof IFException) { throw (IFException)se.getCause(); } } else if (te.getCause() instanceof IFException) { throw (IFException)te.getCause(); } throw te; }
// in src/java/org/apache/fop/events/DefaultEventBroadcaster.java
catch (TransformerException e) { throw new MissingResourceException( "Error reading " + resourceName + ": " + e.getMessage(), DefaultEventBroadcaster.class.getName(), ""); }
// in src/java/org/apache/fop/util/XMLResourceBundle.java
catch (TransformerException e) { throw new IOException("Error while parsing XML resource bundle: " + e.getMessage()); }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollectorTask.java
catch (TransformerException te) { throw new IOException(te.getMessage()); }
0
unknown (Lib) TransformerFactoryConfigurationError 0 0 0 1
            
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerFactoryConfigurationError e) { throw new IOException(e.getMessage()); }
1
            
// in src/java/org/apache/fop/events/model/EventModel.java
catch (TransformerFactoryConfigurationError e) { throw new IOException(e.getMessage()); }
0
unknown (Lib) URISyntaxException 0 0 2
            
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void fromUCD(boolean hexcode, String unidataPath, String outfilePath) throws IOException, URISyntaxException { URI unidata; if (unidataPath.endsWith("/")) { unidata = new URI(unidataPath); } else { unidata = new URI(unidataPath + "/"); } String scheme = unidata.getScheme(); if (scheme == null || !(scheme.equals("file") || scheme.equals("http"))) { throw new FileNotFoundException ("URI with file or http scheme required for UNIDATA input directory"); } File f = new File(outfilePath); if (f.exists()) { f.delete(); } f.createNewFile(); FileOutputStream fw = new FileOutputStream(f); OutputStreamWriter ow = new OutputStreamWriter(fw, "utf-8"); URI inuri = unidata.resolve("Blocks.txt"); InputStream inis = null; if (scheme.equals("file")) { File in = new File(inuri); inis = new FileInputStream(in); } else if (scheme.equals("http")) { inis = inuri.toURL().openStream(); } InputStreamReader insr = new InputStreamReader(inis, "utf-8"); BufferedReader inbr = new BufferedReader(insr); Map blocks = new HashMap(); for (String line = inbr.readLine(); line != null; line = inbr.readLine()) { if (line.startsWith("#") || line.matches("^\\s*$")) { continue; } String[] parts = line.split(";"); String block = parts[1].trim(); String[] indices = parts[0].split("\\.\\."); int[] ind = {Integer.parseInt(indices[0], 16), Integer.parseInt(indices[1], 16)}; blocks.put(block, ind); } inbr.close(); inuri = unidata.resolve("UnicodeData.txt"); if (scheme.equals("file")) { File in = new File(inuri); inis = new FileInputStream(in); } else if (scheme.equals("http")) { inis = inuri.toURL().openStream(); } insr = new InputStreamReader(inis, "utf-8"); inbr = new BufferedReader(insr); int maxChar; maxChar = Character.MAX_VALUE; ow.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n"); License.writeXMLLicenseId(ow); ow.write("\n"); writeGenerated(ow); ow.write("\n"); ow.write("<classes>\n"); for (String line = inbr.readLine(); line != null; line = inbr.readLine()) { String[] fields = line.split(";", NUM_FIELDS); int code = Integer.parseInt(fields[UNICODE], 16); if (code > maxChar) { break; } if (((fields[GENERAL_CATEGORY].equals("Ll") || fields[GENERAL_CATEGORY].equals("Lu") || fields[GENERAL_CATEGORY].equals("Lt")) && ("".equals(fields[SIMPLE_LOWERCASE_MAPPING]) || fields[UNICODE].equals(fields[SIMPLE_LOWERCASE_MAPPING]))) || fields[GENERAL_CATEGORY].equals("Lo")) { String[] blockNames = {"Superscripts and Subscripts", "Letterlike Symbols", "Alphabetic Presentation Forms", "Halfwidth and Fullwidth Forms", "CJK Unified Ideographs", "CJK Unified Ideographs Extension A", "Hangul Syllables"}; int j; for (j = 0; j < blockNames.length; ++j) { int[] ind = (int[]) blocks.get(blockNames[j]); if (code >= ind[0] && code <= ind[1]) { break; } } if (j < blockNames.length) { continue; } int uppercode = -1; int titlecode = -1; if (!"".equals(fields[SIMPLE_UPPERCASE_MAPPING])) { uppercode = Integer.parseInt(fields[SIMPLE_UPPERCASE_MAPPING], 16); } if (!"".equals(fields[SIMPLE_TITLECASE_MAPPING])) { titlecode = Integer.parseInt(fields[SIMPLE_TITLECASE_MAPPING], 16); } StringBuilder s = new StringBuilder(); if (hexcode) { s.append("0x" + fields[UNICODE].replaceFirst("^0+", "").toLowerCase() + " "); } s.append(Character.toChars(code)); if (uppercode != -1 && uppercode != code) { s.append(Character.toChars(uppercode)); } if (titlecode != -1 && titlecode != code && titlecode != uppercode) { s.append(Character.toChars(titlecode)); } ow.write(s.toString() + "\n"); } } ow.write("</classes>\n"); ow.flush(); ow.close(); inbr.close(); }
// in src/codegen/unicode/java/org/apache/fop/hyphenation/UnicodeClasses.java
public static void main(String[] args) throws IOException, URISyntaxException { String type = "ucd"; String prefix = "--"; String infile = null; String outfile = null; boolean hexcode = false; int i; for (i = 0; i < args.length && args[i].startsWith(prefix); ++i) { String option = args[i].substring(prefix.length()); if (option.equals("java") || option.equals("ucd") || option.equals("tex")) { type = option; } else if (option.equals("hexcode")) { hexcode = true; } else { System.err.println("Unknown option: " + option); System.exit(1); } } if (i < args.length) { outfile = args[i]; } else { System.err.println("Output file is required; aborting"); System.exit(1); } if (++i < args.length) { infile = args[i]; } if (type.equals("java") && infile != null) { System.err.println("Type java does not allow an infile"); System.exit(1); } else if (type.equals("ucd") && infile == null) { infile = UNICODE_DIR; } else if (type.equals("tex") && infile == null) { System.err.println("Type tex requires an input file"); System.exit(1); } if (type.equals("java")) { fromJava(hexcode, outfile); } else if (type.equals("ucd")) { fromUCD(hexcode, infile, outfile); } else if (type.equals("tex")) { fromTeX(hexcode, infile, outfile); } else { System.err.println("Unknown type: " + type + ", nothing done"); System.exit(1); } }
11
            
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (URISyntaxException e) { //TODO not ideal: our base URLs are actually base URIs. throw new MalformedURLException(e.getMessage()); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (URISyntaxException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fo/properties/URIProperty.java
catch (URISyntaxException use) { // Let PropertyList propagate the exception throw new PropertyException("Invalid URI specified"); }
// in src/java/org/apache/fop/render/pdf/extensions/PDFEmbeddedFileElement.java
catch (URISyntaxException e) { //Filename could not be deduced from URI missingPropertyError("name"); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
catch (URISyntaxException e) { eventProducer.invalidConfiguration(this, e); return null; }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (URISyntaxException urie) { throw new IFException("Could not handle resource url" + pageSegment.getURI(), urie); }
// in src/java/org/apache/fop/render/afp/extensions/AFPIncludeFormMapElement.java
catch (URISyntaxException e) { getFOValidationEventProducer().invalidPropertyValue(this, elementName, ATT_SRC, attr, null, getLocator()); }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
catch (URISyntaxException e) { throw new SAXException("Invalid URI: " + src, e); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (URISyntaxException e) { throw new FileNotFoundException("Invalid filename: " + filename + " (" + e.getMessage() + ")"); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
catch (URISyntaxException e) { throw new IOException("Could not create URI from resource name: " + resourceName + " (" + e.getMessage() + ")"); }
// in src/java/org/apache/fop/layoutmgr/ExternalDocumentLayoutManager.java
catch (URISyntaxException e) { getResourceEventProducer().uriError(this, uri, e, getExternalDocument().getLocator()); }
7
            
// in src/java/org/apache/fop/apps/FOURIResolver.java
catch (URISyntaxException e) { //TODO not ideal: our base URLs are actually base URIs. throw new MalformedURLException(e.getMessage()); }
// in src/java/org/apache/fop/apps/FopFactoryConfigurator.java
catch (URISyntaxException e) { throw new FOPException(e); }
// in src/java/org/apache/fop/fo/properties/URIProperty.java
catch (URISyntaxException use) { // Let PropertyList propagate the exception throw new PropertyException("Invalid URI specified"); }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
catch (URISyntaxException urie) { throw new IFException("Could not handle resource url" + pageSegment.getURI(), urie); }
// in src/java/org/apache/fop/render/afp/extensions/AFPExtensionHandler.java
catch (URISyntaxException e) { throw new SAXException("Invalid URI: " + src, e); }
// in src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
catch (URISyntaxException e) { throw new FileNotFoundException("Invalid filename: " + filename + " (" + e.getMessage() + ")"); }
// in src/java/org/apache/fop/afp/AFPResourceManager.java
catch (URISyntaxException e) { throw new IOException("Could not create URI from resource name: " + resourceName + " (" + e.getMessage() + ")"); }
0
unknown (Lib) UnsupportedEncodingException 0 0 6
            
// in src/java/org/apache/fop/afp/DataStream.java
public void createText(final AFPTextDataInfo textDataInfo, final int letterSpacing, final int wordSpacing, final Font font, final CharacterSet charSet) throws UnsupportedEncodingException { int rotation = paintingState.getRotation(); if (rotation != 0) { textDataInfo.setRotation(rotation); Point p = getPoint(textDataInfo.getX(), textDataInfo.getY()); textDataInfo.setX(p.x); textDataInfo.setY(p.y); } // use PtocaProducer to create PTX records PtocaProducer producer = new PtocaProducer() { public void produce(PtocaBuilder builder) throws IOException { builder.setTextOrientation(textDataInfo.getRotation()); builder.absoluteMoveBaseline(textDataInfo.getY()); builder.absoluteMoveInline(textDataInfo.getX()); builder.setExtendedTextColor(textDataInfo.getColor()); builder.setCodedFont((byte)textDataInfo.getFontReference()); int l = textDataInfo.getString().length(); StringBuffer sb = new StringBuffer(); int interCharacterAdjustment = 0; AFPUnitConverter unitConv = paintingState.getUnitConverter(); if (letterSpacing != 0) { interCharacterAdjustment = Math.round(unitConv.mpt2units(letterSpacing)); } builder.setInterCharacterAdjustment(interCharacterAdjustment); int spaceWidth = font.getCharWidth(CharUtilities.SPACE); int spacing = spaceWidth + letterSpacing; int fixedSpaceCharacterIncrement = Math.round(unitConv.mpt2units(spacing)); int varSpaceCharacterIncrement = fixedSpaceCharacterIncrement; if (wordSpacing != 0) { varSpaceCharacterIncrement = Math.round(unitConv.mpt2units( spaceWidth + wordSpacing + letterSpacing)); } builder.setVariableSpaceCharacterIncrement(varSpaceCharacterIncrement); boolean fixedSpaceMode = false; for (int i = 0; i < l; i++) { char orgChar = textDataInfo.getString().charAt(i); float glyphAdjust = 0; if (CharUtilities.isFixedWidthSpace(orgChar)) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( fixedSpaceCharacterIncrement); fixedSpaceMode = true; sb.append(CharUtilities.SPACE); int charWidth = font.getCharWidth(orgChar); glyphAdjust += (charWidth - spaceWidth); } else { if (fixedSpaceMode) { flushText(builder, sb, charSet); builder.setVariableSpaceCharacterIncrement( varSpaceCharacterIncrement); fixedSpaceMode = false; } char ch; if (orgChar == CharUtilities.NBSPACE) { ch = ' '; //converted to normal space to allow word spacing } else { ch = orgChar; } sb.append(ch); } if (glyphAdjust != 0) { flushText(builder, sb, charSet); int increment = Math.round(unitConv.mpt2units(glyphAdjust)); builder.relativeMoveInline(increment); } } flushText(builder, sb, charSet); } private void flushText(PtocaBuilder builder, StringBuffer sb, final CharacterSet charSet) throws IOException { if (sb.length() > 0) { builder.addTransparentData(charSet.encodeChars(sb)); sb.setLength(0); } } }; currentPage.createText(producer); }
// in src/java/org/apache/fop/afp/goca/GraphicsCharacterString.java
private byte[] getStringAsBytes() throws UnsupportedEncodingException, CharacterCodingException { return charSet.encodeChars(str).getBytes(); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
public void createTextData(AFPTextDataInfo textDataInfo) throws UnsupportedEncodingException { createControlSequences(new TextDataInfoProducer(textDataInfo)); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
public void createControlSequences(PtocaProducer producer) throws UnsupportedEncodingException { if (currentPresentationTextData == null) { startPresentationTextData(); } try { producer.produce(builder); } catch (UnsupportedEncodingException e) { endPresentationTextData(); throw e; } catch (IOException ioe) { endPresentationTextData(); handleUnexpectedIOError(ioe); } }
// in src/java/org/apache/fop/afp/modca/AbstractPageObject.java
public void createText(PtocaProducer producer) throws UnsupportedEncodingException { //getPresentationTextObject().createTextData(textDataInfo); getPresentationTextObject().createControlSequences(producer); }
// in src/java/org/apache/fop/afp/util/AFPResourceUtil.java
private static String getResourceName(UnparsedStructuredField field) throws UnsupportedEncodingException { //The first 8 bytes of the field data represent the resource name byte[] nameBytes = new byte[8]; byte[] fieldData = field.getData(); if (fieldData.length < 8) { throw new IllegalArgumentException("Field data does not contain a resource name"); } System.arraycopy(fieldData, 0, nameBytes, 0, 8); return new String(nameBytes, AFPConstants.EBCIDIC_ENCODING); }
17
            
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFDocument.java
catch (UnsupportedEncodingException uee) { return text.getBytes(); }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
catch (java.io.UnsupportedEncodingException e) { throw new RuntimeException("Incompatible VM. It doesn't support the US-ASCII encoding"); }
// in src/java/org/apache/fop/fonts/truetype/TTFDirTabEntry.java
catch (UnsupportedEncodingException e) { return this.toString(); // Should never happen. }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
catch (java.io.UnsupportedEncodingException e) { // This should never happen! }
// in src/java/org/apache/fop/afp/fonts/CharacterSet.java
catch (UnsupportedEncodingException usee) { nameBytes = name.getBytes(); LOG.warn( "UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/afp/modca/MapPageSegment.java
catch (UnsupportedEncodingException usee) { LOG.error("UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/afp/modca/AbstractNamedAFPObject.java
catch (UnsupportedEncodingException usee) { nameBytes = name.getBytes(); LOG.warn( "Constructor:: UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (UnsupportedEncodingException e) { endPresentationTextData(); throw e; }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (UnsupportedEncodingException e) { handleUnexpectedIOError(e); //Won't happen for lines }
// in src/java/org/apache/fop/afp/modca/triplets/AttributeValueTriplet.java
catch (UnsupportedEncodingException usee) { tleByteValue = attVal.getBytes(); throw new IllegalArgumentException(attVal + " encoding failed"); }
// in src/java/org/apache/fop/afp/modca/triplets/FullyQualifiedNameTriplet.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( encoding + " encoding failed"); }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); }
// in src/java/org/apache/fop/afp/modca/MapPageOverlay.java
catch (UnsupportedEncodingException usee) { LOG.error("addOverlay():: UnsupportedEncodingException translating the name " + name); }
// in src/java/org/apache/fop/datatypes/URISpecification.java
catch (UnsupportedEncodingException e) { throw new Error("Incompatible JVM. UTF-8 not supported."); }
9
            
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/pdf/PDFText.java
catch (java.io.UnsupportedEncodingException uee) { throw new CascadingRuntimeException("Incompatible VM", uee); }
// in src/java/org/apache/fop/fonts/type1/PFBParser.java
catch (java.io.UnsupportedEncodingException e) { throw new RuntimeException("Incompatible VM. It doesn't support the US-ASCII encoding"); }
// in src/java/org/apache/fop/afp/modca/PresentationTextObject.java
catch (UnsupportedEncodingException e) { endPresentationTextData(); throw e; }
// in src/java/org/apache/fop/afp/modca/triplets/AttributeValueTriplet.java
catch (UnsupportedEncodingException usee) { tleByteValue = attVal.getBytes(); throw new IllegalArgumentException(attVal + " encoding failed"); }
// in src/java/org/apache/fop/afp/modca/triplets/FullyQualifiedNameTriplet.java
catch (UnsupportedEncodingException e) { throw new IllegalArgumentException( encoding + " encoding failed"); }
// in src/java/org/apache/fop/afp/modca/MapCodedFont.java
catch (UnsupportedEncodingException ex) { throw new FontRuntimeException("Failed to create font " + " due to a UnsupportedEncodingException", ex); }
// in src/java/org/apache/fop/datatypes/URISpecification.java
catch (UnsupportedEncodingException e) { throw new Error("Incompatible JVM. UTF-8 not supported."); }
5
runtime (Lib) UnsupportedOperationException 98
            
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
private static String toString(Paint paint) { //TODO Paint serialization: Fine-tune and extend! if (paint instanceof Color) { return ColorUtil.colorToString((Color)paint); } else { throw new UnsupportedOperationException("Paint not supported: " + paint); } }
// in src/sandbox/org/apache/fop/render/svg/SVGPainter.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof Metadata) { Metadata meta = (Metadata)extension; try { establish(MODE_NORMAL); handler.startElement("metadata"); meta.toSAX(this.handler); handler.endElement("metadata"); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { throw new UnsupportedOperationException( "Don't know how to handle extension object: " + extension); } }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
private static Cipher initCipher(byte[] key) { try { Cipher c = Cipher.getInstance("RC4"); SecretKeySpec keyspec = new SecretKeySpec(key, "RC4"); c.init(Cipher.ENCRYPT_MODE, keyspec); return c; } catch (InvalidKeyException e) { throw new IllegalStateException(e); } catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); } catch (NoSuchPaddingException e) { throw new UnsupportedOperationException(e); } }
// in src/java/org/apache/fop/pdf/PDFObject.java
public void outputInline(OutputStream out, Writer writer) throws IOException { throw new UnsupportedOperationException("Don't use anymore: " + getClass().getName()); }
// in src/java/org/apache/fop/pdf/PDFObject.java
protected String toPDFString() { throw new UnsupportedOperationException("Not implemented. " + "Use output(OutputStream) instead."); }
// in src/java/org/apache/fop/pdf/AlphaRasterImage.java
public void outputContents(OutputStream out) throws IOException { int w = getWidth(); int h = getHeight(); //Check Raster int nbands = alpha.getNumBands(); if (nbands != 1) { throw new UnsupportedOperationException( "Expected only one band/component for the alpha channel"); } //...and write the Raster line by line with a reusable buffer int dataType = alpha.getDataBuffer().getDataType(); if (dataType == DataBuffer.TYPE_BYTE) { byte[] line = new byte[nbands * w]; for (int y = 0; y < h; y++) { alpha.getDataElements(0, y, w, 1, line); out.write(line); } } else if (dataType == DataBuffer.TYPE_USHORT) { short[] sline = new short[nbands * w]; byte[] line = new byte[nbands * w]; for (int y = 0; y < h; y++) { alpha.getDataElements(0, y, w, 1, sline); for (int i = 0; i < w; i++) { //this compresses a 16-bit alpha channel to 8 bits! //we probably don't ever need a 16-bit channel line[i] = (byte)(sline[i] >> 8); } out.write(line); } } else if (dataType == DataBuffer.TYPE_INT) { //Is there an better way to get a 8bit raster from a TYPE_INT raster? int shift = 24; SampleModel sampleModel = alpha.getSampleModel(); if (sampleModel instanceof SinglePixelPackedSampleModel) { SinglePixelPackedSampleModel m = (SinglePixelPackedSampleModel)sampleModel; shift = m.getBitOffsets()[0]; } int[] iline = new int[nbands * w]; byte[] line = new byte[nbands * w]; for (int y = 0; y < h; y++) { alpha.getDataElements(0, y, w, 1, iline); for (int i = 0; i < w; i++) { line[i] = (byte)(iline[i] >> shift); } out.write(line); } } else { throw new UnsupportedOperationException("Unsupported DataBuffer type: " + alpha.getDataBuffer().getClass().getName()); } }
// in src/java/org/apache/fop/pdf/PDFInternalLink.java
protected String toPDFString() { throw new UnsupportedOperationException("This method should not be called"); }
// in src/java/org/apache/fop/fo/properties/TableColLength.java
public double getNumericValue() { throw new UnsupportedOperationException( "Must call getNumericValue with PercentBaseContext"); }
// in src/java/org/apache/fop/fo/properties/TableColLength.java
public int getValue() { throw new UnsupportedOperationException( "Must call getValue with PercentBaseContext"); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
Override public Property getComponent(int cmpId) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
Override public Property getConditionality() { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
Override public Length getLength() { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
Override public Property getLengthComponent() { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/properties/CommonBorderPaddingBackground.java
Override public void setComponent(int cmpId, Property cmpnValue, boolean isDefault) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/flow/table/EmptyGridUnit.java
public PrimaryGridUnit getPrimary() { throw new UnsupportedOperationException(); // return this; TODO }
// in src/java/org/apache/fop/fo/FONode.java
public void setStructureTreeElement(StructureTreeElement structureTreeElement) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/CharIterator.java
public void remove() { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGElement.java
public AffineTransform getScreenTransform() { throw new UnsupportedOperationException("NYI"); }
// in src/java/org/apache/fop/fo/extensions/svg/SVGElement.java
public void setScreenTransform(AffineTransform at) { throw new UnsupportedOperationException("NYI"); }
// in src/java/org/apache/fop/hyphenation/Hyphenator.java
public static HyphenationTree getUserHyphenationTree(String key, HyphenationTreeResolver resolver) { HyphenationTree hTree = null; // I use here the following convention. The file name specified in // the configuration is taken as the base name. First we try // name + ".hyp" assuming a serialized HyphenationTree. If that fails // we try name + ".xml", assumming a raw hyphenation pattern file. // first try serialized object String name = key + ".hyp"; Source source = resolver.resolve(name); if (source != null) { try { InputStream in = null; if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null) { if (source.getSystemId() != null) { in = new java.net.URL(source.getSystemId()).openStream(); } else { throw new UnsupportedOperationException ("Cannot load hyphenation pattern file" + " with the supplied Source object: " + source); } } in = new BufferedInputStream(in); try { hTree = readHyphenationTree(in); } finally { IOUtils.closeQuietly(in); } return hTree; } catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("I/O problem while trying to load " + name, ioe); } } } // try the raw XML file name = key + ".xml"; source = resolver.resolve(name); if (source != null) { hTree = new HyphenationTree(); try { InputStream in = null; if (source instanceof StreamSource) { in = ((StreamSource) source).getInputStream(); } if (in == null) { if (source.getSystemId() != null) { in = new java.net.URL(source.getSystemId()).openStream(); } else { throw new UnsupportedOperationException( "Cannot load hyphenation pattern file" + " with the supplied Source object: " + source); } } if (!(in instanceof BufferedInputStream)) { in = new BufferedInputStream(in); } try { InputSource src = new InputSource(in); src.setSystemId(source.getSystemId()); hTree.loadPatterns(src); } finally { IOUtils.closeQuietly(in); } if (statisticsDump) { System.out.println("Stats: "); hTree.printStats(); } return hTree; } catch (HyphenationException ex) { log.error("Can't load user patterns from XML file " + source.getSystemId() + ": " + ex.getMessage()); return null; } catch (IOException ioe) { if (log.isDebugEnabled()) { log.debug("I/O problem while trying to load " + name, ioe); } return null; } } else { if (log.isDebugEnabled()) { log.debug("Could not load user hyphenation file for '" + key + "'."); } return null; } }
// in src/java/org/apache/fop/fonts/apps/TTFReader.java
public TTFFile loadTTF(String fileName, String fontName, boolean useKerning, boolean useAdvanced) throws IOException { TTFFile ttfFile = new TTFFile(useKerning, useAdvanced); log.info("Reading " + fileName + "..."); FontFileReader reader = new FontFileReader(fileName); boolean supported = ttfFile.readFont(reader, fontName); if (!supported) { return null; } log.info("Font Family: " + ttfFile.getFamilyNames()); if (ttfFile.isCFF()) { throw new UnsupportedOperationException( "OpenType fonts with CFF data are not supported, yet"); } return ttfFile; }
// in src/java/org/apache/fop/fonts/Font.java
public CharSequence performSubstitution ( CharSequence cs, String script, String language ) { if ( metric instanceof Substitutable ) { Substitutable s = (Substitutable) metric; return s.performSubstitution ( cs, script, language ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/fonts/Font.java
public CharSequence reorderCombiningMarks ( CharSequence cs, int[][] gpa, String script, String language ) { if ( metric instanceof Substitutable ) { Substitutable s = (Substitutable) metric; return s.reorderCombiningMarks ( cs, gpa, script, language ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/fonts/Font.java
public int[][] performPositioning ( CharSequence cs, String script, String language, int fontSize ) { if ( metric instanceof Positionable ) { Positionable p = (Positionable) metric; return p.performPositioning ( cs, script, language, fontSize ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/fonts/MultiByteFont.java
public int[][] performPositioning ( CharSequence cs, String script, String language ) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/fonts/type1/PFBData.java
public void setPFBFormat(int format) { switch (format) { case PFB_RAW: case PFB_PC: this.pfbFormat = format; break; case PFB_MAC: throw new UnsupportedOperationException("Mac format is not yet implemented"); default: throw new IllegalArgumentException("Invalid value for PFB format: " + format); } }
// in src/java/org/apache/fop/fonts/truetype/TTFSubSetFile.java
private int determineTableCount() { int numTables = 4; //4 req'd tables: head,hhea,hmtx,maxp if (isCFF()) { throw new UnsupportedOperationException( "OpenType fonts with CFF glyphs are not supported"); } else { numTables += 2; //1 req'd table: glyf,loca if (hasCvt()) { numTables++; } if (hasFpgm()) { numTables++; } if (hasPrep()) { numTables++; } } return numTables; }
// in src/java/org/apache/fop/fonts/truetype/TTFFontLoader.java
private void buildFont(TTFFile ttf, String ttcFontName) { if (ttf.isCFF()) { throw new UnsupportedOperationException( "OpenType fonts with CFF data are not supported, yet"); } boolean isCid = this.embedded; if (this.encodingMode == EncodingMode.SINGLE_BYTE) { isCid = false; } if (isCid) { multiFont = new MultiByteFont(); returnFont = multiFont; multiFont.setTTCName(ttcFontName); } else { singleFont = new SingleByteFont(); returnFont = singleFont; } returnFont.setResolver(resolver); returnFont.setFontName(ttf.getPostScriptName()); returnFont.setFullName(ttf.getFullName()); returnFont.setFamilyNames(ttf.getFamilyNames()); returnFont.setFontSubFamilyName(ttf.getSubFamilyName()); returnFont.setCapHeight(ttf.getCapHeight()); returnFont.setXHeight(ttf.getXHeight()); returnFont.setAscender(ttf.getLowerCaseAscent()); returnFont.setDescender(ttf.getLowerCaseDescent()); returnFont.setFontBBox(ttf.getFontBBox()); returnFont.setFlags(ttf.getFlags()); returnFont.setStemV(Integer.parseInt(ttf.getStemV())); //not used for TTF returnFont.setItalicAngle(Integer.parseInt(ttf.getItalicAngle())); returnFont.setMissingWidth(0); returnFont.setWeight(ttf.getWeightClass()); if (isCid) { multiFont.setCIDType(CIDFontType.CIDTYPE2); int[] wx = ttf.getWidths(); multiFont.setWidthArray(wx); List entries = ttf.getCMaps(); BFEntry[] bfentries = new BFEntry[entries.size()]; int pos = 0; Iterator iter = ttf.getCMaps().listIterator(); while (iter.hasNext()) { TTFCmapEntry ce = (TTFCmapEntry)iter.next(); bfentries[pos] = new BFEntry(ce.getUnicodeStart(), ce.getUnicodeEnd(), ce.getGlyphStartIndex()); pos++; } multiFont.setBFEntries(bfentries); } else { singleFont.setFontType(FontType.TRUETYPE); singleFont.setEncoding(ttf.getCharSetName()); returnFont.setFirstChar(ttf.getFirstChar()); returnFont.setLastChar(ttf.getLastChar()); copyWidthsSingleByte(ttf); } if (useKerning) { copyKerning(ttf, isCid); } if (useAdvanced) { copyAdvanced(ttf); } if (this.embedded) { if (ttf.isEmbeddable()) { returnFont.setEmbedFileName(this.fontFileURI); } else { String msg = "The font " + this.fontFileURI + " is not embeddable due to a" + " licensing restriction."; throw new RuntimeException(msg); } } }
// in src/java/org/apache/fop/render/pdf/ImageRenderedAdapter.java
Override public void populateXObjectDictionary(PDFDictionary dict) { ColorModel cm = getEffectiveColorModel(); if (cm instanceof IndexColorModel) { IndexColorModel icm = (IndexColorModel)cm; PDFArray indexed = new PDFArray(dict); indexed.add(new PDFName("Indexed")); if (icm.getColorSpace().getType() != ColorSpace.TYPE_RGB) { log.warn("Indexed color space is not using RGB as base color space." + " The image may not be handled correctly." + " Base color space: " + icm.getColorSpace() + " Image: " + image.getInfo()); } indexed.add(new PDFName(toPDFColorSpace(icm.getColorSpace()).getName())); int c = icm.getMapSize(); int hival = c - 1; if (hival > MAX_HIVAL) { throw new UnsupportedOperationException("hival must not go beyond " + MAX_HIVAL); } indexed.add(Integer.valueOf(hival)); int[] palette = new int[c]; icm.getRGBs(palette); ByteArrayOutputStream baout = new ByteArrayOutputStream(); for (int i = 0; i < c; i++) { //TODO Probably doesn't work for non RGB based color spaces //See log warning above int entry = palette[i]; baout.write((entry & 0xFF0000) >> 16); baout.write((entry & 0xFF00) >> 8); baout.write(entry & 0xFF); } indexed.add(baout.toByteArray()); IOUtils.closeQuietly(baout); dict.put("ColorSpace", indexed); dict.put("BitsPerComponent", icm.getPixelSize()); Integer index = getIndexOfFirstTransparentColorInPalette(getImage().getRenderedImage()); if (index != null) { PDFArray mask = new PDFArray(dict); mask.add(index); mask.add(index); dict.put("Mask", mask); } } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
public void addResolvedAction(AbstractAction action) throws IFException { assert action.isComplete(); PDFAction pdfAction = (PDFAction)this.incompleteActions.remove(action.getID()); if (pdfAction == null) { getAction(action); } else if (pdfAction instanceof PDFGoTo) { PDFGoTo pdfGoTo = (PDFGoTo)pdfAction; updateTargetLocation(pdfGoTo, (GoToXYAction)action); } else { throw new UnsupportedOperationException( "Action type not supported: " + pdfAction.getClass().getName()); } }
// in src/java/org/apache/fop/render/pdf/PDFDocumentNavigationHandler.java
private PDFAction getAction(AbstractAction action) throws IFException { if (action == null) { return null; } PDFAction pdfAction = (PDFAction)this.completeActions.get(action.getID()); if (pdfAction != null) { return pdfAction; } else if (action instanceof GoToXYAction) { pdfAction = (PDFAction) incompleteActions.get(action.getID()); if (pdfAction != null) { return pdfAction; } else { GoToXYAction a = (GoToXYAction)action; PDFGoTo pdfGoTo = new PDFGoTo(null); getPDFDoc().assignObjectNumber(pdfGoTo); if (action.isComplete()) { updateTargetLocation(pdfGoTo, a); } else { this.incompleteActions.put(action.getID(), pdfGoTo); } return pdfGoTo; } } else if (action instanceof URIAction) { URIAction u = (URIAction)action; assert u.isComplete(); String uri = u.getURI(); PDFFactory factory = getPDFDoc().getFactory(); pdfAction = factory.getExternalAction(uri, u.isNewWindow()); if (!pdfAction.hasObjectNumber()) { //Some PDF actions are pooled getPDFDoc().registerObject(pdfAction); } this.completeActions.put(action.getID(), pdfAction); return pdfAction; } else { throw new UnsupportedOperationException("Unsupported action type: " + action + " (" + action.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/pdf/PDFRendererConfigurator.java
public void configure(Renderer renderer) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/render/pdf/PDFPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { generator.endTextObject(); if (fill != null) { if (fill instanceof Color) { generator.updateColor((Color)fill, true, null); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } } StringBuffer sb = new StringBuffer(); sb.append(format(rect.x)).append(' '); sb.append(format(rect.y)).append(' '); sb.append(format(rect.width)).append(' '); sb.append(format(rect.height)).append(" re"); if (fill != null) { sb.append(" f"); } /* Removed from method signature as it is currently not used if (stroke != null) { sb.append(" S"); }*/ sb.append('\n'); generator.add(sb.toString()); } }
// in src/java/org/apache/fop/render/pdf/PDFBorderPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) { if (start.y != end.y) { //TODO Support arbitrary lines if necessary throw new UnsupportedOperationException( "Can only deal with horizontal lines right now"); } saveGraphicsState(); int half = width / 2; int starty = start.y - half; Rectangle boundingRect = new Rectangle(start.x, start.y - half, end.x - start.x, width); switch (style.getEnumValue()) { case Constants.EN_SOLID: case Constants.EN_DASHED: case Constants.EN_DOUBLE: drawBorderLine(start.x, start.y - half, end.x, end.y + half, true, true, style.getEnumValue(), color); break; case Constants.EN_DOTTED: generator.clipRect(boundingRect); //This displaces the dots to the right by half a dot's width //TODO There's room for improvement here generator.add("1 0 0 1 " + format(half) + " 0 cm\n"); drawBorderLine(start.x, start.y - half, end.x, end.y + half, true, true, style.getEnumValue(), color); break; case Constants.EN_GROOVE: case Constants.EN_RIDGE: generator.setColor(ColorUtil.lightenColor(color, 0.6f), true); generator.add(format(start.x) + " " + format(starty) + " m\n"); generator.add(format(end.x) + " " + format(starty) + " l\n"); generator.add(format(end.x) + " " + format(starty + 2 * half) + " l\n"); generator.add(format(start.x) + " " + format(starty + 2 * half) + " l\n"); generator.add("h\n"); generator.add("f\n"); generator.setColor(color, true); if (style == RuleStyle.GROOVE) { generator.add(format(start.x) + " " + format(starty) + " m\n"); generator.add(format(end.x) + " " + format(starty) + " l\n"); generator.add(format(end.x) + " " + format(starty + half) + " l\n"); generator.add(format(start.x + half) + " " + format(starty + half) + " l\n"); generator.add(format(start.x) + " " + format(starty + 2 * half) + " l\n"); } else { generator.add(format(end.x) + " " + format(starty) + " m\n"); generator.add(format(end.x) + " " + format(starty + 2 * half) + " l\n"); generator.add(format(start.x) + " " + format(starty + 2 * half) + " l\n"); generator.add(format(start.x) + " " + format(starty + half) + " l\n"); generator.add(format(end.x - half) + " " + format(starty + half) + " l\n"); } generator.add("h\n"); generator.add("f\n"); break; default: throw new UnsupportedOperationException("rule style not supported"); } restoreGraphicsState(); }
// in src/java/org/apache/fop/render/RendererFactory.java
public Renderer createRenderer(FOUserAgent userAgent, String outputFormat) throws FOPException { if (userAgent.getDocumentHandlerOverride() != null) { return createRendererForDocumentHandler(userAgent.getDocumentHandlerOverride()); } else if (userAgent.getRendererOverride() != null) { return userAgent.getRendererOverride(); } else { Renderer renderer; if (isRendererPreferred()) { //Try renderer first renderer = tryRendererMaker(userAgent, outputFormat); if (renderer == null) { renderer = tryIFDocumentHandlerMaker(userAgent, outputFormat); } } else { //Try document handler first renderer = tryIFDocumentHandlerMaker(userAgent, outputFormat); if (renderer == null) { renderer = tryRendererMaker(userAgent, outputFormat); } } if (renderer == null) { throw new UnsupportedOperationException( "No renderer for the requested format available: " + outputFormat); } return renderer; } }
// in src/java/org/apache/fop/render/RendererFactory.java
public FOEventHandler createFOEventHandler(FOUserAgent userAgent, String outputFormat, OutputStream out) throws FOPException { if (userAgent.getFOEventHandlerOverride() != null) { return userAgent.getFOEventHandlerOverride(); } else { AbstractFOEventHandlerMaker maker = getFOEventHandlerMaker(outputFormat); if (maker != null) { return maker.makeFOEventHandler(userAgent, out); } else { AbstractRendererMaker rendMaker = getRendererMaker(outputFormat); AbstractIFDocumentHandlerMaker documentHandlerMaker = null; boolean outputStreamMissing = (userAgent.getRendererOverride() == null) && (userAgent.getDocumentHandlerOverride() == null); if (rendMaker == null) { documentHandlerMaker = getDocumentHandlerMaker(outputFormat); if (documentHandlerMaker != null) { outputStreamMissing &= (out == null) && (documentHandlerMaker.needsOutputStream()); } } else { outputStreamMissing &= (out == null) && (rendMaker.needsOutputStream()); } if (userAgent.getRendererOverride() != null || rendMaker != null || userAgent.getDocumentHandlerOverride() != null || documentHandlerMaker != null) { if (outputStreamMissing) { throw new FOPException( "OutputStream has not been set"); } //Found a Renderer so we need to construct an AreaTreeHandler. return new AreaTreeHandler(userAgent, outputFormat, out); } else { throw new UnsupportedOperationException( "Don't know how to handle \"" + outputFormat + "\" as an output format." + " Neither an FOEventHandler, nor a Renderer could be found" + " for this output format."); } } } }
// in src/java/org/apache/fop/render/RendererFactory.java
public IFDocumentHandler createDocumentHandler(FOUserAgent userAgent, String outputFormat) throws FOPException { if (userAgent.getDocumentHandlerOverride() != null) { return userAgent.getDocumentHandlerOverride(); } AbstractIFDocumentHandlerMaker maker = getDocumentHandlerMaker(outputFormat); if (maker == null) { throw new UnsupportedOperationException( "No IF document handler for the requested format available: " + outputFormat); } IFDocumentHandler documentHandler = maker.makeIFDocumentHandler(userAgent); IFDocumentHandlerConfigurator configurator = documentHandler.getConfigurator(); if (configurator != null) { configurator.configure(documentHandler); } return new EventProducingFilter(documentHandler, userAgent); }
// in src/java/org/apache/fop/render/intermediate/AbstractIFPainter.java
protected void drawImage(Image image, Rectangle rect, RenderingContext context, boolean convert, Map additionalHints) throws IOException, ImageException { ImageManager manager = getFopFactory().getImageManager(); ImageHandlerRegistry imageHandlerRegistry = getFopFactory().getImageHandlerRegistry(); Image effImage; context.putHints(additionalHints); if (convert) { Map hints = createDefaultImageProcessingHints(getUserAgent().getImageSessionContext()); if (additionalHints != null) { hints.putAll(additionalHints); } effImage = manager.convertImage(image, imageHandlerRegistry.getSupportedFlavors(context), hints); } else { effImage = image; } //First check for a dynamically registered handler ImageHandler handler = imageHandlerRegistry.getHandler(context, effImage); if (handler == null) { throw new UnsupportedOperationException( "No ImageHandler available for image: " + effImage.getInfo() + " (" + effImage.getClass().getName() + ")"); } if (log.isTraceEnabled()) { log.trace("Using ImageHandler: " + handler.getClass().getName()); } handler.handleImage(context, effImage, rect); }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
private static String toString(Paint paint) { if (paint instanceof Color) { return ColorUtil.colorToString((Color)paint); } else { throw new UnsupportedOperationException("Paint not supported: " + paint); } }
// in src/java/org/apache/fop/render/intermediate/IFSerializer.java
public void handleExtensionObject(Object extension) throws IFException { if (extension instanceof XMLizable) { try { ((XMLizable)extension).toSAX(this.handler); } catch (SAXException e) { throw new IFException("SAX error while handling extension object", e); } } else { throw new UnsupportedOperationException( "Extension must implement XMLizable: " + extension + " (" + extension.getClass().getName() + ")"); } }
// in src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
public void setResult(Result result) throws IFException { if (result instanceof StreamResult) { StreamResult streamResult = (StreamResult)result; OutputStream out = streamResult.getOutputStream(); if (out == null) { if (streamResult.getWriter() != null) { throw new IllegalArgumentException( "FOP cannot use a Writer. Please supply an OutputStream!"); } try { URL url = new URL(streamResult.getSystemId()); File f = FileUtils.toFile(url); if (f != null) { out = new java.io.FileOutputStream(f); } else { out = url.openConnection().getOutputStream(); } } catch (IOException ioe) { throw new IFException("I/O error while opening output stream" , ioe); } out = new java.io.BufferedOutputStream(out); this.ownOutputStream = true; } if (out == null) { throw new IllegalArgumentException("Need a StreamResult with an OutputStream"); } this.outputStream = out; } else { throw new UnsupportedOperationException( "Unsupported Result subclass: " + result.getClass().getName()); } }
// in src/java/org/apache/fop/render/pcl/PCLGraphics2D.java
protected void handleUnsupportedFeature(String msg) { if (this.failOnUnsupportedFeature) { throw new UnsupportedOperationException(msg); } }
// in src/java/org/apache/fop/render/pcl/PCLPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { Color fillColor = null; if (fill != null) { if (fill instanceof Color) { fillColor = (Color)fill; } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } try { setCursorPos(rect.x, rect.y); gen.fillRect(rect.width, rect.height, fillColor); } catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); } } } }
// in src/java/org/apache/fop/render/pcl/PCLRendererConfigurator.java
public void configure(Renderer renderer) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/render/bitmap/TIFFRenderer.java
public void remove() { throw new UnsupportedOperationException( "Method 'remove' is not supported."); }
// in src/java/org/apache/fop/render/afp/AFPRendererConfigurator.java
Override public void configure(Renderer renderer) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/render/afp/AFPDocumentHandler.java
public void endPageSequence() throws IFException { try { //Process deferred page-sequence-level extensions Iterator<AFPPageSetup> iter = this.deferredPageSequenceExtensions.iterator(); while (iter.hasNext()) { AFPPageSetup aps = iter.next(); iter.remove(); if (AFPElementMapping.NO_OPERATION.equals(aps.getElementName())) { handleNOP(aps); } else { throw new UnsupportedOperationException("Don't know how to handle " + aps); } } //End page sequence dataStream.endPageGroup(); } catch (IOException ioe) { throw new IFException("I/O error in endPageSequence()", ioe); } this.location = Location.ELSEWHERE; }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { if (fill instanceof Color) { getPaintingState().setColor((Color)fill); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } RectanglePaintingInfo rectanglePaintInfo = new RectanglePaintingInfo( toPoint(rect.x), toPoint(rect.y), toPoint(rect.width), toPoint(rect.height)); try { rectanglePainter.paint(rectanglePaintInfo); } catch (IOException ioe) { throw new IFException("IO error while painting rectangle", ioe); } } }
// in src/java/org/apache/fop/render/afp/AFPPainter.java
Override public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IOException { if (start.y != end.y) { //TODO Support arbitrary lines if necessary throw new UnsupportedOperationException( "Can only deal with horizontal lines right now"); } //Simply delegates to drawBorderLine() as AFP line painting is not very sophisticated. int halfWidth = width / 2; drawBorderLine(start.x, start.y - halfWidth, end.x, start.y + halfWidth, true, true, style.getEnumValue(), color); }
// in src/java/org/apache/fop/render/afp/AFPForeignAttributeReader.java
public AFPResourceLevel getResourceLevel(Map/*<QName, String>*/ foreignAttributes) { AFPResourceLevel resourceLevel = null; if (foreignAttributes != null && !foreignAttributes.isEmpty()) { if (foreignAttributes.containsKey(RESOURCE_LEVEL)) { String levelString = (String)foreignAttributes.get(RESOURCE_LEVEL); resourceLevel = AFPResourceLevel.valueOf(levelString); // if external get resource group file attributes if (resourceLevel != null && resourceLevel.isExternal()) { String resourceGroupFile = (String)foreignAttributes.get(RESOURCE_GROUP_FILE); if (resourceGroupFile == null) { String msg = RESOURCE_GROUP_FILE + " not specified"; LOG.error(msg); throw new UnsupportedOperationException(msg); } File resourceExternalGroupFile = new File(resourceGroupFile); SecurityManager security = System.getSecurityManager(); try { if (security != null) { security.checkWrite(resourceExternalGroupFile.getPath()); } } catch (SecurityException ex) { String msg = "unable to gain write access to external resource file: " + resourceGroupFile; LOG.error(msg); } try { boolean exists = resourceExternalGroupFile.exists(); if (exists) { LOG.warn("overwriting external resource file: " + resourceGroupFile); } resourceLevel.setExternalFilePath(resourceGroupFile); } catch (SecurityException ex) { String msg = "unable to gain read access to external resource file: " + resourceGroupFile; LOG.error(msg); } } } } return resourceLevel; }
// in src/java/org/apache/fop/render/afp/extensions/AFPPageSetup.java
public void setPlacement(ExtensionPlacement placement) { if (!AFPElementMapping.NO_OPERATION.equals(getElementName())) { throw new UnsupportedOperationException( "The attribute 'placement' can currently only be set for NOPs!"); } this.placement = placement; }
// in src/java/org/apache/fop/render/ps/PSRendererConfigurator.java
public void configure(Renderer renderer) { throw new UnsupportedOperationException(); }
// in src/java/org/apache/fop/render/ps/ResourceHandler.java
private void generateFormForImage(PSGenerator gen, PSImageFormResource form) throws IOException { final String uri = form.getImageURI(); ImageManager manager = userAgent.getFactory().getImageManager(); ImageInfo info = null; try { ImageSessionContext sessionContext = userAgent.getImageSessionContext(); info = manager.getImageInfo(uri, sessionContext); //Create a rendering context for form creation PSRenderingContext formContext = new PSRenderingContext( userAgent, gen, fontInfo, true); ImageFlavor[] flavors; ImageHandlerRegistry imageHandlerRegistry = userAgent.getFactory().getImageHandlerRegistry(); flavors = imageHandlerRegistry.getSupportedFlavors(formContext); Map hints = ImageUtil.getDefaultHints(sessionContext); org.apache.xmlgraphics.image.loader.Image img = manager.getImage( info, flavors, hints, sessionContext); ImageHandler basicHandler = imageHandlerRegistry.getHandler(formContext, img); if (basicHandler == null) { throw new UnsupportedOperationException( "No ImageHandler available for image: " + img.getInfo() + " (" + img.getClass().getName() + ")"); } if (!(basicHandler instanceof PSImageHandler)) { throw new IllegalStateException( "ImageHandler implementation doesn't behave properly." + " It should have returned false in isCompatible(). Class: " + basicHandler.getClass().getName()); } PSImageHandler handler = (PSImageHandler)basicHandler; if (log.isTraceEnabled()) { log.trace("Using ImageHandler: " + handler.getClass().getName()); } handler.generateForm(formContext, img, form); } catch (ImageException ie) { ResourceEventProducer eventProducer = ResourceEventProducer.Provider.get( userAgent.getEventBroadcaster()); eventProducer.imageError(resTracker, (info != null ? info.toString() : uri), ie, null); } }
// in src/java/org/apache/fop/render/ps/PSPainter.java
public void fillRect(Rectangle rect, Paint fill) throws IFException { if (fill == null) { return; } if (rect.width != 0 && rect.height != 0) { try { endTextObject(); PSGenerator generator = getGenerator(); if (fill != null) { if (fill instanceof Color) { generator.useColor((Color)fill); } else { throw new UnsupportedOperationException("Non-Color paints NYI"); } } generator.defineRect(rect.x / 1000.0, rect.y / 1000.0, rect.width / 1000.0, rect.height / 1000.0); generator.writeln(generator.mapCommand("fill")); } catch (IOException ioe) { throw new IFException("I/O error in fillRect()", ioe); } } }
// in src/java/org/apache/fop/render/ps/PSBorderPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) throws IOException { if (start.y != end.y) { //TODO Support arbitrary lines if necessary throw new UnsupportedOperationException( "Can only deal with horizontal lines right now"); } saveGraphicsState(); int half = width / 2; int starty = start.y - half; //Rectangle boundingRect = new Rectangle(start.x, start.y - half, end.x - start.x, width); switch (style.getEnumValue()) { case Constants.EN_SOLID: case Constants.EN_DASHED: case Constants.EN_DOUBLE: drawBorderLine(start.x, starty, end.x, starty + width, true, true, style.getEnumValue(), color); break; case Constants.EN_DOTTED: clipRect(start.x, starty, end.x - start.x, width); //This displaces the dots to the right by half a dot's width //TODO There's room for improvement here generator.concatMatrix(1, 0, 0, 1, toPoints(half), 0); drawBorderLine(start.x, starty, end.x, starty + width, true, true, style.getEnumValue(), color); break; case Constants.EN_GROOVE: case Constants.EN_RIDGE: generator.useColor(ColorUtil.lightenColor(color, 0.6f)); moveTo(start.x, starty); lineTo(end.x, starty); lineTo(end.x, starty + 2 * half); lineTo(start.x, starty + 2 * half); closePath(); generator.write(" " + generator.mapCommand("fill")); generator.writeln(" " + generator.mapCommand("newpath")); generator.useColor(color); if (style == RuleStyle.GROOVE) { moveTo(start.x, starty); lineTo(end.x, starty); lineTo(end.x, starty + half); lineTo(start.x + half, starty + half); lineTo(start.x, starty + 2 * half); } else { moveTo(end.x, starty); lineTo(end.x, starty + 2 * half); lineTo(start.x, starty + 2 * half); lineTo(start.x, starty + half); lineTo(end.x - half, starty + half); } closePath(); generator.write(" " + generator.mapCommand("fill")); generator.writeln(" " + generator.mapCommand("newpath")); break; default: throw new UnsupportedOperationException("rule style not supported"); } restoreGraphicsState(); }
// in src/java/org/apache/fop/render/ps/NativeTextHandler.java
public void drawString(String text, float x, float y) throws IOException { // TODO Remove me after removing the deprecated method in TextHandler. throw new UnsupportedOperationException("Deprecated method!"); }
// in src/java/org/apache/fop/render/java2d/Java2DBorderPainter.java
public void drawLine(Point start, Point end, int width, Color color, RuleStyle style) { if (start.y != end.y) { //TODO Support arbitrary lines if necessary throw new UnsupportedOperationException( "Can only deal with horizontal lines right now"); } saveGraphicsState(); int half = width / 2; int starty = start.y - half; Rectangle boundingRect = new Rectangle(start.x, start.y - half, end.x - start.x, width); getG2DState().updateClip(boundingRect); switch (style.getEnumValue()) { case Constants.EN_SOLID: case Constants.EN_DASHED: case Constants.EN_DOUBLE: drawBorderLine(start.x, start.y - half, end.x, end.y + half, true, true, style.getEnumValue(), color); break; case Constants.EN_DOTTED: int shift = half; //This shifts the dots to the right by half a dot's width drawBorderLine(start.x + shift, start.y - half, end.x + shift, end.y + half, true, true, style.getEnumValue(), color); break; case Constants.EN_GROOVE: case Constants.EN_RIDGE: getG2DState().updateColor(ColorUtil.lightenColor(color, 0.6f)); moveTo(start.x, starty); lineTo(end.x, starty); lineTo(end.x, starty + 2 * half); lineTo(start.x, starty + 2 * half); closePath(); getG2D().fill(currentPath); currentPath = null; getG2DState().updateColor(color); if (style.getEnumValue() == Constants.EN_GROOVE) { moveTo(start.x, starty); lineTo(end.x, starty); lineTo(end.x, starty + half); lineTo(start.x + half, starty + half); lineTo(start.x, starty + 2 * half); } else { moveTo(end.x, starty); lineTo(end.x, starty + 2 * half); lineTo(start.x, starty + 2 * half); lineTo(start.x, starty + half); lineTo(end.x - half, starty + half); } closePath(); getG2D().fill(currentPath); currentPath = null; case Constants.EN_NONE: // No rule is drawn break; default: } // end switch restoreGraphicsState(); }
// in src/java/org/apache/fop/afp/AFPDataObjectFactory.java
public ResourceObject createResource(AbstractNamedAFPObject namedObj, AFPResourceInfo resourceInfo, Registry.ObjectType objectType) { ResourceObject resourceObj = null; String resourceName = resourceInfo.getName(); if (resourceName != null) { resourceObj = factory.createResource(resourceName); } else { resourceObj = factory.createResource(); } if (namedObj instanceof Document) { resourceObj.setType(ResourceObject.TYPE_DOCUMENT); } else if (namedObj instanceof PageSegment) { resourceObj.setType(ResourceObject.TYPE_PAGE_SEGMENT); } else if (namedObj instanceof Overlay) { resourceObj.setType(ResourceObject.TYPE_OVERLAY_OBJECT); } else if (namedObj instanceof AbstractDataObject) { AbstractDataObject dataObj = (AbstractDataObject)namedObj; if (namedObj instanceof ObjectContainer) { resourceObj.setType(ResourceObject.TYPE_OBJECT_CONTAINER); // set object classification final boolean dataInContainer = true; final boolean containerHasOEG = false; // must be included final boolean dataInOCD = true; // mandatory triplet for object container resourceObj.setObjectClassification( ObjectClassificationTriplet.CLASS_TIME_INVARIANT_PAGINATED_PRESENTATION_OBJECT, objectType, dataInContainer, containerHasOEG, dataInOCD); } else if (namedObj instanceof ImageObject) { // ioca image type resourceObj.setType(ResourceObject.TYPE_IMAGE); } else if (namedObj instanceof GraphicsObject) { resourceObj.setType(ResourceObject.TYPE_GRAPHIC); } else { throw new UnsupportedOperationException( "Unsupported resource object for data object type " + dataObj); } } else { throw new UnsupportedOperationException( "Unsupported resource object type " + namedObj); } // set the resource information/classification on the data object resourceObj.setDataObject(namedObj); return resourceObj; }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public void add(LayoutManager lm) throws UnsupportedOperationException { throw new UnsupportedOperationException("LMiter doesn't support add"); }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public void set(LayoutManager lm) throws UnsupportedOperationException { throw new UnsupportedOperationException("LMiter doesn't support set"); }
// in src/java/org/apache/fop/layoutmgr/AbstractBaseLayoutManager.java
public int getContentAreaIPD() { throw new UnsupportedOperationException( "getContentAreaIPD() called when it should have been overridden"); }
// in src/java/org/apache/fop/layoutmgr/AbstractBaseLayoutManager.java
public int getContentAreaBPD() { throw new UnsupportedOperationException( "getContentAreaBPD() called when it should have been overridden"); }
// in src/java/org/apache/fop/layoutmgr/AbstractBaseLayoutManager.java
public void reset() { throw new UnsupportedOperationException("Not implemented"); }
// in src/java/org/apache/fop/layoutmgr/AbstractBaseLayoutManager.java
public List getNextKnuthElements(LayoutContext context, int alignment, Stack lmStack, Position positionAtIPDChange, LayoutManager restartAtLM) { throw new UnsupportedOperationException("Not implemented"); }
// in src/java/org/apache/fop/layoutmgr/AbstractBreaker.java
protected List<KnuthElement> getNextKnuthElements(LayoutContext context, int alignment, Position positionAtIPDChange, LayoutManager restartAtLM) { throw new UnsupportedOperationException("TODO: implement acceptable fallback"); }
// in src/java/org/apache/fop/layoutmgr/AbstractBreaker.java
private int getNextBlockListChangedIPD(LayoutContext childLC, PageBreakingAlgorithm alg, BlockSequence effectiveList) { int nextSequenceStartsOn; KnuthNode optimalBreak = alg.getBestNodeBeforeIPDChange(); int positionIndex = optimalBreak.position; log.trace("IPD changes at index " + positionIndex); KnuthElement elementAtBreak = alg.getElement(positionIndex); Position positionAtBreak = elementAtBreak.getPosition(); if (!(positionAtBreak instanceof SpaceResolver.SpaceHandlingBreakPosition)) { throw new UnsupportedOperationException( "Don't know how to restart at position " + positionAtBreak); } /* Retrieve the original position wrapped into this space position */ positionAtBreak = positionAtBreak.getPosition(); LayoutManager restartAtLM = null; List<KnuthElement> firstElements = Collections.emptyList(); if (containsNonRestartableLM(positionAtBreak)) { if (alg.getIPDdifference() > 0) { EventBroadcaster eventBroadcaster = getCurrentChildLM().getFObj() .getUserAgent().getEventBroadcaster(); BlockLevelEventProducer eventProducer = BlockLevelEventProducer.Provider.get(eventBroadcaster); eventProducer.nonRestartableContentFlowingToNarrowerPage(this); } firstElements = new LinkedList<KnuthElement>(); boolean boxFound = false; Iterator<KnuthElement> iter = effectiveList.listIterator(positionIndex + 1); Position position = null; while (iter.hasNext() && (position == null || containsNonRestartableLM(position))) { positionIndex++; KnuthElement element = iter.next(); position = element.getPosition(); if (element.isBox()) { boxFound = true; firstElements.add(element); } else if (boxFound) { firstElements.add(element); } } if (position instanceof SpaceResolver.SpaceHandlingBreakPosition) { /* Retrieve the original position wrapped into this space position */ positionAtBreak = position.getPosition(); } else { positionAtBreak = null; } } if (positionAtBreak != null && positionAtBreak.getIndex() == -1) { /* * This is an indication that we are between two blocks * (possibly surrounded by another block), not inside a * paragraph. */ Position position; Iterator<KnuthElement> iter = effectiveList.listIterator(positionIndex + 1); do { KnuthElement nextElement = iter.next(); position = nextElement.getPosition(); } while (position == null || position instanceof SpaceResolver.SpaceHandlingPosition || position instanceof SpaceResolver.SpaceHandlingBreakPosition && position.getPosition().getIndex() == -1); LayoutManager surroundingLM = positionAtBreak.getLM(); while (position.getLM() != surroundingLM) { position = position.getPosition(); } restartAtLM = position.getPosition().getLM(); } nextSequenceStartsOn = getNextBlockList(childLC, Constants.EN_COLUMN, positionAtBreak, restartAtLM, firstElements); return nextSequenceStartsOn; }
// in src/java/org/apache/fop/layoutmgr/PositionIterator.java
public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException("PositionIterator doesn't support remove"); }
// in src/java/org/apache/fop/layoutmgr/table/CollapsingBorderModel.java
public static CollapsingBorderModel getBorderModelFor(int borderCollapse) { switch (borderCollapse) { case Constants.EN_COLLAPSE: if (collapse == null) { collapse = new CollapsingBorderModelEyeCatching(); } return collapse; case Constants.EN_COLLAPSE_WITH_PRECEDENCE: throw new UnsupportedOperationException ( "collapse-with-precedence not yet supported" ); default: throw new IllegalArgumentException("Illegal border-collapse mode."); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new SingleSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new SingleSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new PairSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new PairSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new CursiveSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new MarkToBaseSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new MarkToLigatureSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new MarkToMarkSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new ContextualSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new ContextualSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 3 ) { return new ContextualSubtableFormat3 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphPositioningTable.java
static GlyphPositioningSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new ChainedContextualSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new ChainedContextualSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 3 ) { return new ChainedContextualSubtableFormat3 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new SingleSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new SingleSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new MultipleSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new AlternateSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new LigatureSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new ContextualSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new ContextualSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 3 ) { return new ContextualSubtableFormat3 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new ChainedContextualSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 2 ) { return new ChainedContextualSubtableFormat2 ( id, sequence, flags, format, coverage, entries ); } else if ( format == 3 ) { return new ChainedContextualSubtableFormat3 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphSubstitutionTable.java
static GlyphSubstitutionSubtable create ( String id, int sequence, int flags, int format, GlyphCoverageTable coverage, List entries ) { if ( format == 1 ) { return new ReverseChainedSingleSubtableFormat1 ( id, sequence, flags, format, coverage, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java
protected void addSubtable ( GlyphSubtable subtable ) { if ( subtable instanceof GlyphClassSubtable ) { this.gct = (GlyphClassSubtable) subtable; } else if ( subtable instanceof AttachmentPointSubtable ) { // TODO - not yet used // this.apt = (AttachmentPointSubtable) subtable; } else if ( subtable instanceof LigatureCaretSubtable ) { // TODO - not yet used // this.lct = (LigatureCaretSubtable) subtable; } else if ( subtable instanceof MarkAttachmentSubtable ) { this.mat = (MarkAttachmentSubtable) subtable; } else { throw new UnsupportedOperationException ( "unsupported glyph definition subtable type: " + subtable ); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java
static GlyphDefinitionSubtable create ( String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries ) { if ( format == 1 ) { return new GlyphClassSubtableFormat1 ( id, sequence, flags, format, mapping, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java
static GlyphDefinitionSubtable create ( String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries ) { if ( format == 1 ) { return new AttachmentPointSubtableFormat1 ( id, sequence, flags, format, mapping, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java
static GlyphDefinitionSubtable create ( String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries ) { if ( format == 1 ) { return new LigatureCaretSubtableFormat1 ( id, sequence, flags, format, mapping, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/java/org/apache/fop/complexscripts/fonts/GlyphDefinitionTable.java
static GlyphDefinitionSubtable create ( String id, int sequence, int flags, int format, GlyphMappingTable mapping, List entries ) { if ( format == 1 ) { return new MarkAttachmentSubtableFormat1 ( id, sequence, flags, format, mapping, entries ); } else { throw new UnsupportedOperationException(); } }
// in src/codegen/java/org/apache/fop/tools/EventProducerCollector.java
private EventMethodModel createMethodModel(JavaMethod method) throws EventConventionException, ClassNotFoundException { JavaClass clazz = method.getParentClass(); //Check EventProducer conventions if (!method.getReturnType().isVoid()) { throw new EventConventionException("All methods of interface " + clazz.getFullyQualifiedName() + " must have return type 'void'!"); } String methodSig = clazz.getFullyQualifiedName() + "." + method.getCallSignature(); JavaParameter[] params = method.getParameters(); if (params.length < 1) { throw new EventConventionException("The method " + methodSig + " must have at least one parameter: 'Object source'!"); } Type firstType = params[0].getType(); if (firstType.isPrimitive() || !"source".equals(params[0].getName())) { throw new EventConventionException("The first parameter of the method " + methodSig + " must be: 'Object source'!"); } //build method model DocletTag tag = method.getTagByName("event.severity"); EventSeverity severity; if (tag != null) { severity = EventSeverity.valueOf(tag.getValue()); } else { severity = EventSeverity.INFO; } EventMethodModel methodMeta = new EventMethodModel( method.getName(), severity); if (params.length > 1) { for (int j = 1, cj = params.length; j < cj; j++) { JavaParameter p = params[j]; Class<?> type; JavaClass pClass = p.getType().getJavaClass(); if (p.getType().isPrimitive()) { type = PRIMITIVE_MAP.get(pClass.getName()); if (type == null) { throw new UnsupportedOperationException( "Primitive datatype not supported: " + pClass.getName()); } } else { String className = pClass.getFullyQualifiedName(); type = Class.forName(className); } methodMeta.addParameter(type, p.getName()); } } Type[] exceptions = method.getExceptions(); if (exceptions != null && exceptions.length > 0) { //We only use the first declared exception because that is always thrown JavaClass cl = exceptions[0].getJavaClass(); methodMeta.setExceptionClass(cl.getFullyQualifiedName()); methodMeta.setSeverity(EventSeverity.FATAL); //In case it's not set in the comments } return methodMeta; }
3
            
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e.getMessage()); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchAlgorithmException e) { throw new UnsupportedOperationException(e); }
// in src/java/org/apache/fop/pdf/PDFEncryptionJCE.java
catch (NoSuchPaddingException e) { throw new UnsupportedOperationException(e); }
3
            
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public void add(LayoutManager lm) throws UnsupportedOperationException { throw new UnsupportedOperationException("LMiter doesn't support add"); }
// in src/java/org/apache/fop/layoutmgr/LMiter.java
public void set(LayoutManager lm) throws UnsupportedOperationException { throw new UnsupportedOperationException("LMiter doesn't support set"); }
// in src/java/org/apache/fop/layoutmgr/PositionIterator.java
public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException("PositionIterator doesn't support remove"); }
2
            
// in src/java/org/apache/fop/fonts/SingleByteFont.java
catch (UnsupportedOperationException e) { log.error("Font '" + super.getFontName() + "': " + e.getMessage()); }
// in src/java/org/apache/fop/render/pcl/PCLImageHandlerGraphics2D.java
catch (UnsupportedOperationException uoe) { log.debug( "Cannot paint graphic natively. Falling back to bitmap painting. Reason: " + uoe.getMessage()); }
0 0
unknown (Domain) ValidationException
public class ValidationException extends FOPException {

    /**
     * Construct a validation exception instance.
     * @param message a message
     */
    public ValidationException(String message) {
        super(message);
    }

    /**
     * Construct a validation exception instance.
     * @param message a message
     * @param locator a locator
     */
    public ValidationException(String message, Locator locator) {
        super(message, locator);
    }
}
1
            
// in src/java/org/apache/fop/fo/flow/table/FixedColRowGroupBuilder.java
void endTablePart() throws ValidationException { if (rows.size() > 0) { throw new ValidationException( "A table-cell is spanning more rows than available in its parent element."); } setFlagForCols(GridUnit.LAST_IN_PART, lastRow); borderResolver.endPart(); }
0 90
            
// in src/java/org/apache/fop/fo/XMLObj.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/PropertyList.java
private String addAttributeToList(Attributes attributes, String attributeName) throws ValidationException { String attributeValue = attributes.getValue(attributeName); if ( attributeValue != null ) { convertAttributeToProperty(attributes, attributeName, attributeValue); } return attributeValue; }
// in src/java/org/apache/fop/fo/PropertyList.java
public void addAttributesToList(Attributes attributes) throws ValidationException { /* * Give writing-mode highest conversion priority. */ addAttributeToList(attributes, "writing-mode"); /* * If column-number/number-columns-spanned are specified, then we * need them before all others (possible from-table-column() on any * other property further in the list... */ addAttributeToList(attributes, "column-number"); addAttributeToList(attributes, "number-columns-spanned"); /* * If font-size is set on this FO, must set it first, since * other attributes specified in terms of "ems" depend on it. */ String checkValue = addAttributeToList(attributes, "font"); if (checkValue == null || "".equals(checkValue)) { /* * font shorthand wasn't specified, so still need to process * explicit font-size */ addAttributeToList(attributes, "font-size"); } String attributeNS; String attributeName; String attributeValue; FopFactory factory = getFObj().getUserAgent().getFactory(); for (int i = 0; i < attributes.getLength(); i++) { /* convert all attributes with the same namespace as the fo element * the "xml:lang" and "xml:base" properties are special cases */ attributeNS = attributes.getURI(i); attributeName = attributes.getQName(i); attributeValue = attributes.getValue(i); if (attributeNS == null || attributeNS.length() == 0 || "xml:lang".equals(attributeName) || "xml:base".equals(attributeName)) { convertAttributeToProperty(attributes, attributeName, attributeValue); } else if (!factory.isNamespaceIgnored(attributeNS)) { ElementMapping mapping = factory.getElementMappingRegistry().getElementMapping( attributeNS); QName attr = new QName(attributeNS, attributeName); if (mapping != null) { if (mapping.isAttributeProperty(attr) && mapping.getStandardPrefix() != null) { convertAttributeToProperty(attributes, mapping.getStandardPrefix() + ":" + attr.getLocalName(), attributeValue); } else { getFObj().addForeignAttribute(attr, attributeValue); } } else { handleInvalidProperty(attr); } } } }
// in src/java/org/apache/fop/fo/PropertyList.java
private void convertAttributeToProperty(Attributes attributes, String attributeName, String attributeValue) throws ValidationException { if (attributeName.startsWith("xmlns:") || "xmlns".equals(attributeName)) { /* Ignore namespace declarations if the XML parser/XSLT processor * reports them as 'regular' attributes */ return; } if (attributeValue != null) { /* Handle "compound" properties, ex. space-before.minimum */ String basePropertyName = findBasePropertyName(attributeName); String subPropertyName = findSubPropertyName(attributeName); int propId = FOPropertyMapping.getPropertyId(basePropertyName); int subpropId = FOPropertyMapping.getSubPropertyId(subPropertyName); if (propId == -1 || (subpropId == -1 && subPropertyName != null)) { handleInvalidProperty(new QName(null, attributeName)); } FObj parentFO = fobj.findNearestAncestorFObj(); PropertyMaker propertyMaker = findMaker(propId); if (propertyMaker == null) { log.warn("No PropertyMaker registered for " + attributeName + ". Ignoring property."); return; } try { Property prop = null; if (subPropertyName == null) { // base attribute only found /* Do nothing if the base property has already been created. * This is e.g. the case when a compound attribute was * specified before the base attribute; in these cases * the base attribute was already created in * findBaseProperty() */ if (getExplicit(propId) != null) { return; } prop = propertyMaker.make(this, attributeValue, parentFO); } else { // e.g. "leader-length.maximum" Property baseProperty = findBaseProperty(attributes, parentFO, propId, basePropertyName, propertyMaker); prop = propertyMaker.make(baseProperty, subpropId, this, attributeValue, parentFO); } if (prop != null) { putExplicit(propId, prop); } } catch (PropertyException e) { fobj.getFOValidationEventProducer().invalidPropertyValue(this, fobj.getName(), attributeName, attributeValue, e, fobj.locator); } } }
// in src/java/org/apache/fop/fo/PropertyList.java
protected void handleInvalidProperty(QName attr) throws ValidationException { if (!attr.getQName().startsWith("xmlns")) { fobj.getFOValidationEventProducer().invalidProperty(this, fobj.getName(), attr, true, fobj.locator); } }
// in src/java/org/apache/fop/fo/flow/AbstractListItemPart.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(%block;)"); } } else if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else { blockItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/ListItem.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (label != null) { nodesOutOfOrderError(loc, "fo:marker", "fo:list-item-label"); } } else if (localName.equals("list-item-label")) { if (label != null) { tooManyNodesError(loc, "fo:list-item-label"); } } else if (localName.equals("list-item-body")) { if (label == null) { nodesOutOfOrderError(loc, "fo:list-item-label", "fo:list-item-body"); } else if (body != null) { tooManyNodesError(loc, "fo:list-item-body"); } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/Float.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/PageNumber.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/Wrapper.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ("marker".equals(localName)) { if (blockOrInlineItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(#PCDATA|%inline;|%block;)"); } } else if (isBlockOrInlineItem(nsURI, localName)) { /* delegate validation to parent, but keep the error reporting * tidy. If we would simply call validateChildNode() on the * parent, the user would get a wrong impression, as only the * locator (if any) will contain a reference to the offending * fo:wrapper. */ try { FONode.validateChildNode(this.parent, loc, nsURI, localName); } catch (ValidationException vex) { invalidChildError(loc, getName(), FO_URI, localName, "rule.wrapperInvalidChildForParent"); } blockOrInlineItemFound = true; } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/InlineContainer.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(%block;)"); } } else if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else { blockItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/BasicLink.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockOrInlineItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(#PCDATA|%inline;|%block;)"); } } else if (!isBlockOrInlineItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else { blockOrInlineItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/FootnoteBody.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/Leader.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ( localName.equals("leader") || localName.equals("inline-container") || localName.equals("block-container") || localName.equals("float") || localName.equals("marker") || !isInlineItem(nsURI, localName) ) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/InitialPropertySet.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/AbstractPageNumberCitation.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/ListBlock.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (hasListItem) { nodesOutOfOrderError(loc, "fo:marker", "fo:list-item"); } } else if (localName.equals("list-item")) { hasListItem = true; } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/Inline.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockOrInlineItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(#PCDATA|%inline;|%block;)"); } } else if (!isBlockOrInlineItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else if (!canHaveBlockLevelChildren && isBlockItem(nsURI, localName) && !isNeutralItem(nsURI, localName)) { invalidChildError(loc, getName(), nsURI, localName, "rule.inlineContent"); } else { blockOrInlineItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/MultiToggle.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!isBlockOrInlineItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/InstreamForeignObject.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } else if (firstChild != null) { tooManyNodesError(loc, new QName(nsURI, null, localName)); } }
// in src/java/org/apache/fop/fo/flow/ExternalGraphic.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/AbstractRetrieveMarker.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/MultiProperties.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("multi-property-set")) { if (hasWrapper) { nodesOutOfOrderError(loc, "fo:multi-property-set", "fo:wrapper"); } else { hasMultiPropertySet = true; } } else if (localName.equals("wrapper")) { if (hasWrapper) { tooManyNodesError(loc, "fo:wrapper"); } else { hasWrapper = true; } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/BlockContainer.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ("marker".equals(localName)) { if (commonAbsolutePosition.absolutePosition == EN_ABSOLUTE || commonAbsolutePosition.absolutePosition == EN_FIXED) { getFOValidationEventProducer() .markerBlockContainerAbsolutePosition(this, locator); } if (blockItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(%block;)"); } } else if (!isBlockItem(FO_URI, localName)) { invalidChildError(loc, FO_URI, localName); } else { blockItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/MultiPropertySet.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/Character.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/Footnote.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("inline")) { if (footnoteCitation != null) { tooManyNodesError(loc, "fo:inline"); } } else if (localName.equals("footnote-body")) { if (footnoteCitation == null) { nodesOutOfOrderError(loc, "fo:inline", "fo:footnote-body"); } else if (footnoteBody != null) { tooManyNodesError(loc, "fo:footnote-body"); } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/Marker.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!isBlockOrInlineItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/Marker.java
public void addAttributesToList(Attributes attributes) throws ValidationException { this.attribs = new MarkerAttribute[attributes.getLength()]; String name; String value; String namespace; String qname; for (int i = attributes.getLength(); --i >= 0;) { namespace = attributes.getURI(i); qname = attributes.getQName(i); name = attributes.getLocalName(i); value = attributes.getValue(i); this.attribs[i] = MarkerAttribute.getInstance(namespace, qname, name, value); } }
// in src/java/org/apache/fop/fo/flow/Block.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ("marker".equals(localName)) { if (blockOrInlineItemFound || initialPropertySetFound) { nodesOutOfOrderError(loc, "fo:marker", "initial-property-set? (#PCDATA|%inline;|%block;)"); } } else if ("initial-property-set".equals(localName)) { if (initialPropertySetFound) { tooManyNodesError(loc, "fo:initial-property-set"); } else if (blockOrInlineItemFound) { nodesOutOfOrderError(loc, "fo:initial-property-set", "(#PCDATA|%inline;|%block;)"); } else { initialPropertySetFound = true; } } else if (isBlockOrInlineItem(nsURI, localName)) { blockOrInlineItemFound = true; } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/table/TableRow.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ("marker".equals(localName)) { if (this.firstChild != null) { //a table-cell has already been added to this row nodesOutOfOrderError(loc, "fo:marker", "(table-cell+)"); } } else if (!"table-cell".equals(localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/table/TableCell.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(%block;)"); } } else if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else { blockItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/table/VariableColRowGroupBuilder.java
void endTablePart() throws ValidationException { // TODO catch the ValidationException sooner? events.add(new Event() { public void play(RowGroupBuilder rowGroupBuilder) throws ValidationException { rowGroupBuilder.endTablePart(); } }); }
// in src/java/org/apache/fop/fo/flow/table/VariableColRowGroupBuilder.java
public void play(RowGroupBuilder rowGroupBuilder) throws ValidationException { rowGroupBuilder.endTablePart(); }
// in src/java/org/apache/fop/fo/flow/table/VariableColRowGroupBuilder.java
void endTable() throws ValidationException { RowGroupBuilder delegate = new FixedColRowGroupBuilder(table); for (Iterator eventIter = events.iterator(); eventIter.hasNext();) { ((Event) eventIter.next()).play(delegate); } delegate.endTable(); }
// in src/java/org/apache/fop/fo/flow/table/FixedColRowGroupBuilder.java
void endTablePart() throws ValidationException { if (rows.size() > 0) { throw new ValidationException( "A table-cell is spanning more rows than available in its parent element."); } setFlagForCols(GridUnit.LAST_IN_PART, lastRow); borderResolver.endPart(); }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
protected void finishLastRowGroup() throws ValidationException { if (!inMarker()) { RowGroupBuilder rowGroupBuilder = getTable().getRowGroupBuilder(); if (tableRowsFound) { rowGroupBuilder.endTableRow(); } else if (!lastCellEndsRow) { rowGroupBuilder.endRow(this); } try { rowGroupBuilder.endTablePart(); } catch (ValidationException e) { e.setLocator(locator); throw e; } } }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (tableRowsFound || tableCellsFound) { nodesOutOfOrderError(loc, "fo:marker", "(table-row+|table-cell+)"); } } else if (localName.equals("table-row")) { tableRowsFound = true; if (tableCellsFound) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noMixRowsAndCells(this, getName(), getLocator()); } } else if (localName.equals("table-cell")) { tableCellsFound = true; if (tableRowsFound) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.noMixRowsAndCells(this, getName(), getLocator()); } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/table/TableColumn.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/flow/table/TableCaption.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(%block;)"); } } else if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else { blockItemFound = true; } } }
// in src/java/org/apache/fop/fo/flow/table/Table.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ("marker".equals(localName)) { if (tableColumnFound || tableHeaderFound || tableFooterFound || tableBodyFound) { nodesOutOfOrderError(loc, "fo:marker", "(table-column*,table-header?,table-footer?,table-body+)"); } } else if ("table-column".equals(localName)) { tableColumnFound = true; if (tableHeaderFound || tableFooterFound || tableBodyFound) { nodesOutOfOrderError(loc, "fo:table-column", "(table-header?,table-footer?,table-body+)"); } } else if ("table-header".equals(localName)) { if (tableHeaderFound) { tooManyNodesError(loc, "table-header"); } else { tableHeaderFound = true; if (tableFooterFound || tableBodyFound) { nodesOutOfOrderError(loc, "fo:table-header", "(table-footer?,table-body+)"); } } } else if ("table-footer".equals(localName)) { if (tableFooterFound) { tooManyNodesError(loc, "table-footer"); } else { tableFooterFound = true; if (tableBodyFound) { if (getUserAgent().validateStrictly()) { nodesOutOfOrderError(loc, "fo:table-footer", "(table-body+)", true); } if (!isSeparateBorderModel()) { TableEventProducer eventProducer = TableEventProducer.Provider.get( getUserAgent().getEventBroadcaster()); eventProducer.footerOrderCannotRecover(this, getName(), getLocator()); } } } } else if ("table-body".equals(localName)) { tableBodyFound = true; } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/table/TableAndCaption.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (tableCaptionFound) { nodesOutOfOrderError(loc, "fo:marker", "fo:table-caption"); } else if (tableFound) { nodesOutOfOrderError(loc, "fo:marker", "fo:table"); } } else if (localName.equals("table-caption")) { if (tableCaptionFound) { tooManyNodesError(loc, "fo:table-caption"); } else if (tableFound) { nodesOutOfOrderError(loc, "fo:table-caption", "fo:table"); } else { tableCaptionFound = true; } } else if (localName.equals("table")) { if (tableFound) { tooManyNodesError(loc, "fo:table"); } else { tableFound = true; } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/flow/MultiSwitch.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!localName.equals("multi-case")) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!localName.equals("simple-page-master") && !localName.equals("page-sequence-master")) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
private void checkRegionNames() throws ValidationException { // (user-entered) region-name to default region map. Map<String, String> allRegions = new java.util.HashMap<String, String>(); for (SimplePageMaster simplePageMaster : simplePageMasters.values()) { Map<String, Region> spmRegions = simplePageMaster.getRegions(); for (Region region : spmRegions.values()) { if (allRegions.containsKey(region.getRegionName())) { String defaultRegionName = allRegions.get(region.getRegionName()); if (!defaultRegionName.equals(region.getDefaultRegionName())) { getFOValidationEventProducer().regionNameMappedToMultipleRegionClasses(this, region.getRegionName(), defaultRegionName, region.getDefaultRegionName(), getLocator()); } } allRegions.put(region.getRegionName(), region.getDefaultRegionName()); } } }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
private void resolveSubSequenceReferences() throws ValidationException { for (PageSequenceMaster psm : pageSequenceMasters.values()) { for (SubSequenceSpecifier subSequenceSpecifier : psm.getSubSequenceSpecifier()) { subSequenceSpecifier.resolveReferences(this); } } }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
protected void addSimplePageMaster(SimplePageMaster sPM) throws ValidationException { // check for duplication of master-name String masterName = sPM.getMasterName(); if (existsName(masterName)) { getFOValidationEventProducer().masterNameNotUnique(this, getName(), masterName, sPM.getLocator()); } this.simplePageMasters.put(masterName, sPM); }
// in src/java/org/apache/fop/fo/pagination/LayoutMasterSet.java
protected void addPageSequenceMaster(String masterName, PageSequenceMaster pSM) throws ValidationException { // check against duplication of master-name if (existsName(masterName)) { getFOValidationEventProducer().masterNameNotUnique(this, getName(), masterName, pSM.getLocator()); } this.pageSequenceMasters.put(masterName, pSM); }
// in src/java/org/apache/fop/fo/pagination/Declarations.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!localName.equals("color-profile")) { invalidChildError(loc, nsURI, localName); } } // anything outside of XSL namespace is OK. }
// in src/java/org/apache/fop/fo/pagination/Root.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("layout-master-set")) { if (layoutMasterSet != null) { tooManyNodesError(loc, "fo:layout-master-set"); } } else if (localName.equals("declarations")) { if (layoutMasterSet == null) { nodesOutOfOrderError(loc, "fo:layout-master-set", "fo:declarations"); } else if (declarations != null) { tooManyNodesError(loc, "fo:declarations"); } else if (bookmarkTree != null) { nodesOutOfOrderError(loc, "fo:declarations", "fo:bookmark-tree"); } else if (pageSequenceFound) { nodesOutOfOrderError(loc, "fo:declarations", "fo:page-sequence"); } } else if (localName.equals("bookmark-tree")) { if (layoutMasterSet == null) { nodesOutOfOrderError(loc, "fo:layout-master-set", "fo:bookmark-tree"); } else if (bookmarkTree != null) { tooManyNodesError(loc, "fo:bookmark-tree"); } else if (pageSequenceFound) { nodesOutOfOrderError(loc, "fo:bookmark-tree", "fo:page-sequence"); } } else if (localName.equals("page-sequence")) { if (layoutMasterSet == null) { nodesOutOfOrderError(loc, "fo:layout-master-set", "fo:page-sequence"); } else { pageSequenceFound = true; } } else { invalidChildError(loc, nsURI, localName); } } else { if (FOX_URI.equals(nsURI)) { if ("external-document".equals(localName)) { pageSequenceFound = true; } } //invalidChildError(loc, nsURI, localName); //Ignore non-FO elements under root } }
// in src/java/org/apache/fop/fo/pagination/Root.java
protected void validateChildNode(Locator loc, FONode child) throws ValidationException { if (child instanceof AbstractPageSequence) { pageSequenceFound = true; } }
// in src/java/org/apache/fop/fo/pagination/SimplePageMaster.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("region-body")) { if (hasRegionBody) { tooManyNodesError(loc, "fo:region-body"); } else { hasRegionBody = true; } } else if (localName.equals("region-before")) { if (!hasRegionBody) { nodesOutOfOrderError(loc, "fo:region-body", "fo:region-before"); } else if (hasRegionBefore) { tooManyNodesError(loc, "fo:region-before"); } else if (hasRegionAfter) { nodesOutOfOrderError(loc, "fo:region-before", "fo:region-after"); } else if (hasRegionStart) { nodesOutOfOrderError(loc, "fo:region-before", "fo:region-start"); } else if (hasRegionEnd) { nodesOutOfOrderError(loc, "fo:region-before", "fo:region-end"); } else { hasRegionBefore = true; } } else if (localName.equals("region-after")) { if (!hasRegionBody) { nodesOutOfOrderError(loc, "fo:region-body", "fo:region-after"); } else if (hasRegionAfter) { tooManyNodesError(loc, "fo:region-after"); } else if (hasRegionStart) { nodesOutOfOrderError(loc, "fo:region-after", "fo:region-start"); } else if (hasRegionEnd) { nodesOutOfOrderError(loc, "fo:region-after", "fo:region-end"); } else { hasRegionAfter = true; } } else if (localName.equals("region-start")) { if (!hasRegionBody) { nodesOutOfOrderError(loc, "fo:region-body", "fo:region-start"); } else if (hasRegionStart) { tooManyNodesError(loc, "fo:region-start"); } else if (hasRegionEnd) { nodesOutOfOrderError(loc, "fo:region-start", "fo:region-end"); } else { hasRegionStart = true; } } else if (localName.equals("region-end")) { if (!hasRegionBody) { nodesOutOfOrderError(loc, "fo:region-body", "fo:region-end"); } else if (hasRegionEnd) { tooManyNodesError(loc, "fo:region-end"); } else { hasRegionEnd = true; } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/Flow.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("marker")) { if (blockItemFound) { nodesOutOfOrderError(loc, "fo:marker", "(%block;)"); } } else if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } else { blockItemFound = true; } } }
// in src/java/org/apache/fop/fo/pagination/StaticContent.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!isBlockItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/Title.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!isInlineItem(nsURI, localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { invalidChildError(loc, nsURI, localName); }
// in src/java/org/apache/fop/fo/pagination/ConditionalPageMasterReference.java
public void resolveReferences(LayoutMasterSet layoutMasterSet) throws ValidationException { master = layoutMasterSet.getSimplePageMaster(masterReference); if (master == null) { BlockLevelEventProducer.Provider.get( getUserAgent().getEventBroadcaster()) .noMatchingPageMaster(this, parent.getName(), masterReference, getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!localName.equals("conditional-page-master-reference")) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterAlternatives.java
public void resolveReferences(LayoutMasterSet layoutMasterSet) throws ValidationException { for (ConditionalPageMasterReference conditionalPageMasterReference : conditionalPageMasterRefs) { conditionalPageMasterReference.resolveReferences(layoutMasterSet); } }
// in src/java/org/apache/fop/fo/pagination/bookmarks/BookmarkTitle.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/pagination/bookmarks/Bookmark.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (localName.equals("bookmark-title")) { if (bookmarkTitle != null) { tooManyNodesError(loc, "fo:bookmark-title"); } } else if (localName.equals("bookmark")) { if (bookmarkTitle == null) { nodesOutOfOrderError(loc, "fo:bookmark-title", "fo:bookmark"); } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/bookmarks/BookmarkTree.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!localName.equals("bookmark")) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/SinglePageMasterReference.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/pagination/SinglePageMasterReference.java
public void resolveReferences(LayoutMasterSet layoutMasterSet) throws ValidationException { master = layoutMasterSet.getSimplePageMaster(masterReference); if (master == null) { BlockLevelEventProducer.Provider.get( getUserAgent().getEventBroadcaster()) .noMatchingPageMaster(this, parent.getName(), masterReference, getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/PageSequenceWrapper.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!(localName.equals("page-sequence") || localName.equals("page-sequence-wrapper"))) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/ColorProfile.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { invalidChildError(loc, nsURI, localName); }
// in src/java/org/apache/fop/fo/pagination/RepeatablePageMasterReference.java
public void resolveReferences(LayoutMasterSet layoutMasterSet) throws ValidationException { master = layoutMasterSet.getSimplePageMaster(masterReference); if (master == null) { BlockLevelEventProducer.Provider.get( getUserAgent().getEventBroadcaster()) .noMatchingPageMaster(this, parent.getName(), masterReference, getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/Region.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if ("title".equals(localName)) { if (titleFO != null) { tooManyNodesError(loc, "fo:title"); } else if (!flowMap.isEmpty()) { nodesOutOfOrderError(loc, "fo:title", "fo:static-content"); } else if (mainFlow != null) { nodesOutOfOrderError(loc, "fo:title", "fo:flow"); } } else if ("static-content".equals(localName)) { if (mainFlow != null) { nodesOutOfOrderError(loc, "fo:static-content", "fo:flow"); } } else if ("flow".equals(localName)) { if (mainFlow != null) { tooManyNodesError(loc, "fo:flow"); } } else { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/pagination/PageSequence.java
private void addFlow(Flow flow) throws ValidationException { String flowName = flow.getFlowName(); if (hasFlowName(flowName)) { getFOValidationEventProducer().duplicateFlowNameInPageSequence(this, flow.getName(), flowName, flow.getLocator()); } if (!getRoot().getLayoutMasterSet().regionNameExists(flowName) && !flowName.equals("xsl-before-float-separator") && !flowName.equals("xsl-footnote-separator")) { getFOValidationEventProducer().flowNameNotMapped(this, flow.getName(), flowName, flow.getLocator()); } }
// in src/java/org/apache/fop/fo/pagination/PageSequenceMaster.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { if (!"single-page-master-reference".equals(localName) && !"repeatable-page-master-reference".equals(localName) && !"repeatable-page-master-alternatives".equals(localName)) { invalidChildError(loc, nsURI, localName); } } }
// in src/java/org/apache/fop/fo/FObj.java
private void checkId(String id) throws ValidationException { if (!inMarker() && !id.equals("")) { Set idrefs = getBuilderContext().getIDReferences(); if (!idrefs.contains(id)) { idrefs.add(id); } else { getFOValidationEventProducer().idNotUnique(this, getName(), id, true, locator); } } }
// in src/java/org/apache/fop/fo/FONode.java
protected void validateChildNode( Locator loc, String namespaceURI, String localName) throws ValidationException { //nop }
// in src/java/org/apache/fop/fo/FONode.java
protected static void validateChildNode( FONode fo, Locator loc, String namespaceURI, String localName) throws ValidationException { fo.validateChildNode(loc, namespaceURI, localName); }
// in src/java/org/apache/fop/fo/FONode.java
protected void tooManyNodesError(Locator loc, String nsURI, String lName) throws ValidationException { tooManyNodesError(loc, new QName(nsURI, lName)); }
// in src/java/org/apache/fop/fo/FONode.java
protected void tooManyNodesError(Locator loc, QName offendingNode) throws ValidationException { getFOValidationEventProducer().tooManyNodes(this, getName(), offendingNode, loc); }
// in src/java/org/apache/fop/fo/FONode.java
protected void tooManyNodesError(Locator loc, String offendingNode) throws ValidationException { tooManyNodesError(loc, new QName(FO_URI, offendingNode)); }
// in src/java/org/apache/fop/fo/FONode.java
protected void nodesOutOfOrderError(Locator loc, String tooLateNode, String tooEarlyNode) throws ValidationException { nodesOutOfOrderError(loc, tooLateNode, tooEarlyNode, false); }
// in src/java/org/apache/fop/fo/FONode.java
protected void nodesOutOfOrderError(Locator loc, String tooLateNode, String tooEarlyNode, boolean canRecover) throws ValidationException { getFOValidationEventProducer().nodeOutOfOrder(this, getName(), tooLateNode, tooEarlyNode, canRecover, loc); }
// in src/java/org/apache/fop/fo/FONode.java
protected void invalidChildError(Locator loc, String nsURI, String lName) throws ValidationException { invalidChildError(loc, getName(), nsURI, lName, null); }
// in src/java/org/apache/fop/fo/FONode.java
protected void invalidChildError(Locator loc, String parentName, String nsURI, String lName, String ruleViolated) throws ValidationException { String prefix = getNodePrefix ( nsURI ); QName qn; // qualified name of offending node if ( prefix != null ) { qn = new QName(nsURI, prefix, lName); } else { qn = new QName(nsURI, lName); } getFOValidationEventProducer().invalidChild(this, parentName, qn, ruleViolated, loc); }
// in src/java/org/apache/fop/fo/FONode.java
protected void missingChildElementError(String contentModel) throws ValidationException { getFOValidationEventProducer().missingChildElement(this, getName(), contentModel, false, locator); }
// in src/java/org/apache/fop/fo/FONode.java
protected void missingChildElementError(String contentModel, boolean canRecover) throws ValidationException { getFOValidationEventProducer().missingChildElement(this, getName(), contentModel, canRecover, locator); }
// in src/java/org/apache/fop/fo/FONode.java
protected void missingPropertyError(String propertyName) throws ValidationException { getFOValidationEventProducer().missingProperty(this, getName(), propertyName, locator); }
// in src/java/org/apache/fop/fo/extensions/ExternalDocument.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { invalidChildError(loc, nsURI, localName); }
// in src/java/org/apache/fop/fo/extensions/destination/Destination.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { invalidChildError(loc, nsURI, localName); }
// in src/java/org/apache/fop/render/afp/extensions/AbstractAFPExtensionObject.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/render/ps/extensions/AbstractPSExtensionElement.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
// in src/java/org/apache/fop/render/ps/extensions/AbstractPSExtensionObject.java
protected void validateChildNode(Locator loc, String nsURI, String localName) throws ValidationException { if (FO_URI.equals(nsURI)) { invalidChildError(loc, nsURI, localName); } }
2
            
// in src/java/org/apache/fop/fo/flow/Wrapper.java
catch (ValidationException vex) { invalidChildError(loc, getName(), FO_URI, localName, "rule.wrapperInvalidChildForParent"); }
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
catch (ValidationException e) { e.setLocator(locator); throw e; }
1
            
// in src/java/org/apache/fop/fo/flow/table/TablePart.java
catch (ValidationException e) { e.setLocator(locator); throw e; }
0

Miscellanous Metrics

nF = Number of Finally 69
nF = Number of Try-Finally (without catch) 54
Number of Methods with Finally (nMF) 64 / 13847 (0.5%)
Number of Finally with a Continue 0
Number of Finally with a Return 0
Number of Finally with a Throw 0
Number of Finally with a Break 0
Number of different exception types thrown 41
Number of Domain exception types thrown 15
Number of different exception types caught 49
Number of Domain exception types caught 10
Number of exception declarations in signatures 2585
Number of different exceptions types declared in method signatures 45
Number of library exceptions types declared in method signatures 32
Number of Domain exceptions types declared in method signatures 13
Number of Catch with a continue 3
Number of Catch with a return 51
Number of Catch with a Break 0
nbIf = Number of If 10708
nbFor = Number of For 1344
Number of Method with an if 4074 / 13847
Number of Methods with a for 931 / 13847
Number of Method starting with a try 159 / 13847 (1.1%)
Number of Expressions 166580
Number of Expressions in try 9207 (5.5%)