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.onehippo.cms7.autoexport.Exporter.java

private void exportPropertyInstruction(DeltaInstruction instruction, ContentHandler handler, boolean override)
        throws SAXException, RepositoryException {
    Property property = session.getProperty(instruction.getContextPath());
    AttributesImpl attr = new AttributesImpl();
    attr.addAttribute(SV_URI, NAME, QNAME, CDATA, instruction.getName());
    attr.addAttribute(SV_URI, TYPE, QTYPE, CDATA, PropertyType.nameFromValue(property.getType()));
    if (override) {
        attr.addAttribute(DELTA_URI, MERGE, QMERGE, CDATA, "override");
    }// ww  w  . j a  v a 2  s  . co m
    if (property.isMultiple()) {
        attr.addAttribute(SV_URI, "multiple", "sv:multiple", CDATA, "true");
    }
    handler.startElement(SV_URI, PROPERTY, QPROPERTY, attr);
    attr = new AttributesImpl();
    if (property.isMultiple()) {
        for (Value value : property.getValues()) {
            handler.startElement(SV_URI, VALUE, QVALUE, attr);
            String stringValue = value.getString();
            handler.characters(stringValue.toCharArray(), 0, stringValue.length());
            handler.endElement(SV_URI, VALUE, QVALUE);
        }
    } else {
        Value value = property.getValue();
        handler.startElement(SV_URI, VALUE, QVALUE, attr);
        String stringValue = value.getString();
        handler.characters(stringValue.toCharArray(), 0, stringValue.length());
        handler.endElement(SV_URI, VALUE, QVALUE);
    }
    handler.endElement(SV_URI, PROPERTY, QPROPERTY);
}

From source file:org.onehippo.repository.xml.SysViewSAXEventGenerator.java

private void exportValue(final Value val) throws RepositoryException, SAXException {

    if (val.getType() == BINARY && binaries != null) {
        File file = createBinaryFile(val);
        binaries.add(file);/*  ww  w. java 2  s .  c o m*/
        AttributesImpl attributes = new AttributesImpl();
        attributes.addAttribute(NS_XMLIMPORT_URI, "file", "h:file", CDATA_TYPE, file.getName());
        contentHandler.startPrefixMapping(NS_XMLIMPORT_PREFIX, NS_XMLIMPORT_URI);
        startElement(SV_VALUE, attributes);
        endElement(SV_VALUE);
        contentHandler.endPrefixMapping(NS_XMLIMPORT_PREFIX);
    } else {
        Attributes attributes = ATTRS_EMPTY;
        final boolean mustSendBinary = mustSendBinary(val);
        if (mustSendBinary) {
            contentHandler.startPrefixMapping(NS_XMLSCHEMA_INSTANCE_PREFIX, NS_XMLSCHEMA_INSTANCE_URI);
            contentHandler.startPrefixMapping(NS_XMLSCHEMA_PREFIX, NS_XMLSCHEMA_URI);
            attributes = ATTRS_BINARY_ENCODED_VALUE;
        }
        startElement(SV_VALUE, attributes);

        try {
            ValueHelper.serialize(val, false, mustSendBinary, new ContentHandlerWriter(contentHandler));
        } catch (IOException ioe) {
            Throwable t = ioe.getCause();
            if (t != null && t instanceof SAXException) {
                throw (SAXException) t;
            } else {
                throw new SAXException(ioe);
            }
        }

        endElement(SV_VALUE);

        if (mustSendBinary) {
            contentHandler.endPrefixMapping(NS_XMLSCHEMA_INSTANCE_PREFIX);
            contentHandler.endPrefixMapping(NS_XMLSCHEMA_PREFIX);
        }
    }

}

From source file:org.onehippo.repository.xml.SysViewSAXEventGenerator.java

protected void addAttribute(AttributesImpl attributes, Name name, String type, String value)
        throws NamespaceException {
    attributes.addAttribute(name.getNamespaceURI(), name.getLocalName(), resolver.getJCRName(name), type,
            value);//from  w  w  w  . jav a  2  s  .  c  o  m
}

From source file:org.orbeon.oxf.processor.generator.RequestGenerator.java

@Override
public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new DigestTransformerOutputImpl(RequestGenerator.this, name) {
        public void readImpl(final PipelineContext pipelineContext, XMLReceiver xmlReceiver) {
            final State state = (State) getFilledOutState(pipelineContext);
            // Transform the resulting document into SAX

            TransformerUtils.sourceToSAX(new DocumentSource(state.requestDocument),
                    new ForwardingXMLReceiver(xmlReceiver) {
                        @Override
                        public void startElement(String uri, String localname, String qName,
                                Attributes attributes) throws SAXException {
                            try {
                                if (REQUEST_PRIVATE_NAMESPACE_URI.equals(uri)) {
                                    // Special treatment for this element
                                    if (FILE_ITEM_ELEMENT.equals(qName)) {
                                        // Marker for file item

                                        final String parameterName = attributes
                                                .getValue(PARAMETER_NAME_ATTRIBUTE);
                                        final int parameterPosition = Integer
                                                .parseInt(attributes.getValue(PARAMETER_POSITION_ATTRIBUTE));
                                        final FileItem fileItem = (FileItem) ((Object[]) getRequest(
                                                pipelineContext).getParameterMap()
                                                        .get(parameterName))[parameterPosition];

                                        final AttributesImpl newAttributes = new AttributesImpl();
                                        super.startPrefixMapping(XMLConstants.XSI_PREFIX, XMLConstants.XSI_URI);
                                        super.startPrefixMapping(XMLConstants.XSD_PREFIX, XMLConstants.XSD_URI);
                                        newAttributes.addAttribute(XMLConstants.XSI_URI, "type", "xsi:type",
                                                "CDATA",
                                                useBase64(pipelineContext, fileItem)
                                                        ? XMLConstants.XS_BASE64BINARY_QNAME.getQualifiedName()
                                                        : XMLConstants.XS_ANYURI_QNAME.getQualifiedName());
                                        super.startElement("", "value", "value", newAttributes);
                                        writeFileItem(pipelineContext, fileItem, state.isSessionScope,
                                                useBase64(pipelineContext, fileItem), getXMLReceiver());
                                        super.endElement("", "value", "value");
                                        super.endPrefixMapping(XMLConstants.XSD_PREFIX);
                                        super.endPrefixMapping(XMLConstants.XSI_PREFIX);
                                    }/*from   w  w w .  j a  v  a 2s .com*/
                                } else if (localname.equals("body") && uri.equals("")) {
                                    // Marker for request body

                                    // Read InputStream into FileItem object, if not already present

                                    // We do this so we can read the body multiple times, if needed.
                                    // For large files, there will be a performance hit. If we knew
                                    // we didn't need to read it multiple times, we could avoid
                                    // saving the stream, but practically, it can happen, and it is
                                    // convenient.
                                    final Context context = getContext(pipelineContext);
                                    if (context.bodyFileItem != null
                                            || getRequest(pipelineContext).getInputStream() != null) {

                                        final ExternalContext.Request request = getRequest(pipelineContext);

                                        if (context.bodyFileItem == null) {
                                            final FileItem fileItem = new DiskFileItemFactory(
                                                    getMaxMemorySizeProperty(),
                                                    SystemUtils.getTemporaryDirectory()).createItem("dummy",
                                                            "dummy", false, null);
                                            pipelineContext.addContextListener(
                                                    new PipelineContext.ContextListenerAdapter() {
                                                        public void contextDestroyed(boolean success) {
                                                            fileItem.delete();
                                                        }
                                                    });
                                            final OutputStream outputStream = fileItem.getOutputStream();
                                            NetUtils.copyStream(request.getInputStream(), outputStream);
                                            outputStream.close();
                                            context.bodyFileItem = fileItem;
                                        }
                                        // Serialize the stream into the body element
                                        final AttributesImpl newAttributes = new AttributesImpl();
                                        super.startPrefixMapping(XMLConstants.XSI_PREFIX, XMLConstants.XSI_URI);
                                        super.startPrefixMapping(XMLConstants.XSD_PREFIX, XMLConstants.XSD_URI);
                                        newAttributes.addAttribute(XMLConstants.XSI_URI, "type", "xsi:type",
                                                "CDATA",
                                                useBase64(pipelineContext, context.bodyFileItem)
                                                        ? XMLConstants.XS_BASE64BINARY_QNAME.getQualifiedName()
                                                        : XMLConstants.XS_ANYURI_QNAME.getQualifiedName());
                                        super.startElement(uri, localname, qName, newAttributes);
                                        final String uriOrNull = writeFileItem(pipelineContext,
                                                context.bodyFileItem, state.isSessionScope,
                                                useBase64(pipelineContext, context.bodyFileItem),
                                                getXMLReceiver());
                                        super.endElement(uri, localname, qName);
                                        super.endPrefixMapping(XMLConstants.XSD_PREFIX);
                                        super.endPrefixMapping(XMLConstants.XSI_PREFIX);

                                        // If the body is available as a URL, store it into the pipeline context.
                                        // This is done so that native code can access the body even if it has been read
                                        // already. Possibly, this could be handled more transparently by ExternalContext,
                                        // so that Request.getInputStream() works even upon multiple reads.
                                        // NOTE 2013-05-30: We used to store this into the request, but request attributes
                                        // are forwarded by LocalRequest. This means that a forwarded-to request might get
                                        // the wrong body! Instead, we now use PipelineContext, which is scoped to be per
                                        // request. Again, if ExternalContext was handling this, we could just leave it to
                                        // ExternalContext.
                                        if (uriOrNull != null)
                                            pipelineContext.setAttribute(BODY_REQUEST_ATTRIBUTE, uriOrNull);
                                    }
                                } else {
                                    super.startElement(uri, localname, qName, attributes);
                                }
                            } catch (IOException e) {
                                throw new OXFException(e);
                            }
                        }

                        @Override
                        public void endElement(String uri, String localname, String qName) throws SAXException {
                            if (REQUEST_PRIVATE_NAMESPACE_URI.equals(uri)
                                    || localname.equals("body") && uri.equals("")) {
                                // Ignore end element
                            } else {
                                super.endElement(uri, localname, qName);
                            }
                        }
                    });
        }

        protected boolean fillOutState(PipelineContext pipelineContext, DigestState digestState) {
            final State state = (State) digestState;
            if (state.requestDocument == null) {
                // Read config document
                final Document config = readCacheInputAsDOM4J(pipelineContext, INPUT_CONFIG);

                // Try to find stream-type attribute
                final QName streamTypeQName = Dom4jUtils.extractAttributeValueQName(config.getRootElement(),
                        "stream-type");
                if (streamTypeQName != null && !(streamTypeQName.equals(XMLConstants.XS_BASE64BINARY_QNAME)
                        || streamTypeQName.equals(XMLConstants.XS_ANYURI_QNAME)))
                    throw new OXFException(
                            "Invalid value for stream-type attribute: " + streamTypeQName.getQualifiedName());
                state.requestedStreamType = streamTypeQName;
                state.isSessionScope = "session".equals(config.getRootElement().attributeValue("stream-scope"));

                // Read and store request
                state.requestDocument = readRequestAsDOM4J(pipelineContext, config);

                // Check if the body was requested
                state.bodyRequested = XPathUtils.selectSingleNode(state.requestDocument, "/*/body") != null;
            }
            final Context context = getContext(pipelineContext);
            return !context.hasUpload && !state.bodyRequested;
        }

        protected byte[] computeDigest(PipelineContext pipelineContext, DigestState digestState) {
            final State state = (State) digestState;
            return DigestContentHandler.getDigest(new DocumentSource(state.requestDocument));
        }
    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.processor.zip.UnzipProcessor.java

@Override
public ProcessorOutput createOutput(String name) {
    final ProcessorOutput output = new ProcessorOutputImpl(UnzipProcessor.this, name) {

        public void readImpl(PipelineContext context, XMLReceiver xmlReceiver) {
            try {
                // Read input in a temporary file
                final File temporaryZipFile;
                {//w  ww. j  av a 2  s .  c  o  m
                    final FileItem fileItem = NetUtils.prepareFileItem(NetUtils.REQUEST_SCOPE, logger);
                    final OutputStream fileOutputStream = fileItem.getOutputStream();
                    readInputAsSAX(context, getInputByName(INPUT_DATA),
                            new BinaryTextXMLReceiver(fileOutputStream));
                    temporaryZipFile = ((DiskFileItem) fileItem).getStoreLocation();
                }

                xmlReceiver.startDocument();
                // <files>
                xmlReceiver.startElement("", "files", "files", SAXUtils.EMPTY_ATTRIBUTES);
                ZipFile zipFile = new ZipFile(temporaryZipFile);
                for (Enumeration entries = zipFile.entries(); entries.hasMoreElements();) {
                    // Go through each entry in the zip file
                    ZipEntry zipEntry = (ZipEntry) entries.nextElement();
                    // Get file name
                    String fileName = zipEntry.getName();
                    long fileSize = zipEntry.getSize();
                    String fileTime = DateUtils.DateTime().print(zipEntry.getTime());

                    InputStream entryInputStream = zipFile.getInputStream(zipEntry);
                    String uri = NetUtils.inputStreamToAnyURI(entryInputStream, NetUtils.REQUEST_SCOPE, logger);
                    // <file name="filename.ext">uri</file>
                    AttributesImpl fileAttributes = new AttributesImpl();
                    fileAttributes.addAttribute("", "name", "name", "CDATA", fileName);
                    fileAttributes.addAttribute("", "size", "size", "CDATA", Long.toString(fileSize));
                    fileAttributes.addAttribute("", "dateTime", "dateTime", "CDATA", fileTime);
                    xmlReceiver.startElement("", "file", "file", fileAttributes);
                    xmlReceiver.characters(uri.toCharArray(), 0, uri.length());
                    // </file>
                    xmlReceiver.endElement("", "file", "file");
                }
                // </files>
                xmlReceiver.endElement("", "files", "files");
                xmlReceiver.endDocument();

            } catch (IOException e) {
                throw new OXFException(e);
            } catch (SAXException e) {
                throw new OXFException(e);
            }
        }

        // We don't do any caching here since the file we produce are temporary. So we don't want a processor
        // downstream to keep a reference to a document that contains temporary URI that have since been deleted.

    };
    addOutput(name, output);
    return output;
}

From source file:org.orbeon.oxf.xforms.control.controls.XXFormsAttributeControl.java

@Override
public void outputAjaxDiff(ContentHandlerHelper ch, XFormsControl other, AttributesImpl attributesImpl,
        boolean isNewlyVisibleSubtree) {

    assert attributesImpl.getLength() == 0;

    final XXFormsAttributeControl attributeControl2 = this;

    // Whether it is necessary to output information about this control
    boolean doOutputElement = false;

    // Control id
    attributesImpl.addAttribute("", "id", "id", ContentHandlerHelper.CDATA,
            XFormsUtils.namespaceId(containingDocument(), attributeControl2.getEffectiveId()));

    // The client does not store an HTML representation of the xxf:attribute control, so we
    // have to output these attributes.
    {/*from w w w.j  av a  2  s  . c o m*/
        // HTML element id
        final String effectiveFor2 = attributeControl2.getEffectiveForAttribute();
        doOutputElement |= AjaxSupport.addOrAppendToAttributeIfNeeded(attributesImpl, "for",
                XFormsUtils.namespaceId(containingDocument(), effectiveFor2), isNewlyVisibleSubtree, false);
    }

    {
        // Attribute name
        final String name2 = attributeControl2.getAttributeName();
        doOutputElement |= AjaxSupport.addOrAppendToAttributeIfNeeded(attributesImpl, "name", name2,
                isNewlyVisibleSubtree, false);
    }

    // Output element
    outputValueElement(ch, attributeControl2, doOutputElement, isNewlyVisibleSubtree, attributesImpl,
            "attribute");
}

From source file:org.orbeon.oxf.xforms.processor.handlers.xhtml.XFormsBaseHandlerXHTML.java

public static void outputDisabledAttribute(AttributesImpl newAttributes) {
    // @disabled="disabled"
    // HTML 4: @disabled supported on: input, button, select, optgroup, option, and textarea.
    newAttributes.addAttribute("", "disabled", "disabled", XMLReceiverHelper.CDATA, "disabled");
}

From source file:org.orbeon.oxf.xforms.processor.handlers.xhtml.XFormsBaseHandlerXHTML.java

protected void handleLabelHintHelpAlert(LHHAAnalysis lhhaAnalysis, String targetControlEffectiveId,
        String forEffectiveId, XFormsBaseHandler.LHHAC lhhaType, XFormsControl control, boolean isTemplate,
        boolean isExternal) throws SAXException {

    final AttributesImpl staticLHHAAttributes = Dom4jUtils.getSAXAttributes(lhhaAnalysis.element());

    final boolean isLabel = lhhaType == LHHAC.LABEL;
    final boolean isHelp = lhhaType == LHHAC.HELP;
    final boolean isHint = lhhaType == LHHAC.HINT;
    final boolean isAlert = lhhaType == LHHAC.ALERT;

    if (staticLHHAAttributes != null || isAlert) {
        // If no attributes were found, there is no such label / help / hint / alert

        if (handlerContext.isNoScript() && isHelp) {
            if (control != null) {

                final ContentHandler contentHandler = handlerContext.getController().getOutput();
                final String xhtmlPrefix = handlerContext.findXHTMLPrefix();

                // <a href="#my-control-id-help">

                final AttributesImpl aAttributes = new AttributesImpl();
                aAttributes.addAttribute("", "href", "href", XMLReceiverHelper.CDATA,
                        "#" + getLHHACId(containingDocument, targetControlEffectiveId,
                                LHHAC_CODES.get(LHHAC.HELP)));
                aAttributes.addAttribute("", "class", "class", XMLReceiverHelper.CDATA, "xforms-help-anchor");

                final String aQName = XMLUtils.buildQName(xhtmlPrefix, "a");
                contentHandler.startElement(XMLConstants.XHTML_NAMESPACE_URI, "a", aQName, aAttributes);
                contentHandler.endElement(XMLConstants.XHTML_NAMESPACE_URI, "a", aQName);
            }/*from ww  w . ja  va 2  s  .com*/
        } else {

            final String labelHintHelpAlertValue;
            final boolean mustOutputHTMLFragment;
            if (control != null) {
                // Get actual value from control
                if (isLabel) {
                    labelHintHelpAlertValue = control.getLabel();
                    mustOutputHTMLFragment = control.isHTMLLabel();
                } else if (isHelp) {
                    // NOTE: Special case here where we get the escaped help to facilitate work below. Help is a special
                    // case because it is stored as escaped HTML within a <label> element.
                    labelHintHelpAlertValue = control.getEscapedHelp();
                    mustOutputHTMLFragment = false;
                } else if (isHint) {
                    labelHintHelpAlertValue = control.getHint();
                    mustOutputHTMLFragment = control.isHTMLHint();
                } else if (isAlert) {
                    labelHintHelpAlertValue = control.getAlert();
                    mustOutputHTMLFragment = control.isHTMLAlert();
                } else {
                    throw new IllegalStateException("Illegal type requested");
                }
            } else {
                // Placeholder
                labelHintHelpAlertValue = null;
                mustOutputHTMLFragment = false;
            }

            final String elementName;
            {
                if (isLabel) {
                    elementName = handlerContext.getLabelElementName();
                } else if (isHelp) {
                    elementName = handlerContext.getHelpElementName();
                } else if (isHint) {
                    elementName = handlerContext.getHintElementName();
                } else if (isAlert) {
                    elementName = handlerContext.getAlertElementName();
                } else {
                    throw new IllegalStateException("Illegal type requested");
                }
            }

            final StringBuilder classes = new StringBuilder(30);

            // Put user classes first if any
            if (staticLHHAAttributes != null) {
                final String userClass = staticLHHAAttributes.getValue("class");
                if (userClass != null)
                    classes.append(userClass);
            }

            // Mark alert as active if needed
            if (isAlert) {
                if (control instanceof XFormsSingleNodeControl) {
                    final XFormsSingleNodeControl singleNodeControl = (XFormsSingleNodeControl) control;
                    final scala.Option<ValidationLevels.ValidationLevel> constraintLevel = singleNodeControl
                            .alertLevel();

                    if (constraintLevel.isDefined()) {
                        if (classes.length() > 0)
                            classes.append(' ');
                        classes.append("xforms-active");
                    }

                    // Constraint classes are placed on the control if the alert is not external
                    if (isExternal)
                        addConstraintClasses(classes, constraintLevel);
                }
            }

            // Handle visibility
            // TODO: It would be great to actually know about the relevance of help, hint, and label. Right now, we just look at whether the value is empty
            if (control != null) {
                if (isAlert || isLabel) {
                    // Allow empty labels and alerts
                    if (!control.isRelevant()) {
                        if (classes.length() > 0)
                            classes.append(' ');
                        classes.append("xforms-disabled");
                    }
                } else {
                    // For help and hint, consider "non-relevant" if empty
                    final boolean isHintHelpRelevant = control.isRelevant()
                            && StringUtils.isNotEmpty(labelHintHelpAlertValue);
                    if (!isHintHelpRelevant) {
                        if (classes.length() > 0)
                            classes.append(' ');
                        classes.append("xforms-disabled");
                    }
                }
            } else if (!isTemplate || isHelp) {
                // Null control outside of template OR help within template
                if (classes.length() > 0)
                    classes.append(' ');
                classes.append("xforms-disabled");
            }

            // LHHA name
            if (classes.length() > 0)
                classes.append(' ');
            classes.append("xforms-");
            classes.append(lhhaType.name().toLowerCase());

            // We handle null attributes as well because we want a placeholder for "alert" even if there is no xf:alert
            final Attributes newAttributes = (staticLHHAAttributes != null) ? staticLHHAAttributes
                    : new AttributesImpl();

            lhhaAnalysis.encodeAndAppendAppearances(classes);

            outputLabelFor(handlerContext, getIdClassXHTMLAttributes(newAttributes, classes.toString(), null),
                    targetControlEffectiveId, forEffectiveId, lhhaType, elementName, labelHintHelpAlertValue,
                    mustOutputHTMLFragment, isExternal);
        }
    }
}

From source file:org.orbeon.oxf.xforms.processor.handlers.xhtml.XFormsBaseHandlerXHTML.java

protected static void outputLabelForStart(HandlerContext handlerContext, Attributes attributes,
        String targetControlEffectiveId, String forEffectiveId, LHHAC lhha, String elementName, boolean addIds)
        throws SAXException {

    assert lhha != null;
    assert !addIds || targetControlEffectiveId != null;

    // Replace id attribute to be foo-label, foo-hint, foo-help, or foo-alert
    final AttributesImpl newAttribute;
    if (addIds && targetControlEffectiveId != null) {
        // Add or replace existing id attribute
        // NOTE: addIds == true for external LHHA
        newAttribute = SAXUtils.addOrReplaceAttribute(attributes, "", "", "id", getLHHACId(
                handlerContext.getContainingDocument(), targetControlEffectiveId, LHHAC_CODES.get(lhha)));
    } else {/*from  ww  w  .  j a v  a2 s  . co m*/
        // Remove existing id attribute if any
        newAttribute = SAXUtils.removeAttribute(attributes, "", "id");
    }

    // Add @for attribute if specified and element is a label
    if (forEffectiveId != null && elementName.equals("label"))
        newAttribute.addAttribute("", "for", "for", XMLReceiverHelper.CDATA, forEffectiveId);

    final String xhtmlPrefix = handlerContext.findXHTMLPrefix();
    final String labelQName = XMLUtils.buildQName(xhtmlPrefix, elementName);
    final ContentHandler contentHandler = handlerContext.getController().getOutput();

    contentHandler.startElement(XMLConstants.XHTML_NAMESPACE_URI, elementName, labelQName, newAttribute);
}

From source file:org.orbeon.oxf.xforms.processor.handlers.xhtml.XFormsControlLifecyleHandler.java

protected AttributesImpl getEmptyNestedControlAttributesMaybeWithId(String uri, String localname,
        Attributes attributes, String effectiveId, XFormsControl control, boolean addId) {
    reusableAttributes.clear();/*from   w w w. j  a  v a  2s.c  o m*/
    final AttributesImpl containerAttributes = reusableAttributes;
    if (addId)
        containerAttributes.addAttribute("", "id", "id", XMLReceiverHelper.CDATA,
                getLHHACId(containingDocument, effectiveId, LHHAC_CODES.get(LHHAC.CONTROL)));

    return containerAttributes;
}