Browse Source

Removed URI resolving class that are no longer needed and handled data URIs


git-svn-id: https://svn.apache.org/repos/asf/xmlgraphics/fop/branches/Temp_URI_Unification@1350248 13f79535-47bb-0310-9956-ffa450edef68
tags/fop-2_0
Mehdi Houshmand 12 years ago
parent
commit
d17d05e36c
29 changed files with 206 additions and 591 deletions
  1. 5
    24
      src/java/org/apache/fop/afp/AFPStreamer.java
  2. 12
    12
      src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java
  3. 2
    18
      src/java/org/apache/fop/apps/FOUserAgent.java
  4. 0
    12
      src/java/org/apache/fop/apps/FopConfParser.java
  5. 1
    34
      src/java/org/apache/fop/apps/FopFactory.java
  6. 0
    60
      src/java/org/apache/fop/apps/FopFactoryBuilder.java
  7. 0
    29
      src/java/org/apache/fop/apps/FopFactoryConfig.java
  8. 1
    1
      src/java/org/apache/fop/apps/io/ResourceResolverFactory.java
  9. 57
    0
      src/java/org/apache/fop/apps/io/TempResourceURIGenerator.java
  10. 23
    3
      src/java/org/apache/fop/apps/io/URIResolverWrapper.java
  11. 19
    28
      src/java/org/apache/fop/area/CachedRenderPagesModel.java
  12. 0
    2
      src/java/org/apache/fop/fo/extensions/svg/SVGElement.java
  13. 0
    38
      src/java/org/apache/fop/hyphenation/HyphenationTreeResolver.java
  14. 46
    100
      src/java/org/apache/fop/hyphenation/Hyphenator.java
  15. 2
    3
      src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java
  16. 0
    19
      src/java/org/apache/fop/pdf/PDFDocument.java
  17. 6
    56
      src/java/org/apache/fop/pdf/StreamCacheFactory.java
  18. 5
    15
      src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java
  19. 0
    1
      src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java
  20. 0
    8
      src/java/org/apache/fop/render/pcl/PCLGenerator.java
  21. 11
    12
      src/java/org/apache/fop/render/ps/PSDocumentHandler.java
  22. 10
    23
      src/java/org/apache/fop/util/ColorSpaceCache.java
  23. 2
    6
      src/java/org/apache/fop/util/ColorUtil.java
  24. 0
    8
      test/java/org/apache/fop/apps/FopConfParserTestCase.java
  25. 0
    59
      test/java/org/apache/fop/config/FOURIResolverTestCase.java
  26. 1
    2
      test/java/org/apache/fop/config/UserConfigTestSuite.java
  27. 0
    14
      test/java/org/apache/fop/fotreetest/FOTreeTestCase.java
  28. 2
    3
      test/java/org/apache/fop/util/ColorUtilTestCase.java
  29. 1
    1
      test/layoutengine/standard-testcases/external-graphic_rfc2397.xml

+ 5
- 24
src/java/org/apache/fop/afp/AFPStreamer.java View File

import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.URI; import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;
import java.util.concurrent.atomic.AtomicLong;


import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;


import org.apache.fop.afp.modca.ResourceGroup; import org.apache.fop.afp.modca.ResourceGroup;
import org.apache.fop.afp.modca.StreamedResourceGroup; import org.apache.fop.afp.modca.StreamedResourceGroup;
import org.apache.fop.apps.io.TempResourceURIGenerator;
import org.apache.fop.apps.io.URIResolverWrapper; import org.apache.fop.apps.io.URIResolverWrapper;


/** /**


private static final String DEFAULT_EXTERNAL_RESOURCE_FILENAME = "resources.afp"; private static final String DEFAULT_EXTERNAL_RESOURCE_FILENAME = "resources.afp";


private static final TempResourceURIGenerator TEMP_URI_GENERATOR
= new TempResourceURIGenerator("AFPDataStream_");

private final Factory factory; private final Factory factory;


private final URIResolverWrapper uriResolverWrapper; private final URIResolverWrapper uriResolverWrapper;
public AFPStreamer(Factory factory, URIResolverWrapper uriResolverWrapper) { public AFPStreamer(Factory factory, URIResolverWrapper uriResolverWrapper) {
this.factory = factory; this.factory = factory;
this.uriResolverWrapper = uriResolverWrapper; this.uriResolverWrapper = uriResolverWrapper;
this.tempUri = TempUriGenerator.INSTANCE.generate();
this.tempUri = TEMP_URI_GENERATOR.generate();
defaultResourceGroupUri = URI.create(DEFAULT_EXTERNAL_RESOURCE_FILENAME); defaultResourceGroupUri = URI.create(DEFAULT_EXTERNAL_RESOURCE_FILENAME);


} }
tempInputStream.close(); tempInputStream.close();
os.flush(); os.flush();
} }

private static final class TempUriGenerator {

private static final TempUriGenerator INSTANCE = new TempUriGenerator();

private static final String AFPDATASTREAM_TEMP_URL_PREFIX = "tmp:///AFPDataStream_";

private final AtomicLong counter;

private TempUriGenerator() {
counter = new AtomicLong();
}

public URI generate() {
try {
return new URI(AFPDATASTREAM_TEMP_URL_PREFIX + counter.getAndIncrement());
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
}
} }

+ 12
- 12
src/java/org/apache/fop/afp/fonts/CharacterSetBuilder.java View File

* @return an inputStream * @return an inputStream
* @throws IOException in the event that an I/O exception of some sort has occurred * @throws IOException in the event that an I/O exception of some sort has occurred
*/ */
protected InputStream openInputStream(AFPResourceAccessor accessor, String uriStr,
private InputStream openInputStream(AFPResourceAccessor accessor, String uriStr,
AFPEventProducer eventProducer) AFPEventProducer eventProducer)
throws IOException { throws IOException {
URI uri; URI uri;
* *
* @param inputStream the inputstream to close * @param inputStream the inputstream to close
*/ */
protected void closeInputStream(InputStream inputStream) {
private void closeInputStream(InputStream inputStream) {
try { try {
if (inputStream != null) { if (inputStream != null) {
inputStream.close(); inputStream.close();
* @return a class representing the font descriptor * @return a class representing the font descriptor
* @throws IOException if an I/O exception of some sort has occurred. * @throws IOException if an I/O exception of some sort has occurred.
*/ */
protected static FontDescriptor processFontDescriptor(
StructuredFieldReader structuredFieldReader)
throws IOException {
private static FontDescriptor processFontDescriptor(
StructuredFieldReader structuredFieldReader) throws IOException {


byte[] fndData = structuredFieldReader.getNext(FONT_DESCRIPTOR_SF); byte[] fndData = structuredFieldReader.getNext(FONT_DESCRIPTOR_SF);
return new FontDescriptor(fndData); return new FontDescriptor(fndData);
* @return the FontControl * @return the FontControl
* @throws IOException if an I/O exception of some sort has occurred. * @throws IOException if an I/O exception of some sort has occurred.
*/ */
protected FontControl processFontControl(StructuredFieldReader structuredFieldReader)
throws IOException {
private FontControl processFontControl(StructuredFieldReader structuredFieldReader)
throws IOException {


byte[] fncData = structuredFieldReader.getNext(FONT_CONTROL_SF); byte[] fncData = structuredFieldReader.getNext(FONT_CONTROL_SF);


* @return CharacterSetOrientation array * @return CharacterSetOrientation array
* @throws IOException if an I/O exception of some sort has occurred. * @throws IOException if an I/O exception of some sort has occurred.
*/ */
protected CharacterSetOrientation[] processFontOrientation(
private CharacterSetOrientation[] processFontOrientation(
StructuredFieldReader structuredFieldReader) throws IOException { StructuredFieldReader structuredFieldReader) throws IOException {


byte[] data = structuredFieldReader.getNext(FONT_ORIENTATION_SF); byte[] data = structuredFieldReader.getNext(FONT_ORIENTATION_SF);
* font metric values * font metric values
* @throws IOException if an I/O exception of some sort has occurred. * @throws IOException if an I/O exception of some sort has occurred.
*/ */
protected void processFontPosition(StructuredFieldReader structuredFieldReader,
private void processFontPosition(StructuredFieldReader structuredFieldReader,
CharacterSetOrientation[] characterSetOrientations, double metricNormalizationFactor) CharacterSetOrientation[] characterSetOrientations, double metricNormalizationFactor)
throws IOException { throws IOException {


* font metric values * font metric values
* @throws IOException if an I/O exception of some sort has occurred. * @throws IOException if an I/O exception of some sort has occurred.
*/ */
protected void processFontIndex(StructuredFieldReader structuredFieldReader,
private void processFontIndex(StructuredFieldReader structuredFieldReader,
CharacterSetOrientation cso, Map<String, String> codepage, CharacterSetOrientation cso, Map<String, String> codepage,
double metricNormalizationFactor) double metricNormalizationFactor)
throws IOException { throws IOException {
return INSTANCE; return INSTANCE;
} }


@Override
protected Map<String, String> loadCodePage(String codePage, String encoding, protected Map<String, String> loadCodePage(String codePage, String encoding,
AFPResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException { AFPResourceAccessor accessor, AFPEventProducer eventProducer) throws IOException {
// Create the HashMap to store code page information // Create the HashMap to store code page information
Map<String, String> codePages = new HashMap<String, String>(); Map<String, String> codePages = new HashMap<String, String>();
InputStream inputStream = null; InputStream inputStream = null;
try { try {
inputStream = openInputStream(accessor, codePage.trim(), eventProducer);
inputStream = super.openInputStream(accessor, codePage.trim(), eventProducer);
} catch (IOException e) { } catch (IOException e) {
eventProducer.codePageNotFound(this, e); eventProducer.codePageNotFound(this, e);
throw e; throw e;
} }
} }
} finally { } finally {
closeInputStream(inputStream);
super.closeInputStream(inputStream);
} }
return codePages; return codePages;
} }

+ 2
- 18
src/java/org/apache/fop/apps/FOUserAgent.java View File

import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;
import java.util.Date; import java.util.Date;
import java.util.Map; import java.util.Map;
import org.apache.xmlgraphics.image.loader.ImageSessionContext; import org.apache.xmlgraphics.image.loader.ImageSessionContext;
import org.apache.xmlgraphics.image.loader.impl.AbstractImageSessionContext; import org.apache.xmlgraphics.image.loader.impl.AbstractImageSessionContext;
import org.apache.xmlgraphics.util.UnitConv; import org.apache.xmlgraphics.util.UnitConv;
import org.apache.xmlgraphics.util.uri.CommonURIResolver;


import org.apache.fop.Version; import org.apache.fop.Version;
import org.apache.fop.accessibility.Accessibility; import org.apache.fop.accessibility.Accessibility;
import org.apache.fop.fo.ElementMappingRegistry; import org.apache.fop.fo.ElementMappingRegistry;
import org.apache.fop.fo.FOEventHandler; import org.apache.fop.fo.FOEventHandler;
import org.apache.fop.fonts.FontManager; import org.apache.fop.fonts.FontManager;
import org.apache.fop.hyphenation.HyphenationTreeResolver;
import org.apache.fop.layoutmgr.LayoutManagerMaker; import org.apache.fop.layoutmgr.LayoutManagerMaker;
import org.apache.fop.render.ImageHandlerRegistry; import org.apache.fop.render.ImageHandlerRegistry;
import org.apache.fop.render.Renderer; import org.apache.fop.render.Renderer;
setStructureTreeEventHandler(documentHandler.getStructureTreeEventHandler()); setStructureTreeEventHandler(documentHandler.getStructureTreeEventHandler());
} }
this.documentHandlerOverride = documentHandler; this.documentHandlerOverride = documentHandler;

} }


/** /**
public Source resolveURI(String uri) { public Source resolveURI(String uri) {
// TODO: What do we want to do when resources aren't found??? // TODO: What do we want to do when resources aren't found???
try { try {
Source src;
// Have to do this so we can resolve data URIs // Have to do this so we can resolve data URIs
if (uri.startsWith("data:")) {
CommonURIResolver uriResolver = new CommonURIResolver();
src = uriResolver.resolve(uri, "");
} else {
URI actualUri = URIResolverWrapper.cleanURI(uri);
src = new StreamSource(newUriResolver.resolveIn(actualUri));
src.setSystemId(uri);
}
Source src = new StreamSource(newUriResolver.resolveIn(uri));
src.setSystemId(uri);
return src; return src;
} catch (URISyntaxException use) { } catch (URISyntaxException use) {
return null; return null;
return factory.getColorSpaceCache(); return factory.getColorSpaceCache();
} }


/** @return the HyphenationTreeResolver for resolving user-supplied hyphenation patterns. */
public HyphenationTreeResolver getHyphenationTreeResolver() {
return factory.getHyphenationTreeResolver();
}

public Map<String, String> getHyphPatNames() { public Map<String, String> getHyphPatNames() {
return factory.getHyphPatNames(); return factory.getHyphPatNames();
} }

+ 0
- 12
src/java/org/apache/fop/apps/FopConfParser.java View File

} }
} }


if (cfg.getChild("hyphenation-base", false) != null) {
String path = cfg.getChild("hyphenation-base").getValue(null);
if (defaultBaseURI != null) {
try {
URI hyphBaseUri = URIResolverWrapper.getBaseURI(path);
fopFactoryBuilder.setHyphenationBaseURI(defaultBaseURI.resolve(hyphBaseUri));
} catch (URISyntaxException use) {
LogUtil.handleException(log, use, strict);
}
}
}

// renderer options // renderer options
if (cfg.getChild("source-resolution", false) != null) { if (cfg.getChild("source-resolution", false) != null) {
float srcRes = cfg.getChild("source-resolution").getValueAsFloat( float srcRes = cfg.getChild("source-resolution").getValueAsFloat(

+ 1
- 34
src/java/org/apache/fop/apps/FopFactory.java View File

import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;


import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;

import org.xml.sax.SAXException; import org.xml.sax.SAXException;


import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.Configuration;
import org.apache.fop.fo.ElementMapping; import org.apache.fop.fo.ElementMapping;
import org.apache.fop.fo.ElementMappingRegistry; import org.apache.fop.fo.ElementMappingRegistry;
import org.apache.fop.fonts.FontManager; import org.apache.fop.fonts.FontManager;
import org.apache.fop.hyphenation.HyphenationTreeResolver;
import org.apache.fop.layoutmgr.LayoutManagerMaker; import org.apache.fop.layoutmgr.LayoutManagerMaker;
import org.apache.fop.render.ImageHandlerRegistry; import org.apache.fop.render.ImageHandlerRegistry;
import org.apache.fop.render.RendererConfig; import org.apache.fop.render.RendererConfig;
this.config = config; this.config = config;
this.uriResolverWrapper = new URIResolverWrapper(config.getBaseURI(), config.getNewURIResolver()); this.uriResolverWrapper = new URIResolverWrapper(config.getBaseURI(), config.getNewURIResolver());
this.elementMappingRegistry = new ElementMappingRegistry(this); this.elementMappingRegistry = new ElementMappingRegistry(this);
this.colorSpaceCache = new ColorSpaceCache(config.getURIResolver());
this.colorSpaceCache = new ColorSpaceCache(uriResolverWrapper);
this.rendererFactory = new RendererFactory(config.preferRenderer()); this.rendererFactory = new RendererFactory(config.preferRenderer());
this.xmlHandlers = new XMLHandlerRegistry(); this.xmlHandlers = new XMLHandlerRegistry();
this.imageHandlers = new ImageHandlerRegistry(); this.imageHandlers = new ImageHandlerRegistry();
return config.getLayoutManagerMakerOverride(); return config.getLayoutManagerMakerOverride();
} }


/** @return the hyphen base URI */
public String getHyphenBaseURI() {
return config.getHyphenationBaseURI().toASCIIString();
}

/** @return the HyphenationTreeResolver for resolving user-supplied hyphenation patterns. */
public HyphenationTreeResolver getHyphenationTreeResolver() {
return config.getHyphenationTreeResolver();
}


public Map<String, String> getHyphPatNames() { public Map<String, String> getHyphPatNames() {
return config.getHyphPatNames(); return config.getHyphPatNames();
return config.getFontManager(); return config.getFontManager();
} }


/**
* Attempts to resolve the given URI.
* Will use the configured resolver and if not successful fall back
* to the default resolver.
* @param href URI to access
* @param baseUri the base URI to resolve against
* @return A {@link javax.xml.transform.Source} object, or null if the URI
* cannot be resolved.
* @see org.apache.fop.apps.io.FOURIResolver
*/
public Source resolveURI(String href, String baseUri) {
Source source = null;
try {
source = config.getURIResolver().resolve(href, baseUri);
} catch (TransformerException e) {
log.error("Attempt to resolve URI '" + href + "' failed: ", e);
}
return source;
}

/** /**
* Returns the color space cache for this instance. * Returns the color space cache for this instance.
* <p> * <p>

+ 0
- 60
src/java/org/apache/fop/apps/FopFactoryBuilder.java View File

import org.apache.xmlgraphics.image.loader.ImageContext; import org.apache.xmlgraphics.image.loader.ImageContext;
import org.apache.xmlgraphics.image.loader.ImageManager; import org.apache.xmlgraphics.image.loader.ImageManager;


import org.apache.fop.apps.io.FOURIResolver;
import org.apache.fop.apps.io.ResourceResolver; import org.apache.fop.apps.io.ResourceResolver;
import org.apache.fop.apps.io.ResourceResolverFactory; import org.apache.fop.apps.io.ResourceResolverFactory;
import org.apache.fop.fonts.FontManager; import org.apache.fop.fonts.FontManager;
import org.apache.fop.hyphenation.HyphenationTreeResolver;
import org.apache.fop.layoutmgr.LayoutManagerMaker; import org.apache.fop.layoutmgr.LayoutManagerMaker;


/** /**
return this; return this;
} }


/**
* Sets the base URI for hyphenation data.
*
* @param hyphenationBase the hyphenation-base-URI
* @return <code>this</code>
* @deprecated this will be phased out in favour of a unified URI resolution mechanism
*/
public FopFactoryBuilder setHyphenationBaseURI(URI hyphenationBase) {
fopFactoryConfigBuilder.setHyphenationBaseURI(hyphenationBase);
return this;
}

/**
* Sets the URI resolver specific to Hyphenation data.
*
* @param hyphResolver the hyphenation-URI-resolver
* @return <code>this</code>
* @deprecated this will be phased out in favour of a unified URI resolution mechanism
*/
public FopFactoryBuilder setHyphenationTreeResolver(
HyphenationTreeResolver hyphResolver) {
fopFactoryConfigBuilder.setHyphenationTreeResolver(hyphResolver);
return this;

}

/** /**
* Sets whether to perform strict validation on the FO used. * Sets whether to perform strict validation on the FO used.
* *


private URI baseURI; private URI baseURI;


private URI hyphenationBaseURI;

private HyphenationTreeResolver hyphenationTreeResolver;

private boolean hasStrictFOValidation = true; private boolean hasStrictFOValidation = true;


private boolean hasStrictUserValidation = FopFactoryConfig.DEFAULT_STRICT_USERCONFIG_VALIDATION; private boolean hasStrictUserValidation = FopFactoryConfig.DEFAULT_STRICT_USERCONFIG_VALIDATION;
this.enviro = enviro; this.enviro = enviro;
this.baseURI = enviro.getDefaultBaseURI(); this.baseURI = enviro.getDefaultBaseURI();
this.imageManager = new ImageManager(new ImageContextImpl(this)); this.imageManager = new ImageManager(new ImageContextImpl(this));
this.resolver = new FOURIResolver();
} }


/** {@inheritDoc} */ /** {@inheritDoc} */
return baseURI; return baseURI;
} }


/** {@inheritDoc} */
public URI getHyphenationBaseURI() {
return hyphenationBaseURI;
}

/** {@inheritDoc} */
public HyphenationTreeResolver getHyphenationTreeResolver() {
return hyphenationTreeResolver;
}

/** {@inheritDoc} */ /** {@inheritDoc} */
public boolean validateStrictly() { public boolean validateStrictly() {
return hasStrictFOValidation; return hasStrictFOValidation;


void setBaseURI(URI baseURI); void setBaseURI(URI baseURI);


void setHyphenationBaseURI(URI hyphenationBase);

void setHyphenationTreeResolver(HyphenationTreeResolver hyphResolver);

void setStrictFOValidation(boolean validateStrictly); void setStrictFOValidation(boolean validateStrictly);


void setStrictUserConfigValidation(boolean validateStrictly); void setStrictUserConfigValidation(boolean validateStrictly);
throwIllegalStateException(); throwIllegalStateException();
} }


public void setHyphenationTreeResolver(
HyphenationTreeResolver hyphResolver) {
throwIllegalStateException();
}

public void setStrictFOValidation(boolean validateStrictly) { public void setStrictFOValidation(boolean validateStrictly) {
throwIllegalStateException(); throwIllegalStateException();
} }
config.baseURI = baseURI; config.baseURI = baseURI;
} }


public void setHyphenationBaseURI(URI hyphenationBase) {
config.hyphenationBaseURI = hyphenationBase;
}

public void setHyphenationTreeResolver(HyphenationTreeResolver hyphResolver) {
config.hyphenationTreeResolver = hyphResolver;
}

public void setStrictFOValidation(boolean validateStrictly) { public void setStrictFOValidation(boolean validateStrictly) {
config.hasStrictFOValidation = validateStrictly; config.hasStrictFOValidation = validateStrictly;
} }

+ 0
- 29
src/java/org/apache/fop/apps/FopFactoryConfig.java View File

import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;


import javax.xml.transform.URIResolver;

import org.apache.avalon.framework.configuration.Configuration; import org.apache.avalon.framework.configuration.Configuration;


import org.apache.xmlgraphics.image.loader.ImageManager; import org.apache.xmlgraphics.image.loader.ImageManager;


import org.apache.fop.apps.io.ResourceResolver; import org.apache.fop.apps.io.ResourceResolver;
import org.apache.fop.fonts.FontManager; import org.apache.fop.fonts.FontManager;
import org.apache.fop.hyphenation.HyphenationTreeResolver;
import org.apache.fop.layoutmgr.LayoutManagerMaker; import org.apache.fop.layoutmgr.LayoutManagerMaker;


/** /**
*/ */
ResourceResolver getNewURIResolver(); ResourceResolver getNewURIResolver();


/**
* The URI resolver for controlling file access.
*
* @return the URI resolver
* @deprecated please use the {@link #getNewURIResolver()} method.
*/
URIResolver getURIResolver();

/** /**
* The base URI from which URIs are resolved against. * The base URI from which URIs are resolved against.
* *
*/ */
URI getBaseURI(); URI getBaseURI();


/**
* The base URI of hyphenation data.
*
* @return the hyphenation-base-URI
* @deprecated this intelligence can be configured in the URI resolver set in
* {@link #getNewURIResolver()}
*/
URI getHyphenationBaseURI();

/**
* The URI resolver for resolving hyphenation data.
*
* @return the hyphenation-URI-resolver
* @deprecated this intelligence can be configured in the URI resolver set in
* {@link #getNewURIResolver()}
*/
HyphenationTreeResolver getHyphenationTreeResolver();

/** @see {@link FopFactory#validateStrictly()} */ /** @see {@link FopFactory#validateStrictly()} */
boolean validateStrictly(); boolean validateStrictly();



+ 1
- 1
src/java/org/apache/fop/apps/io/ResourceResolverFactory.java View File

} }


private static boolean isTempUri(URI uri) { private static boolean isTempUri(URI uri) {
return "tmp".equals(uri.getScheme());
return TempResourceURIGenerator.isTempUri(uri);
} }


public Resource getResource(URI uri) throws IOException { public Resource getResource(URI uri) throws IOException {

+ 57
- 0
src/java/org/apache/fop/apps/io/TempResourceURIGenerator.java View File

/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.apache.fop.apps.io;

import java.net.URI;
import java.util.concurrent.atomic.AtomicLong;

/**
* Creates a URI for any temporary resource used within FOP.
*/
public final class TempResourceURIGenerator {

private static final String TMP_SCHEMA = "tmp";

private final String tempURIPrefix;

private final AtomicLong counter;

/**
* @param uriPrefix a prefix used to name the unique URI
*/
public TempResourceURIGenerator(String uriPrefix) {
counter = new AtomicLong();
tempURIPrefix = URI.create(TMP_SCHEMA + ":///" + uriPrefix).toASCIIString();
}

/**
* Generate a unique URI for a temporary resource
* @return the URI
*/
public URI generate() {
return URI.create(tempURIPrefix + getUniqueId());
}

private String getUniqueId() {
return Long.toHexString(counter.getAndIncrement());
}

public static boolean isTempUri(URI uri) {
return TMP_SCHEMA.equals(uri.getScheme());
}
}

+ 23
- 3
src/java/org/apache/fop/apps/io/URIResolverWrapper.java View File

import java.net.URI; import java.net.URI;
import java.net.URISyntaxException; import java.net.URISyntaxException;


import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import javax.xml.transform.stream.StreamSource;

import org.apache.xmlgraphics.util.uri.DataURIResolver;


public class URIResolverWrapper { public class URIResolverWrapper {
private final URI baseUri; private final URI baseUri;
private final ResourceResolver uriResolver; private final ResourceResolver uriResolver;
private final DataURIResolver dataSchemeResolver = new DataURIResolver();


public URIResolverWrapper(URI baseUri, ResourceResolver uriResolver) { public URIResolverWrapper(URI baseUri, ResourceResolver uriResolver) {
this.baseUri = baseUri; this.baseUri = baseUri;
} }


public InputStream resolveIn(String stringUri) throws IOException, URISyntaxException { public InputStream resolveIn(String stringUri) throws IOException, URISyntaxException {
if (stringUri.startsWith("data:")) {
return resolveDataURI(stringUri);
}
return resolveIn(cleanURI(stringUri)); return resolveIn(cleanURI(stringUri));
} }


public InputStream resolveIn(URI uri) throws IOException { public InputStream resolveIn(URI uri) throws IOException {
if (uri.getScheme() != null && uri.getScheme().startsWith("data")) {
return resolveDataURI(uri.toASCIIString());
}
return uriResolver.getResource(resolveFromBase(uri)); return uriResolver.getResource(resolveFromBase(uri));
} }


return baseUri.resolve(uri); return baseUri.resolve(uri);
} }


public static URI cleanURI(String base) throws URISyntaxException {
public static URI cleanURI(String uriStr) throws URISyntaxException {
// replace back slash with forward slash to ensure windows file:/// URLS are supported // replace back slash with forward slash to ensure windows file:/// URLS are supported
if (base == null) {
if (uriStr == null) {
return null; return null;
} }
String fixedUri = base.replace('\\', '/');
String fixedUri = uriStr.replace('\\', '/');
fixedUri = fixedUri.replace(" ", "%20"); fixedUri = fixedUri.replace(" ", "%20");
URI baseURI = new URI(fixedUri); URI baseURI = new URI(fixedUri);
return baseURI; return baseURI;
return cleanURI(path); return cleanURI(path);
} }


private InputStream resolveDataURI(String dataURI) {
try {
Source src = dataSchemeResolver.resolve(dataURI, "");
return src == null ? null : ((StreamSource) src).getInputStream();
} catch (TransformerException e) {
throw new RuntimeException(e);
}
}
} }

+ 19
- 28
src/java/org/apache/fop/area/CachedRenderPagesModel.java View File



import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream; import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; import java.io.ObjectOutputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.URI;
import java.util.HashMap; import java.util.HashMap;
import java.util.Iterator; import java.util.Iterator;
import java.util.Map; import java.util.Map;


import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;


import org.apache.fop.ResourceEventProducer;
import org.apache.fop.apps.FOPException; import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent; import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.io.TempResourceURIGenerator;
import org.apache.fop.fonts.FontInfo; import org.apache.fop.fonts.FontInfo;


/** /**
*/ */
public class CachedRenderPagesModel extends RenderPagesModel { public class CachedRenderPagesModel extends RenderPagesModel {


private Map<PageViewport, String> pageMap = new HashMap<PageViewport, String>();
private Map<PageViewport, URI> pageMap = new HashMap<PageViewport, URI>();


/** Base directory to save temporary file in, typically points to the user's temp dir. */ /** Base directory to save temporary file in, typically points to the user's temp dir. */
protected File baseDir;
private final URI tempBaseURI;
private static final TempResourceURIGenerator TEMP_URI_GENERATOR
= new TempResourceURIGenerator("cached-pages");


/** /**
* Main Constructor * Main Constructor
public CachedRenderPagesModel (FOUserAgent userAgent, String outputFormat, public CachedRenderPagesModel (FOUserAgent userAgent, String outputFormat,
FontInfo fontInfo, OutputStream stream) throws FOPException { FontInfo fontInfo, OutputStream stream) throws FOPException {
super(userAgent, outputFormat, fontInfo, stream); super(userAgent, outputFormat, fontInfo, stream);
//TODO: Avoid System.getProperty()?
this.baseDir = new File(System.getProperty("java.io.tmpdir"));
tempBaseURI = TEMP_URI_GENERATOR.generate();
} }


/** {@inheritDoc} */ /** {@inheritDoc} */
if (pageViewport != newpage) { if (pageViewport != newpage) {
try { try {
// load page from cache // load page from cache
String name = pageMap.get(pageViewport);
File tempFile = new File(baseDir, name);
log.debug("Loading page from: " + tempFile);
ObjectInputStream in = new ObjectInputStream(
new BufferedInputStream(
new FileInputStream(tempFile)));
URI tempURI = pageMap.get(pageViewport);
log.debug("Loading page from: " + tempURI);
InputStream inStream = renderer.getUserAgent().getNewURIResolver().resolveIn(tempURI);
ObjectInputStream in = new ObjectInputStream(new BufferedInputStream(inStream));
try { try {
pageViewport.loadPage(in); pageViewport.loadPage(in);
} finally { } finally {
IOUtils.closeQuietly(inStream);
IOUtils.closeQuietly(in); IOUtils.closeQuietly(in);
} }
if (!tempFile.delete()) {
ResourceEventProducer eventProducer
= ResourceEventProducer.Provider.get(
renderer.getUserAgent().getEventBroadcaster());
eventProducer.cannotDeleteTempFile(this, tempFile);
}
pageMap.remove(pageViewport); pageMap.remove(pageViewport);
} catch (Exception e) { } catch (Exception e) {
AreaEventProducer eventProducer
= AreaEventProducer.Provider.get(
AreaEventProducer eventProducer = AreaEventProducer.Provider.get(
renderer.getUserAgent().getEventBroadcaster()); renderer.getUserAgent().getEventBroadcaster());
eventProducer.pageLoadError(this, pageViewport.getPageNumberString(), e); eventProducer.pageLoadError(this, pageViewport.getPageNumberString(), e);
} }
// save page to cache // save page to cache
ObjectOutputStream tempstream; ObjectOutputStream tempstream;
String fname = "fop-page-" + page.getPageIndex() + ".ser"; String fname = "fop-page-" + page.getPageIndex() + ".ser";
File tempFile = new File(baseDir, fname);
tempFile.deleteOnExit();
tempstream = new ObjectOutputStream(new BufferedOutputStream(
new FileOutputStream(tempFile)));
URI tempURI = tempBaseURI.resolve(fname);
OutputStream outStream = renderer.getUserAgent().getNewURIResolver().resolveOut(tempURI);
tempstream = new ObjectOutputStream(new BufferedOutputStream(outStream));
try { try {
page.savePage(tempstream); page.savePage(tempstream);
} finally { } finally {
IOUtils.closeQuietly(tempstream); IOUtils.closeQuietly(tempstream);
} }
pageMap.put(page, fname);
pageMap.put(page, tempURI);
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Page saved to temporary file: " + tempFile);
log.debug("Page saved to temporary file: " + tempURI);
} }
} catch (IOException ioe) { } catch (IOException ioe) {
AreaEventProducer eventProducer AreaEventProducer eventProducer

+ 0
- 2
src/java/org/apache/fop/fo/extensions/svg/SVGElement.java View File

import java.awt.geom.AffineTransform; import java.awt.geom.AffineTransform;
import java.awt.geom.Point2D; import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D; import java.awt.geom.Rectangle2D;
import java.io.File;
import java.net.URI; import java.net.URI;


import org.w3c.dom.Element; import org.w3c.dom.Element;


try { try {
URI baseUri = getUserAgent().getNewURIResolver().getBaseURI(); URI baseUri = getUserAgent().getNewURIResolver().getBaseURI();
baseUri = baseUri == null ? new File("").toURI() : baseUri;
if (baseUri != null) { if (baseUri != null) {
SVGOMDocument svgdoc = (SVGOMDocument)doc; SVGOMDocument svgdoc = (SVGOMDocument)doc;
svgdoc.setURLObject(baseUri.toURL()); svgdoc.setURLObject(baseUri.toURL());

+ 0
- 38
src/java/org/apache/fop/hyphenation/HyphenationTreeResolver.java View File

/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/* $Id$ */

package org.apache.fop.hyphenation;

import javax.xml.transform.Source;

/**
* <p>This interface is used to resolve relative URIs pointing to hyphenation tree files.</p>
*/
public interface HyphenationTreeResolver {

/**
* Called to resolve an URI to a Source instance. The base URI needed by the URIResolver's
* resolve() method is defined to be implicitely available in this case. If the URI cannot
* be resolved, null is returned.
* @param href An href attribute, which may be relative or absolute.
* @return A Source object, or null if the href could not resolved.
*/
Source resolve(String href);

}

+ 46
- 100
src/java/org/apache/fop/hyphenation/Hyphenator.java View File

package org.apache.fop.hyphenation; package org.apache.fop.hyphenation;


import java.io.BufferedInputStream; import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.ObjectInputStream; import java.io.ObjectInputStream;
import java.net.URISyntaxException;
import java.util.Map; import java.util.Map;


import javax.xml.transform.Source;
import javax.xml.transform.stream.StreamSource;

import org.xml.sax.InputSource; import org.xml.sax.InputSource;


import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;


import org.apache.fop.apps.io.URIResolverWrapper;

/** /**
* <p>This class is the main entry point to the hyphenation package. * <p>This class is the main entry point to the hyphenation package.
* You can use only the static methods or create an instance.</p> * You can use only the static methods or create an instance.</p>
* @return the hyphenation tree * @return the hyphenation tree
*/ */
public static HyphenationTree getHyphenationTree(String lang, public static HyphenationTree getHyphenationTree(String lang,
String country, HyphenationTreeResolver resolver, Map hyphPatNames) {
String country, URIResolverWrapper resolver, Map hyphPatNames) {
String llccKey = HyphenationTreeCache.constructLlccKey(lang, country); String llccKey = HyphenationTreeCache.constructLlccKey(lang, country);
HyphenationTreeCache cache = getHyphenationTreeCache(); HyphenationTreeCache cache = getHyphenationTreeCache();


* @param hyphPatNames the map with user-configured hyphenation pattern file names * @param hyphPatNames the map with user-configured hyphenation pattern file names
* @return the hyphenation tree * @return the hyphenation tree
*/ */
private static HyphenationTree getHyphenationTree2(String lang,
String country, HyphenationTreeResolver resolver, Map hyphPatNames) {
public static HyphenationTree getHyphenationTree2(String lang,
String country, URIResolverWrapper resolver, Map hyphPatNames) {
String llccKey = HyphenationTreeCache.constructLlccKey(lang, country); String llccKey = HyphenationTreeCache.constructLlccKey(lang, country);
HyphenationTreeCache cache = getHyphenationTreeCache(); HyphenationTreeCache cache = getHyphenationTreeCache();


return hTree; return hTree;
} }


/**
* Load tree from serialized file or xml file
* using configuration settings
* @param key language key for the requested hyphenation file
* @param hyphenDir base directory to find hyphenation files in
* @return the requested HypenationTree or null if it is not available
*/
public static HyphenationTree getUserHyphenationTree(String key,
String hyphenDir) {
final File baseDir = new File(hyphenDir);
HyphenationTreeResolver resolver = new HyphenationTreeResolver() {
public Source resolve(String href) {
File f = new File(baseDir, href);
return new StreamSource(f);
}
};
return getUserHyphenationTree(key, resolver);
}

/** /**
* Load tree from serialized file or xml file * Load tree from serialized file or xml file
* using configuration settings * using configuration settings
* @return the requested HypenationTree or null if it is not available * @return the requested HypenationTree or null if it is not available
*/ */
public static HyphenationTree getUserHyphenationTree(String key, public static HyphenationTree getUserHyphenationTree(String key,
HyphenationTreeResolver resolver) {
URIResolverWrapper resolver) {
HyphenationTree hTree = null; HyphenationTree hTree = null;
// I use here the following convention. The file name specified in // I use here the following convention. The file name specified in
// the configuration is taken as the base name. First we try // the configuration is taken as the base name. First we try


// first try serialized object // first try serialized object
String name = key + ".hyp"; String name = key + ".hyp";
Source source = resolver.resolve(name);
if (source != null) {
try {
InputStream in = getHyphenationTreeStream(name, resolver);
try { 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);
}
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 // try the raw XML file
name = key + ".xml"; name = key + ".xml";
source = resolver.resolve(name);
if (source != null) {
hTree = new HyphenationTree();
hTree = new HyphenationTree();
try {
InputStream in = getHyphenationTreeStream(name, resolver);
try { 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;
InputSource src = new InputSource(in);
src.setSystemId(name);
hTree.loadPatterns(src);
} finally {
IOUtils.closeQuietly(in);
}
if (statisticsDump) {
System.out.println("Stats: ");
hTree.printStats();
} }
} else {
return hTree;
} catch (HyphenationException ex) {
log.error("Can't load user patterns from XML file " + name + ": " + ex.getMessage());
return null;
} catch (IOException ioe) {
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
log.debug("Could not load user hyphenation file for '" + key + "'.");
log.debug("I/O problem while trying to load " + name, ioe);
} }
return null; return null;
} }
} }


private static InputStream getHyphenationTreeStream(String name, URIResolverWrapper resolver)
throws IOException {
try {
return new BufferedInputStream(resolver.resolveIn(name));
} catch (URISyntaxException use) {
log.debug("An exception was thrown while attempting to load " + name, use);
}
return null;
}

/** /**
* Hyphenates a word. * Hyphenates a word.
* @param lang the language * @param lang the language
* @return the hyphenation result * @return the hyphenation result
*/ */
public static Hyphenation hyphenate(String lang, String country, public static Hyphenation hyphenate(String lang, String country,
HyphenationTreeResolver resolver,
Map hyphPatNames,
String word,
int leftMin, int rightMin) {
URIResolverWrapper resolver, Map hyphPatNames, String word, int leftMin, int rightMin) {
HyphenationTree hTree = getHyphenationTree(lang, country, resolver, hyphPatNames); HyphenationTree hTree = getHyphenationTree(lang, country, resolver, hyphPatNames);
if (hTree == null) { if (hTree == null) {
return null; return null;
} }
return hTree.hyphenate(word, leftMin, rightMin); return hTree.hyphenate(word, leftMin, rightMin);
} }

} }

+ 2
- 3
src/java/org/apache/fop/layoutmgr/inline/LineLayoutManager.java View File

// TextLM which generate the hyphenation buffer, // TextLM which generate the hyphenation buffer,
// since these properties inherit and could be specified // since these properties inherit and could be specified
// on an inline or wrapper below the block level. // on an inline or wrapper below the block level.
Hyphenation hyph
= Hyphenator.hyphenate(hyphenationProperties.language.getString(),
Hyphenation hyph = Hyphenator.hyphenate(hyphenationProperties.language.getString(),
hyphenationProperties.country.getString(), hyphenationProperties.country.getString(),
getFObj().getUserAgent().getHyphenationTreeResolver(),
getFObj().getUserAgent().getNewURIResolver(),
getFObj().getUserAgent().getHyphPatNames(), getFObj().getUserAgent().getHyphPatNames(),
sbChars.toString(), sbChars.toString(),
hyphenationProperties.hyphenationRemainCharacterCount.getValue(), hyphenationProperties.hyphenationRemainCharacterCount.getValue(),

+ 0
- 19
src/java/org/apache/fop/pdf/PDFDocument.java View File



// Java // Java
import java.io.IOException; import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.io.UnsupportedEncodingException; import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException; import java.security.NoSuchAlgorithmException;
return this.fontMap; return this.fontMap;
} }


/**
* Resolve a URI.
*
* @param uri the uri to resolve
* @throws java.io.FileNotFoundException if the URI could not be resolved
* @return the InputStream from the URI.
*/
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);
}
}

/** /**
* Get an image from the image map. * Get an image from the image map.
* *

+ 6
- 56
src/java/org/apache/fop/pdf/StreamCacheFactory.java View File

/** /**
* This class is serves as a factory from * This class is serves as a factory from
*/ */
public class StreamCacheFactory {
public final class StreamCacheFactory {


private static boolean defaultCacheToFile = false;
private static StreamCacheFactory fileInstance = null;
private static StreamCacheFactory memoryInstance = null;

private boolean cacheToFile = false;
private static StreamCacheFactory memoryInstance = new StreamCacheFactory();


/** /**
* Returns an instance of a StreamCacheFactory with the requested features. * Returns an instance of a StreamCacheFactory with the requested features.
* @param cacheToFile True if file shall be cached using a temporary file * @param cacheToFile True if file shall be cached using a temporary file
* @return StreamCacheFactory the requested factory * @return StreamCacheFactory the requested factory
*/ */
public static StreamCacheFactory getInstance(boolean cacheToFile) {
if (cacheToFile) {
if (fileInstance == null) {
fileInstance = new StreamCacheFactory(true);
}
return fileInstance;
} else {
if (memoryInstance == null) {
memoryInstance = new StreamCacheFactory(false);
}
return memoryInstance;
}
}

/**
* Returns an instance of a StreamCacheFactory depending on the default
* setting for cacheToFile.
* @return StreamCacheFactory the requested factory
*/
public static StreamCacheFactory getInstance() { public static StreamCacheFactory getInstance() {
return getInstance(defaultCacheToFile);
}

/**
* Sets the global default for cacheToFile
* @param cacheToFile True if stream caches should be held in files.
*/
public static void setDefaultCacheToFile(boolean cacheToFile) {
defaultCacheToFile = cacheToFile;
return memoryInstance;
} }


/** /**
* Creates a new StreamCacheFactory. * Creates a new StreamCacheFactory.
* @param cacheToFile True if file shall be cached using a temporary file * @param cacheToFile True if file shall be cached using a temporary file
*/ */
public StreamCacheFactory(boolean cacheToFile) {
this.cacheToFile = cacheToFile;
private StreamCacheFactory() {
} }


/** /**
* @return a new StreamCache for caching streams * @return a new StreamCache for caching streams
*/ */
public StreamCache createStreamCache() throws IOException { public StreamCache createStreamCache() throws IOException {
if (this.cacheToFile) {
return new TempFileStreamCache();
} else {
return new InMemoryStreamCache();
}
return new InMemoryStreamCache();
} }


/** /**
* @return a new StreamCache for caching streams * @return a new StreamCache for caching streams
*/ */
public StreamCache createStreamCache(int hintSize) throws IOException { public StreamCache createStreamCache(int hintSize) throws IOException {
if (this.cacheToFile) {
return new TempFileStreamCache();
} else {
return new InMemoryStreamCache(hintSize);
}
}

/**
* Get the value of the global cacheToFile flag.
* @return the current cache to file flag
*/
public boolean getCacheToFile() {
return this.cacheToFile;
return new InMemoryStreamCache(hintSize);
} }


} }

+ 5
- 15
src/java/org/apache/fop/render/intermediate/AbstractBinaryWritingIFDocumentHandler.java View File



package org.apache.fop.render.intermediate; package org.apache.fop.render.intermediate;


import java.io.File;
import java.io.BufferedOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.URL;
import java.net.URI;


import javax.xml.transform.Result; import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamResult;


import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils; import org.apache.commons.io.IOUtils;


import org.apache.fop.fonts.FontCollection; import org.apache.fop.fonts.FontCollection;
/** {@inheritDoc} */ /** {@inheritDoc} */
public void setResult(Result result) throws IFException { public void setResult(Result result) throws IFException {
if (result instanceof StreamResult) { if (result instanceof StreamResult) {
StreamResult streamResult = (StreamResult)result;
StreamResult streamResult = (StreamResult) result;
OutputStream out = streamResult.getOutputStream(); OutputStream out = streamResult.getOutputStream();
if (out == null) { if (out == null) {
if (streamResult.getWriter() != null) { if (streamResult.getWriter() != null) {
"FOP cannot use a Writer. Please supply an OutputStream!"); "FOP cannot use a Writer. Please supply an OutputStream!");
} }
try { 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();
}
URI resultURI = URI.create(streamResult.getSystemId());
out = new BufferedOutputStream(getUserAgent().getNewURIResolver().resolveOut(resultURI));
} catch (IOException ioe) { } catch (IOException ioe) {
throw new IFException("I/O error while opening output stream" , ioe); throw new IFException("I/O error while opening output stream" , ioe);
} }
out = new java.io.BufferedOutputStream(out);
this.ownOutputStream = true; this.ownOutputStream = true;
} }
if (out == null) {
throw new IllegalArgumentException("Need a StreamResult with an OutputStream");
}
this.outputStream = out; this.outputStream = out;
} else { } else {
throw new UnsupportedOperationException( throw new UnsupportedOperationException(

+ 0
- 1
src/java/org/apache/fop/render/pcl/PCLDocumentHandler.java View File

public void endPageContent() throws IFException { public void endPageContent() throws IFException {
if (this.currentImage != null) { if (this.currentImage != null) {
try { try {
//ImageWriterUtil.saveAsPNG(this.currentImage, new java.io.File("D:/page.png"));
Rectangle printArea = this.currentPageDefinition.getLogicalPageRect(); Rectangle printArea = this.currentPageDefinition.getLogicalPageRect();
gen.setCursorPos(0, 0); gen.setCursorPos(0, 0);
gen.paintBitmap(this.currentImage, printArea.getSize(), true); gen.paintBitmap(this.currentImage, printArea.getSize(), true);

+ 0
- 8
src/java/org/apache/fop/render/pcl/PCLGenerator.java View File

} finally { } finally {
g2d.dispose(); g2d.dispose();
} }
/*
try {
BatchDiffer.saveAsPNG(alpha, new java.io.File("D:/out-alpha.png"));
BatchDiffer.saveAsPNG(mask, new java.io.File("D:/out-mask.png"));
} catch (IOException e) {
e.printStackTrace();
}*/
return mask; return mask;
} else { } else {
return null; return null;
(int)Math.ceil(UnitConv.mpt2px(targetDim.height, effResolution))); (int)Math.ceil(UnitConv.mpt2px(targetDim.height, effResolution)));
} }
boolean scaled = !orgDim.equals(effDim); boolean scaled = !orgDim.equals(effDim);
//ImageWriterUtil.saveAsPNG(img, new java.io.File("D:/text-0-org.png"));


boolean monochrome = isMonochromeImage(img); boolean monochrome = isMonochromeImage(img);
if (!monochrome) { if (!monochrome) {

+ 11
- 12
src/java/org/apache/fop/render/ps/PSDocumentHandler.java View File

import java.awt.Dimension; import java.awt.Dimension;
import java.awt.geom.Dimension2D; import java.awt.geom.Dimension2D;
import java.awt.geom.Rectangle2D; import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException; import java.io.IOException;
import java.io.InputStream; import java.io.InputStream;
import java.io.OutputStream; import java.io.OutputStream;
import java.net.URI;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
import org.apache.xmlgraphics.ps.dsc.events.DSCCommentHiResBoundingBox; import org.apache.xmlgraphics.ps.dsc.events.DSCCommentHiResBoundingBox;


import org.apache.fop.apps.MimeConstants; import org.apache.fop.apps.MimeConstants;
import org.apache.fop.apps.io.TempResourceURIGenerator;
import org.apache.fop.render.intermediate.AbstractBinaryWritingIFDocumentHandler; import org.apache.fop.render.intermediate.AbstractBinaryWritingIFDocumentHandler;
import org.apache.fop.render.intermediate.IFContext; import org.apache.fop.render.intermediate.IFContext;
import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator; import org.apache.fop.render.intermediate.IFDocumentHandlerConfigurator;
protected PSGenerator gen; protected PSGenerator gen;


/** the temporary file in case of two-pass processing */ /** the temporary file in case of two-pass processing */
private File tempFile;
private URI tempURI;
private static final TempResourceURIGenerator TEMP_URI_GENERATOR
= new TempResourceURIGenerator("ps-optimize");


private int currentPageNumber = 0; private int currentPageNumber = 0;
private PageDefinition currentPageDefinition; private PageDefinition currentPageDefinition;
super.startDocument(); super.startDocument();
this.fontResources = new FontResourceCache(getFontInfo()); this.fontResources = new FontResourceCache(getFontInfo());
try { try {
OutputStream out;
final OutputStream out;
if (psUtil.isOptimizeResources()) { if (psUtil.isOptimizeResources()) {
this.tempFile = File.createTempFile("fop", null);
out = new java.io.FileOutputStream(this.tempFile);
out = new java.io.BufferedOutputStream(out);
tempURI = TEMP_URI_GENERATOR.generate();
out = new BufferedOutputStream(getUserAgent().getNewURIResolver().resolveOut(tempURI));
} else { } else {
out = this.outputStream; out = this.outputStream;
} }
log.debug("Processing PostScript resources..."); log.debug("Processing PostScript resources...");
long startTime = System.currentTimeMillis(); long startTime = System.currentTimeMillis();
ResourceTracker resTracker = gen.getResourceTracker(); ResourceTracker resTracker = gen.getResourceTracker();
InputStream in = new java.io.FileInputStream(this.tempFile);
in = new java.io.BufferedInputStream(in);
InputStream in = new BufferedInputStream(getUserAgent().getNewURIResolver().resolveIn(tempURI));
try { try {
try { try {
ResourceHandler handler = new ResourceHandler(getUserAgent(), this.fontInfo, ResourceHandler handler = new ResourceHandler(getUserAgent(), this.fontInfo,
} }
} finally { } finally {
IOUtils.closeQuietly(in); IOUtils.closeQuietly(in);
if (!this.tempFile.delete()) {
this.tempFile.deleteOnExit();
log.warn("Could not delete temporary file: " + this.tempFile);
}
} }
if (log.isDebugEnabled()) { if (log.isDebugEnabled()) {
long duration = System.currentTimeMillis() - startTime; long duration = System.currentTimeMillis() - startTime;

+ 10
- 23
src/java/org/apache/fop/util/ColorSpaceCache.java View File



import java.awt.color.ColorSpace; import java.awt.color.ColorSpace;
import java.awt.color.ICC_Profile; import java.awt.color.ICC_Profile;
import java.net.URI;
import java.net.URISyntaxException;
import java.io.InputStream;
import java.util.Collections; import java.util.Collections;
import java.util.HashMap;
import java.util.Map; import java.util.Map;


import javax.xml.transform.Source;
import javax.xml.transform.URIResolver;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;


import org.apache.xmlgraphics.java2d.color.ICCColorSpaceWithIntent; import org.apache.xmlgraphics.java2d.color.ICCColorSpaceWithIntent;
import org.apache.xmlgraphics.java2d.color.RenderingIntent; import org.apache.xmlgraphics.java2d.color.RenderingIntent;
import org.apache.xmlgraphics.java2d.color.profile.ColorProfileUtil;


import org.apache.fop.apps.io.URIResolverWrapper; import org.apache.fop.apps.io.URIResolverWrapper;


/** logger instance */ /** logger instance */
private static Log log = LogFactory.getLog(ColorSpaceCache.class); private static Log log = LogFactory.getLog(ColorSpaceCache.class);


private URIResolver resolver;
private Map<String, ColorSpace> colorSpaceMap
= Collections.synchronizedMap(new java.util.HashMap<String, ColorSpace>());
private URIResolverWrapper resolver;
private Map<String, ColorSpace> colorSpaceMap = Collections.synchronizedMap(new HashMap<String, ColorSpace>());


/** /**
* Default constructor * Default constructor
* @param resolver uri resolver * @param resolver uri resolver
*/ */
public ColorSpaceCache(URIResolver resolver) {
public ColorSpaceCache(URIResolverWrapper resolver) {
this.resolver = resolver; this.resolver = resolver;
} }


* @param renderingIntent overriding rendering intent * @param renderingIntent overriding rendering intent
* @return ICC ColorSpace object or null if ColorSpace could not be created * @return ICC ColorSpace object or null if ColorSpace could not be created
*/ */
public ColorSpace get(String profileName, String base, String iccProfileSrc,
public ColorSpace get(String profileName, String iccProfileSrc,
RenderingIntent renderingIntent) { RenderingIntent renderingIntent) {
String key = profileName + ":" + base + iccProfileSrc;
String key = profileName + ":" + iccProfileSrc;
// TODO: This stuff needs some TLC, fix it!! // TODO: This stuff needs some TLC, fix it!!
try {
URI uri = URIResolverWrapper.getBaseURI(base);
key = uri.resolve(URIResolverWrapper.cleanURI(iccProfileSrc)).toASCIIString();
} catch (URISyntaxException e) {
// TODO: handle this
}
ColorSpace colorSpace = null; ColorSpace colorSpace = null;
if (!colorSpaceMap.containsKey(key)) { if (!colorSpaceMap.containsKey(key)) {
try { try {
ICC_Profile iccProfile = null; ICC_Profile iccProfile = null;
// First attempt to use the FOP URI resolver to locate the ICC // First attempt to use the FOP URI resolver to locate the ICC
// profile // profile
Source src = resolver.resolve(iccProfileSrc, base);
if (src != null && src instanceof StreamSource) {
InputStream stream = resolver.resolveIn(iccProfileSrc);
if (stream != null) {
// FOP URI resolver found ICC profile - create ICC profile // FOP URI resolver found ICC profile - create ICC profile
// from the Source // from the Source
iccProfile = ColorProfileUtil.getICC_Profile(((StreamSource) src)
.getInputStream());
iccProfile = ICC_Profile.getInstance(stream);
} else { } else {
// TODO - Would it make sense to fall back on VM ICC // TODO - Would it make sense to fall back on VM ICC
// resolution // resolution

+ 2
- 6
src/java/org/apache/fop/util/ColorUtil.java View File

RenderingIntent renderingIntent = RenderingIntent.AUTO; RenderingIntent renderingIntent = RenderingIntent.AUTO;
//TODO connect to fo:color-profile/@rendering-intent //TODO connect to fo:color-profile/@rendering-intent
colorSpace = foUserAgent.getColorSpaceCache().get( colorSpace = foUserAgent.getColorSpaceCache().get(
iccProfileName,
foUserAgent.getNewURIResolver().getBaseURI().toASCIIString(),
iccProfileSrc, renderingIntent);
iccProfileName, iccProfileSrc, renderingIntent);
} }
if (colorSpace != null) { if (colorSpace != null) {
// ColorSpace is available // ColorSpace is available
RenderingIntent renderingIntent = RenderingIntent.AUTO; RenderingIntent renderingIntent = RenderingIntent.AUTO;
//TODO connect to fo:color-profile/@rendering-intent //TODO connect to fo:color-profile/@rendering-intent
colorSpace = (ICC_ColorSpace)foUserAgent.getColorSpaceCache().get( colorSpace = (ICC_ColorSpace)foUserAgent.getColorSpaceCache().get(
iccProfileName,
foUserAgent.getNewURIResolver().getBaseURI().toASCIIString(),
iccProfileSrc, renderingIntent);
iccProfileName, iccProfileSrc, renderingIntent);
} }
if (colorSpace != null) { if (colorSpace != null) {
ICC_Profile profile = colorSpace.getProfile(); ICC_Profile profile = colorSpace.getProfile();

+ 0
- 8
test/java/org/apache/fop/apps/FopConfParserTestCase.java View File

assertFalse(buildFactory().isAccessibilityEnabled()); assertFalse(buildFactory().isAccessibilityEnabled());
} }


@Test
public void testHyphenationBaseURI() {
String hyphBaseURI = "./test/base/uri/";
builder.setHyphenationBaseURI(hyphBaseURI);
assertEquals(baseURI.resolve(hyphBaseURI),
URI.create(buildFactory().getHyphenBaseURI()));
}

@Test @Test
public void testSourceResolution() { public void testSourceResolution() {
float srcRes = 123.456f; float srcRes = 123.456f;

+ 0
- 59
test/java/org/apache/fop/config/FOURIResolverTestCase.java View File

/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/* $Id$ */

package org.apache.fop.config;

import static org.junit.Assert.fail;

import java.net.MalformedURLException;

import org.apache.fop.apps.io.FOURIResolver;
import org.junit.Test;

/**
* This tests some aspects of the {@link FOURIResolver} class.
*/
public class FOURIResolverTestCase {

/**
* Checks the {@link FOURIResolver#checkBaseURL(String)} method.
* @throws Exception if an error occurs
*/
@Test
public void testCheckBaseURI() throws Exception {
FOURIResolver resolver = new FOURIResolver(true);
System.out.println(resolver.checkBaseURL("./test/config"));
System.out.println(resolver.checkBaseURL("file:test/config"));
System.out.println(resolver.checkBaseURL("fantasy:myconfig"));
System.out.println(resolver.checkBaseURL("file:test\\config\\"));
try {
resolver.checkBaseURL("./doesnotexist");
fail("Expected an exception for a inexistent base directory");
} catch (MalformedURLException mfue) {
//expected
}
try {
resolver.checkBaseURL("file:doesnotexist");
fail("Expected an exception for a inexistent base URI");
} catch (MalformedURLException mfue) {
//expected
}
}

}

+ 1
- 2
test/java/org/apache/fop/config/UserConfigTestSuite.java View File

FontMetricsUrlMalformedTestCase.class, FontMetricsUrlMalformedTestCase.class,
FontsDirectoryRecursiveTestCase.class, FontsDirectoryRecursiveTestCase.class,
FontsAutoDetectTestCase.class, FontsAutoDetectTestCase.class,
FontsSubstitutionTestCase.class,
FOURIResolverTestCase.class
FontsSubstitutionTestCase.class
}) })
public class UserConfigTestSuite { public class UserConfigTestSuite {
} }

+ 0
- 14
test/java/org/apache/fop/fotreetest/FOTreeTestCase.java View File



import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory; import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.URIResolver;


import org.junit.BeforeClass; import org.junit.BeforeClass;
import org.junit.Test; import org.junit.Test;
import org.apache.fop.apps.io.ResourceResolver; import org.apache.fop.apps.io.ResourceResolver;
import org.apache.fop.fonts.FontManager; import org.apache.fop.fonts.FontManager;
import org.apache.fop.fotreetest.ext.TestElementMapping; import org.apache.fop.fotreetest.ext.TestElementMapping;
import org.apache.fop.hyphenation.HyphenationTreeResolver;
import org.apache.fop.layoutengine.LayoutEngineTestUtils; import org.apache.fop.layoutengine.LayoutEngineTestUtils;
import org.apache.fop.layoutengine.TestFilesConfiguration; import org.apache.fop.layoutengine.TestFilesConfiguration;
import org.apache.fop.layoutmgr.LayoutManagerMaker; import org.apache.fop.layoutmgr.LayoutManagerMaker;
return delegate.getNewURIResolver(); return delegate.getNewURIResolver();
} }


public URIResolver getURIResolver() {
return delegate.getURIResolver();
}

public URI getBaseURI() { public URI getBaseURI() {
return delegate.getBaseURI(); return delegate.getBaseURI();
} }


public URI getHyphenationBaseURI() {
return delegate.getHyphenationBaseURI();
}

public HyphenationTreeResolver getHyphenationTreeResolver() {
return delegate.getHyphenationTreeResolver();
}

public boolean validateStrictly() { public boolean validateStrictly() {
return delegate.validateStrictly(); return delegate.validateStrictly();
} }

+ 2
- 3
test/java/org/apache/fop/util/ColorUtilTestCase.java View File

*/ */
public class ColorUtilTestCase { public class ColorUtilTestCase {
private FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()); private FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
private final String thisDirectory = "file:" + new File("./").getAbsolutePath();


/** /**
* Test serialization to String. * Test serialization to String.
FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI()); FopFactory fopFactory = FopFactory.newInstance(new File(".").toURI());
URI sRGBLoc = new URI("src/java/org/apache/fop/pdf/sRGB%20Color%20Space%20Profile.icm"); URI sRGBLoc = new URI("src/java/org/apache/fop/pdf/sRGB%20Color%20Space%20Profile.icm");
ColorSpace cs = fopFactory.getColorSpaceCache().get( ColorSpace cs = fopFactory.getColorSpaceCache().get(
"sRGBAlt", thisDirectory, sRGBLoc.toASCIIString(), RenderingIntent.AUTO);
"sRGBAlt", sRGBLoc.toASCIIString(), RenderingIntent.AUTO);
assertNotNull("Color profile not found", cs); assertNotNull("Color profile not found", cs);


FOUserAgent ua = fopFactory.newFOUserAgent(); FOUserAgent ua = fopFactory.newFOUserAgent();
FopFactory fopFactory = FopFactory.newInstance(new File("./").toURI()); FopFactory fopFactory = FopFactory.newInstance(new File("./").toURI());
URI ncpLoc = new URI("test/resources/color/ncp-example.icc"); URI ncpLoc = new URI("test/resources/color/ncp-example.icc");
ColorSpace cs = fopFactory.getColorSpaceCache().get( ColorSpace cs = fopFactory.getColorSpaceCache().get(
"NCP", thisDirectory, ncpLoc.toASCIIString(), RenderingIntent.AUTO);
"NCP", ncpLoc.toASCIIString(), RenderingIntent.AUTO);
assertNotNull("Color profile not found", cs); assertNotNull("Color profile not found", cs);


FOUserAgent ua = fopFactory.newFOUserAgent(); FOUserAgent ua = fopFactory.newFOUserAgent();

+ 1
- 1
test/layoutengine/standard-testcases/external-graphic_rfc2397.xml
File diff suppressed because it is too large
View File


Loading…
Cancel
Save