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:immf.AppNotifications.java

private boolean auth() {
    boolean httpOk = false;
    while (!httpOk) {
        try {/*from ww w .  j  av  a  2  s  .c om*/
            SAXParserFactory spfactory = SAXParserFactory.newInstance();
            SAXParser parser = spfactory.newSAXParser();
            byte[] xml = this.getCredentials();
            InputStream is = new ByteArrayInputStream(xml);
            parser.parse(is, this);
            httpOk = true;
        } catch (Exception e) {
            log.warn("5????", e);
            try {
                Thread.sleep(ReconnectInterval * ReconnectCount);
            } catch (Exception ee) {
            }
        }
    }
    if (!ok.equals("OK")) {
        ok = "";
        return false;
    }
    this.setCredentials();
    return true;
}

From source file:kmlvalidator.KmlValidatorServlet.java

/**
 * Handles POST requests for the servlet.
 */// w  ww  .j  ava 2 s. c o  m
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // Our response is always JSON.
    response.setContentType("application/json");

    // Create the JSON response objects to be filled in later.
    JSONObject responseObj = new JSONObject();
    JSONArray responseErrors = new JSONArray();

    try {
        // Load XSD files here. Note that the Java runtime should be caching
        // these files.
        Object[] schemas = {
                new URL("http://schemas.opengis.net/kml/2.2.0/atom-author-link.xsd").openConnection()
                        .getInputStream(),
                new URL("http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd").openConnection().getInputStream(),
                new URL("http://code.google.com/apis/kml/schema/kml22gx.xsd").openConnection()
                        .getInputStream() };

        // Create a SAX parser factory (not a DOM parser, we don't need the
        // overhead) and set it to validate and be namespace aware, for
        // we want to validate against multiple XSDs.
        SAXParserFactory parserFactory = SAXParserFactory.newInstance();
        parserFactory.setValidating(true);
        parserFactory.setNamespaceAware(true);

        // Create a SAX parser and prepare for XSD validation.
        SAXParser parser = parserFactory.newSAXParser();
        parser.setProperty(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        parser.setProperty(JAXP_SCHEMA_SOURCE, schemas);

        // Create a parser handler to trap errors during parse.
        KmlValidatorParserHandler parserHandler = new KmlValidatorParserHandler();

        // Parse the KML and send all errors to our handler.
        parser.parse(request.getInputStream(), parserHandler);

        // Check our handler for validation results.
        if (parserHandler.getErrors().size() > 0) {
            // There were errors, enumerate through them and create JSON objects
            // for each one.
            for (KmlValidationError e : parserHandler.getErrors()) {
                JSONObject error = new JSONObject();

                switch (e.getType()) {
                case KmlValidationError.VALIDATION_WARNING:
                    error.put("type", "warning");
                    break;

                case KmlValidationError.VALIDATION_ERROR:
                    error.put("type", "error");
                    break;

                case KmlValidationError.VALIDATION_FATAL_ERROR:
                    error.put("type", "fatal_error");
                    break;

                default:
                    error.put("type", "fatal_error");
                }

                // fill in parse exception details
                SAXParseException innerException = e.getInnerException();
                error.put("message", innerException.getMessage());

                if (innerException.getLineNumber() >= 0)
                    error.put("line", innerException.getLineNumber());

                if (innerException.getColumnNumber() >= 0)
                    error.put("column", innerException.getColumnNumber());

                // add this error to the list
                responseErrors.add(error);
            }

            // The KML wasn't valid.
            responseObj.put("status", "invalid");
        } else {
            // The KML is valid against the XSDs.
            responseObj.put("status", "valid");
        }
    } catch (SAXException e) {
        // We should never get here due to regular parse errors. This error
        // must've been thrown by the schema factory.
        responseObj.put("status", "internal_error");

        JSONObject error = new JSONObject();
        error.put("type", "fatal_error");
        error.put("message", "Internal error: " + e.getMessage());
        responseErrors.add(error);

    } catch (ParserConfigurationException e) {
        // Internal error at this point.
        responseObj.put("status", "internal_error");

        JSONObject error = new JSONObject();
        error.put("type", "fatal_error");
        error.put("message", "Internal parse error.");
        responseErrors.add(error);
    }

    // If there were errors, add them to the final response JSON object.
    if (responseErrors.size() > 0) {
        responseObj.put("errors", responseErrors);
    }

    // output the JSON object as the HTTP response and append a newline for
    // prettiness
    response.getWriter().print(responseObj);
    response.getWriter().println();
}

From source file:com.sun.faban.harness.webclient.CLIServlet.java

private void sendLogs(String[] reqC, HttpServletResponse response) throws ServletException, IOException {
    if (reqC.length < 2) {
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Missing RunId.");
        return;//from  w  w  w  . j a v a2 s .c om
    }
    RunId runId = new RunId(reqC[1]);
    boolean[] options = new boolean[2];
    options[TAIL] = false;
    options[FOLLOW] = false;
    for (int i = 2; i < reqC.length; i++) {
        if ("tail".equals(reqC[i])) {
            options[TAIL] = true;
        } else if ("follow".equals(reqC[i])) {
            options[FOLLOW] = true;
        } else {
            response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid option \"" + reqC[i] + "\".");
            ;
            return;
        }
    }
    File logFile = new File(Config.OUT_DIR + runId, "log.xml");
    String status = null;
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();
    while (!logFile.exists()) {
        String[] pending = RunQ.listPending();
        if (pending == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND, "RunId " + runId + " not found");
            return;
        }
        boolean queued = false;
        for (String run : pending) {
            if (run.equals(runId.toString())) {
                if (status == null) {
                    status = "QUEUED";
                    out.println(status);
                    response.flushBuffer();
                }
                queued = true;
                try {
                    Thread.sleep(1000); // Check back in one sec.
                } catch (InterruptedException e) {
                    //Noop, just look it up again.
                }
                break;
            }
        }
        if (!queued) { // Either never queued or deleted from queue.
            // Check for 10x, 100ms each to allow for start time.
            for (int i = 0; i < 10; i++) {
                if (logFile.exists()) {
                    status = "STARTED";
                    break;
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    logger.log(Level.WARNING, "Interrupted checking existence of log file.");
                }
            }

            if (!"STARTED".equals(status)) {
                if ("QUEUED".equals(status)) { // was queued before
                    status = "DELETED";
                    out.println(status);
                    out.flush();
                    out.close();
                    return;
                } else { // Never queued or just removed.
                    response.sendError(HttpServletResponse.SC_NOT_FOUND, "RunId " + runId + " not found");
                    return;
                }
            }
        }
    }

    LogOutputHandler handler = new LogOutputHandler(response, options);
    InputStream logInput;
    if (options[FOLLOW]) {
        // The XMLInputStream reads streaming XML and does not EOF.
        XMLInputStream input = new XMLInputStream(logFile);
        input.addEOFListener(handler);
        logInput = input;
    } else {
        logInput = new FileInputStream(logFile);
    }
    try {
        SAXParserFactory sFact = SAXParserFactory.newInstance();
        sFact.setFeature("http://xml.org/sax/features/validation", false);
        sFact.setFeature("http://apache.org/xml/features/" + "allow-java-encodings", true);
        sFact.setFeature("http://apache.org/xml/features/nonvalidating/" + "load-dtd-grammar", false);
        sFact.setFeature("http://apache.org/xml/features/nonvalidating/" + "load-external-dtd", false);
        SAXParser parser = sFact.newSAXParser();
        parser.parse(logInput, handler);
        handler.xmlComplete = true; // If we get here, the XML is good.
    } catch (ParserConfigurationException e) {
        throw new ServletException(e);
    } catch (SAXParseException e) {
        Throwable t = e.getCause();
        // If it is caused by an IOException, we'll just throw it.
        if (t != null) {
            if (t instanceof IOException)
                throw (IOException) t;
            else if (options[FOLLOW])
                throw new ServletException(t);
        } else if (options[FOLLOW]) {
            throw new ServletException(e);
        }
    } catch (SAXException e) {
        throw new ServletException(e);
    } finally {
        if (options[TAIL] && !options[FOLLOW]) // tail not yet printed
            handler.eof();
    }
}

From source file:msi.gama.util.file.GamaOsmFile.java

private void readXML(final IScope scope, final Sink sink) throws GamaRuntimeException {
    try {//w w  w.  ja  v a 2s  .c  o  m
        InputStream inputStream = new FileInputStream(getFile(scope));
        final String ext = getExtension(scope);
        switch (ext) {
        case "gz":
            inputStream = new GZIPInputStream(inputStream);
            break;
        case "bz2":
            inputStream = new BZip2CompressorInputStream(inputStream);
            break;
        }
        try (InputStream stream = inputStream) {
            final SAXParser parser = SaxParserFactory.createParser();
            parser.parse(stream, new OsmHandler(sink, false));
        }
    } catch (final Exception e) {
        throw GamaRuntimeException.error("Unable to parse xml file " + getName(scope) + ": " + e.getMessage(),
                scope);
    }

}

From source file:com.mercatis.lighthouse3.commons.commons.XmlMuncher.java

/**
 * The constructor, which sets up the XML muncher against an XML document
 *
 * @param xml the XML document to munch.
 * @throws DOMException an exception is thrown in case of an error during XML parsing
 *//*ww w  .  j a va2s .c om*/
public XmlMuncher(String xml) throws DOMException {
    SAXParser saxParser = null;
    try {
        saxParser = (SAXParser) pool.borrowObject();
        saxParser.parse(new InputSource(new StringReader(xml)), new DefaultHandler() {

            private LinkedList<String> currentPathStack = new LinkedList<String>();
            private StringBuilder currentValue;

            @Override
            public void characters(char[] ch, int start, int length) throws SAXException {
                if (this.currentValue != null)
                    this.currentValue.append(ch, start, length);
            }

            @Override
            public void startElement(String uri, String localName, String name, Attributes attributes)
                    throws SAXException {

                this.currentValue = new StringBuilder();
                String newPath = null;

                if (this.currentPathStack.isEmpty()) {
                    newPath = "/" + localName;
                    rootElementName = localName;
                    documentPaths.add(new LinkedHashMap<String, String>());
                } else {
                    newPath = this.currentPathStack.getFirst() + "/" + localName;
                }

                this.currentPathStack.add(0, newPath);

                addDocumentPath(documentPaths, newPath, null);

            }

            @Override
            public void endElement(String uri, String localName, String name) throws SAXException {
                String currentPath = this.currentPathStack.removeFirst();

                if (currentValue != null && !"".equals(this.currentValue.toString()))
                    addDocumentPath(documentPaths, currentPath, this.currentValue.toString());

                this.currentValue = null;
            }
        });

    } catch (ParserConfigurationException e) {
        throw new DOMException((short) 0,
                "SAX-Parser configuration exception caught while munching XML document: " + e.getMessage());
    } catch (SAXException e) {
        throw new DOMException((short) 0,
                "SAX parsing exception caught while munching XML document: " + e.getMessage());
    } catch (IOException e) {
        throw new DOMException((short) 0, "IO exception caught while munching XML document: " + e.getMessage());
    } catch (Exception e) {
        throw new DOMException((short) 0, "exception caught while munching XML document: " + e.getMessage());
    } finally {
        try {
            pool.returnObject(saxParser);
        } catch (Exception e) {
            throw new DOMException((short) 0,
                    "exception caught while munching XML document: " + e.getMessage());
        }
    }
}

From source file:net.sf.ehcache.config.Configurator.java

/**
 * Configures a bean from an XML file in the classpath.
 *///from  w w w  .j a v a  2 s  . c om
public void configure(final Object bean) throws Exception {
    final SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    final BeanHandler handler = new BeanHandler(bean);
    URL url = getClass().getResource(DEFAULT_CLASSPATH_CONFIGURATION_FILE);
    if (url != null) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Configuring ehcache from ehcache.xml found in the classpath: " + url);
        }
    } else {
        url = getClass().getResource(FAILSAFE_CLASSPATH_CONFIGURATION_FILE);
        if (LOG.isWarnEnabled()) {
            LOG.warn("No configuration found. Configuring ehcache from ehcache-failsafe.xml"
                    + " found in the classpath: " + url);
        }
    }
    parser.parse(url.toExternalForm(), handler);
}

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);// w w  w.ja v  a 2 s. c o m

    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: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  www .j  a va  2 s .  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.trailmagic.image.util.ImagesParserImpl.java

@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void parse(InputStream inputStream) {
    try {/* ww  w .j  a v a 2s .c om*/

        SAXParserFactory factory = SAXParserFactory.newInstance();
        factory.setValidating(true);
        SAXParser parser = factory.newSAXParser();
        XMLReader reader = parser.getXMLReader();

        //            CatalogManager cm = new CatalogManager();
        //            Catalog catalog = cm.getCatalog();
        //            catalog.parseCatalog(getClass().getClassLoader().getResource("CatalogManager.properties"));
        //            reader.setEntityResolver(new CatalogResolver(cm));

        s_logger.info("Parsing input stream...");
        parser.parse(inputStream, this);
        s_logger.info("done");
    } catch (Throwable t) {
        t.printStackTrace();
        System.exit(1);
    }
}

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

/**
 *
 *
 * @param in/*ww  w  .j a va 2 s.  c  om*/
 *
 * @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 {
    }
}