List of usage examples for javax.xml.transform Source getSystemId
public String getSystemId();
From source file:org.apache.fop.hyphenation.Hyphenator.java
/** * Load tree from serialized file or xml file * using configuration settings/* w w w .jav a 2s .co m*/ * @param key language key for the requested hyphenation file * @param resolver resolver to find the hyphenation files * @return the requested HypenationTree or null if it is not available */ 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; } }
From source file:org.apache.fop.pdf.PDFFactory.java
/** * Embeds a font.//w ww . j a va 2s. co m * @param desc FontDescriptor of the font. * @return PDFStream The embedded font file */ 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(); subset.readFont(reader, mbfont.getTTCName(), mbfont.getUsedGlyphs()); byte[] subsetFont = subset.getFontSubset(); // 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; } }
From source file:org.apache.fop.render.pdf.PDFRenderingUtil.java
private void addDefaultOutputProfile() throws IOException { if (this.outputProfile != null) { return;// www.j a va2s . com } 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(); } }
From source file: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())); }//from ww w. j ava 2 s.c o m 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; } }
From source file:org.apache.fop.threading.FOProcessorImpl.java
/** {@inheritDoc} */ public void process(Source src, Templates templates, OutputStream out) throws org.apache.fop.apps.FOPException, java.io.IOException { FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); foUserAgent.setBaseURL(src.getSystemId()); try {// w w w. j av a2 s. c o m URL url = new URL(src.getSystemId()); String filename = FilenameUtils.getName(url.getPath()); foUserAgent.getEventBroadcaster().addEventListener(new AvalonAdapter(getLogger(), filename)); } catch (MalformedURLException mfue) { throw new RuntimeException(mfue); } Fop fop = fopFactory.newFop(this.mime, foUserAgent, out); try { Transformer transformer; if (templates == null) { transformer = factory.newTransformer(); } else { transformer = templates.newTransformer(); } Result res = new SAXResult(fop.getDefaultHandler()); transformer.transform(src, res); } catch (TransformerException e) { throw new FOPException(e); } }
From source file:org.apache.fop.threading.IFProcessorImpl.java
/** {@inheritDoc} * @throws IFException */// ww w .j a v a 2s. c o m public void process(Source src, Templates templates, OutputStream out) throws org.apache.fop.apps.FOPException, java.io.IOException, IFException { FOUserAgent foUserAgent = fopFactory.newFOUserAgent(); foUserAgent.setBaseURL(src.getSystemId()); try { URL url = new URL(src.getSystemId()); String filename = FilenameUtils.getName(url.getPath()); foUserAgent.getEventBroadcaster().addEventListener(new AvalonAdapter(getLogger(), filename)); } catch (MalformedURLException mfue) { throw new RuntimeException(mfue); } //Setup target handler IFDocumentHandler targetHandler = fopFactory.getRendererFactory().createDocumentHandler(foUserAgent, mime); //Setup fonts IFUtil.setupFonts(targetHandler); targetHandler.setResult(new StreamResult(out)); try { Transformer transformer; if (templates == null) { transformer = factory.newTransformer(); } else { transformer = templates.newTransformer(); } IFParser parser = new IFParser(); ContentHandler contentHandler = parser.getContentHandler(targetHandler, foUserAgent); Result res = new SAXResult(contentHandler); transformer.transform(src, res); } catch (TransformerException e) { throw new FOPException(e); } }
From source file:org.apache.xmlgraphics.image.loader.impl.AbstractImageSessionContext.java
/** {@inheritDoc} */ public Source newSource(String uri) { Source source = resolveURI(uri); if (source == null) { if (log.isDebugEnabled()) { log.debug("URI could not be resolved: " + uri); }//w w w . j av a2s . c o m return null; } if (!(source instanceof StreamSource) && !(source instanceof SAXSource)) { //Return any non-stream Sources and let the ImageLoaders deal with them return source; } ImageSource imageSource = null; String resolvedURI = source.getSystemId(); URL url; try { url = new URL(resolvedURI); } catch (MalformedURLException e) { url = null; } File f = /*FileUtils.*/toFile(url); if (f != null) { boolean directFileAccess = true; assert (source instanceof StreamSource) || (source instanceof SAXSource); InputStream in = ImageUtil.getInputStream(source); if (in == null) { try { in = new java.io.FileInputStream(f); } catch (FileNotFoundException fnfe) { log.error("Error while opening file." + " Could not load image from system identifier '" + source.getSystemId() + "' (" + fnfe.getMessage() + ")"); return null; } } if (in != null) { in = ImageUtil.decorateMarkSupported(in); try { if (ImageUtil.isGZIPCompressed(in)) { //GZIPped stream are not seekable, so buffer/cache like other URLs directFileAccess = false; } } catch (IOException ioe) { log.error("Error while checking the InputStream for GZIP compression." + " Could not load image from system identifier '" + source.getSystemId() + "' (" + ioe.getMessage() + ")"); return null; } } if (directFileAccess) { //Close as the file is reopened in a more optimal way IOUtils.closeQuietly(in); try { // We let the OS' file system cache do the caching for us // --> lower Java memory consumption, probably no speed loss final ImageInputStream newInputStream = ImageIO.createImageInputStream(f); if (newInputStream == null) { log.error("Unable to create ImageInputStream for local file " + f + " from system identifier '" + source.getSystemId() + "'"); return null; } else { imageSource = new ImageSource(newInputStream, resolvedURI, true); } } catch (IOException ioe) { log.error("Unable to create ImageInputStream for local file" + " from system identifier '" + source.getSystemId() + "' (" + ioe.getMessage() + ")"); } } } if (imageSource == null) { if (ImageUtil.hasReader(source) && !ImageUtil.hasInputStream(source)) { //We don't handle Reader instances here so return the Source unchanged return source; } // Got a valid source, obtain an InputStream from it InputStream in = ImageUtil.getInputStream(source); if (in == null && url != null) { try { in = url.openStream(); } catch (Exception ex) { log.error("Unable to obtain stream from system identifier '" + source.getSystemId() + "'"); } } if (in == null) { log.error("The Source that was returned from URI resolution didn't contain" + " an InputStream for URI: " + uri); return null; } try { //Buffer and uncompress if necessary in = ImageUtil.autoDecorateInputStream(in); imageSource = new ImageSource(createImageInputStream(in), source.getSystemId(), false); } catch (IOException ioe) { log.error("Unable to create ImageInputStream for InputStream" + " from system identifier '" + source.getSystemId() + "' (" + ioe.getMessage() + ")"); } } return imageSource; }
From source file:org.apereo.portal.io.xml.JaxbPortalDataHandlerService.java
@Override public final void importData(final Source source, PortalDataKey portalDataKey) { //Get a StAX reader for the source to determine info about the data to import final BufferedXMLEventReader bufferedXmlEventReader = createSourceXmlEventReader(source); //If no PortalDataKey was passed build it from the source if (portalDataKey == null) { final StartElement rootElement = StaxUtils.getRootElement(bufferedXmlEventReader); portalDataKey = new PortalDataKey(rootElement); bufferedXmlEventReader.reset();//from ww w .j ava2 s . co m } final String systemId = source.getSystemId(); //Post Process the PortalDataKey to see if more complex import operations are needed final IPortalDataType portalDataType = this.dataKeyTypes.get(portalDataKey); if (portalDataType == null) { throw new RuntimeException("No IPortalDataType configured for " + portalDataKey + ", the resource will be ignored: " + getPartialSystemId(systemId)); } final Set<PortalDataKey> postProcessedPortalDataKeys = portalDataType.postProcessPortalDataKey(systemId, portalDataKey, bufferedXmlEventReader); bufferedXmlEventReader.reset(); //If only a single result from post processing import if (postProcessedPortalDataKeys.size() == 1) { this.importOrUpgradeData(systemId, DataAccessUtils.singleResult(postProcessedPortalDataKeys), bufferedXmlEventReader); } //If multiple results from post processing ordering is needed else { //Iterate over the data key order list to run the imports in the correct order for (final PortalDataKey orderedPortalDataKey : this.dataKeyImportOrder) { if (postProcessedPortalDataKeys.contains(orderedPortalDataKey)) { //Reset the to start of the XML document for each import/upgrade call bufferedXmlEventReader.reset(); this.importOrUpgradeData(systemId, orderedPortalDataKey, bufferedXmlEventReader); } } } }
From source file:org.dhatim.delivery.AbstractParser.java
protected static Reader getReader(Source source, String contentEncoding) { if (source != null) { if (source instanceof StreamSource) { StreamSource streamSource = (StreamSource) source; if (streamSource.getReader() != null) { return streamSource.getReader(); } else if (streamSource.getInputStream() != null) { return streamToReader(streamSource.getInputStream(), contentEncoding); } else if (streamSource.getSystemId() != null) { return systemIdToReader(streamSource.getSystemId(), contentEncoding); }//w w w . j a v a 2 s. c o m throw new SmooksException("Invalid " + StreamSource.class.getName() + ". No InputStream, Reader or SystemId instance."); } else if (source.getSystemId() != null) { return systemIdToReader(source.getSystemId(), contentEncoding); } } return new NullReader(); }
From source file:org.dita2indesign.indesign.builders.InDesignFromDitaMapBuilder.java
/** * Applies the specified transform to the map document in order to generate * InCopy articles for the topics in the map. * @param mapDoc//from w ww. j a v a 2 s . c om * @param options Options used to configure the transform, including the URL of the * transform itself. * @throws Exception */ private void generateInCopyArticlesForTopics(Document mapDoc, Map2InDesignOptions options) throws Exception { URL xsltUrl = options.getXsltUrl(); if (xsltUrl == null) { throw new Exception("No XSLT URL option value specified."); } Source style = new StreamSource(xsltUrl.openStream()); style.setSystemId(xsltUrl.toExternalForm()); Source xmlSource = new DOMSource(mapDoc); String mapDocUri = mapDoc.getDocumentURI(); xmlSource.setSystemId(mapDocUri); if (log.isDebugEnabled()) log.debug("xmlSource.systemId=\"" + xmlSource.getSystemId() + "\""); // Create a temp file in the same directory as the real INX file so the // XSLT transform will generate its output in the right place: File resultFile = File.createTempFile("map2indesign", ".inx", options.getResultFile().getParentFile()); // NOTE: The top-level file is not used. if (log.isDebugEnabled()) log.debug("Calling transform()..."); Source xsltSource = new StreamSource(xsltUrl.openStream()); xsltSource.setSystemId(xsltUrl.toExternalForm()); XsltTransformer trans = getSaxonTransformer(xmlSource, resultFile, xsltSource); trans.setParameter(new QName("styleCatalogUrl"), new XdmAtomicValue(options.getStyleCatalogUrl())); trans.setParameter(new QName("outputPath"), new XdmAtomicValue(resultFile.getParent())); trans.setParameter(new QName("linksPath"), new XdmAtomicValue(options.getLinksPath())); trans.setParameter(new QName("debug"), new XdmAtomicValue(options.getDebug())); trans.transform(); if (log.isDebugEnabled()) log.debug("Transformation complete."); resultFile.delete(); // Don't need the result file since each article is generated as a separate file. }