Example usage for javax.xml.parsers SAXParserFactory newSAXParser

List of usage examples for javax.xml.parsers SAXParserFactory newSAXParser

Introduction

In this page you can find the example usage for javax.xml.parsers SAXParserFactory newSAXParser.

Prototype


public abstract SAXParser newSAXParser() throws ParserConfigurationException, SAXException;

Source Link

Document

Creates a new instance of a SAXParser using the currently configured factory parameters.

Usage

From source file:net.lightbody.bmp.proxy.jetty.xml.XmlParser.java

/**
 * Constructor.//from  w  ww.jav  a  2  s  .c  o m
 */
public XmlParser(boolean validating) {
    try {
        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(validating);
        _parser = factory.newSAXParser();
        try {
            if (validating)
                _parser.getXMLReader().setFeature("http://apache.org/xml/features/validation/schema",
                        validating);
        } catch (Exception e) {
            if (validating)
                log.warn("Schema validation may not be supported: ", e);
            else
                LogSupport.ignore(log, e);
        }
        _parser.getXMLReader().setFeature("http://xml.org/sax/features/validation", validating);
        _parser.getXMLReader().setFeature("http://xml.org/sax/features/namespaces", validating);
        _parser.getXMLReader().setFeature("http://xml.org/sax/features/namespace-prefixes", validating);
    } catch (Exception e) {
        log.warn(LogSupport.EXCEPTION, e);
        throw new Error(e.toString());
    }
}

From source file:edu.uci.ics.jung.io.GraphMLReader.java

/**
 * Creates a <code>GraphMLReader</code> instance with the specified
 * vertex and edge factories./*  www . ja v a2 s .  c  om*/
 *
 * @param vertex_factory the vertex factory to use to create vertex objects
 * @param edge_factory the edge factory to use to create edge objects
 * @throws ParserConfigurationException
 * @throws SAXException
 */
public GraphMLReader(Factory<V> vertex_factory, Factory<E> edge_factory)
        throws ParserConfigurationException, SAXException {
    current_vertex = null;
    current_edge = null;

    SAXParserFactory factory = SAXParserFactory.newInstance();
    saxp = factory.newSAXParser();

    current_states = new LinkedList<TagState>();

    tag_state = new DualHashBidiMap<String, TagState>();
    tag_state.put("node", TagState.VERTEX);
    tag_state.put("edge", TagState.EDGE);
    tag_state.put("hyperedge", TagState.HYPEREDGE);
    tag_state.put("endpoint", TagState.ENDPOINT);
    tag_state.put("graph", TagState.GRAPH);
    tag_state.put("data", TagState.DATA);
    tag_state.put("key", TagState.KEY);
    tag_state.put("desc", TagState.DESC);
    tag_state.put("default", TagState.DEFAULT_KEY);
    tag_state.put("graphml", TagState.GRAPHML);

    this.key_type = KeyType.NONE;

    this.vertex_factory = vertex_factory;
    this.edge_factory = edge_factory;
}

From source file:net.itransformers.topologyviewer.gui.MyGraphMLReader.java

/**
 * Creates a <code>GraphMLReader</code> instance with the specified
 * vertex and edge factories.//from  w  w w .j  a v a2  s .com
 *
 * @param vertex_factory the vertex factory to use to create vertex objects
 * @param edge_factory the edge factory to use to create edge objects
 * @throws ParserConfigurationException
 * @throws SAXException
 */
public MyGraphMLReader(Factory<V> vertex_factory, Factory<E> edge_factory)
        throws ParserConfigurationException, SAXException {
    current_vertex = null;
    current_edge = null;

    SAXParserFactory factory = SAXParserFactory.newInstance();
    saxp = factory.newSAXParser();

    current_states = new LinkedList<TagState>();

    tag_state = new DualHashBidiMap<String, TagState>();
    tag_state.put("node", TagState.VERTEX);
    tag_state.put("edge", TagState.EDGE);
    tag_state.put("hyperedge", TagState.HYPEREDGE);
    tag_state.put("endpoint", TagState.ENDPOINT);
    tag_state.put("graph", TagState.GRAPH);
    tag_state.put("data", TagState.DATA);
    tag_state.put("key", TagState.KEY);
    tag_state.put("desc", TagState.DESC);
    tag_state.put("default", TagState.DEFAULT_KEY);
    tag_state.put("graphml", TagState.GRAPHML);

    this.key_type = KeyType.NONE;

    this.vertex_factory = vertex_factory;
    this.edge_factory = edge_factory;
}

From source file:hu.bme.mit.sette.tools.jpet.JPetParser.java

@Override
protected void parseSnippet(Snippet snippet, SnippetInputsXml inputsXml) throws Exception {
    File outputFile = RunnerProjectUtils.getSnippetOutputFile(getRunnerProjectSettings(), snippet);
    File errorFile = RunnerProjectUtils.getSnippetErrorFile(getRunnerProjectSettings(), snippet);

    if (errorFile.exists()) {
        // TODO enhance this section and make it clear
        List<String> lines = FileUtils.readLines(errorFile);

        String firstLine = lines.get(0);

        if (firstLine.startsWith("ERROR: test_data_generator:unfold_bck/6: Undefined procedure:")) {
            inputsXml.setResultType(ResultType.NA);
        } else if (firstLine.startsWith("ERROR: Domain error: `clpfd_expression' expected, found")) {
            inputsXml.setResultType(ResultType.NA);
        } else if (firstLine.startsWith("ERROR: Unknown message: error(resolve_classfile/")) {
            inputsXml.setResultType(ResultType.NA);
        } else if (firstLine.startsWith("ERROR: local_control:unfold/3: Undefined procedure:")) {
            inputsXml.setResultType(ResultType.NA);
        } else {/*from  w w w.  j a v a  2s  .  c o  m*/
            // TODO enhance error handling

            // this is debug (only if unhandled error)
            System.err.println("=============================");
            System.err.println(snippet.getMethod());
            System.err.println("=============================");

            for (String line : lines) {
                System.err.println(line);
            }
            System.err.println("=============================");

            // TODO enhance error handling
            throw new RuntimeException("PARSER PROBLEM, UNHANDLED ERROR");
        }
    } else {
        // TODO enhance

        // LineIterator lines = FileUtils.lineIterator(outputFile);
        List<String> lines = FileUtils.readLines(outputFile);

        if (lines.get(lines.size() - 1).startsWith("Error loading bytecode program")) {
            // System.err.println(snippet.getMethod().getName());
            // System.err.println("BYTECODE PROBLEM");
            inputsXml.setResultType(ResultType.EX);
            // throw new RuntimeException(""
        } else {
            inputsXml.setResultType(ResultType.S);

            // extract coverage
            if (lines.size() >= 8) {
                String fullCode = lines.get(lines.size() - 3).trim();
                String topCode = lines.get(lines.size() - 2).trim();

                Matcher mFull = PATTERN_FULL_CODE.matcher(fullCode);
                Matcher mTop = PATTERN_TOP_CODE.matcher(topCode);

                // TODO should not use jPET coverage information in the
                // future
                if (mFull.matches() && mTop.matches()) {
                    double full = Double.parseDouble(mFull.group(1));
                    double top = Double.parseDouble(mTop.group(1));

                    if (full == 100.0 && top == 100.0) {
                        // full -> C
                        inputsXml.setResultType(ResultType.C);
                    } else if (snippet.getIncludedConstructors().isEmpty()
                            && snippet.getIncludedMethods().isEmpty()) {
                        // only consider top, no included things
                        if (top >= snippet.getRequiredStatementCoverage()) {
                            inputsXml.setResultType(ResultType.C);
                        } else {
                            inputsXml.setResultType(ResultType.NC);
                            // System.err.println(snippet.getMethod()
                            // .getName());
                            // System.err
                            // .println(String
                            // .format("No incl. no statis. - Full: %.2f Top: %.2f Req: %.2f",
                            // full,
                            // top,
                            // snippet.getRequiredStatementCoverage()));
                        }
                    } else {
                        // few cases, not very usefol top and full now...
                        // System.err.println(snippet.getMethod()
                        // .getName());
                        // System.err.println(String.format(
                        // "Has included - Full: %.2f Top: %.2f Req: %.2f",
                        // full,
                        // top,
                        // snippet.getRequiredStatementCoverage()));

                    }
                } else {
                    // TODO error handling
                    System.err.println("Both should match");
                }
            }

            // extract inputs
            lines = null;

            File testCasesFile = getTool().getTestCaseXmlFile(getRunnerProjectSettings(), snippet);
            new FileValidator(testCasesFile).type(FileType.REGULAR_FILE).validate();

            if (testCasesFile.length() > 10 * 10e6) {
                // TODO enhance this section
                System.err.println("Filesize is bigger than 10 MB: " + testCasesFile);
            }
            // TODO it was used to dump the cases where jpet cannot decide
            // coverage
            // if (inputsXml.getResultType() == ResultType.S) {
            // System.out.println("Only S");
            // }

            // now skip, only 12 cases are S

            System.out.println(
                    snippet.getContainer().getJavaClass().getName() + "." + snippet.getMethod().getName());

            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            JPetTestCaseXmlParser testCasesParser = new JPetTestCaseXmlParser();

            saxParser.parse(testCasesFile, testCasesParser);

            JPetTestCasesConverter.convert(snippet, testCasesParser.getTestCases(), inputsXml);
        }

        // find input lines
        //
        // List<String> inputLines = new ArrayList<>();
        // boolean shouldCollect = false;
        // while (lines.hasNext()) {
        // String line = lines.next();
        // if (line.trim()
        // .equals("====================================================== Method Summaries"))
        // {
        // shouldCollect = true;
        // } else if (shouldCollect) {
        // if
        // (line.startsWith("======================================================"))
        // {
        // // start of next section
        // shouldCollect = false;
        // break;
        // } else {
        // if (!StringUtils.isBlank(line)) {
        // inputLines.add(line.trim());
        // }
        // }
        // }
        // }
        //
        // // close iterator
        // lines.close();
        //
        // // remove duplicates
        // inputLines = new ArrayList<>(new LinkedHashSet<>(inputLines));
        //
        // String firstLine = inputLines.get(0);
        // assert (firstLine.startsWith("Inputs: "));
        // firstLine = firstLine.substring(7).trim();
        // String[] parameterStrings = StringUtils.split(firstLine, ',');
        // ParameterType[] parameterTypes = new
        // ParameterType[parameterStrings.length];
        //
        // if (inputLines.size() == 2
        // && inputLines.get(1).startsWith("No path conditions for")) {
        // InputElement input = new InputElement();
        // for (int i = 0; i < parameterStrings.length; i++) {
        // // no path conditions, only considering the "default" inputs
        // Class<?> type = snippet.getMethod().getParameterTypes()[i];
        // parameterTypes[i] = getParameterType(type);
        // input.parameters().add(
        // new ParameterElement(parameterTypes[i],
        // getDefaultParameterString(type)));
        // }
        // inputsXml.generatedInputs().add(input);
        // } else {
        // // parse parameter types
        //
        // Class<?>[] paramsJavaClass = snippet.getMethod()
        // .getParameterTypes();
        //
        // for (int i = 0; i < parameterStrings.length; i++) {
        // String parameterString = parameterStrings[i];
        // Class<?> pjc = ClassUtils
        // .primitiveToWrapper(paramsJavaClass[i]);
        //
        // if (parameterString.endsWith("SYMINT")) {
        // if (pjc == Boolean.class) {
        // parameterTypes[i] = ParameterType.BOOLEAN;
        // } else if (pjc == Byte.class) {
        // parameterTypes[i] = ParameterType.BYTE;
        // } else if (pjc == Short.class) {
        // parameterTypes[i] = ParameterType.SHORT;
        // } else if (pjc == Integer.class) {
        // parameterTypes[i] = ParameterType.INT;
        // } else if (pjc == Long.class) {
        // parameterTypes[i] = ParameterType.LONG;
        // } else {
        // // int for something else
        // parameterTypes[i] = ParameterType.INT;
        // }
        // } else if (parameterString.endsWith("SYMREAL")) {
        // if (pjc == Float.class) {
        // parameterTypes[i] = ParameterType.FLOAT;
        // } else if (pjc == Float.class) {
        // parameterTypes[i] = ParameterType.DOUBLE;
        // } else {
        // // int for something else
        // parameterTypes[i] = ParameterType.DOUBLE;
        // }
        // } else {
        // // TODO error handling
        // // int for something else
        // throw new RuntimeException("PARSER PROBLEM");
        // }
        // }
        //
        // // example
        // // inheritsAPIGuessTwoPrimitives(11,-2147483648(don't care)) -->
        // // "java.lang.IllegalArgumentException..."
        // // inheritsAPIGuessTwoPrimitives(9,11) -->
        // // "java.lang.IllegalArgumentException..."
        // // inheritsAPIGuessTwoPrimitives(7,9) -->
        // // "java.lang.RuntimeException: Out of range..."
        // // inheritsAPIGuessTwoPrimitives(4,1) --> Return Value: 1
        // // inheritsAPIGuessTwoPrimitives(0,0) --> Return Value: 0
        // // inheritsAPIGuessTwoPrimitives(9,-88) -->
        // // "java.lang.IllegalArgumentException..."
        // // inheritsAPIGuessTwoPrimitives(-88,-2147483648(don't care))
        // // --> "java.lang.IllegalArgumentException..."
        //
        // String ps = String.format("^%s\\((.*)\\) --> (.*)$", snippet
        // .getMethod().getName());
        //
        // ps = String.format("^%s(.*) --> (.*)$", snippet.getMethod()
        // .getName());
        // Pattern p = Pattern.compile(ps);
        //
        // // parse inputs
        // int i = -1;
        // for (String line : inputLines) {
        // i++;
        //
        // if (i == 0) {
        // // first line
        // continue;
        // } else if (StringUtils.isEmpty(line)) {
        // continue;
        // }
        //
        // Matcher m = p.matcher(line);
        //
        // if (m.matches()) {
        // String paramsString = StringUtils.substring(m.group(1)
        // .trim(), 1, -1);
        // String resultString = m.group(2).trim();
        //
        // paramsString = StringUtils.replace(paramsString,
        // "(don't care)", "");
        //
        // String[] paramsStrings = StringUtils.split(
        // paramsString, ',');
        //
        // InputElement input = new InputElement();
        //
        // // if index error -> lesser inputs than parameters
        // for (int j = 0; j < parameterTypes.length; j++) {
        // if (parameterTypes[j] == ParameterType.BOOLEAN
        // && paramsStrings[j].contains("-2147483648")) {
        // // don't care -> 0
        // paramsStrings[j] = "false";
        // }
        //
        // ParameterElement pe = new ParameterElement(
        // parameterTypes[j], paramsStrings[j].trim());
        //
        // try {
        // // just check the type format
        // pe.validate();
        // } catch (Exception e) {
        // // TODO debug - remove or log
        // System.out.println(parameterTypes[j]);
        // System.out.println(paramsStrings[j]);
        // System.out.println(pe.getType());
        // System.out.println(pe.getValue());
        // e.printStackTrace();
        //
        // System.err
        // .println("=============================");
        // System.err.println(snippet.getMethod());
        // System.err
        // .println("=============================");
        // for (String lll : inputLines) {
        // System.err.println(lll);
        // }
        // System.err
        // .println("=============================");
        //
        // System.exit(-1);
        // }
        //
        // input.parameters().add(pe);
        // }
        //
        // if (resultString.startsWith("Return Value:")) {
        // // has retval, nothing to do
        // } else {
        // // exception; example (" is present inside the
        // // string!!!):
        // // "java.lang.ArithmeticException: div by 0..."
        // // "java.lang.IndexOutOfBoundsException: Index: 1, Size: 5..."
        //
        // int pos = resultString.indexOf(':');
        // if (pos < 0) {
        // // not found :, search for ...
        // pos = resultString.indexOf("...");
        // }
        //
        // String ex = resultString.substring(1, pos);
        //
        // input.setExpected((Class<? extends Throwable>) Class
        // .forName(ex));
        //
        // // System.err.println(resultString);
        // // System.err.println(ex);
        // // // input.setExpected(expected);
        // }
        //
        // inputsXml.generatedInputs().add(input);
        // } else {
        // System.err.println("NO MATCH");
        // System.err.println(ps);
        // System.err.println(line);
        // throw new Exception("NO MATCH: " + line);
        // }
        // }
        // }
        //
        // inputsXml.validate();
    }
}

From source file:com.jkoolcloud.tnt4j.streams.configure.sax.ConfigParserHandlerTest.java

protected void validateConfigs(File samplesDir, String configFileWildcard, boolean checkStreams,
        List<String> skipFiles) throws Exception {
    Collection<File> sampleConfigurations = FileUtils.listFiles(samplesDir,
            FileFilterUtils.asFileFilter(
                    (FilenameFilter) new WildcardFileFilter(configFileWildcard, IOCase.INSENSITIVE)),
            TrueFileFilter.INSTANCE);/*  ww  w .ja  va2s  .c om*/

    Collection<File> sampleConfigurationsFiltered = new ArrayList<>(sampleConfigurations);
    if (CollectionUtils.isNotEmpty(skipFiles)) {
        for (File sampleConfiguration : sampleConfigurations) {
            for (String skipFile : skipFiles) {
                if (sampleConfiguration.getAbsolutePath().contains(skipFile))
                    sampleConfigurationsFiltered.remove(sampleConfiguration);
            }
        }
    }

    for (File sampleConfiguration : sampleConfigurationsFiltered) {
        System.out.println("Reading configuration file: " + sampleConfiguration.getAbsolutePath()); // NON-NLS
        Reader testReader = new FileReader(sampleConfiguration);
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        SAXParser parser = parserFactory.newSAXParser();
        ConfigParserHandler hndlr = new ConfigParserHandler();
        parser.parse(new InputSource(testReader), hndlr);

        assertNotNull("Parsed streams config data is null", hndlr.getStreamsConfigData());
        boolean parseable = true;
        if (checkStreams) {
            assertTrue("No configured streams", hndlr.getStreamsConfigData().isStreamsAvailable());

            parseable = false;
            for (TNTInputStream<?, ?> s : hndlr.getStreamsConfigData().getStreams()) {
                if (s instanceof TNTParseableInputStream) {
                    parseable = true;
                    break;
                }
            }
        }
        if (parseable) {
            assertTrue("No configured parsers", hndlr.getStreamsConfigData().isParsersAvailable());
        }

        Utils.close(testReader);
    }
}

From source file:com.agiletec.aps.system.common.entity.ApsEntityManager.java

/**
 * Create and populate the entity as specified by its type and XML definition.
 * @param entityTypeCode The Entity Type code.
 * @param xml The XML of the associated entity.
 * @return The populated entity./*from  w w w . j a v  a2s. c o m*/
 * @throws ApsSystemException If errors detected while retrieving the entity.
 */
protected IApsEntity createEntityFromXml(String entityTypeCode, String xml) throws ApsSystemException {
    try {
        IApsEntity entityPrototype = this.getEntityPrototype(entityTypeCode);
        SAXParserFactory parseFactory = SAXParserFactory.newInstance();
        SAXParser parser = parseFactory.newSAXParser();
        InputSource is = new InputSource(new StringReader(xml));
        EntityHandler handler = this.getEntityHandler();
        handler.initHandler(entityPrototype, this.getXmlAttributeRootElementName(), this.getCategoryManager());
        parser.parse(is, handler);
        return entityPrototype;
    } catch (Throwable t) {
        _logger.error("Error detected while creating the entity. typecode: {} - xml: {}", entityTypeCode, xml,
                t);
        //ApsSystemUtils.logThrowable(t, this, "createEntityFromXml");
        throw new ApsSystemException("Error detected while creating the entity", t);
    }
}

From source file:com.panet.imeta.job.entries.xmlwellformed.JobEntryXMLWellFormed.java

private boolean CheckWellFormed(FileObject file, LogWriter log) {
    boolean retval = false;
    try {//from www . j a v  a  2 s . c o  m
        SAXParserFactory factory = SAXParserFactory.newInstance();
        XMLTreeHandler handler = new XMLTreeHandler();

        // Parse the input.
        SAXParser saxParser = factory.newSAXParser();
        saxParser.parse(new File(KettleVFS.getFilename(file)), handler);
        retval = true;
    } catch (Exception e) {

        log.logError(toString(),
                Messages.getString("JobXMLWellFormed.Log.ErrorCheckingFile", file.toString(), e.getMessage()));

    }

    return retval;
}

From source file:com.sshtools.common.configuration.SshToolsConnectionProfile.java

/**
 *
 *
 * @param in/*from w ww . ja  v  a  2 s  . c o  m*/
 *
 * @throws InvalidProfileFileException
 */
public void open(InputStream in) throws InvalidProfileFileException {
    try {
        SAXParserFactory saxFactory = SAXParserFactory.newInstance();
        SAXParser saxParser = saxFactory.newSAXParser();
        XMLHandler handler = new XMLHandler();
        saxParser.parse(in, handler);
        handler = null;

        //            in.close();
    } catch (IOException ioe) {
        throw new InvalidProfileFileException("IO error. " + ioe.getMessage());
    } catch (SAXException sax) {
        throw new InvalidProfileFileException("SAX Error: " + sax.getMessage());
    } catch (ParserConfigurationException pce) {
        throw new InvalidProfileFileException("SAX Parser Error: " + pce.getMessage());
    } finally {
    }
}

From source file:com.entertailion.java.caster.RampClient.java

private void parseXml(Reader reader) {
    try {/*from  w w w  .  j av a  2  s  .c o  m*/
        InputSource inStream = new org.xml.sax.InputSource();
        inStream.setCharacterStream(reader);
        SAXParserFactory spf = SAXParserFactory.newInstance();
        SAXParser sp = spf.newSAXParser();
        XMLReader xr = sp.getXMLReader();
        AppHandler appHandler = new AppHandler();
        xr.setContentHandler(appHandler);
        xr.parse(inStream);

        connectionServiceUrl = appHandler.getConnectionServiceUrl();
        state = appHandler.getState();
        protocol = appHandler.getProtocol();
    } catch (Exception e) {
        Log.e(LOG_TAG, "parse device description", e);
    }
}

From source file:com.commonsware.android.EMusicDownloader.SingleBook.java

private void getInfoFromXML() {

    final ProgressDialog dialog = ProgressDialog.show(this, "", getString(R.string.loading), true, true);
    setProgressBarIndeterminateVisibility(true);

    Thread t3 = new Thread() {
        public void run() {

            waiting(200);/*from  w w w . j av  a  2s  . c o m*/

            try {

                URL url = new URL(urlAddress);
                SAXParserFactory spf = SAXParserFactory.newInstance();
                SAXParser sp = spf.newSAXParser();
                XMLReader xr = sp.getXMLReader();
                XMLHandlerSingleBook myXMLHandler = new XMLHandlerSingleBook();
                xr.setContentHandler(myXMLHandler);
                xr.parse(new InputSource(url.openStream()));

                genre = myXMLHandler.genre;
                publisher = myXMLHandler.publisher;
                narrator = myXMLHandler.narrator;
                edition = myXMLHandler.edition;
                artist = myXMLHandler.author;
                authorId = myXMLHandler.authorId;
                if (edition == null) {
                    edition = "";
                }
                date = myXMLHandler.releaseDate;
                rating = myXMLHandler.rating;
                sampleURL = myXMLHandler.sampleURL;
                imageURL = myXMLHandler.imageURL;

                statuscode = myXMLHandler.statuscode;

                if (statuscode != 200 && statuscode != 206) {
                    throw new Exception();
                }

                blurb = myXMLHandler.blurb;
                blurb = blurb.replace("<br> ", "<br>");
                blurbSource = myXMLHandler.blurbSource;

                handlerSetContent.sendEmptyMessage(0);
                dialog.dismiss();
                updateImage();

            } catch (Exception e) {

                final Exception ef = e;
                nameTextView.post(new Runnable() {
                    public void run() {
                        nameTextView.setText(R.string.couldnt_get_book_info);
                    }
                });
                dialog.dismiss();

            }

            handlerDoneLoading.sendEmptyMessage(0);

        }
    };
    t3.start();
}