Example usage for org.xml.sax.helpers DefaultHandler DefaultHandler

List of usage examples for org.xml.sax.helpers DefaultHandler DefaultHandler

Introduction

In this page you can find the example usage for org.xml.sax.helpers DefaultHandler DefaultHandler.

Prototype

DefaultHandler

Source Link

Usage

From source file:org.eclipse.wb.internal.core.databinding.wizards.autobindings.DescriptorContainer.java

/**
 * Parse descriptors XML file./*w  w w  .j av  a 2  s . c o m*/
 * 
 * @return {@link Map} with all descriptors.
 */
public static Map<String, DescriptorContainer> parseDescriptors(InputStream stream,
        final ClassLoader classLoader, final IImageLoader imageLoader) throws Exception {
    final Map<String, DescriptorContainer> containers = Maps.newHashMap();
    //
    SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    parser.parse(stream, new DefaultHandler() {
        private DescriptorContainer m_container;
        private AbstractDescriptor m_descriptor;
        private Class<?> m_descriptorClass;

        //
        @Override
        public void startElement(String uri, String localName, String name, Attributes attributes)
                throws SAXException {
            try {
                if ("descriptors".equals(name)) {
                    // create container
                    m_container = new DescriptorContainer();
                    containers.put(attributes.getValue("name"), m_container);
                    m_descriptorClass = classLoader.loadClass(attributes.getValue("class"));
                } else if ("descriptor".equals(name)) {
                    // create descriptor
                    m_descriptor = (AbstractDescriptor) m_descriptorClass.newInstance();
                } else if (m_descriptor != null) {
                    // fill attributes
                    if (attributes.getLength() == 0) {
                        // method without parameters
                        ReflectionUtils.invokeMethod(m_descriptor, name + "()", ArrayUtils.EMPTY_OBJECT_ARRAY);
                    } else {
                        if (name.endsWith("Image")) {
                            // special support for images
                            try {
                                ReflectionUtils.invokeMethod(m_descriptor,
                                        name + "(org.eclipse.swt.graphics.Image)",
                                        new Object[] { imageLoader.getImage(attributes.getValue("value")) });
                            } catch (Throwable e) {
                                DesignerPlugin.log(
                                        "DescriptorContainer: error load image " + attributes.getValue("value"),
                                        e);
                            }
                        } else {
                            // method with single String parameter
                            ReflectionUtils.invokeMethod(m_descriptor, name + "(java.lang.String)",
                                    new Object[] { attributes.getValue("value") });
                        }
                    }
                }
            } catch (Exception e) {
                throw new SAXException("startElement", e);
            }
        }

        @Override
        public void endElement(String uri, String localName, String name) throws SAXException {
            // clear state
            if ("descriptors".equals(name)) {
                m_container = null;
            } else if ("descriptor".equals(name)) {
                m_container.addDescriptor(m_descriptor);
                m_descriptor = null;
            }
        }
    });
    //
    return containers;
}

From source file:org.eclipse.wb.internal.core.editor.palette.PaletteManager.java

private void commandsRead_fromStream0(InputStream inputStream) throws Exception {
    SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    parser.parse(inputStream, new DefaultHandler() {
        @Override/*from   w w  w  .j  a va 2 s .  c  om*/
        public void startElement(String uri, String localName, final String name, final Attributes attributes) {
            ExecutionUtils.runIgnore(new RunnableEx() {
                public void run() throws Exception {
                    commandsRead_singleCommand(name, attributes);
                }
            });
        }
    });
}

From source file:org.eclipse.wb.internal.core.editor.palette.PaletteManager.java

/**
 * Parses single custom palette contribution.
 *
 * @param inputStream//from   w w w.  j ava  2s.c  o  m
 *          the {@link InputStream} with palette XML.
 * @param sourceDescription
 *          the textual description to show for user, that can help in detecting palette XML in
 *          case of any error.
 */
private void parseCustomPalette(InputStream inputStream, String sourceDescription) throws Exception {
    try {
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        parser.parse(inputStream, new DefaultHandler() {
            private CategoryInfo m_category;
            private String m_factoryClassName;
            private boolean m_factoryStatic;

            @Override
            public void startElement(String uri, String localTag, String tag, Attributes attributes)
                    throws SAXException {
                if ("category".equals(tag)) {
                    AttributesProvider attributesProvider = AttributesProviders.get(attributes);
                    // may be there is already category with this ID
                    {
                        String id = attributesProvider.getAttribute("id");
                        m_category = m_paletteInfo.getCategory(id);
                    }
                    // new category, usual case
                    if (m_category == null) {
                        m_category = new CategoryInfo(attributesProvider);
                        m_paletteInfo.addCategory(m_category);
                        addReorderRequest(m_category, attributesProvider);
                    }
                } else if ("component".equals(tag)) {
                    CategoryInfo category = getTargetCategory(attributes);
                    AttributesProvider attributesProvider = AttributesProviders.get(attributes);
                    ComponentEntryInfo component = new ComponentEntryInfo(category, attributesProvider);
                    category.addEntry(component);
                } else if ("static-factory".equals(tag)) {
                    m_factoryClassName = getRequiredString(attributes, "class");
                    m_factoryStatic = true;
                } else if ("instance-factory".equals(tag)) {
                    m_factoryClassName = getRequiredString(attributes, "class");
                    m_factoryStatic = false;
                } else if ("method".equals(tag)) {
                    CategoryInfo category = getTargetCategory(attributes);
                    FactoryEntryInfo entry = createFactoryEntry(category, attributes);
                    category.addEntry(entry);
                }
            }

            private CategoryInfo getTargetCategory(Attributes attributes) {
                CategoryInfo category = m_category;
                if (category == null) {
                    String categoryId = attributes.getValue("category");
                    Assert.isNotNull(categoryId,
                            "Element defined outside of category, so requires 'category' attribute.");
                    category = m_paletteInfo.getCategory(categoryId);
                    Assert.isNotNull(category, "No category with id '" + categoryId + "' found.");
                }
                return category;
            }

            private FactoryEntryInfo createFactoryEntry(CategoryInfo category, Attributes attributes) {
                Assert.isNotNull(m_factoryClassName,
                        "Attempt to use 'method' " + "outside of <static-factory> or <instance-factory> tags.");
                AttributesProvider attributesProvider = AttributesProviders.get(attributes);
                if (m_factoryStatic) {
                    return new StaticFactoryEntryInfo(category, m_factoryClassName, attributesProvider);
                } else {
                    return new InstanceFactoryEntryInfo(category, m_factoryClassName, attributesProvider);
                }
            }

            @Override
            public void endElement(String uri, String localName, String tag) throws SAXException {
                if ("category".equals(tag)) {
                    m_category = null;
                } else if ("static-factory".equals(tag) || "instance-factory".equals(tag)) {
                    m_factoryClassName = null;
                }
            }

            /**
             * @return the value of attribute with given name, throws exception if no such attribute
             *         found.
             */
            private String getRequiredString(Attributes attributes, String name) {
                String value = attributes.getValue(name);
                Assert.isNotNull(value, "No value for attribute '" + name + "'.");
                return value;
            }
        });
    } catch (Throwable e) {
        DesignerPlugin.log("Exception during loading project palette: " + sourceDescription, e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.eclipse.wb.internal.core.xml.editor.palette.PaletteManager.java

/**
 * Parses single custom palette contribution.
 * //  w w  w  . ja  va  2 s . com
 * @param inputStream
 *          the {@link InputStream} with palette XML.
 * @param sourceDescription
 *          the textual description to show for user, that can help in detecting palette XML in
 *          case of any error.
 */
private void parseCustomPalette(InputStream inputStream, String sourceDescription) throws Exception {
    try {
        SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        parser.parse(inputStream, new DefaultHandler() {
            private CategoryInfo m_category;

            @Override
            public void startElement(String uri, String localTag, String tag, Attributes attributes)
                    throws SAXException {
                if ("category".equals(tag)) {
                    AttributesProvider attributesProvider = AttributesProviders.get(attributes);
                    m_category = new CategoryInfo(attributesProvider);
                    m_paletteInfo.addCategory(m_category);
                    addReorderRequest(m_category, attributesProvider);
                } else if ("component".equals(tag)) {
                    CategoryInfo category = getTargetCategory(attributes);
                    AttributesProvider attributesProvider = AttributesProviders.get(attributes);
                    ComponentEntryInfo component = new ComponentEntryInfo(category, attributesProvider);
                    category.addEntry(component);
                }
            }

            private CategoryInfo getTargetCategory(Attributes attributes) {
                CategoryInfo category = m_category;
                if (category == null) {
                    String categoryId = attributes.getValue("category");
                    Assert.isNotNull(categoryId,
                            "Element defined outside of category, so requires 'category' attribute.");
                    category = m_paletteInfo.getCategory(categoryId);
                    Assert.isNotNull(category, "No category with id '" + categoryId + "' found.");
                }
                return category;
            }

            @Override
            public void endElement(String uri, String localName, String tag) throws SAXException {
                if ("category".equals(tag)) {
                    m_category = null;
                }
            }
        });
    } catch (Throwable e) {
        DesignerPlugin.log("Exception during loading project palette: " + sourceDescription, e);
    } finally {
        IOUtils.closeQuietly(inputStream);
    }
}

From source file:org.eclipse.wb.internal.swing.databinding.model.decorate.DecorationUtils.java

private static void loadDecorations() throws Exception {
    if (m_loadDecorations) {
        return;// w  ww  .  ja v  a  2s.  c  o m
    }
    m_loadDecorations = true;
    InputStream stream = Activator.getFile("templates/Decorations.xml");
    SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
    parser.parse(stream, new DefaultHandler() {
        BeanDecorationInfo m_lastDecoration;

        @Override
        public void startElement(String uri, String localName, String name, Attributes attributes)
                throws SAXException {
            if (name.equals("decoration")) {
                BeanDecorationInfo parent = DECORATIONS.get(attributes.getValue("parent"));
                m_lastDecoration = new BeanDecorationInfo(parent);
                DECORATIONS.put(attributes.getValue("class"), m_lastDecoration);
            } else if (name.equals("preferred")) {
                m_lastDecoration.setPreferredProperties(getProperties(attributes));
            } else if (name.equals("advanced")) {
                m_lastDecoration.setAdvancedProperties(getProperties(attributes));
            } else if (name.equals("hidden")) {
                m_lastDecoration.setHiddenProperties(getProperties(attributes));
            }
        }
    });
    IOUtils.closeQuietly(stream);
}

From source file:org.eclipse.wb.internal.swing.laf.LafSupport.java

/**
 * Applies commands for modifying list of LAFs.
 *///from w  w w .  jav a  2  s  .  c  o m
private static void commands_apply() {
    try {
        // prepare mapping: id -> command class
        if (m_idToCommandClass == null) {
            m_idToCommandClass = Maps.newTreeMap();
            for (Class<? extends Command> commandClass : m_commandClasses) {
                String id = (String) commandClass.getField("ID").get(null);
                m_idToCommandClass.put(id, commandClass);
            }
        }
        // read commands
        m_commands = Lists.newArrayList();
        File commandsFile = commands_getFile();
        if (commandsFile.exists()) {
            FileInputStream inputStream = new FileInputStream(commandsFile);
            try {
                SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
                parser.parse(inputStream, new DefaultHandler() {
                    @Override
                    public void startElement(String uri, String localName, String name, Attributes attributes) {
                        try {
                            // prepare command class
                            Class<? extends Command> commandClass;
                            {
                                commandClass = m_idToCommandClass.get(name);
                                if (commandClass == null) {
                                    return;
                                }
                            }
                            // create command
                            Command command;
                            {
                                Constructor<? extends Command> constructor = commandClass
                                        .getConstructor(new Class[] { Attributes.class });
                                command = constructor.newInstance(new Object[] { attributes });
                            }
                            // add command
                            commands_addExecute(command);
                        } catch (Throwable e) {
                        }
                    }
                });
            } finally {
                inputStream.close();
            }
        }
    } catch (Throwable e) {
    }
}

From source file:org.eobjects.analyzer.cli.MainTest.java

public void testWriteHtmlToFile() throws Throwable {
    String filename = "target/test_write_html_to_file.html";
    Main.main(("-conf examples/conf.xml -job examples/employees_job.xml -of " + filename + " -ot HTML")
            .split(" "));

    File file = new File(filename);
    assertTrue(file.exists());/* w w  w  . jav a2s .  c o  m*/

    {
        String result = FileHelper.readFileAsString(file);
        String[] lines = result.split("\n");

        assertEquals("<html>", lines[1]);
    }

    InputStream in = FileHelper.getInputStream(file);
    try {
        // parse it with validator.nu for HTML correctness
        final HtmlParser htmlParser = new HtmlParser(XmlViolationPolicy.FATAL);
        final AtomicInteger elementCounter = new AtomicInteger();
        htmlParser.setContentHandler(new DefaultHandler() {
            @Override
            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                elementCounter.incrementAndGet();
            }
        });
        final List<Exception> warningsAndErrors = new ArrayList<Exception>();
        htmlParser.setErrorHandler(new ErrorHandler() {
            @Override
            public void warning(SAXParseException exception) throws SAXException {
                System.err.println("Warning: " + exception.getMessage());
                warningsAndErrors.add(exception);
            }

            @Override
            public void fatalError(SAXParseException exception) throws SAXException {
                System.out.println("Fatal error: " + exception.getMessage());
                throw exception;
            }

            @Override
            public void error(SAXParseException exception) throws SAXException {
                System.err.println("Error: " + exception.getMessage());
                warningsAndErrors.add(exception);
            }
        });

        htmlParser.parse(new InputSource(in));

        // the output has approx 3600 XML elements
        int elementCount = elementCounter.get();
        assertTrue("Element count: " + elementCount, elementCount > 3000);
        assertTrue("Element count: " + elementCount, elementCount < 5000);

        if (!warningsAndErrors.isEmpty()) {
            for (Exception error : warningsAndErrors) {
                if (error.getMessage()
                        .startsWith("No explicit character encoding declaration has been seen yet")) {
                    // ignore/accept this one
                    continue;
                }
                error.printStackTrace();
                fail("Got " + warningsAndErrors.size() + " warnings and errors, see log for details");
            }
        }
    } finally {
        in.close();
    }
}

From source file:org.everit.osgi.authentication.cas.internal.CasAuthenticationComponent.java

/**
 * Returns the value of an XML element. This method is used to process the XMLs sent by the CAS server.
 *
 * @param xmlAsString/*from   w ww.j  av  a 2  s  .  co m*/
 *            the XML string to process
 * @param elementName
 *            the name of the queried element
 * @return the value assigned to the queried element name
 * @throws RuntimeException
 *             if any error occurs during the parsing of the XML string
 */
private String getTextForElement(final String xmlAsString, final String elementName) {

    XMLReader xmlReader;
    try {
        xmlReader = saxParserFactory.newSAXParser().getXMLReader();
        xmlReader.setFeature("http://xml.org/sax/features/namespaces", true);
        xmlReader.setFeature("http://xml.org/sax/features/namespace-prefixes", false);
        xmlReader.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
    } catch (final Exception e) {
        throw new RuntimeException("Unable to create XMLReader", e);
    }

    StringBuilder builder = new StringBuilder();

    DefaultHandler handler = new DefaultHandler() {

        private boolean foundElement = false;

        @Override
        public void characters(final char[] ch, final int start, final int length) throws SAXException {
            if (foundElement) {
                builder.append(ch, start, length);
            }
        }

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

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

    xmlReader.setContentHandler(handler);
    xmlReader.setErrorHandler(handler);

    try {
        xmlReader.parse(new InputSource(new StringReader(xmlAsString)));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

    return builder.toString();
}

From source file:org.exjello.mail.Exchange2003Connection.java

public List<String> getMessages(String name) throws Exception {
    final List<String> messages = new ArrayList<String>();

    /* by default we list inbox */
    String currentFolder = inbox;
    if (name.equalsIgnoreCase(ExchangeFolder.INBOX)) {
        currentFolder = inbox;/*w  w  w.j a  v a 2  s . co m*/
    } else if (name.equalsIgnoreCase(ExchangeFolder.SENTITEMS)) {
        currentFolder = sentitems;
    } else if (name.equalsIgnoreCase(ExchangeFolder.OUTBOX)) {
        currentFolder = outbox;
    } else if (name.equalsIgnoreCase(ExchangeFolder.DRAFT)) {
        currentFolder = drafts;
    }

    listFolder(new DefaultHandler() {
        private final StringBuilder content = new StringBuilder();

        public void characters(char[] ch, int start, int length) throws SAXException {
            content.append(ch, start, length);
        }

        public void startElement(String uri, String localName, String qName, Attributes attributes)
                throws SAXException {
            content.setLength(0);
        }

        public void endElement(String uri, String localName, String qName) throws SAXException {
            if (!DAV_NAMESPACE.equals(uri))
                return;
            if (!"href".equals(localName))
                return;
            messages.add(content.toString());
        }
    }, currentFolder);
    return Collections.unmodifiableList(messages);
}

From source file:org.exjello.mail.Exchange2003Connection.java

private void findInbox() throws Exception {
    inbox = null;//from   w w w  . jav  a2  s .c om
    drafts = null;
    submissionUri = null;
    sentitems = null;
    outbox = null;
    HttpClient client = getClient();
    ExchangeMethod op = new ExchangeMethod(PROPFIND_METHOD, server + "/exchange/" + mailbox);
    op.setHeader("Content-Type", XML_CONTENT_TYPE);
    op.setHeader("Depth", "0");
    op.setHeader("Brief", "t");
    op.setRequestEntity(createFindInboxEntity());
    InputStream stream = null;
    try {
        int status = client.executeMethod(op);
        stream = op.getResponseBodyAsStream();
        if (status >= 300) {
            throw new IllegalStateException("Unable to obtain inbox.");
        }
        SAXParserFactory spf = SAXParserFactory.newInstance();
        spf.setNamespaceAware(true);
        SAXParser parser = spf.newSAXParser();
        parser.parse(stream, new DefaultHandler() {
            private final StringBuilder content = new StringBuilder();

            public void startElement(String uri, String localName, String qName, Attributes attributes)
                    throws SAXException {
                content.setLength(0);
            }

            public void characters(char[] ch, int start, int length) throws SAXException {
                content.append(ch, start, length);
            }

            public void endElement(String uri, String localName, String qName) throws SAXException {
                if (!HTTPMAIL_NAMESPACE.equals(uri))
                    return;
                if ("inbox".equals(localName)) {
                    Exchange2003Connection.this.inbox = content.toString();
                } else if ("drafts".equals(localName)) {
                    Exchange2003Connection.this.drafts = content.toString();
                } else if ("sentitems".equals(localName)) {
                    Exchange2003Connection.this.sentitems = content.toString();
                } else if ("outbox".equals(localName)) {
                    Exchange2003Connection.this.outbox = content.toString();
                } else if ("sendmsg".equals(localName)) {
                    Exchange2003Connection.this.submissionUri = content.toString();
                }
            }
        });
        stream.close();
        stream = null;
    } finally {
        try {
            if (stream != null) {
                byte[] buf = new byte[65536];
                try {
                    if (session.getDebug()) {
                        PrintStream log = session.getDebugOut();
                        log.println("Response Body:");
                        int count;
                        while ((count = stream.read(buf, 0, 65536)) != -1) {
                            log.write(buf, 0, count);
                        }
                        log.flush();
                        log.println();
                    } else {
                        while (stream.read(buf, 0, 65536) != -1)
                            ;
                    }
                } catch (Exception ignore) {
                } finally {
                    try {
                        stream.close();
                    } catch (Exception ignore2) {
                    }
                }
            }
        } finally {
            op.releaseConnection();
        }
    }
}