Example usage for javax.xml.parsers SAXParser parse

List of usage examples for javax.xml.parsers SAXParser parse

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParser parse.

Prototype

public void parse(InputSource is, DefaultHandler dh) throws SAXException, IOException 

Source Link

Document

Parse the content given org.xml.sax.InputSource as XML using the specified org.xml.sax.helpers.DefaultHandler .

Usage

From source file:org.jahia.services.importexport.ImportExportBaseService.java

/**
 * Detects the type of the import from the provided stream.
 *
 * @param is the input stream to read imported content from
 * @return the type of the import from the provided stream
 * @see XMLFormatDetectionHandler//  w w w .j  a va  2  s.c o  m
 */
public int detectXmlFormat(InputStream is) {
    XMLFormatDetectionHandler handler = new XMLFormatDetectionHandler();
    try {
        SAXParser parser = JahiaSAXParserFactory.newInstance().newSAXParser();

        parser.parse(is, handler);
    } catch (Exception e) {
    }
    return handler.getType();
}

From source file:org.jajuk.base.Collection.java

/**
 * Parse collection.xml file and put all collection information into memory
 *
 * @param file /*  w ww.j a v  a  2 s  .c  o m*/
 *
 * @throws SAXException the SAX exception
 * @throws ParserConfigurationException the parser configuration exception
 * @throws JajukException the jajuk exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static void load(File file)
        throws SAXException, ParserConfigurationException, JajukException, IOException {
    // If we load the regular collection.xml file, try to recover it from previous crash
    java.io.File regularFile = SessionService.getConfFileByPath(Const.FILE_COLLECTION);
    if (file.equals(regularFile)) {
        UtilSystem.recoverFileIfRequired(regularFile);
    }
    Log.debug("Loading: " + file.getName());
    if (!file.exists()) {
        throw new JajukException(5, file.toString());
    }
    lTime = System.currentTimeMillis();
    SAXParserFactory spf = SAXParserFactory.newInstance();
    spf.setValidating(false);
    spf.setNamespaceAware(false);
    // See http://xerces.apache.org/xerces-j/features.html for details
    spf.setFeature("http://xml.org/sax/features/external-general-entities", false);
    spf.setFeature("http://xml.org/sax/features/string-interning", true);
    SAXParser saxParser = spf.newSAXParser();
    saxParser.parse(file.toURI().toURL().toString(), getInstance());
}

From source file:org.jamwiki.migrate.MediaWikiXmlImporter.java

/**
 *
 *///from  w  ww.ja v a  2 s.c  o  m
private void importWikiXml(File file) throws MigrationException {
    FileInputStream fis = null;
    try {
        // at least in 1.5, the SaxParser has a bug where files with names like "%25s"
        // will be read as "%s", generating FileNotFound exceptions.  To work around this
        // issue use a FileInputStream rather than just SAXParser.parse(file, handler)
        fis = new FileInputStream(file);
        SAXParser saxParser = SAX_PARSER_FACTORY.newSAXParser();
        saxParser.parse(fis, this);
    } catch (ParserConfigurationException e) {
        throw new MigrationException(e);
    } catch (IOException e) {
        throw new MigrationException(e);
    } catch (SAXException e) {
        if (e.getCause() instanceof DataAccessException || e.getCause() instanceof WikiException) {
            throw new MigrationException(e.getCause());
        } else {
            throw new MigrationException(e);
        }
    } finally {
        IOUtils.closeQuietly(fis);
    }
}

From source file:org.jamwiki.utils.XMLTopicFactory.java

/**
 *
 *//* ww w .  j a v  a2 s. c  om*/
public String importWikiXml(File file) throws Exception {
    //read ini params from file
    // TODO read all params from JAMWiki properties
    //importProps = Environment.loadProperties(PROPERTY_FILE_NAME);
    //For big file parsing
    System.setProperty("entityExpansionLimit", "1000000");
    // Use an instance of ourselves as the SAX event handler
    // DefaultHandler handler = new XMLPageFactory();
    // Use the default (non-validating) parser
    SAXParserFactory factory = SAXParserFactory.newInstance();
    try {
        // Parse the input file
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(file, this);
    } catch (Throwable t) {
        logger.severe("Error by importing " + ((XMLTopicFactory) this).pageName, t);
        throw new Exception("Error by import: " + t.getMessage(), t);
    }
    return this.processedTopicName;
}

From source file:org.jbuiltDemo.managed.view.Xhtml2Jbuilt.java

public String convertToJbuilt(InputStream xhtmlSource) throws Exception {
    this.info = new ParsingInfo();

    SAXParser parser = this.createParser();
    parser.parse(xhtmlSource, this);
    xhtmlSource.close();//  w w  w. java 2  s .c om

    StringBuffer code = new StringBuffer();
    code.append("package org.jbuiltDemo.managed.view;\n").append("import javax.faces.component.UIComponent;\n")
            .append("import javax.faces.context.FacesContext;\n")
            .append("import org.jbuilt.view.componentTree.JsfViewDirector;\n")
            .append("import org.jbuiltDemo.managed.annotations._UIViewRoot;\n")
            .append("import org.jbuiltDemo.managed.annotations._grid;\n")
            .append("import com.google.inject.Inject;\n")
            .append("public class " + fileName + " extends BaseViewClosure {\n").append("@Inject\n")
            .append(fileName + "(@_UIViewRoot UIComponent tree, FacesContext facesContext, \n")
            .append("@_" + ownerName + " JsfViewDirector owner){\n").append("super(tree, facesContext);\n")
            .append("this.owner = owner;\n").append("this.tree = tree;\n")
            .append("this.facesContext = facesContext;\n").append("}\n").append("@Override\n")
            .append("public Object doExecute(Object... args) {\n").append("UIComponent html =\n");

    for (String mapping : info.mappings.keySet()) {
        if (defaultMappings.containsKey(mapping)) {
            continue;
        }
        code.append(info.mappings.get(mapping)).append(" = ns.\"").append(mapping).append("\"\n");
    }

    code.append("\n");

    //      if (info.dtd != null) code.append("println \"").append(info.dtd.replaceAll("\"", "\\\\\""))
    //         .append("\"").append("\n");
    this.convertNode(info.root, code, "");
    code.append("\n").append("\t").append(";\n return html;\n}\n}");
    String codeAsString = code.toString().trim();
    //      codeAsString = codeAsString.replaceAll("/\\*P\\*/\r\t\t\\(/\\*Z\\*/", ",");
    codeAsString = codeAsString.replaceAll("\\(/\\*Z\\*/", ",");
    codeAsString = codeAsString.replaceAll("([a-z0-9]+)\\s,", "$1(");
    codeAsString = codeAsString.replaceAll("/\\*L no CH\\*/", ",");
    codeAsString = codeAsString.replaceAll("/\\*[A-Z0-9a-z]*\\*/", "");

    //        \)/\*L no CH\*/
    //        /\*[A-Z0-9a-z]*\*/
    return codeAsString;

}

From source file:org.ksoap2.transport.HttpTransportSE2.java

/**
 * ? ?    web-??//from  w w w  .j  a  v  a  2s . c o m
 *
 * @param is
 * @param file
 * @return
 */
private boolean parseXml(InputStream is, File file) {
    boolean complete = false;
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();

        SAXParser parser = factory.newSAXParser();
        SaxHandler saxHandler = new SaxHandler(file);

        parser.parse(is, saxHandler);
        complete = saxHandler.isComplete();

    } catch (ParserConfigurationException e) {
        Dbg.printStackTrace(e);
    } catch (SAXException e) {
        Dbg.printStackTrace(e);
    } catch (IOException e) {
        Dbg.printStackTrace(e);
    }
    return complete;
}

From source file:org.kuali.core.db.torque.KualiXmlToAppData.java

/**
 * Parses a XML input file and returns a newly created and
 * populated Database structure./*from  w w w. jav  a 2s.  c o m*/
 *
 * @param xmlFile The input file to parse.
 * @return Database populated by <code>xmlFile</code>.
 */
public KualiDatabase 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;

        saxFactory.setValidating(false);
        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(xmlFile);
            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.kuali.kra.test.OjbRepositoryMappingTest.java

/**
 * This method verifies the tables for a repository file
 * @throws SQLException/*w w  w  .  j ava2  s.  c  o  m*/
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 * @throws ClassNotFoundException 
 */
private void verifyTableForRepository(String repositoryFilePath)
        throws SQLException, ParserConfigurationException, SAXException, IOException, ClassNotFoundException {

    //loading the driver class so that DriverManager can find it
    Class.forName(dsDriver);
    final Connection conn = DriverManager.getConnection(dsUrl, dsUser, dsPass);
    final DefaultHandler handler = new TableValidationHandler(conn);

    LOG.debug(String.format("Starting XML validation"));
    final InputStream repositoryStream = getFileResource(repositoryFilePath).getInputStream();

    LOG.debug(String.format("Found repository url %s\n", repositoryFilePath));

    final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setValidating(true);
    saxParserFactory.setNamespaceAware(false);

    final SAXParser parser = saxParserFactory.newSAXParser();
    try {
        parser.parse(repositoryStream, handler);
    } finally {
        try {
            conn.close();
        } catch (Exception e) {
        }
    }
}

From source file:org.kuali.kra.test.OjbRepositoryMappingTest.java

/**
 * @param repositoryFilePath//  w  ww  . j  av a 2 s.co m
 * @throws ParserConfigurationException
 * @throws SAXException
 */
private void validateXml(String repositoryFilePath) throws Exception {
    LOG.debug(String.format("Starting XML validation"));
    SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
    saxParserFactory.setValidating(true);
    saxParserFactory.setNamespaceAware(false);

    SAXParser parser = saxParserFactory.newSAXParser();
    final InputStream repositoryStream = getFileResource(repositoryFilePath).getInputStream();
    parser.parse(repositoryStream, new DefaultHandler());
}

From source file:org.languagetool.dev.wikipedia.CheckWikipediaDump.java

private void run(File propFile, Set<String> disabledRules, String langCode, String xmlFileName,
        String[] ruleIds, int maxArticles, int maxErrors)
        throws IOException, SAXException, ParserConfigurationException {
    //final long startTime = System.currentTimeMillis();
    final File file = new File(xmlFileName);
    if (!file.exists() || !file.isFile()) {
        throw new IOException("File doesn't exist or isn't a file: " + xmlFileName);
    }//w w  w.  java2 s. c o m
    final Language lang = Language.getLanguageForShortName(langCode);
    final JLanguageTool languageTool = new MultiThreadedJLanguageTool(lang);
    languageTool.activateDefaultPatternRules();
    if (ruleIds != null) {
        enableSpecifiedRules(ruleIds, languageTool);
    } else {
        applyRuleDeactivation(languageTool, disabledRules);
    }
    disableSpellingRules(languageTool);
    final Date dumpDate = getDumpFileDate(file);
    System.out.println("Dump date: " + dumpDate + ", language: " + langCode);
    System.out.println("Article limit: " + (maxArticles > 0 ? maxArticles : "no limit"));
    System.out.println("Error limit: " + (maxErrors > 0 ? maxErrors : "no limit"));
    BaseWikipediaDumpHandler xmlHandler = null;
    try {
        if (propFile != null) {
            xmlHandler = new DatabaseDumpHandler(languageTool, dumpDate, langCode, propFile, lang);
        } else {
            xmlHandler = new OutputDumpHandler(languageTool, dumpDate, langCode, lang);
        }
        xmlHandler.setMaximumArticles(maxArticles);
        xmlHandler.setMaximumErrors(maxErrors);
        final SAXParserFactory factory = SAXParserFactory.newInstance();
        final SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(file, xmlHandler);
    } catch (ErrorLimitReachedException | ArticleLimitReachedException e) {
        System.out.println(e);
    } finally {
        if (xmlHandler != null) {
            final float matchesPerDoc = (float) xmlHandler.getRuleMatchCount() / xmlHandler.getArticleCount();
            System.out.printf(lang + ": %d total matches\n", xmlHandler.getRuleMatchCount());
            System.out.printf(lang + ": %.2f rule matches per document\n", matchesPerDoc);
            //System.out.printf(lang + ": %s total runtime\n", getRunTime(startTime));
            xmlHandler.close();
        }
    }
}