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.orbeon.oxf.xforms.XFormsModelSchemaValidator.java

private boolean validateElement(final Element element, final Acceptor acceptor, final IDConstraintChecker icc,
        final boolean isReportErrors) {

    boolean isElementValid = true;

    // Create StartTagInfo
    final StartTagInfo startTagInfo;
    {/*w  ww  .j  a  v  a  2  s . c om*/
        final String uri = element.getNamespaceURI();
        final String name = element.getName();
        final String qName = element.getQualifiedName();
        final List attributesList = element.attributes();
        final AttributesImpl attributes = new AttributesImpl();

        for (Object anAttributesList : attributesList) {
            final Attribute attribute = (Attribute) anAttributesList;
            final String attributeURI = attribute.getNamespaceURI();
            final String attributeName = attribute.getName();
            final String attributeQName = attribute.getQualifiedName();
            final String attributeValue = attribute.getValue();
            attributes.addAttribute(attributeURI, attributeName, attributeQName, null, attributeValue);
        }
        validationContext.setCurrentElement(element);
        startTagInfo = new StartTagInfo(uri, name, qName, attributes, validationContext);
    }

    final StringRef stringRef = new StringRef();

    // Get child acceptor
    final Acceptor childAcceptor;
    {
        Acceptor tempChildAcceptor = acceptor.createChildAcceptor(startTagInfo, null);
        if (tempChildAcceptor == null) {
            if (isReportErrors) {
                tempChildAcceptor = acceptor.createChildAcceptor(startTagInfo, stringRef);
                addSchemaError(element, stringRef.str);
                isElementValid = false;
            } else {
                return false;
            }
        }
        childAcceptor = tempChildAcceptor;
    }

    // Handle id errors
    if (icc != null && isReportErrors) {
        icc.onNextAcceptorReady(startTagInfo, childAcceptor, element);
        isElementValid &= handleIDErrors(icc);
    }

    // Validate children
    final DatatypeRef datatypeRef = new DatatypeRef();
    final boolean childrenValid = validateChildren(element, childAcceptor, startTagInfo, icc, datatypeRef,
            isReportErrors);
    if (!childrenValid) {
        if (isReportErrors)
            isElementValid = false;
        else
            return false;
    }

    // TODO: MSV doesn't allow getting the type if validity check fails. However, we would like to obtain datatype validity in XForms.
    if (!childAcceptor.isAcceptState(null)) {
        if (isReportErrors) {
            childAcceptor.isAcceptState(stringRef);
            addSchemaError(element, stringRef.str);
            isElementValid = false;
        } else {
            return false;
        }
    } else {
        // Attempt to set datatype name
        setDataType(datatypeRef, element);
    }

    // Handle id errors
    if (icc != null && isReportErrors) {
        icc.endElement(element, datatypeRef.types);
        isElementValid &= handleIDErrors(icc);
    }

    // Get back to parent acceptor
    if (!acceptor.stepForward(childAcceptor, null)) {
        if (isReportErrors) {
            acceptor.stepForward(childAcceptor, stringRef);
            addSchemaError(element, stringRef.str);
            isElementValid = false;
        } else {
            return false;
        }
    }

    if (isReportErrors) {
        // Element may be invalid or not
        return isElementValid;
    } else {
        // This element is valid
        return true;
    }
}

From source file:org.programmatori.domotica.own.plugin.map.Map.java

private void createStatusFile(String fileName) {
    StreamResult streamResult = new StreamResult(new File(fileName));

    SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
    TransformerHandler hd = null;
    try {/*w w  w.  ja  va2  s.co m*/
        hd = tf.newTransformerHandler();
    } catch (TransformerConfigurationException e) {
        e.printStackTrace();
    }
    Transformer serializer = hd.getTransformer();

    serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
    //serializer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, "users.dtd");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    //serializer.setOutputProperty( XalanOutputKeys.OUTPUT_PROP_INDENT_AMOUNT, "2" );

    hd.setResult(streamResult);
    try {
        hd.startDocument();

        AttributesImpl attrs = new AttributesImpl();
        hd.startElement("", "", "home", attrs);

        hd.startElement("", "", "version", attrs);
        hd.characters("2.0".toCharArray(), 0, 3);
        hd.endElement("", "", "version");

        attrs.clear();
        attrs.addAttribute("", "", "unit", "CDATA", "min");
        hd.startElement("", "", "statusSave", attrs);
        hd.characters("10".toCharArray(), 0, 2);
        hd.endElement("", "", "statusSave");

        // ----------------------------------------- Area
        for (Iterator<Integer> iterAree = localBus.keySet().iterator(); iterAree.hasNext();) {
            Integer area = (Integer) iterAree.next();

            attrs.clear();
            attrs.addAttribute("", "", "id", "CDATA", area.toString());
            attrs.addAttribute("", "", "name", "CDATA", Config.getInstance().getRoomName(area));
            hd.startElement("", "", "area", attrs);

            // ----------------------------------------- Component
            Set<SCSComponent> rooms = localBus.get(area);
            for (Iterator<SCSComponent> iterRoom = rooms.iterator(); iterRoom.hasNext();) {
                SCSComponent c = (SCSComponent) iterRoom.next();
                log.info("PL: " + c.getStatus().getWhere().getPL() + "("
                        + Config.getInstance().getWhoDescription(c.getStatus().getWho().getMain()) + ")");

                attrs.clear();
                attrs.addAttribute("", "", "type", "CDATA",
                        Config.getInstance().getWhoDescription(c.getStatus().getWho().getMain()));
                attrs.addAttribute("", "", "pl", "CDATA", "" + c.getStatus().getWhere().getPL());
                hd.startElement("", "", "component", attrs);
                hd.characters("0".toCharArray(), 0, 1);
                hd.endElement("", "", "component");
            }
            // ----------------------------------------- Component

            hd.endElement("", "", "area");
        }
        // ----------------------------------------- End Area

        // ----------------------------------------- Scheduler
        attrs.clear();
        hd.startElement("", "", "scheduler", attrs);

        attrs.clear();
        attrs.addAttribute("", "", "time", "CDATA", "-1");
        hd.startElement("", "", "command2", attrs);
        hd.characters("*1*1*11##".toCharArray(), 0, 9);
        hd.endElement("", "", "command2");

        hd.endElement("", "", "scheduler");
        // ----------------------------------------- End Scheduler

        hd.endElement("", "", "home");
        hd.endDocument();
    } catch (SAXException e) {
        e.printStackTrace();
    }

    //      for (Iterator<Integer> iterAree = localBus.keySet().iterator(); iterAree.hasNext();) {
    //         Integer area = (Integer) iterAree.next();
    //
    //         log.info("Room: " + area + " - " + Config.getInstance().getRoomName(area));
    //         Set<SCSComponent> rooms = localBus.get(area);
    //         for (Iterator<SCSComponent> iterRoom = rooms.iterator(); iterRoom.hasNext();) {
    //            SCSComponent c = (SCSComponent) iterRoom.next();
    //            log.info("PL: " + c.getStatus().getWhere().getPL() + "(" + Config.getInstance().getWhoDescription(c.getStatus().getWho().getMain()) + ")");
    //         }
    //      }
}

From source file:org.tizzit.util.xml.SAXHelper.java

/**
 * Sets an attribute of an SAX AttributesImpl to a specific value (namespace supported).<br/>
 * If it exists, the value will be overwritten.
 *
 * @param attr The AttributesImpl//from   w w w  . j a v  a 2 s .c  o m
 * @param namespaceUri
 * @param attrName The name
 * @param attrValue The (new) value
 * @since tizzit-common 15.10.2009
 */
public static void setSAXAttr(AttributesImpl attr, String namespaceUri, String attrName, String attrValue) {
    if (attrName != null) {
        int idx = attr.getIndex(attrName);
        String saveVal = (attrValue == null) ? "" : attrValue;
        if (idx >= 0) {
            String dd = attr.getType(attrName);
            attr.setAttribute(idx, namespaceUri, attrName, attrName, dd, saveVal);
        } else {
            attr.addAttribute(namespaceUri, attrName, attrName, "CDATA", saveVal);
        }
    }
}

From source file:org.xchain.example.namespaces.xhtml.OptionCommand.java

public boolean execute(JXPathContext context) throws Exception {
    String value = getValue(context);
    String currentValue = (String) ((ScopedQNameVariables) context.getVariables())
            .getVariable(SelectCommand.SELECTED_VARIABLE_NAME, Scope.execution);

    // get the xhtml prefix and make sure that there is a mapping for it.
    String xhtmlPrefix = context.getPrefix(XHTML_NAMESPACE);
    if (xhtmlPrefix == null) {
        throw new IllegalStateException("There is no mapping defined for " + XHTML_NAMESPACE);
    }//from   www.jav  a 2  s.  com

    AttributesImpl attributes = new AttributesImpl();
    if (value != null) {
        attributes.addAttribute("", VALUE_LOCAL_NAME, VALUE_LOCAL_NAME, "CDATA", value);
    }
    if (value != null && value.equals(currentValue)) {
        attributes.addAttribute("", SELECTED_LOCAL_NAME, SELECTED_LOCAL_NAME, "CDATA", SELECTED_VALUE);
    }

    ContentHandler handler = getContentHandler();
    handler.startElement(XHTML_NAMESPACE, OPTION_LOCAL_NAME, qNameString(xhtmlPrefix, OPTION_LOCAL_NAME),
            attributes);

    boolean result = false;
    Exception exception = null;

    try {
        result = super.execute(context);
    } catch (Exception e) {
        exception = e;
    }
    if (exception == null || !(exception instanceof SAXException)) {
        handler.endElement(XHTML_NAMESPACE, OPTION_LOCAL_NAME, qNameString(xhtmlPrefix, OPTION_LOCAL_NAME));
    }

    if (exception != null) {
        throw exception;
    }
    return result;
}

From source file:org.xchain.example.namespaces.xhtml.SelectCommand.java

public boolean execute(JXPathContext context) throws Exception {
    // get the request and the name from the context.
    HttpServletRequest request = getRequest(context);
    String name = getName(context);

    // get the original value of the name.
    String currentValue = request.getParameter(name);

    // get the xhtml prefix and make sure that there is a mapping for it.
    String xhtmlPrefix = context.getPrefix(XHTML_NAMESPACE);
    if (xhtmlPrefix == null) {
        throw new IllegalStateException("There is no mapping defined for " + XHTML_NAMESPACE);
    }/*from   ww w.ja v a2s  .  c om*/

    // create the attributes for the element we are going to output.
    AttributesImpl attributes = new AttributesImpl();
    if (hasId()) {
        attributes.addAttribute("", ID_LOCAL_NAME, ID_LOCAL_NAME, "CDATA", getId(context));
    }
    attributes.addAttribute("", NAME_LOCAL_NAME, NAME_LOCAL_NAME, "CDATA", getName(context));

    ((ScopedQNameVariables) context.getVariables()).declareVariable(SELECTED_VARIABLE_NAME, currentValue,
            Scope.execution);
    ContentHandler handler = getContentHandler();
    handler.startElement(XHTML_NAMESPACE, SELECT_LOCAL_NAME, qNameString(xhtmlPrefix, SELECT_LOCAL_NAME),
            attributes);

    boolean result = false;
    Exception exception = null;

    // execute the children and catch any exceptions.
    try {
        result = super.execute(context);
    } catch (Exception e) {
        exception = e;
    }

    // if there was not an exception, or the exception is not a sax exception, then we need to finish the output.
    if (exception == null || !(exception instanceof SAXException)) {
        handler.endElement(XHTML_NAMESPACE, SELECT_LOCAL_NAME, qNameString(xhtmlPrefix, SELECT_LOCAL_NAME));
    }

    // rethrow the exception.
    if (exception != null) {
        throw exception;
    }
    return result;
}

From source file:org.xchain.framework.jsl.SaxTemplateHandler.java

/**
 * Handles start element events for all JSL elements.
 *//* w  ww.j a v  a2  s  . com*/
protected void startJslElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
    // scan for jsl elements that come out of order.
    if (TEMPLATE_LOCAL_NAME.equals(localName)) {
        templateElementDepth++;
    } else if (templateElementDepth == 0) {
        throw new SAXException("The element {" + uri + "}" + localName + "was found outside of a {"
                + JSL_NAMESPACE + "}template element.");
    }

    boolean startSource = elementInfoStack.size() == 1
            || elementInfoStack.get(1).getElementType() == ElementType.COMMAND_ELEMENT_TYPE;
    // if the parent element is null or a command element, then we need to start a new template source.
    if (startSource) {
        sourceBuilder.startSource(elementInfoStack.getFirst().getSourcePrefixMapping(),
                elementInfoStack.getFirst().getSourceExcludeResultPrefixSet(),
                TEMPLATE_LOCAL_NAME.equals(localName));
    }

    if (TEMPLATE_LOCAL_NAME.equals(localName)) {
        startJslTemplateElement(uri, localName, qName, attributes);
    } else if (VALUE_OF_LOCAL_NAME.equals(localName)) {
        startJslValueOfElement(uri, localName, qName, attributes);
    } else if (TEXT_LOCAL_NAME.equals(localName)) {
        startJslTextElement(uri, localName, qName, attributes);
    } else if (COMMENT_LOCAL_NAME.equals(localName)) {
        startJslCommentElement(uri, localName, qName, attributes);
    } else if (ELEMENT_LOCAL_NAME.equals(localName)) {
        startJslDynamicElement(uri, localName, qName, attributes);
    } else if (ATTRIBUTE_LOCAL_NAME.equals(localName)) {
        startJslDynamicAttribute(uri, localName, qName, attributes);
    } else {
        throw new SAXException("Unknown template element '{" + uri + "}" + localName + "'.");
    }

    if (startSource) {
        // send start prefix mapping events to the digester.
        for (Map.Entry<String, String> mapping : elementInfoStack.getFirst().getHandlerPrefixMapping()
                .entrySet()) {
            getContentHandler().startPrefixMapping(mapping.getKey(), mapping.getValue());
        }

        // create a new attributes object with any attributes that are in an xchain namespace.
        AttributesImpl digesterAttributes = new AttributesImpl();
        for (int i = 0; i < attributes.getLength(); i++) {
            if (commandNamespaceSet.contains(attributes.getURI(i))) {
                digesterAttributes.addAttribute(attributes.getURI(i), attributes.getLocalName(i),
                        attributes.getQName(i), attributes.getType(i), attributes.getValue(i));
            }
        }

        // send the start template element to the digester.
        getContentHandler().startElement(JSL_NAMESPACE, TEMPORARY_CHAIN_LOCAL_NAME, temporaryChainQName(),
                digesterAttributes);
    }
}

From source file:org.xchain.framework.jsl.SaxTemplateHandler.java

/**
 * Handles start element events for template elements.
 *///from w w w .  j a  va2 s .c o  m
protected void startTemplateElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
    if (templateElementDepth == 0) {
        throw new SAXException(
                "The element {" + uri + "}" + localName + " was found outside of a template element.");
    }

    // push characters target.
    charactersTargetStack.addFirst(CharacterTarget.SOURCE_BUILDER);

    // push ignorable whitespace target.
    ignorableWhitespaceTargetStack.addFirst(CharacterTarget.SOURCE_BUILDER);

    boolean startSource = elementInfoStack.size() == 1
            || elementInfoStack.get(1).getElementType() == ElementType.COMMAND_ELEMENT_TYPE;
    // if the parent element is null or a command element, then we need to start a new template source.
    if (startSource) {
        sourceBuilder.startSource(elementInfoStack.getFirst().getSourcePrefixMapping(),
                elementInfoStack.getFirst().getSourceExcludeResultPrefixSet(), false);
    }

    try {
        // get the element info for the head of the stack.
        ElementInfo elementInfo = elementInfoStack.getFirst();

        // let the source builder know that we are starting a start element.
        sourceBuilder.startStartElement();

        // send the prefix mappings to the source builder.
        for (Map.Entry<String, String> prefixMapping : elementInfo.getPrefixMapping().entrySet()) {
            sourceBuilder.appendStartPrefixMapping(prefixMapping.getKey(), prefixMapping.getValue());
        }

        // send any exclude result prefix events that need to go out.
        for (String excludeResultPrefix : elementInfo.getExcludeResultPrefixSet()) {
            sourceBuilder.appendStartExcludeResultPrefix(excludeResultPrefix);
        }

        // send the attributes to the source builder.
        for (int i = 0; i < attributes.getLength(); i++) {
            sourceBuilder.appendAttributeValueTemplate(attributes.getURI(i), attributes.getLocalName(i),
                    attributes.getQName(i), attributes.getValue(i));
        }

        // append the start element.
        sourceBuilder.appendStartElement(uri, localName, qName);

        // let the source builder know that we are ending a start element.
        sourceBuilder.endStartElement();
    } catch (SAXException e) {
        throw e;
    } catch (Exception e) {
        throw new SAXException(e);
    }

    // we need to do this just before we stop templating, so this kind of code should be in start command, or end jsl template and end template when there was not
    // a nested command.  We need to delay this, since the passed through template must provide the namespaces state from all of the consumed elements.
    if (startSource) {
        // send start prefix mapping events to the digester.
        for (Map.Entry<String, String> mapping : elementInfoStack.getFirst().getHandlerPrefixMapping()
                .entrySet()) {
            getContentHandler().startPrefixMapping(mapping.getKey(), mapping.getValue());
        }

        // create a new attributes object with any attributes that are in an xchain namespace.
        AttributesImpl digesterAttributes = new AttributesImpl();
        for (int i = 0; i < attributes.getLength(); i++) {
            if (commandNamespaceSet.contains(attributes.getURI(i))) {
                digesterAttributes.addAttribute(attributes.getURI(i), attributes.getLocalName(i),
                        attributes.getQName(i), attributes.getType(i), attributes.getValue(i));
            }
        }

        // send the start template element to the digester.
        getContentHandler().startElement(JSL_NAMESPACE, TEMPORARY_CHAIN_LOCAL_NAME, temporaryChainQName(),
                digesterAttributes);
    }
}

From source file:org.xwiki.portlet.view.HTMLIdAttributeXMLFilter.java

@Override
public void startDocument() throws SAXException {
    super.startDocument();

    if (wrapOutput) {
        // Start the portlet output container.
        AttributesImpl attributes = new AttributesImpl();
        attributes.addAttribute(null, ID, ID, ID.toUpperCase(), namespace);
        super.startElement(null, DIV, DIV, attributes);
    }/*  w  w  w. j ava 2  s. com*/
}

From source file:org.xwiki.portlet.view.HTMLMetaDataXMLFilter.java

/**
 * Outputs an {@code <input type="hidden">} HTML element that holds the given meta data.
 * /* ww w  .j a  va 2 s . c o  m*/
 * @param key the meta data key
 * @param value the meta data value
 * @param withId {@code true} to output the 'id' attribute, {@code false} otherwise
 * @param withName {@code true} to output the 'name' attribute, {@code false} otherwise
 * @throws SAXException if writing the meta data fails
 */
private void outputMetaData(String key, String value, boolean withId, boolean withName) throws SAXException {
    AttributesImpl attributes = new AttributesImpl();
    if (withId) {
        attributes.addAttribute(null, ID, ID, "ID", key);
    }
    if (withName) {
        attributes.addAttribute(null, NAME, NAME, CDATA, key);
    }
    attributes.addAttribute(null, TYPE, TYPE, CDATA, "hidden");
    attributes.addAttribute(null, VALUE, VALUE, CDATA, StringUtils.defaultString(value));
    super.startElement(null, INPUT, INPUT, attributes);
    super.endElement(null, INPUT, INPUT);
}

From source file:org.xwiki.rendering.xdomxmlcurrent.internal.renderer.XDOMXMLChainingStreamRenderer.java

private void addInlineParameters(AttributesImpl attributes, List<Object> parameters, ListenerElement element) {
    for (int i = 0; i < parameters.size(); ++i) {
        Object parameter = parameters.get(i);

        if (parameter != null) {
            Type type = element.getParameters().get(i);
            Class<?> typeClass = ReflectionUtils.getTypeClass(type);

            if (XDOMXMLCurrentUtils.isSimpleType(typeClass)) {
                attributes.addAttribute(null, null, XDOMXMLConstants.ELEM_PARAMETER + i, null,
                        this.converter.<String>convert(String.class, parameter));

                parameters.set(i, null);
            } else if (ObjectUtils.equals(XDOMXMLCurrentUtils.defaultValue(typeClass), parameter)) {
                attributes.addAttribute(null, null, XDOMXMLConstants.ELEM_PARAMETER + i, null, "");

                parameters.set(i, null);
            }//w  w  w  .jav a  2s . co m
        }
    }
}