Search in sources :

Example 41 with ErrorHandler

use of org.xml.sax.ErrorHandler in project tdi-studio-se by Talend.

the class ImportProjectSettings method updateProjectSettings.

public void updateProjectSettings() throws ParserConfigurationException, SAXException, IOException {
    if (this.path == null) {
        return;
    }
    File file = new File(path);
    org.talend.core.model.properties.Project project = pro.getEmfProject();
    final DocumentBuilderFactory fabrique = DocumentBuilderFactory.newInstance();
    DocumentBuilder analyseur = fabrique.newDocumentBuilder();
    analyseur.setErrorHandler(new ErrorHandler() {

        @Override
        public void error(final SAXParseException exception) throws SAXException {
            throw exception;
        }

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

        @Override
        public void warning(final SAXParseException exception) throws SAXException {
            throw exception;
        }
    });
    final Document document = analyseur.parse(file);
    // PTODO, if need, get the version from the imported file.
    // NodeList exportParametersNodes = document.getElementsByTagName("exportParameters");
    // String importStudioVersion=null;
    //$NON-NLS-1$
    final NodeList nodes = document.getElementsByTagName("exportParameter");
    List addedComponentSetting = new ArrayList();
    List technical = project.getTechnicalStatus();
    List documentation = project.getDocumentationStatus();
    technical.clear();
    documentation.clear();
    for (int i = 0; i < nodes.getLength(); i++) {
        final Node node = nodes.item(i);
        final NamedNodeMap attrMap = node.getAttributes();
        //$NON-NLS-1$
        final Node typeAttr = attrMap.getNamedItem("type");
        if ("technicalStatus".equals(typeAttr.getTextContent())) {
            //$NON-NLS-1$
            //$NON-NLS-1$
            updateStatus(node, attrMap, technical, "technicalStatus");
        } else if ("documentationStatus".equals(typeAttr.getTextContent())) {
            //$NON-NLS-1$
            //$NON-NLS-1$
            updateStatus(node, attrMap, documentation, "documentationStatus");
        } else if ("security".equals(typeAttr.getTextContent())) {
            //$NON-NLS-1$
            project.isHidePassword();
            project.setHidePassword(Boolean.valueOf(node.getTextContent()));
        } else if ("statAndLogs".equals(typeAttr.getTextContent())) {
            //$NON-NLS-1$
            if (project.getStatAndLogsSettings() == null) {
                TalendFileFactory talendF = TalendFileFactory.eINSTANCE;
                StatAndLogsSettings stats = PropertiesFactory.eINSTANCE.createStatAndLogsSettings();
                project.setStatAndLogsSettings(stats);
                stats.setParameters(talendF.createParametersType());
            }
            List statAndLogs = project.getStatAndLogsSettings().getParameters().getElementParameter();
            updateParameters(node, attrMap, statAndLogs);
        } else if ("implicitContext".equals(typeAttr.getTextContent())) {
            //$NON-NLS-1$
            if (project.getImplicitContextSettings() == null) {
                TalendFileFactory talendF = TalendFileFactory.eINSTANCE;
                ImplicitContextSettings implicit = PropertiesFactory.eINSTANCE.createImplicitContextSettings();
                project.setImplicitContextSettings(implicit);
                implicit.setParameters(talendF.createParametersType());
            }
            List implicitContexts = project.getImplicitContextSettings().getParameters().getElementParameter();
            updateParameters(node, attrMap, implicitContexts);
        } else if ("palette".equals(typeAttr.getTextContent())) {
            //$NON-NLS-1$
            List componentSettings = project.getComponentsSettings();
            boolean existed = false;
            //$NON-NLS-1$
            String name = attrMap.getNamedItem("name").getTextContent();
            //$NON-NLS-1$
            final Node familyAttr = attrMap.getNamedItem("family");
            Boolean hide = Boolean.valueOf(node.getTextContent());
            for (Object obj : componentSettings) {
                ComponentSetting setting = (ComponentSetting) obj;
                if (setting.getName().equals(name)) {
                    if (familyAttr != null && familyAttr.getTextContent().equals(setting.getFamily())) {
                        existed = true;
                        setting.setHidden(hide);
                    }
                }
            }
            if (!existed && familyAttr != null) {
                ComponentSetting setting = PropertiesFactory.eINSTANCE.createComponentSetting();
                setting.setFamily(familyAttr.getTextContent());
                setting.setName(name);
                setting.setHidden(hide);
                addedComponentSetting.add(setting);
            }
        }
    }
    project.getComponentsSettings().addAll(addedComponentSetting);
}
Also used : DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Node(org.w3c.dom.Node) ArrayList(java.util.ArrayList) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) TalendFileFactory(org.talend.designer.core.model.utils.emf.talendfile.TalendFileFactory) SAXParseException(org.xml.sax.SAXParseException) StatAndLogsSettings(org.talend.core.model.properties.StatAndLogsSettings) ArrayList(java.util.ArrayList) NodeList(org.w3c.dom.NodeList) List(java.util.List) ErrorHandler(org.xml.sax.ErrorHandler) NamedNodeMap(org.w3c.dom.NamedNodeMap) NodeList(org.w3c.dom.NodeList) ComponentSetting(org.talend.core.model.properties.ComponentSetting) ImplicitContextSettings(org.talend.core.model.properties.ImplicitContextSettings) DocumentBuilder(javax.xml.parsers.DocumentBuilder) File(java.io.File)

Example 42 with ErrorHandler

use of org.xml.sax.ErrorHandler in project tdi-studio-se by Talend.

the class AutoConvertTypesUtils method save.

public static boolean save(List<AutoConversionType> beans, File file) throws Exception {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    OutputStreamWriter output = null;
    try {
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setErrorHandler(new ErrorHandler() {

            @Override
            public void error(final SAXParseException exception) throws SAXException {
                throw exception;
            }

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

            @Override
            public void warning(final SAXParseException exception) throws SAXException {
                throw exception;
            }
        });
        Document document = builder.newDocument();
        //document.setXmlVersion("1.0");//$NON-NLS-1$
        //$NON-NLS-1$
        Element root = document.createElement("mapping");
        document.appendChild(root);
        for (int i = 0; i < beans.size(); i++) {
            AutoConversionType bean = beans.get(i);
            //$NON-NLS-1$
            Element typeNode = document.createElement("conversionType");
            //$NON-NLS-1$
            typeNode.setAttribute("source", bean.getSourceDataType());
            //$NON-NLS-1$
            typeNode.setAttribute("target", bean.getTargetDataType());
            //$NON-NLS-1$
            typeNode.setAttribute("function", bean.getConversionFunction());
            root.appendChild(typeNode);
        }
        // save into file
        if (document != null) {
            XMLSerializer serializer = new XMLSerializer();
            OutputFormat outputFormat = new OutputFormat();
            outputFormat.setIndenting(true);
            serializer.setOutputFormat(outputFormat);
            output = new OutputStreamWriter(new FileOutputStream(file));
            serializer.setOutputCharStream(output);
            serializer.serialize(document);
            // update
            beanList = new ArrayList<>();
            beanList.addAll(beans);
        }
    } catch (ParserConfigurationException e) {
        e.printStackTrace();
    } finally {
        if (output != null) {
            output.close();
        }
    }
    return true;
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) XMLSerializer(com.sun.org.apache.xml.internal.serialize.XMLSerializer) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) Element(org.w3c.dom.Element) OutputFormat(com.sun.org.apache.xml.internal.serialize.OutputFormat) Document(org.w3c.dom.Document) SAXException(org.xml.sax.SAXException) AutoConversionType(org.talend.core.model.metadata.types.AutoConversionType) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SAXParseException(org.xml.sax.SAXParseException) FileOutputStream(java.io.FileOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException)

Example 43 with ErrorHandler

use of org.xml.sax.ErrorHandler in project JGroups by belaban.

the class XmlConfigurator method parse.

protected static XmlConfigurator parse(InputStream stream, Boolean validate) throws java.io.IOException {
    /**
     * CAUTION: crappy code ahead ! I (bela) am not an XML expert, so the code below is pretty
     * amateurish... But it seems to work, and it is executed only on startup, so no perf loss
     * on the critical path. If somebody wants to improve this, please be my guest.
     */
    try {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        boolean validation = false;
        String tmp = Util.getProperty(new String[] { Global.XML_VALIDATION }, null, null, null);
        if (tmp != null) {
            validation = Boolean.valueOf(tmp);
        } else if (validate != null) {
            validation = validate;
        }
        factory.setValidating(validation);
        factory.setNamespaceAware(validation);
        if (validation) {
            factory.setAttribute(JAXP_SCHEMA_LANGUAGE, W3C_XML_SCHEMA);
        }
        DocumentBuilder builder = factory.newDocumentBuilder();
        builder.setEntityResolver((publicId, systemId) -> {
            if (systemId != null && systemId.startsWith("http://www.jgroups.org/schema/JGroups-")) {
                String schemaName = systemId.substring("http://www.jgroups.org/".length());
                InputStream schemaIs = getAsInputStreamFromClassLoader(schemaName);
                if (schemaIs == null) {
                    throw new IOException("Schema not found from classloader: " + schemaName);
                }
                InputSource source = new InputSource(schemaIs);
                source.setPublicId(publicId);
                source.setSystemId(systemId);
                return source;
            }
            return null;
        });
        // Use AtomicReference to allow make variable final, not for atomicity
        // We store only last exception
        final AtomicReference<SAXParseException> exceptionRef = new AtomicReference<>();
        builder.setErrorHandler(new ErrorHandler() {

            public void warning(SAXParseException exception) throws SAXException {
                log.warn(Util.getMessage("ParseFailure"), exception);
            }

            public void fatalError(SAXParseException exception) throws SAXException {
                exceptionRef.set(exception);
            }

            public void error(SAXParseException exception) throws SAXException {
                exceptionRef.set(exception);
            }
        });
        Document document = builder.parse(stream);
        if (exceptionRef.get() != null) {
            throw exceptionRef.get();
        }
        // The root element of the document should be the "config" element,
        // but the parser(Element) method checks this so a check is not
        // needed here.
        Element configElement = document.getDocumentElement();
        return parse(configElement);
    } catch (Exception x) {
        throw new IOException(String.format(Util.getMessage("ParseError"), x.getLocalizedMessage()));
    }
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) InputSource(org.xml.sax.InputSource) DocumentBuilderFactory(javax.xml.parsers.DocumentBuilderFactory) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) IOException(java.io.IOException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException) SAXException(org.xml.sax.SAXException) DocumentBuilder(javax.xml.parsers.DocumentBuilder) SAXParseException(org.xml.sax.SAXParseException)

Example 44 with ErrorHandler

use of org.xml.sax.ErrorHandler in project liferay-ide by liferay.

the class KaleoUtil method createJSONTitleMap.

public static String createJSONTitleMap(String title, String portalLocale) throws JSONException {
    JSONObject jsonTitleMap = new JSONObject();
    try {
        ErrorHandler errorHandle = new ErrorHandler() {

            public void error(SAXParseException exception) throws SAXException {
            }

            public void fatalError(SAXParseException exception) throws SAXException {
            }

            public void warning(SAXParseException exception) throws SAXException {
            }
        };
        Document doc = FileUtil.readXML(new ByteArrayInputStream(title.getBytes()), null, errorHandle);
        String defaultLocale = doc.getDocumentElement().getAttribute("default-locale");
        NodeList titles = doc.getElementsByTagName("Title");
        for (int i = 0; i < titles.getLength(); i++) {
            Node titleNode = titles.item(i);
            String titleValue = titleNode.getTextContent();
            NamedNodeMap nameNodeMap = titleNode.getAttributes();
            Node node = nameNodeMap.getNamedItem("language-id");
            String languageId = node.getNodeValue();
            if (languageId.equals(defaultLocale)) {
                jsonTitleMap.put(languageId, titleValue);
                break;
            }
        }
    } catch (Exception e) {
        jsonTitleMap.put(portalLocale, title);
    }
    return jsonTitleMap.toString();
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) NamedNodeMap(org.w3c.dom.NamedNodeMap) JSONObject(org.json.JSONObject) ByteArrayInputStream(java.io.ByteArrayInputStream) SAXParseException(org.xml.sax.SAXParseException) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Document(org.w3c.dom.Document) JSONException(org.json.JSONException) SAXParseException(org.xml.sax.SAXParseException) SAXException(org.xml.sax.SAXException)

Example 45 with ErrorHandler

use of org.xml.sax.ErrorHandler in project freemarker by apache.

the class DOMConvenienceStaticsTest method toDOM.

private Document toDOM(String content) throws SAXException, IOException, ParserConfigurationException {
    DocumentBuilder builder = NodeModel.getDocumentBuilderFactory().newDocumentBuilder();
    ErrorHandler errorHandler = NodeModel.getErrorHandler();
    if (errorHandler != null)
        builder.setErrorHandler(errorHandler);
    return builder.parse(toInputSource(content));
}
Also used : ErrorHandler(org.xml.sax.ErrorHandler) DocumentBuilder(javax.xml.parsers.DocumentBuilder)

Aggregations

ErrorHandler (org.xml.sax.ErrorHandler)69 SAXException (org.xml.sax.SAXException)59 SAXParseException (org.xml.sax.SAXParseException)55 DocumentBuilder (javax.xml.parsers.DocumentBuilder)26 IOException (java.io.IOException)25 DocumentBuilderFactory (javax.xml.parsers.DocumentBuilderFactory)24 Document (org.w3c.dom.Document)20 InputSource (org.xml.sax.InputSource)17 FileInputStream (java.io.FileInputStream)11 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)11 Element (org.w3c.dom.Element)10 File (java.io.File)9 ByteArrayInputStream (java.io.ByteArrayInputStream)8 InputStream (java.io.InputStream)8 Validator (javax.xml.validation.Validator)8 EntityResolver (org.xml.sax.EntityResolver)8 StreamSource (javax.xml.transform.stream.StreamSource)6 Schema (javax.xml.validation.Schema)6 SchemaFactory (javax.xml.validation.SchemaFactory)6 Node (org.w3c.dom.Node)5