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.torque.engine.database.transform.XmlToAppData.java

/**
 * Parses a XML input file and returns a newly created and
 * populated Database structure./*w  w w.  j a  v a  2 s .  c  o  m*/
 *
 * @param xmlFile The input file to parse.
 * @return Database populated by <code>xmlFile</code>.
 */
public Database parseFile(String xmlFile) throws EngineException {
    try {
        // in case I am missing something, make it obvious
        if (!firstPass) {
            throw new Error("No more double pass");
        }
        // check to see if we alread have parsed the file
        if ((alreadyReadFiles != null) && alreadyReadFiles.contains(xmlFile)) {
            return database;
        } else if (alreadyReadFiles == null) {
            alreadyReadFiles = new Vector(3, 1);
        }

        // remember the file to avoid looping
        alreadyReadFiles.add(xmlFile);

        currentXmlFile = xmlFile;

        SAXParser parser = saxFactory.newSAXParser();

        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(xmlFile);
        } catch (FileNotFoundException fnfe) {
            throw new FileNotFoundException(new File(xmlFile).getAbsolutePath());
        }
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
        try {
            log.info("Parsing file: '" + (new File(xmlFile)).getName() + "'");
            InputSource is = new InputSource(bufferedInputStream);
            is.setSystemId(new File(xmlFile).getAbsolutePath());
            parser.parse(is, this);
        } finally {
            bufferedInputStream.close();
        }
    } catch (SAXParseException e) {
        throw new EngineException("Sax error on line " + e.getLineNumber() + " column " + e.getColumnNumber()
                + " : " + e.getMessage(), e);
    } catch (Exception e) {
        throw new EngineException(e);
    }
    if (!isExternalSchema) {
        firstPass = false;
    }
    database.doFinalInitialization();
    return database;
}

From source file:org.apache.torque.engine.database.transform.XmlToData.java

/**
 *
 *//*from w  ww .  ja v a2 s . c o m*/
public List parseFile(String xmlFile) throws Exception {
    data = new ArrayList();

    SAXParser parser = saxFactory.newSAXParser();

    FileReader fr = new FileReader(xmlFile);
    BufferedReader br = new BufferedReader(fr);
    try {
        InputSource is = new InputSource(br);
        is.setSystemId(xmlFile);
        parser.parse(is, this);
    } finally {
        br.close();
    }
    return data;
}

From source file:org.archive.crawler.settings.XMLSettingsHandler.java

/** Read the CrawlerSettings object from a specific file.
 *
 * @param settings the settings object to be updated with data from the
 *                 persistent storage./*www.  ja v  a2 s. c o m*/
 * @param f the file to read from.
 * @return the updated settings object or null if there was no data for this
 *         in the persistent storage.
 */
protected final CrawlerSettings readSettingsObject(CrawlerSettings settings, File f) {
    CrawlerSettings result = null;
    try {
        InputStream is = null;
        if (!f.exists()) {
            // Perhaps the file we're looking for is on the CLASSPATH.
            // DON'T look on the CLASSPATH for 'settings.xml' files.  The
            // look for 'settings.xml' files happens frequently. Not looking
            // on classpath for 'settings.xml' is an optimization based on
            // ASSUMPTION that there will never be a 'settings.xml' saved
            // on classpath.
            if (!f.getName().startsWith(settingsFilename)) {
                is = XMLSettingsHandler.class.getResourceAsStream(toResourcePath(f));
            }
        } else {
            is = new FileInputStream(f);
        }
        if (is != null) {
            XMLReader parser = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
            InputStream file = new BufferedInputStream(is);
            parser.setContentHandler(new CrawlSettingsSAXHandler(settings));
            InputSource source = new InputSource(file);
            source.setSystemId(f.toURL().toExternalForm());
            parser.parse(source);
            result = settings;
        }
    } catch (SAXParseException e) {
        logger.warning(e.getMessage() + " in '" + e.getSystemId() + "', line: " + e.getLineNumber()
                + ", column: " + e.getColumnNumber());
    } catch (SAXException e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (ParserConfigurationException e) {
        logger.warning(e.getMessage() + ": " + e.getCause().getMessage());
    } catch (FactoryConfigurationError e) {
        logger.warning(e.getMessage() + ": " + e.getException().getMessage());
    } catch (IOException e) {
        logger.warning("Could not access file '" + f.getAbsolutePath() + "': " + e.getMessage());
    }
    return result;
}

From source file:org.betaconceptframework.astroboa.configuration.W3CRelatedSchemaEntityResolver.java

private InputSource locateEntity(String systemId, String publicId) throws IOException {

    URL xsdOrDtdLocation = null;//from  www  . j  a  v  a 2  s  .  c  om

    if (publicId != null && schemaURLsPerPublicId.containsKey(publicId)) {
        xsdOrDtdLocation = schemaURLsPerPublicId.get(publicId);
    }

    if (systemId == null) {
        return null;
    }

    String xsdOrDtdFilename = (systemId.contains(CmsConstants.FORWARD_SLASH)
            ? StringUtils.substringAfterLast(systemId, CmsConstants.FORWARD_SLASH)
            : systemId);

    //Check if schema is available locally
    if (xsdOrDtdLocation == null) {
        xsdOrDtdLocation = this.getClass()
                .getResource(xmlSchemaHomeDir + CmsConstants.FORWARD_SLASH + xsdOrDtdFilename);
    }

    //Try on the WEB
    if (xsdOrDtdLocation == null) {
        xsdOrDtdLocation = new URL(systemId);
    }

    try {
        InputSource is = new InputSource(xsdOrDtdLocation.openStream());

        //System Id is the path of this URL
        is.setSystemId(xsdOrDtdLocation.toString());
        is.setPublicId(publicId);

        schemaURLsPerPublicId.put(publicId, xsdOrDtdLocation);

        return is;
    } catch (Throwable isEx) {

        //Log a warning and let the Xerces parser to locate the schema
        LoggerFactory.getLogger(getClass()).warn("Unable to resolve schema for " + publicId + " " + systemId
                + " in URL " + xsdOrDtdLocation.toString(), isEx);

        //continue with parser provided by Java. If schema cannot be located, an exception will be thrown
        return null;
    }
}

From source file:org.betaconceptframework.astroboa.engine.definition.ContentDefinitionConfiguration.java

public boolean definitionFileForActiveRepositoryIsValid(String definitionToBeValidated,
        String definitionFileName) throws Exception {

    if (StringUtils.isBlank(definitionToBeValidated) || StringUtils.isBlank(definitionFileName)) {
        return false;
    }//w  ww  .  j a v  a2s.  co m

    RepositoryContext repositoryContext = AstroboaClientContextHolder.getRepositoryContextForActiveClient();

    if (repositoryContext == null || repositoryContext.getCmsRepository() == null) {
        //No repository context found. Do nothing
        logger.warn("Unable to validate definition files. No repository context found");
        return false;
    }

    final CmsRepository associatedRepository = repositoryContext.getCmsRepository();

    File[] existingDefinitionFiles = retrieveXmlSchemaFiles(associatedRepository, false);

    CmsEntityResolverForValidation entityResolverForValidation = null;
    XSOMParser xsomParser = null;
    List<InputStream> openStreams = new ArrayList<InputStream>();

    try {
        entityResolverForValidation = createEntityResolverForValidation(existingDefinitionFiles,
                definitionToBeValidated, definitionFileName);

        //Feed parser with user defined schemas
        xsomParser = cmsXsomParserFactory.createXsomParserForValidation(entityResolverForValidation);

        //Feed parser with builtin schemas
        if (MapUtils.isNotEmpty(entityResolverForValidation.getDefinitionSources())) {
            for (Entry<String, String> definitionSource : entityResolverForValidation.getDefinitionSources()
                    .entrySet()) {

                if (!StringUtils.equals(CmsConstants.ASTROBOA_MODEL_SCHEMA_FILENAME_WITH_VERSION,
                        definitionSource.getKey())) {
                    try {
                        InputStream openStream = IOUtils.toInputStream(definitionSource.getValue(), "UTF-8");
                        openStreams.add(openStream);

                        InputSource is = new InputSource(openStream);
                        is.setSystemId(definitionSource.getKey());

                        xsomParser.parse(is);
                    } catch (Exception e) {
                        throw new CmsException("Parse error for definition " + definitionSource.getKey(), e);
                    }
                }
            }
        }

        //Force parser to create XSD schemas. This way more errors can be detected
        xsomParser.getResult().getSchemas();

    } catch (Exception e) {
        throw e;
    } finally {
        xsomParser = null;

        if (entityResolverForValidation != null) {
            entityResolverForValidation.clearDefinitions();
        }

        if (!openStreams.isEmpty()) {
            for (InputStream is : openStreams) {
                IOUtils.closeQuietly(is);
            }
        }
    }

    return true;

}

From source file:org.betaconceptframework.astroboa.engine.definition.RepositoryEntityResolver.java

@Override
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

    if (XMLConstants.W3C_XML_SCHEMA_INSTANCE_NS_URI.equals(systemId) || XMLConstants.XML_NS_URI.equals(systemId)
            || CmsConstants.XML_SCHEMA_LOCATION.equals(systemId)
            || CmsConstants.XML_SCHEMA_DTD_LOCATION.equals(systemId)) {
        return entityResolverForBuiltInSchemas.resolveXmlSchemaRelatedToW3C(publicId, systemId);
    }//from  ww w  .  j  a v  a 2  s .c  o  m

    byte[] schema = getSchema(systemId);

    if (schema == null) {
        return null;
    }

    InputSource is = new InputSource(new ByteArrayInputStream(schema));

    is.setSystemId(systemId);
    is.setPublicId(publicId);

    return is;

}

From source file:org.betaconceptframework.astroboa.engine.definition.xsom.CmsEntityResolverForValidation.java

@Override
/**//from  w ww  .ja  v a2  s  .  com
 * According to XSOM library 
 * By setting EntityResolver to XSOMParser, you can redirect <xs:include>s and <xs:import>s to different resources.
 * For imports, the namespace URI of the target schema is passed as the public ID,
 * and the absolutized value of the schemaLocation attribute will be passed as the system ID. 
 */
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

    if (systemId != null) {

        try {

            String schemaFilename = systemId;

            //We are only interested in file name
            if (schemaFilename.contains(File.separator)) {
                schemaFilename = StringUtils.substringAfterLast(systemId, File.separator);
            } else if (!File.separator.equals(schemaFilename.contains(CmsConstants.FORWARD_SLASH))
                    && schemaFilename.contains(CmsConstants.FORWARD_SLASH)) {
                //Perform the extra check in case File.separator is not '/' and it 
                //does not exist in the schema filename.
                //This case usually appears in a windows environment.
                schemaFilename = StringUtils.substringAfterLast(systemId, CmsConstants.FORWARD_SLASH);
            }

            if (definitionSources.containsKey(schemaFilename)) {
                InputStream inputStream = IOUtils.toInputStream(definitionSources.get(schemaFilename), "UTF-8");
                openStreams.add(inputStream);

                InputSource inputSource = new InputSource(inputStream);

                inputSource.setPublicId(publicId);
                inputSource.setSystemId(schemaFilename);

                return inputSource;
            }

            return entityResolverForBuiltInSchemas.resolveEntity(publicId, systemId);

        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    //Returning null allow XSD Parser to continue with default behavior
    //and will try to resolve entity using its own implementation
    return null;
}

From source file:org.betaconceptframework.astroboa.engine.definition.xsom.EntityResolverForBuiltInSchemas.java

@Override
/**//from w w w  .ja v  a2s  .  co  m
 * According to XSOM library 
 * By setting EntityResolver to XSOMParser, you can redirect <xs:include>s and <xs:import>s to different resources.
 * For imports, the namespace URI of the target schema is passed as the public ID,
 * and the absolutized value of the schemaLocation attribute will be passed as the system ID. 
 */
public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {

    if (publicId != null && publicId.startsWith(BetaConceptNamespaceConstants.ASTROBOA_SCHEMA_URI)
            && systemId != null) {

        try {

            String schemaFilename = systemId;

            //We are only interested in file name
            if (schemaFilename.contains(CmsConstants.FORWARD_SLASH)) {
                schemaFilename = StringUtils.substringAfterLast(systemId, CmsConstants.FORWARD_SLASH);
            }

            URL definitionFileURL = locateBuiltinDefinitionURL(schemaFilename);

            if (definitionFileURL != null) {

                InputSource is = new InputSource(definitionFileURL.openStream());

                /*
                 * SystemId is actual the path to the resource
                 * although its content has been loaded to input source.
                 * Provided value (sustemId) is not set because if in XSD file in the corresponding import's
                 * schemaLocation contains only the schema filename, then XSOM parser will
                 * consider it as a relative path and will prefix it with the correct absolute path.
                 * 
                 * For example, in cases where two different schemas, located in two different directories (portal-1.0.xsd and basicText-1.0.xsd),
                 * import schema astroboa-model-1.2.xsd, xs import will look like
                 * 
                 * <xs:import
                      namespace="http://www.betaconceptframework.org/schema/astroboa/model"
                      schemaLocation="astroboa-model-1.2.xsd" />
                 * 
                 * When XSOM parser will try to load astroboa-model-1.2.xsd, it will append
                 * schemaLocation with the path of the directory where each of the parent XSDs are located. 
                 * 
                 * SchemaLocation value refers to systemId and if it is provided in this input source, XSOM parser
                 * will have two different instances of InputSource referring to the same xsd file  (definitionFileURL),
                 * having the same publiId (namespace) but different systemIds (appended schemaLocation).
                 * 
                 * This situation causes XSOM parser to throw an exception when the second input source is loaded
                 * complaining that it found the same type(s) defined already, which is true since as far as XSOM parser
                 * concerns these input sources are not the same.
                 * 
                 * To overcome this, we set as system id the URL of the XSD file which is the same
                 * in both situations.
                 */
                is.setSystemId(definitionFileURL.toString());
                is.setPublicId(publicId);

                if (systemId.startsWith(BetaConceptNamespaceConstants.ASTROBOA_SCHEMA_URI)) {
                    logger.warn("Schema Location for XSD Schema " + schemaFilename
                            + ", which contains built in Astroboa model, is not relative but absolute."
                            + " Unless this absolute location really 'serves' XSD, there will be a problem "
                            + " when importing XML which contain xml elements derived from this Schema If this location is not real, then you are advised to delete it and leave only"
                            + "the schema file name. Nevertheless the contents of " + schemaFilename
                            + " have been found internally and have been successfully loaded to Astroboa");
                }

                return is;
            }

        } catch (Exception e) {
            throw new IOException(e);
        }
    }

    //Returning null allow XSD Parser to continue with default behavior
    //and will try to resolve entity using its own implementation
    return resolveXmlSchemaRelatedToW3C(publicId, systemId);
}

From source file:org.castor.mapping.MappingUnmarshaller.java

/**
 * Internal recursive loading method. This method will load the mapping document into a mapping
 * object and load all the included mapping along the way into a single collection.
 *
 * @param mapping The mapping instance.//from  w w w.j av a  2 s.c o m
 * @param resolver The entity resolver to use.
 * @param url The URL of the mapping file.
 * @throws IOException An error occured when reading the mapping file.
 * @throws MappingException The mapping file is invalid.
 */
protected void loadMappingInternal(final Mapping mapping, final DTDResolver resolver, final String url)
        throws IOException, MappingException {
    try {
        InputSource source = resolver.resolveEntity(null, url);
        if (source == null) {
            source = new InputSource(url);
        }
        if (source.getSystemId() == null) {
            source.setSystemId(url);
        }
        LOG.info(Messages.format("mapping.loadingFrom", url));
        loadMappingInternal(mapping, resolver, source);
    } catch (SAXException ex) {
        throw new MappingException(ex);
    }
}

From source file:org.castor.xmlctf.xmldiff.xml.XMLFileReader.java

/**
 * Reads an XML Document into an BaseNode from the provided file.
 *
 * @return the BaseNode//  ww w  . ja  v a  2  s .  c  o m
 * @throws java.io.IOException if any exception occurs during parsing
 */
public XMLNode read() throws java.io.IOException {
    XMLNode node = null;

    try {
        InputSource source = new InputSource();
        source.setSystemId(_location);
        source.setCharacterStream(new FileReader(_file));

        XMLContentHandler builder = new XMLContentHandler();

        _parser.setContentHandler(builder);
        _parser.parse(source);

        node = builder.getRoot();
    } catch (SAXException sx) {
        Exception nested = sx.getException();

        SAXParseException sxp = null;
        if (sx instanceof SAXParseException) {
            sxp = (SAXParseException) sx;
        } else if (nested != null && (nested instanceof SAXParseException)) {
            sxp = (SAXParseException) nested;
        } else {
            throw new NestedIOException(sx);
        }

        String err = new StringBuilder(sxp.toString()).append("\n - ").append(sxp.getSystemId())
                .append("; line: ").append(sxp.getLineNumber()).append(", column: ")
                .append(sxp.getColumnNumber()).toString();
        throw new NestedIOException(err, sx);
    }

    Root root = (Root) node;
    return root;
}