Example usage for org.xml.sax InputSource setSystemId

List of usage examples for org.xml.sax InputSource setSystemId

Introduction

In this page you can find the example usage for org.xml.sax InputSource setSystemId.

Prototype

public void setSystemId(String systemId) 

Source Link

Document

Set the system identifier for this input source.

Usage

From source file:org.apache.cocoon.forms.binding.JXPathBindingManager.java

public Binding createBinding(Source source) throws BindingException {
    Binding binding = (Binding) this.cacheManager.get(source, PREFIX);

    if (binding != null && !binding.isValid())
        binding = null; //invalidate

    if (binding == null) {
        try {/*ww  w . ja va  2s . c om*/
            InputSource is = new InputSource(source.getInputStream());
            is.setSystemId(source.getURI());

            Document doc = DomHelper.parse(is, this.manager);
            Element rootElm = doc.getDocumentElement();
            if (BindingManager.NAMESPACE.equals(rootElm.getNamespaceURI())) {
                binding = getBuilderAssistant().getBindingForConfigurationElement(rootElm);
                ((JXPathBindingBase) binding).enableLogging(getLogger());
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("Creation of new binding finished. " + binding);
                }
            } else {
                if (getLogger().isDebugEnabled()) {
                    getLogger().debug("Root Element of said binding file is in wrong namespace.");
                }
            }

            this.cacheManager.set(binding, source, PREFIX);
        } catch (BindingException e) {
            throw e;
        } catch (Exception e) {
            throw new BindingException("Error creating binding from " + source.getURI(), e);
        }
    }
    return binding;
}

From source file:org.apache.cocoon.generation.VelocityGenerator.java

/**
 * Generate XML data using Velocity template.
 *
 * @see org.apache.cocoon.generation.Generator#generate()
 *//*from w w w  .j  av  a  2  s  .c  om*/
public void generate() throws IOException, SAXException, ProcessingException {
    // Guard against calling generate before setup.
    if (!activeFlag) {
        throw new IllegalStateException("generate called on sitemap component before setup.");
    }

    SAXParser parser = null;
    StringWriter w = new StringWriter();
    try {
        parser = (SAXParser) this.manager.lookup(SAXParser.ROLE);
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("Processing File: " + super.source);
        }
        if (!tmplEngineInitialized) {
            tmplEngine.init();
            tmplEngineInitialized = true;
        }
        /* lets render a template */
        this.tmplEngine.mergeTemplate(super.source, velocityContext, w);

        InputSource xmlInput = new InputSource(new StringReader(w.toString()));
        xmlInput.setSystemId(super.source);
        parser.parse(xmlInput, this.xmlConsumer);
    } catch (IOException e) {
        getLogger().warn("VelocityGenerator.generate()", e);
        throw new ResourceNotFoundException("Could not get Resource for VelocityGenerator", e);
    } catch (SAXParseException e) {
        int line = e.getLineNumber();
        int column = e.getColumnNumber();
        if (line <= 0) {
            line = Integer.MAX_VALUE;
        }
        BufferedReader reader = new BufferedReader(new StringReader(w.toString()));
        StringBuffer message = new StringBuffer(e.getMessage());
        message.append(" In generated document:\n");
        for (int i = 0; i < line; i++) {
            String lineStr = reader.readLine();
            if (lineStr == null) {
                break;
            }
            message.append(lineStr);
            message.append("\n");
        }
        if (column > 0) {
            message.append(StringUtils.leftPad("^\n", column + 1));
        }
        SAXException pe = new SAXParseException(message.toString(), e.getPublicId(),
                "(Document generated from template " + e.getSystemId() + ")", e.getLineNumber(),
                e.getColumnNumber(), null);
        getLogger().error("VelocityGenerator.generate()", pe);
        throw pe;
    } catch (SAXException e) {
        getLogger().error("VelocityGenerator.generate()", e);
        throw e;
    } catch (ServiceException e) {
        getLogger().error("Could not get parser", e);
        throw new ProcessingException("Exception in VelocityGenerator.generate()", e);
    } catch (ProcessingException e) {
        throw e;
    } catch (Exception e) {
        getLogger().error("Could not get parser", e);
        throw new ProcessingException("Exception in VelocityGenerator.generate()", e);
    } finally {
        this.manager.release(parser);
    }
}

From source file:org.apache.fop.cli.InputHandler.java

/**
 * Creates a Source for the main input file. Processes XInclude if
 * available in the XML parser./*from  ww  w. j  a v  a 2  s  .  c o m*/
 *
 * @return the Source for the main input file
 */
protected Source createMainSource() {
    Source source;
    InputStream in;
    String uri;
    if (this.sourcefile != null) {
        try {
            in = new java.io.FileInputStream(this.sourcefile);
            uri = this.sourcefile.toURI().toASCIIString();
        } catch (FileNotFoundException e) {
            //handled elsewhere
            return new StreamSource(this.sourcefile);
        }
    } else {
        in = System.in;
        uri = null;
    }
    try {
        InputSource is = new InputSource(in);
        is.setSystemId(uri);
        XMLReader xr = getXMLReader();
        if (entityResolver != null) {
            xr.setEntityResolver(entityResolver);
        }
        source = new SAXSource(xr, is);
    } catch (SAXException e) {
        if (this.sourcefile != null) {
            source = new StreamSource(this.sourcefile);
        } else {
            source = new StreamSource(in, uri);
        }
    } catch (ParserConfigurationException e) {
        if (this.sourcefile != null) {
            source = new StreamSource(this.sourcefile);
        } else {
            source = new StreamSource(in, uri);
        }
    }
    return source;
}

From source file:org.apache.fop.fonts.LazyFont.java

private void load(boolean fail) {
    if (!isMetricsLoaded) {
        try {//from ww w.  ja  v a 2 s  .  co m
            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, subFontName, embedded, embeddingMode,
                        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;
    }
}

From source file:org.apache.fop.hyphenation.Hyphenator.java

/**
 * Load tree from serialized file or xml file
 * using configuration settings/*www  . j a va2s .c om*/
 * @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.geronimo.myfaces.FacesConfigDigester.java

public FacesConfig getFacesConfig(InputStream in, String systemId) throws IOException, SAXException {
    InputSource is = new InputSource(in);
    is.setSystemId(systemId);

    // Fix for http://issues.apache.org/jira/browse/MYFACES-236
    FacesConfig config = (FacesConfig) digester.parse(is);

    for (org.apache.myfaces.config.element.Application application : config.getApplications()) {
        for (org.apache.myfaces.config.element.LocaleConfig localeConfig : application.getLocaleConfig()) {
            if (!localeConfig.getSupportedLocales().contains(localeConfig.getDefaultLocale())) {
                localeConfig.getSupportedLocales().add(localeConfig.getDefaultLocale());
            }//from  w  ww . j a  va 2s  .c om
        }
    }

    return config;
}

From source file:org.apache.jackrabbit.core.config.RepositoryConfig.java

/**
 * Attempts to load a workspace configuration from the given physical
 * workspace subdirectory. If the directory contains a valid workspace
 * configuration file, then the configuration is parsed and returned as a
 * workspace configuration object. The returned configuration object has not
 * been initialized.//w w  w .j a v  a2s. co m
 * <p>
 * This method returns <code>null</code>, if the given directory does
 * not exist or does not contain a workspace configuration file. If an
 * invalid configuration file is found, then a
 * {@link ConfigurationException ConfigurationException} is thrown.
 *
 * @param directory physical workspace configuration directory on disk
 * @return workspace configuration
 * @throws ConfigurationException if the workspace configuration is invalid
 */
private WorkspaceConfig loadWorkspaceConfig(File directory) throws ConfigurationException {
    try {
        File file = new File(directory, WORKSPACE_XML);
        InputSource xml = new InputSource(new FileInputStream(file));
        xml.setSystemId(file.toURI().toString());

        Properties variables = new Properties();
        variables.setProperty(RepositoryConfigurationParser.WORKSPACE_HOME_VARIABLE, directory.getPath());
        RepositoryConfigurationParser localParser = parser.createSubParser(variables);
        return localParser.parseWorkspaceConfig(xml);
    } catch (FileNotFoundException e) {
        return null;
    }
}

From source file:org.apache.jackrabbit.core.config.RepositoryConfig.java

/**
 * Attempts to load a workspace configuration from the given workspace
 * subdirectory within the repository file system. If the directory contains
 * a valid workspace configuration file, then the configuration is parsed
 * and returned as a workspace configuration object. The returned
 * configuration object has not been initialized.
 * <p>//from ww  w  .ja  v  a 2  s  .c  om
 * This method returns <code>null</code>, if the given directory does
 * not exist or does not contain a workspace configuration file. If an
 * invalid configuration file is found, then a
 * {@link ConfigurationException ConfigurationException} is thrown.
 *
 * @param fs virtual file system where to look for the configuration file
 * @param configDir workspace configuration directory in virtual file system
 * @return workspace configuration
 * @throws ConfigurationException if the workspace configuration is invalid
 */
private WorkspaceConfig loadWorkspaceConfig(FileSystem fs, String configDir) throws ConfigurationException {
    Reader configReader = null;
    try {
        String configPath = configDir + FileSystem.SEPARATOR + WORKSPACE_XML;
        if (!fs.exists(configPath)) {
            // no configuration file in this directory
            return null;
        }

        configReader = new InputStreamReader(fs.getInputStream(configPath));
        InputSource xml = new InputSource(configReader);
        xml.setSystemId(configPath);

        // the physical workspace home directory (TODO encode name?)
        File homeDir = new File(workspaceDirectory, FileSystemPathUtil.getName(configDir));
        if (!homeDir.exists()) {
            homeDir.mkdir();
        }
        Properties variables = new Properties(parser.getVariables());
        variables.setProperty(RepositoryConfigurationParser.WORKSPACE_HOME_VARIABLE, homeDir.getPath());
        RepositoryConfigurationParser localParser = parser.createSubParser(variables);
        return localParser.parseWorkspaceConfig(xml);
    } catch (FileSystemException e) {
        throw new ConfigurationException("Failed to load workspace configuration", e);
    } finally {
        IOUtils.closeQuietly(configReader);
    }
}

From source file:org.apache.jetspeed.modules.actions.portlets.PsmlManagerAction.java

/**
 * Loads psml mapping file/*from   w  w w  . j ava  2s.  c om*/
 *
 * @exception Exception
 */
private Mapping loadMapping() throws Exception {
    // get configuration parameters from Jetspeed Resources
    ResourceService serviceConf = ((TurbineServices) TurbineServices.getInstance())
            .getResources(PsmlManagerService.SERVICE_NAME);

    // test the mapping file and create the mapping object
    Mapping mapping = null;
    String mapFile = serviceConf.getString("mapping", "${webappRoot}/WEB-INF/conf/psml-mapping.xml");
    mapFile = TurbineServlet.getRealPath(mapFile);
    if (mapFile != null) {
        File map = new File(mapFile);
        if (logger.isDebugEnabled()) {
            logger.debug("Loading psml mapping file " + mapFile);
        }
        if (map.exists() && map.isFile() && map.canRead()) {
            try {
                mapping = new Mapping();
                InputSource is = new InputSource(new FileReader(map));
                is.setSystemId(mapFile);
                mapping.loadMapping(is);
            } catch (Exception e) {
                logger.error("Error in psml mapping creation", e);
                throw new Exception("Error in mapping");
            }
        } else {
            throw new Exception("PSML Mapping not found or not a file or unreadable: " + mapFile);
        }
    }

    return mapping;
}

From source file:org.apache.myfaces.config.impl.digester.DigesterFacesConfigUnmarshallerImpl.java

public FacesConfigImpl getFacesConfig(InputStream in, String systemId) throws IOException, SAXException {
    InputSource is = new InputSource(in);
    is.setSystemId(systemId);

    // Fix for http://issues.apache.org/jira/browse/MYFACES-236
    FacesConfigImpl config = (FacesConfigImpl) digester.parse(is);

    postProcessFacesConfig(systemId, config);

    return config;
}