Search in sources :

Example 56 with Attributes

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

the class PropertiesUtil method _getResourceNodeInfo.

private static synchronized ResourceNodeInfo _getResourceNodeInfo(IFile portletXml) {
    if ((_tmpResourceNodeInfo == null) || !_tmpResourceNodeInfo.getPortletXml().equals(portletXml) || (_tmpResourceNodeInfo.getModificationStamp() != portletXml.getModificationStamp())) {
        ResourceNodeInfo retval = new ResourceNodeInfo(portletXml);
        try {
            DefaultHandler handler = new DefaultHandler() {

                @Override
                public void characters(char[] ch, int start, int length) throws SAXException {
                    if (_supportedLocaleElem) {
                        _supportedLocaleValues.add(new String(ch, start, length));
                    }
                    if (_resourceBundleElem) {
                        _resourceBundleValue = new String(ch, start, length);
                    }
                }

                @Override
                public void endElement(String uri, String localName, String qName) throws SAXException {
                    if (qName.equals(ELEMENT_RESOURCE_BUNDLE)) {
                        _resourceBundleElem = false;
                    }
                    if (qName.equals(ELEMENT_SUPPORTED_LOCALE)) {
                        _supportedLocaleElem = false;
                    }
                    if (qName.equals(ELEMENT_PORTLET)) {
                        if (!CoreUtil.isNullOrEmpty(_resourceBundleValue)) {
                            String[] resourceBundlesPatterns = generatePropertiesNamePatternsForEncoding(_resourceBundleValue, ELEMENT_RESOURCE_BUNDLE);
                            for (String pattern : resourceBundlesPatterns) {
                                if (!CoreUtil.isNullOrEmpty(pattern)) {
                                    retval.addResourceBundlePattern(pattern);
                                }
                            }
                            if (ListUtil.isNotEmpty(_supportedLocaleValues) && ListUtil.isNotEmpty(resourceBundlesPatterns)) {
                                String resourceBundleValueBase = resourceBundlesPatterns[0];
                                for (String supportedLocaleValue : _supportedLocaleValues) {
                                    retval.addSupportedLocalePattern(resourceBundleValueBase + "_" + supportedLocaleValue);
                                }
                            }
                            String resourceBundle = _resourceBundleValue.replaceAll("(^\\s*)|(\\s*$)", StringPool.BLANK);
                            if (!resourceBundle.endsWith(PROPERTIES_FILE_SUFFIX) && !resourceBundle.contains(IPath.SEPARATOR + "") && !(CoreUtil.isWindows() && resourceBundle.contains("\\"))) {
                                resourceBundle = new Path(resourceBundle.replace(".", IPath.SEPARATOR + "")).toString();
                            }
                            retval.putResourceBundle(resourceBundle);
                        }
                        _resourceBundleValue = null;
                        _supportedLocaleValues.clear();
                    }
                }

                @Override
                public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                    if (qName.equals(ELEMENT_RESOURCE_BUNDLE)) {
                        _resourceBundleElem = true;
                    }
                    if (qName.equals(ELEMENT_SUPPORTED_LOCALE)) {
                        _supportedLocaleElem = true;
                    }
                }

                private boolean _resourceBundleElem = false;

                private String _resourceBundleValue = null;

                private boolean _supportedLocaleElem = false;

                private List<String> _supportedLocaleValues = new ArrayList<>();
            };
            InputStream contents = portletXml.getContents();
            SAXParser saxParser = _saxParserFactory.newSAXParser();
            XMLReader xmlReader = saxParser.getXMLReader();
            xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            xmlReader.setFeature("http://xml.org/sax/features/validation", false);
            saxParser.parse(contents, handler);
            contents.close();
        } catch (SAXException saxe) {
        } catch (Exception e) {
            LiferayCore.logError("Error resolving" + ILiferayConstants.PORTLET_XML_FILE, e);
        }
        _tmpResourceNodeInfo = retval;
    }
    return _tmpResourceNodeInfo;
}
Also used : IPath(org.eclipse.core.runtime.IPath) Path(org.eclipse.core.runtime.Path) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Attributes(org.xml.sax.Attributes) CoreException(org.eclipse.core.runtime.CoreException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SAXException(org.xml.sax.SAXException) SAXParser(javax.xml.parsers.SAXParser) ArrayList(java.util.ArrayList) List(java.util.List) XMLReader(org.xml.sax.XMLReader)

Example 57 with Attributes

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

the class PropertiesUtil method _getLanguageFileInfo.

/**
 * Search all language properties files referenced by liferay-hook.xml
 */
private static synchronized LanguageFileInfo _getLanguageFileInfo(IFile liferayHookXml) {
    if ((_tmpLanguageFileInfo == null) || !_tmpLanguageFileInfo.getLiferayHookXml().equals(liferayHookXml) || (_tmpLanguageFileInfo.getModificationStamp() != liferayHookXml.getModificationStamp())) {
        LanguageFileInfo retval = new LanguageFileInfo(liferayHookXml);
        try {
            DefaultHandler handler = new DefaultHandler() {

                @Override
                public void characters(char[] ch, int start, int length) throws SAXException {
                    if (!_langPropElem) {
                        return;
                    }
                    String languagePropertiesValue = new String(ch, start, length);
                    if (languagePropertiesValue.endsWith(PROPERTIES_FILE_SUFFIX)) {
                        String[] languagePropertiesPatterns = generatePropertiesNamePatternsForEncoding(languagePropertiesValue, ELEMENT_LANGUAGE_PROPERTIES);
                        for (String pattern : languagePropertiesPatterns) {
                            if (pattern != null) {
                                retval.addLanguagePropertiesPattern(pattern);
                            }
                        }
                    }
                }

                @Override
                public void endElement(String uri, String localName, String qName) throws SAXException {
                    if (qName.equals(ELEMENT_LANGUAGE_PROPERTIES)) {
                        _langPropElem = false;
                    }
                }

                @Override
                public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
                    if (qName.equals(ELEMENT_LANGUAGE_PROPERTIES)) {
                        _langPropElem = true;
                    }
                }

                private boolean _langPropElem = false;
            };
            InputStream contents = liferayHookXml.getContents();
            SAXParser saxParser = _saxParserFactory.newSAXParser();
            XMLReader xmlReader = saxParser.getXMLReader();
            xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
            xmlReader.setFeature("http://xml.org/sax/features/validation", false);
            saxParser.parse(contents, handler);
            contents.close();
        } catch (Exception e) {
            LiferayCore.logError("Error resolving " + ILiferayConstants.LIFERAY_HOOK_XML_FILE, e);
        }
        _tmpLanguageFileInfo = retval;
    }
    return _tmpLanguageFileInfo;
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) Attributes(org.xml.sax.Attributes) SAXParser(javax.xml.parsers.SAXParser) XMLReader(org.xml.sax.XMLReader) CoreException(org.eclipse.core.runtime.CoreException) IOException(java.io.IOException) SAXException(org.xml.sax.SAXException) DefaultHandler(org.xml.sax.helpers.DefaultHandler)

Example 58 with Attributes

use of org.xml.sax.Attributes in project iaf by ibissource.

the class ValidatorEntityExpansionTest method parseAndRenderString.

@Override
public String parseAndRenderString(String xsd, String xmlIn) throws Exception {
    // AbstractXmlValidator instance = implementation.newInstance();
    // instance.setSchemasProvider(new SchemasProviderImpl(SCHEMA_NAMESPACE, xsd));
    // instance.setIgnoreUnknownNamespaces(false);
    // instance.setAddNamespaceToSchema(false);
    // instance.configure("Setup");
    // String result=instance.validate(xmlIn, new PipeLineSessionBase(), "test");
    // System.out.println("Validation Result:"+result);
    // return instance.get
    // return result;
    AbstractXmlValidator instance = implementation.newInstance();
    System.out.println("Created instance [" + instance.getClass().getName() + "]");
    instance.setSchemasProvider(new SchemasProviderImpl(SCHEMA_NAMESPACE, xsd));
    instance.setThrowException(true);
    instance.setFullSchemaChecking(true);
    instance.configure("init");
    PipeLineSessionBase session = new PipeLineSessionBase();
    ValidationContext context = instance.createValidationContext(session, null, null);
    XMLReader reader = instance.getValidatingParser(session, context, false);
    StringReader sr = new StringReader(xmlIn);
    InputSource is = new InputSource(sr);
    final StringBuffer sb = new StringBuffer();
    ContentHandler ch = new DefaultHandler() {

        boolean elementOpen;

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            if (elementOpen) {
                sb.append(">");
                elementOpen = false;
            }
            sb.append(ch, start, length);
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
            sb.append("<" + localName);
            sb.append(" xmlns=\"").append(uri).append("\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"");
            for (int i = 0; i < atts.getLength(); i++) {
                sb.append(' ').append(atts.getLocalName(i)).append("=\"").append(atts.getValue(i)).append('"');
            }
            elementOpen = true;
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            if (elementOpen) {
                sb.append("/>");
                elementOpen = false;
            } else {
                sb.append("</" + localName + ">");
            }
        }

        @Override
        public void ignorableWhitespace(char[] ch, int start, int length) throws SAXException {
        // ignore
        }
    };
    // String testString;
    // try {
    // testString = XmlUtils.identityTransform((String) xmlIn);
    // } catch (DomBuilderException e) {
    // throw new XmlValidatorException("caught DomBuilderException", e);
    // }
    // System.out.println("TestStr:"+testString);
    reader.setContentHandler(ch);
    reader.parse(is);
    instance.finalizeValidation(context, session, null);
    XmlValidatorErrorHandler errorHandler = context.getErrorHandler();
    if (errorHandler.hasErrorOccured()) {
        throw new SAXException(errorHandler.getReasons());
    }
    return sb.toString();
}
Also used : InputSource(org.xml.sax.InputSource) Attributes(org.xml.sax.Attributes) ContentHandler(org.xml.sax.ContentHandler) DefaultHandler(org.xml.sax.helpers.DefaultHandler) SAXException(org.xml.sax.SAXException) StringReader(java.io.StringReader) XMLReader(org.xml.sax.XMLReader) PipeLineSessionBase(nl.nn.adapterframework.core.PipeLineSessionBase)

Example 59 with Attributes

use of org.xml.sax.Attributes in project drbookings by DrBookings.

the class XMLStorage method countElements.

public static long countElements(final String tagName, final File file) throws SAXException, IOException, ParserConfigurationException {
    final InputStream in = new FileInputStream(file);
    final SAXParserFactory spf = SAXParserFactory.newInstance();
    final SAXParser saxParser = spf.newSAXParser();
    final AtomicInteger counter = new AtomicInteger();
    saxParser.parse(in, new DefaultHandler() {

        @Override
        public void startElement(final String uri, final String localName, final String qName, final Attributes attributes) {
            if (qName.equals(tagName)) {
                counter.incrementAndGet();
            }
        }
    });
    return counter.longValue();
}
Also used : AtomicInteger(java.util.concurrent.atomic.AtomicInteger) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) Attributes(org.xml.sax.Attributes) SAXParser(javax.xml.parsers.SAXParser) FileInputStream(java.io.FileInputStream) SAXParserFactory(javax.xml.parsers.SAXParserFactory) DefaultHandler(org.xml.sax.helpers.DefaultHandler)

Example 60 with Attributes

use of org.xml.sax.Attributes in project CommandHelper by EngineHub.

the class SAXDocument method parse.

/**
 * Parses the XML document. As elements are loaded, if they match, they are sent to the listeners that match the
 * element.
 *
 * @throws SAXException
 * @throws IOException
 */
public void parse() throws SAXException, IOException {
    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser saxParser;
    try {
        saxParser = factory.newSAXParser();
    } catch (ParserConfigurationException | SAXException ex) {
        throw new RuntimeException(ex);
    }
    saxParser.parse(stream, new DefaultHandler() {

        Stack<String> nodeNames = new Stack<>();

        Stack<Map<String, AtomicInteger>> nodeCount = new Stack<>();

        String lastElement = "";

        Map<String, StringBuilder> contents = new HashMap<>();

        Stack<Attributes> attributeStack = new Stack<>();

        @Override
        public void startDocument() throws SAXException {
            nodeCount.push(new HashMap<String, AtomicInteger>());
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            nodeNames.push(qName);
            Map<String, AtomicInteger> c = nodeCount.peek();
            if (!c.containsKey(qName)) {
                c.put(qName, new AtomicInteger(1));
            } else {
                c.get(qName).incrementAndGet();
            }
            Map<String, AtomicInteger> counts = new HashMap<>();
            nodeCount.push(counts);
            if (!contents.isEmpty()) {
                StringBuilder b = new StringBuilder();
                b.append("<").append(qName).append("");
                for (int i = 0; i < attributes.getLength(); i++) {
                    b.append(" ").append(attributes.getQName(i)).append("=\"").append(attributes.getValue(i).replace("\"", "&quot;")).append("\"");
                }
                b.append(">");
                appendAll(b.toString());
            }
            String path = pathFromMarkers(nodeNames, nodeCount);
            if (hasListener(path)) {
                contents.put(getListenerPath(path), new StringBuilder());
                attributeStack.push(attributes);
            }
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            if (!contents.isEmpty()) {
                String s = fromChars(ch, start, length);
                appendAll(s);
            }
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            String path = pathFromMarkers(nodeNames, nodeCount);
            if (hasListener(path)) {
                String key = getListenerPath(path);
                StringBuilder b = contents.remove(key);
                Attributes attr = attributeStack.pop();
                Map<String, String> attributes = new LinkedHashMap<>();
                for (int i = 0; i < attr.getLength(); i++) {
                    attributes.put(attr.getQName(i), attr.getValue(i));
                }
                notifyListeners(path, qName, attributes, b.toString());
            }
            if (!contents.isEmpty()) {
                appendAll("</" + qName + ">");
            }
            nodeNames.pop();
            nodeCount.pop();
        }

        private void appendAll(String s) {
            for (StringBuilder b : contents.values()) {
                b.append(s);
            }
        }
    });
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Attributes(org.xml.sax.Attributes) SAXException(org.xml.sax.SAXException) DefaultHandler(org.xml.sax.helpers.DefaultHandler) Stack(java.util.Stack) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) SAXParser(javax.xml.parsers.SAXParser) ParserConfigurationException(javax.xml.parsers.ParserConfigurationException) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) SAXParserFactory(javax.xml.parsers.SAXParserFactory)

Aggregations

Attributes (org.xml.sax.Attributes)279 DefaultHandler (org.xml.sax.helpers.DefaultHandler)74 SAXException (org.xml.sax.SAXException)66 AttributesImpl (org.xml.sax.helpers.AttributesImpl)50 SAXParser (javax.xml.parsers.SAXParser)48 Test (org.junit.Test)46 POSaveFailedException (org.adempiere.pipo.exception.POSaveFailedException)37 InputSource (org.xml.sax.InputSource)33 SAXParserFactory (javax.xml.parsers.SAXParserFactory)30 IOException (java.io.IOException)29 File (java.io.File)22 ByteArrayInputStream (java.io.ByteArrayInputStream)19 InputStream (java.io.InputStream)17 ArrayList (java.util.ArrayList)17 ParserConfigurationException (javax.xml.parsers.ParserConfigurationException)17 Test (org.junit.jupiter.api.Test)17 XMLReader (org.xml.sax.XMLReader)17 ContentHandler (org.xml.sax.ContentHandler)15 StringReader (java.io.StringReader)12 Transformer (org.apache.sling.rewriter.Transformer)10