Example usage for org.xml.sax.helpers AttributesImpl addAttribute

List of usage examples for org.xml.sax.helpers AttributesImpl addAttribute

Introduction

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

Prototype

public void addAttribute(String uri, String localName, String qName, String type, String value) 

Source Link

Document

Add an attribute to the end of the list.

Usage

From source file:org.apache.cocoon.generation.XPathTraversableGenerator.java

/**
 * Performs an XPath query on the source.
 * @param in  the Source the XPath is performed on.
 * @throws SAXException  if something goes wrong while adding the XML snippet.
 *//* www .  j a  v a  2s  .  c o  m*/
protected void performXPathQuery(TraversableSource in) throws SAXException {
    doc = null;
    try {
        doc = this.parser.parseDocument(SourceUtil.getInputSource(in));
    } catch (SAXException se) {
        getLogger().error("Warning:" + in.getName() + " is not a valid XML document. Ignoring");
    } catch (Exception e) {
        this.getLogger().error("Unable to resolve and parse document" + e);
    }
    if (doc != null) {
        NodeList nl = processor.selectNodeList(doc.getDocumentElement(), xpath, this.prefixResolver);
        final String id = in.getName();
        AttributesImpl attributes = new AttributesImpl();
        attributes.addAttribute("", RESULT_DOCID_ATTR, RESULT_DOCID_ATTR, " CDATA", id);
        attributes.addAttribute("", QUERY_ATTR_NAME, QUERY_ATTR_NAME, "CDATA", xpath);
        super.contentHandler.startElement(URI, XPATH_NODE_NAME, PREFIX + ":" + XPATH_NODE_NAME, attributes);
        DOMStreamer ds = new DOMStreamer(super.xmlConsumer);
        for (int i = 0; i < nl.getLength(); i++) {
            ds.stream(nl.item(i));
        }
        super.contentHandler.endElement(URI, XPATH_NODE_NAME, PREFIX + ":" + XPATH_NODE_NAME);
    }
}

From source file:org.apache.cocoon.transformation.DASLTransformer.java

protected void performSearchMethod(String query) throws SAXException {
    OptionsMethod optionsMethod = null;/*from w ww .jav a  2s  .c om*/
    SearchMethod searchMethod = null;
    try {
        DOMStreamer propertyStreamer = new DOMStreamer(this.xmlConsumer);
        optionsMethod = new OptionsMethod(this.targetUrl);
        searchMethod = new SearchMethod(this.targetUrl, query);
        HttpURL url = new HttpURL(this.targetUrl);
        HttpState state = new HttpState();
        state.setCredentials(null, new UsernamePasswordCredentials(url.getUser(), url.getPassword()));
        HttpConnection conn = new HttpConnection(url.getHost(), url.getPort());

        // eventcaching stuff
        SourceValidity extraValidity = makeWebdavEventValidity(url);
        if (extraValidity != null && m_validity != null)
            m_validity.add(extraValidity);
        // end eventcaching stuff

        WebdavResource resource = new WebdavResource(new HttpURL(this.targetUrl));
        if (!resource.exists()) {
            throw new SAXException("The WebDAV resource don't exist");
        }
        optionsMethod.execute(state, conn);
        if (!optionsMethod.isAllowed("SEARCH")) {
            throw new SAXException("The server doesn't support the SEARCH method");
        }
        int httpstatus = searchMethod.execute(state, conn);

        this.contentHandler.startElement(DASL_QUERY_NS, RESULT_ROOT_TAG, PREFIX + ":" + RESULT_ROOT_TAG,
                XMLUtils.EMPTY_ATTRIBUTES);

        // something might have gone wrong, report it
        // 207 = multistatus webdav response
        if (httpstatus != 207) {

            this.contentHandler.startElement(DASL_QUERY_NS, ERROR_ROOT_TAG, PREFIX + ":" + ERROR_ROOT_TAG,
                    XMLUtils.EMPTY_ATTRIBUTES);

            // dump whatever the server said
            propertyStreamer.stream(searchMethod.getResponseDocument());

            this.contentHandler.endElement(DASL_QUERY_NS, ERROR_ROOT_TAG, PREFIX + ":" + ERROR_ROOT_TAG);

        } else {
            // show results

            Enumeration enumeration = searchMethod.getAllResponseURLs();

            while (enumeration.hasMoreElements()) {
                String path = (String) enumeration.nextElement();
                Enumeration properties = searchMethod.getResponseProperties(path);
                AttributesImpl attr = new AttributesImpl();
                attr.addAttribute(DASL_QUERY_NS, PATH_NODE_NAME, PREFIX + ":" + PATH_NODE_NAME, "CDATA", path);

                this.contentHandler.startElement(DASL_QUERY_NS, RESOURCE_NODE_NAME,
                        PREFIX + ":" + RESOURCE_NODE_NAME, attr);
                while (properties.hasMoreElements()) {
                    BaseProperty metadata = (BaseProperty) properties.nextElement();
                    Element propertyElement = metadata.getElement();
                    propertyStreamer.stream(propertyElement);
                }

                this.contentHandler.endElement(DASL_QUERY_NS, RESOURCE_NODE_NAME,
                        PREFIX + ":" + RESOURCE_NODE_NAME);
            }
        }

        this.contentHandler.endElement(DASL_QUERY_NS, RESULT_ROOT_TAG, PREFIX + ":" + RESULT_ROOT_TAG);
    } catch (SAXException e) {
        throw new SAXException("Unable to fetch the query data:", e);
    } catch (HttpException e1) {
        this.getLogger().error("Unable to contact Webdav server", e1);
        throw new SAXException("Unable to connect with server: ", e1);
    } catch (IOException e2) {
        throw new SAXException("Unable to connect with server: ", e2);
    } catch (NullPointerException e) {
        throw new SAXException("Unable to fetch the query data:", e);
    } catch (Exception e) {
        throw new SAXException("Generic Error:", e);
    } finally {
        // cleanup
        if (searchMethod != null)
            searchMethod.releaseConnection();
        if (optionsMethod != null)
            optionsMethod.releaseConnection();
    }
}

From source file:org.apache.cocoon.transformation.JPathTransformer.java

/**
 * Helper method to check for the existance of an attribute named
 * jpath:action. If existing the string 'id' is replaced with the
 * continuation id./*from  w  w w  . j  a va  2  s  . c o m*/
 *
 * @param a an {@link AttributesImpl} instance
 */
private void checkJPathAction(final AttributesImpl a) {

    // check for jpath:action attribute
    int idx = a.getIndex(JPATH_ACTION);

    if (idx != -1 && JPATH_NAMESPACE_URI.equals(a.getURI(idx))) {
        if (getLogger().isDebugEnabled()) {
            getLogger().debug("found jpath:action, adjusting");
        }

        String value = a.getValue(idx);

        // REVISIT(MC): support for continuation level
        String id = m_kont.getContinuation(0).getId();

        a.removeAttribute(idx);
        a.addAttribute("", "action", "action", "CDATA", m_re.subst(value, id));
    }
}

From source file:org.apache.cocoon.transformation.PatternTransformer.java

/**
 * @throws SAXException//from  www.j  av a 2s.  c om
 */
private void search() throws SAXException {
    if (buffer.length() <= 0)
        return;

    char[] text = buffer.toString().toCharArray();

    String lexemesymbol;
    String lexemetext;
    String[] groups = null;
    int lexemeindex = 0;
    int position = 0;

    output.setLength(0);
    do {
        lexemesymbol = null;
        lexemetext = null;

        for (lexemeindex = automaton.getLexemeCount() - 1; lexemeindex >= 0; lexemeindex--) {
            processor.setPatternAutomaton(automaton.getLexemeDefinition(lexemeindex));

            if ((processor.match(text, position))
                    && ((lexemetext == null) || (processor.getGroup().length() >= lexemetext.length()))) {
                lexemesymbol = automaton.getLexemeSymbol(lexemeindex);
                lexemetext = processor.getGroup();
                if (this.groups) {
                    groups = new String[processor.getGroupCount()];
                    for (int group = 0; group < processor.getGroupCount(); group++)
                        groups[group] = processor.getGroup(group);
                }
            }
        }

        if ((lexemetext != null) && (lexemetext.length() > 0)) {
            if (lexemesymbol != null) {
                if (logger != null)
                    logger.debug("Recognize token " + lexemesymbol + " with " + Decoder.toString(lexemetext));

                if (output.length() > 0)
                    contentHandler.characters(output.toString().toCharArray(), 0, output.length());

                output.setLength(0);

                contentHandler.startPrefixMapping("", NS);

                AttributesImpl atts = new AttributesImpl();

                atts.addAttribute("", "symbol", "symbol", "CDATA", lexemesymbol);
                atts.addAttribute("", "text", "text", "CDATA", lexemetext);
                contentHandler.startElement(NS, "lexeme", "lexeme", atts);

                if (this.groups) {
                    for (int group = 0; group < groups.length; group++) {
                        contentHandler.startElement(NS, "group", "group", XMLUtils.EMPTY_ATTRIBUTES);
                        contentHandler.characters(groups[group].toCharArray(), 0, groups[group].length());
                        contentHandler.endElement(NS, "group", "group");
                    }
                }

                contentHandler.endElement(NS, "lexeme", "lexeme");
                contentHandler.endPrefixMapping("");
            } else if (logger != null)
                logger.debug("Ignore lexeme with " + Decoder.toString(lexemetext));

            position += lexemetext.length();
        } else {
            output.append(text[position]);
            position++;
        }
    } while (position < text.length);

    if (output.length() > 0)
        contentHandler.characters(output.toString().toCharArray(), 0, output.length());

    buffer.setLength(0);
}

From source file:org.apache.cocoon.transformation.SethTransformer.java

private void attribute(AttributesImpl attr, String name, String value) {
    attr.addAttribute("", name, name, "CDATA", value);
}

From source file:org.apache.cocoon.transformation.SimpleFormTransformer.java

/**
 * Handle input elements that may have a "checked" attributes,
 * i.e. checkbox and radio./*from w  w w  .ja v  a  2s  .c  om*/
 */
protected void startCheckableElement(String aName, String uri, String name, String raw,
        AttributesImpl attributes) throws SAXException {

    // @fixed and this.fixed already considered in startInputElement
    this.values = this.getValues(aName);
    String checked = attributes.getValue("checked");
    String value = attributes.getValue("value");
    boolean found = false;

    if (getLogger().isDebugEnabled())
        getLogger().debug("startCheckableElement " + name + " attributes " + this.printAttributes(attributes));
    if (this.values != null) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("replacing");
        for (int i = 0; i < this.values.length; i++) {
            if (this.values[i].equals(value)) {
                found = true;
                if (checked == null) {
                    attributes.addAttribute("", "checked", "checked", "CDATA", "");
                }
                break;
            }
        }
        if (!found && checked != null) {
            attributes.removeAttribute(attributes.getIndex("checked"));
        }
    }
    this.relayStartElement(uri, name, raw, attributes);
}

From source file:org.apache.cocoon.transformation.SimpleFormTransformer.java

/**
 * Handle input elements that may don't have a "checked"
 * attributes, e.g. text, password, button.
 *///from  w  w w. j  a  va2  s  .co  m
protected void startNonCheckableElement(String aName, String uri, String name, String raw,
        AttributesImpl attributes) throws SAXException {

    // @fixed and this.fixed already considered in startInputElement
    Object fValue = this.getNextValue(aName);
    String value = attributes.getValue("value");
    if (getLogger().isDebugEnabled())
        getLogger()
                .debug("startNonCheckableElement " + name + " attributes " + this.printAttributes(attributes));
    if (fValue != null) {
        if (getLogger().isDebugEnabled())
            getLogger().debug("replacing");
        if (value != null) {
            attributes.setValue(attributes.getIndex("value"), String.valueOf(fValue));
        } else {
            attributes.addAttribute("", "value", "value", "CDATA", String.valueOf(fValue));
        }
    }
    this.relayStartElement(uri, name, raw, attributes);
}

From source file:org.apache.cocoon.transformation.SimpleFormTransformer.java

/**
 * Handle option elements. Uses instance variables set up by
 * startSelectElement. Relies on option having a "value"
 * attribute, i.e. does not check following characters if "value"
 * is not present./*from   w  ww. java  2 s . co  m*/
 */
protected void startOptionElement(String uri, String name, String raw, Attributes attr) throws SAXException {

    // add @selected if @value in request.getParameterValues(@name)
    if (getLogger().isDebugEnabled())
        getLogger().debug("startOptionElement " + name + " attributes " + this.printAttributes(attr));
    if (this.values == null || this.fixed) {
        this.relayStartElement(uri, name, raw, attr);
    } else {
        if (getLogger().isDebugEnabled())
            getLogger().debug("replacing");
        AttributesImpl attributes = null;
        if (attr instanceof AttributesImpl) {
            attributes = (AttributesImpl) attr;
        } else {
            attributes = new AttributesImpl(attr);
        }
        String selected = attributes.getValue("selected");
        String value = attributes.getValue("value");
        boolean found = false;

        for (int i = 0; i < this.values.length; i++) {
            if (this.values[i].equals(value)) {
                found = true;
                if (selected == null) {
                    attributes.addAttribute("", "selected", "selected", "CDATA", "");
                }
                break;
            }
        }
        if (!found && selected != null) {
            attributes.removeAttribute(attributes.getIndex("selected"));
        }

        this.relayStartElement(uri, name, raw, attributes);
    }
}

From source file:org.apache.fop.render.svg.EmbeddedSVGImageHandler.java

private void addAttribute(AttributesImpl atts, QName attribute, String value) {
    atts.addAttribute(attribute.getNamespaceURI(), attribute.getLocalName(), attribute.getQName(), CDATA,
            value);//from w  w w. j  a v  a  2s.  co m
}

From source file:org.apache.fop.render.svg.EmbeddedSVGImageHandler.java

/** {@inheritDoc} */
public void handleImage(RenderingContext context, Image image, final Rectangle pos) throws IOException {
    SVGRenderingContext svgContext = (SVGRenderingContext) context;
    ImageXMLDOM svg = (ImageXMLDOM) image;
    ContentHandler handler = svgContext.getContentHandler();
    AttributesImpl atts = new AttributesImpl();
    atts.addAttribute("", "x", "x", CDATA, SVGUtil.formatMptToPt(pos.x));
    atts.addAttribute("", "y", "y", CDATA, SVGUtil.formatMptToPt(pos.y));
    atts.addAttribute("", "width", "width", CDATA, SVGUtil.formatMptToPt(pos.width));
    atts.addAttribute("", "height", "height", CDATA, SVGUtil.formatMptToPt(pos.height));
    try {/*w w w  .j a  v a2  s  . c  om*/

        Document doc = (Document) svg.getDocument();
        Element svgEl = (Element) doc.getDocumentElement();
        if (svgEl.getAttribute("viewBox").length() == 0) {
            log.warn("SVG doesn't have a viewBox. The result might not be scaled correctly!");
        }

        TransformerFactory tFactory = TransformerFactory.newInstance();
        Transformer transformer = tFactory.newTransformer();
        DOMSource src = new DOMSource(svg.getDocument());
        SAXResult res = new SAXResult(new DelegatingFragmentContentHandler(handler) {

            private boolean topLevelSVGFound = false;

            private void setAttribute(AttributesImpl atts, String localName, String value) {
                int index;
                index = atts.getIndex("", localName);
                if (index < 0) {
                    atts.addAttribute("", localName, localName, CDATA, value);
                } else {
                    atts.setAttribute(index, "", localName, localName, CDATA, value);
                }
            }

            public void startElement(String uri, String localName, String name, Attributes atts)
                    throws SAXException {
                if (!topLevelSVGFound && SVG_ELEMENT.getNamespaceURI().equals(uri)
                        && SVG_ELEMENT.getLocalName().equals(localName)) {
                    topLevelSVGFound = true;
                    AttributesImpl modAtts = new AttributesImpl(atts);
                    setAttribute(modAtts, "x", SVGUtil.formatMptToPt(pos.x));
                    setAttribute(modAtts, "y", SVGUtil.formatMptToPt(pos.y));
                    setAttribute(modAtts, "width", SVGUtil.formatMptToPt(pos.width));
                    setAttribute(modAtts, "height", SVGUtil.formatMptToPt(pos.height));
                    super.startElement(uri, localName, name, modAtts);
                } else {
                    super.startElement(uri, localName, name, atts);
                }
            }

        });
        transformer.transform(src, res);
    } catch (TransformerException te) {
        throw new IOException(te.getMessage());
    }
}