Search in sources :

Example 81 with SAXParseException

use of org.xml.sax.SAXParseException in project dhis2-core by dhis2.

the class DefaultGmlImportService method createNotifierErrorMessage.

private String createNotifierErrorMessage(Throwable throwable) {
    StringBuilder sb = new StringBuilder("GML import failed: ");
    Throwable rootThrowable = ExceptionUtils.getRootCause(throwable);
    if (rootThrowable == null) {
        rootThrowable = throwable;
    }
    if (rootThrowable instanceof SAXParseException) {
        SAXParseException e = (SAXParseException) rootThrowable;
        sb.append(e.getMessage());
        if (e.getLineNumber() >= 0) {
            sb.append(" On line ").append(e.getLineNumber());
            if (e.getColumnNumber() >= 0) {
                sb.append(" column ").append(e.getColumnNumber());
            }
        }
    } else if (rootThrowable instanceof MalformedByteSequenceException) {
        sb.append("Malformed GML file.");
    } else {
        sb.append(rootThrowable.getMessage());
    }
    if (sb.charAt(sb.length() - 1) != '.') {
        sb.append('.');
    }
    return HtmlUtils.htmlEscape(sb.toString());
}
Also used : SAXParseException(org.xml.sax.SAXParseException) MalformedByteSequenceException(org.apache.xerces.impl.io.MalformedByteSequenceException)

Example 82 with SAXParseException

use of org.xml.sax.SAXParseException in project Gargoyle by callakrsos.

the class FileSearcher method listClases.

public static List<ProjectInfo> listClases(String classDirName) throws Exception {
    File file = new File(classDirName);
    // 기본적인 파일의 존재유무 및 디렉토리인지 체크.
    if (!file.exists())
        throw new FileNotFoundException(file + " Not found!");
    //
    if (!file.isDirectory())
        throw new IllegalArgumentException("only directory.");
    /*
		 * 디렉토리안에 클래스패스 정보가 존재하는지 확인하고 존재한다면 classpath에 기술된 정보 기준으로 클래스 파일을
		 * 로드한다. 프로그램내에서 workspace를 선택한 경우일수있고, 프로젝트를 선택한 두가지의 경우가 있기때문에 두가지의
		 * 케이스를 고려한 로직이 들어간다.
		 */
    /*
		 * 일단 워크스페이스를 선택한경우라고 가정하고 워크스페이스내에 폴더들을 순차적으로 돌아보면서 classpath의 존재유무를 찾고
		 * 존재하는케이스는 따로 모아놓는다. 파일레벨은 워크스페이스(0레벨)-프로젝트(1레벨)로 가정하여 1레벨까지만 이동한다.
		 */
    List<File> listFiles = findClassPaths(file);
    /*
		 * classpath파일을 찾은경우 그 파일path를 기준으로 클래스들을 로딩한다.
		 */
    List<ProjectInfo> allClasses = new ArrayList<>();
    if (listFiles != null && !listFiles.isEmpty())
        LOGGER.debug(" im will working...");
    long startTime = System.currentTimeMillis();
    int searchedDirCount = 0;
    StringBuffer srchedDirNames = new StringBuffer();
    for (File f : listFiles) {
        try {
            ClassPath parsingClassPath = parsingClassPath(f.getAbsolutePath());
            // 프로젝트파일.
            File projectFile = f.getParentFile();
            // output 속성값의 존재유무만 확인하여 컴파일되는 경로를 찾는다.
            List<ProjectInfo> collect = parsingClassPath.toStream().filter(entry -> {
                boolean notEmpty = ValueUtil.isNotEmpty(entry.getOutput());
                LOGGER.debug(String.format("srch entry path : %s is Traget %b ", entry.getPath(), notEmpty));
                return notEmpty;
            }).map(pram -> pram.getOutput()).distinct().parallel().flatMap(new Function<String, Stream<ProjectInfo>>() {

                @Override
                public Stream<ProjectInfo> apply(String entry) {
                    LOGGER.debug(String.format("entry : %s", entry));
                    File compiledFilePath = new File(projectFile, entry);
                    int length = compiledFilePath.getAbsolutePath().length() + 1;
                    List<String> findClases = findClases(projectFile.getAbsolutePath(), compiledFilePath, length);
                    LOGGER.debug(compiledFilePath.toString());
                    LOGGER.debug(findClases.toString());
                    LOGGER.debug(String.valueOf(findClases.size()));
                    ProjectInfo classInfo = new ProjectInfo();
                    classInfo.setProjectName(projectFile.getName());
                    classInfo.setProjectDir(compiledFilePath.getAbsolutePath());
                    classInfo.setClasses(findClases);
                    return Stream.of(classInfo);
                }
            }).collect(Collectors.toList());
            allClasses.addAll(collect);
            searchedDirCount++;
            srchedDirNames.append(f.getAbsolutePath()).append(SystemUtils.LINE_SEPARATOR);
        } catch (SAXParseException e) {
            LOGGER.error(String.format("정상적인 XML 형태가 아님. 파일명 :  %s", f.getAbsolutePath()));
            LOGGER.error(String.format("%d 행 :: %d 열", e.getLineNumber(), e.getColumnNumber()));
        }
    }
    long endTime = System.currentTimeMillis();
    long costMillisend = endTime - startTime;
    LOGGER.debug(String.format("Total Cost time : %s (ms) searched Directory Count : %d ", costMillisend, searchedDirCount));
    LOGGER.debug(String.format("Searched Dirs info \n%s", srchedDirNames.toString()));
    return allClasses;
}
Also used : URL(java.net.URL) ZipUtil(com.kyj.fx.voeditor.visual.util.ZipUtil) LoggerFactory(org.slf4j.LoggerFactory) Function(java.util.function.Function) Supplier(java.util.function.Supplier) MimetypesFileTypeMap(javax.activation.MimetypesFileTypeMap) ArrayList(java.util.ArrayList) URLClassLoader(java.net.URLClassLoader) Document(org.w3c.dom.Document) Node(org.w3c.dom.Node) NamedNodeMap(org.w3c.dom.NamedNodeMap) Method(java.lang.reflect.Method) SystemUtils(org.apache.commons.lang.SystemUtils) ClassPathEntry(com.kyj.fx.voeditor.visual.main.model.vo.ClassPathEntry) InputSource(org.xml.sax.InputSource) Logger(org.slf4j.Logger) NodeList(org.w3c.dom.NodeList) MalformedURLException(java.net.MalformedURLException) Predicate(java.util.function.Predicate) ClassPath(com.kyj.fx.voeditor.visual.main.model.vo.ClassPath) ValueUtil(com.kyj.fx.voeditor.visual.util.ValueUtil) FileInputStream(java.io.FileInputStream) Reader(java.io.Reader) ConfigResourceLoader(com.kyj.fx.voeditor.visual.momory.ConfigResourceLoader) InputStreamReader(java.io.InputStreamReader) Collectors(java.util.stream.Collectors) File(java.io.File) FileNotFoundException(java.io.FileNotFoundException) StringUtils(org.h2.util.StringUtils) List(java.util.List) SAXParseException(org.xml.sax.SAXParseException) Stream(java.util.stream.Stream) DocumentBuilder(javax.xml.parsers.DocumentBuilder) FileTypeMap(javax.activation.FileTypeMap) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) ClassPath(com.kyj.fx.voeditor.visual.main.model.vo.ClassPath) FileNotFoundException(java.io.FileNotFoundException) ArrayList(java.util.ArrayList) Function(java.util.function.Function) SAXParseException(org.xml.sax.SAXParseException) File(java.io.File)

Example 83 with SAXParseException

use of org.xml.sax.SAXParseException in project GeoGig by boundlessgeo.

the class XmlReader method run.

/**
     * Reads all data from the file and send it to the sink.
     */
public void run() {
    InputStream inputStream = this.file;
    try {
        SAXParser parser;
        sink.initialize(Collections.<String, Object>emptyMap());
        // make "-" an alias for /dev/stdin
        // if (file.getName().equals("-")) {
        // inputStream = System.in;
        // } else {
        // inputStream = new FileInputStream(file);
        // }
        inputStream = new CompressionActivator(compressionMethod).createCompressionInputStream(inputStream);
        parser = createParser();
        parser.parse(inputStream, new OsmHandler(sink, enableDateParsing));
        sink.complete();
    } catch (SAXParseException e) {
        throw new OsmosisRuntimeException("Unable to parse xml file " + file + ".  publicId=(" + e.getPublicId() + "), systemId=(" + e.getSystemId() + "), lineNumber=" + e.getLineNumber() + ", columnNumber=" + e.getColumnNumber() + ".", e);
    } catch (SAXException e) {
        throw new OsmosisRuntimeException("Unable to parse XML.", e);
    } catch (IOException e) {
        throw new OsmosisRuntimeException("Unable to read XML file " + file + ".", e);
    } finally {
        sink.release();
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                log.log(Level.SEVERE, "Unable to close input stream.", e);
            }
            inputStream = null;
        }
    }
}
Also used : InputStream(java.io.InputStream) SAXParseException(org.xml.sax.SAXParseException) SAXParser(javax.xml.parsers.SAXParser) OsmHandler(org.openstreetmap.osmosis.xml.v0_6.impl.OsmHandler) IOException(java.io.IOException) CompressionActivator(org.openstreetmap.osmosis.xml.common.CompressionActivator) OsmosisRuntimeException(org.openstreetmap.osmosis.core.OsmosisRuntimeException) SAXException(org.xml.sax.SAXException)

Example 84 with SAXParseException

use of org.xml.sax.SAXParseException in project jangaroo-tools by CoreMedia.

the class ExmlValidator method setupSAXParser.

private SAXParser setupSAXParser() throws IOException {
    try {
        SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
        ExmlSchemaResolver exmlSchemaResolver = new ExmlSchemaResolver();
        schemaFactory.setResourceResolver(exmlSchemaResolver);
        List<Source> schemas = new ArrayList<Source>();
        schemas.add(new StreamSource(getClass().getResourceAsStream(Exmlc.EXML_SCHEMA_LOCATION), "exml"));
        schemas.add(new StreamSource(getClass().getResourceAsStream(Exmlc.EXML_UNTYPED_SCHEMA_LOCATION), "untyped"));
        Collection<ExmlSchemaSource> exmlSchemaSources = exmlSchemaSourceByNamespace.values();
        for (ExmlSchemaSource exmlSchemaSource : exmlSchemaSources) {
            schemas.add(exmlSchemaSource.newStreamSource());
        }
        Schema exmlSchema = schemaFactory.newSchema(schemas.toArray(new Source[schemas.size()]));
        final SAXParserFactory saxFactory = SAXParserFactory.newInstance();
        saxFactory.setNamespaceAware(true);
        saxFactory.setSchema(exmlSchema);
        SAXParser saxParser = saxFactory.newSAXParser();
        saxParser.getXMLReader().setEntityResolver(new EntityResolver() {

            @Override
            public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
                // To change body of implemented methods use File | Settings | File Templates.
                return null;
            }
        });
        return saxParser;
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException("A default dom builder should be provided.", e);
    } catch (SAXParseException e) {
        // SAX parser error while parsing EXML schemas: log only, will cause error or warning, depending on configuration:
        logSAXParseException(null, e, true);
        return null;
    } catch (SAXException e) {
        throw new IllegalStateException("SAX parser does not support validation.", e);
    }
}
Also used : SchemaFactory(javax.xml.validation.SchemaFactory) InputSource(org.xml.sax.InputSource) StreamSource(javax.xml.transform.stream.StreamSource) Schema(javax.xml.validation.Schema) ArrayList(java.util.ArrayList) EntityResolver(org.xml.sax.EntityResolver) IOException(java.io.IOException) StreamSource(javax.xml.transform.stream.StreamSource) Source(javax.xml.transform.Source) InputSource(org.xml.sax.InputSource) SAXException(org.xml.sax.SAXException) SAXParseException(org.xml.sax.SAXParseException) SAXParser(javax.xml.parsers.SAXParser) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Example 85 with SAXParseException

use of org.xml.sax.SAXParseException in project wcomponents by BorderTech.

the class DebugValidateXML method validateXMLAgainstSchema.

/**
 * Validate the component to make sure the generated XML is schema compliant.
 *
 * @param xml the xml to validate
 * @return Any errors found, or null if the XML is valid.
 */
public static String validateXMLAgainstSchema(final String xml) {
    // Validate XML against schema
    if (xml != null && !xml.equals("")) {
        // Wrap XML with a root element (if required)
        String testXML = wrapXMLInRootElement(xml);
        try {
            // Create SAX Parser Factory
            SAXParserFactory spf = SAXParserFactory.newInstance();
            spf.setNamespaceAware(true);
            spf.setValidating(true);
            // Create SAX Parser
            SAXParser parser = spf.newSAXParser();
            parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaLanguage", XMLConstants.W3C_XML_SCHEMA_NS_URI);
            // Set schema location
            Object schema = DebugValidateXML.class.getResource(getSchemaPath()).toString();
            parser.setProperty("http://java.sun.com/xml/jaxp/properties/schemaSource", schema);
            // Setup the handler to throw an exception when an error occurs
            DefaultHandler handler = new DefaultHandler() {

                @Override
                public void warning(final SAXParseException e) throws SAXException {
                    LOG.warn("XML Schema warning: " + e.getMessage(), e);
                    super.warning(e);
                }

                @Override
                public void fatalError(final SAXParseException e) throws SAXException {
                    throw e;
                }

                @Override
                public void error(final SAXParseException e) throws SAXException {
                    throw e;
                }
            };
            // Validate the XML
            InputSource xmlSource = new InputSource(new StringReader(testXML));
            parser.parse(xmlSource, handler);
        } catch (SAXParseException e) {
            return "At line " + e.getLineNumber() + ", column: " + e.getColumnNumber() + " ==> " + e.getMessage();
        } catch (Exception e) {
            return e.getMessage();
        }
    }
    return null;
}
Also used : InputSource(org.xml.sax.InputSource) SAXParseException(org.xml.sax.SAXParseException) StringReader(java.io.StringReader) SAXParser(javax.xml.parsers.SAXParser) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) SAXParserFactory(javax.xml.parsers.SAXParserFactory) DefaultHandler(org.xml.sax.helpers.DefaultHandler)

Aggregations

SAXParseException (org.xml.sax.SAXParseException)206 SAXException (org.xml.sax.SAXException)109 IOException (java.io.IOException)75 DocumentBuilder (javax.xml.parsers.DocumentBuilder)53 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)47 Document (org.w3c.dom.Document)47 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)42 InputSource (org.xml.sax.InputSource)39 ErrorHandler (org.xml.sax.ErrorHandler)34 Test (org.junit.Test)28 Element (org.w3c.dom.Element)24 InputStream (java.io.InputStream)20 ArrayList (java.util.ArrayList)18 NodeList (org.w3c.dom.NodeList)18 FileInputStream (java.io.FileInputStream)17 FileNotFoundException (java.io.FileNotFoundException)17 File (java.io.File)16 Node (org.w3c.dom.Node)13 StringReader (java.io.StringReader)12 URL (java.net.URL)11