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:com.rapidminer.gui.properties.OperatorPropertyPanel.java

/**
 * Starts a progress thread which parses the parameter descriptions for the provided operator ,
 * cleans the {@link #parameterDescriptionCache}, and stores parsed descriptions in the
 * {@link #parameterDescriptionCache}./*  ww w  . j a v a2 s  .  c  o  m*/
 */
private void parseParameterDescriptions(final Operator operator) {
    parameterDescriptionCache.clear();
    URL documentationURL = OperatorDocumentationBrowser.getDocResourcePath(operator);
    if (documentationURL != null) {
        try (InputStream documentationStream = documentationURL.openStream()) {
            XMLStreamReader reader = XML_STREAM_FACTORY.createXMLStreamReader(documentationStream);
            String parameterKey = null;

            // The builder that stores the parameter description text
            StringBuilder parameterTextBuilder = null;
            boolean inParameters = false;
            while (reader.hasNext()) {
                switch (reader.next()) {
                case XMLStreamReader.START_ELEMENT:
                    if (!inParameters && reader.getLocalName().equals(TAG_PARAMETERS)) {
                        inParameters = true;
                    } else {
                        AttributesImpl attributes = new AttributesImpl();
                        for (int i = 0; i < reader.getAttributeCount(); i++) {
                            attributes.addAttribute("", reader.getAttributeLocalName(i),
                                    reader.getAttributeName(i).toString(), reader.getAttributeType(i),
                                    reader.getAttributeValue(i));
                        }

                        // Check if no parameter was found
                        if (reader.getLocalName().equals(TAG_PARAMETER)) {
                            parameterKey = attributes.getValue(ATTRIBUTE_PARAMETER_KEY);

                            // In case a parameter key was found, create a new string
                            // builder
                            if (parameterKey != null) {
                                parameterTextBuilder = new StringBuilder();
                            }
                        }

                        if (parameterTextBuilder != null) {
                            appendParameterStartTag(reader.getLocalName(), attributes, parameterTextBuilder);
                        }
                    }
                    break;
                case XMLStreamReader.END_ELEMENT:
                    // end parsing when end of parameters element is reached
                    if (reader.getLocalName().equals(TAG_PARAMETERS)) {
                        return;
                    }

                    if (parameterTextBuilder != null) {

                        // otherwise add element to description text
                        parameterTextBuilder.append("</");
                        parameterTextBuilder.append(reader.getLocalName());
                        parameterTextBuilder.append(">");

                        // Store description when parameter element ends
                        if (reader.getLocalName().equals(TAG_PARAMETER)) {
                            final String parameterDescription = parameterTextBuilder.toString();
                            final String key = parameterKey;
                            if (!parameterDescriptionCache.containsKey(parameterKey)) {
                                Source xmlSource = new StreamSource(new StringReader(parameterDescription));
                                try {
                                    String desc = OperatorDocToHtmlConverter.applyXSLTTransformation(xmlSource);
                                    parameterDescriptionCache.put(key, StringEscapeUtils.unescapeHtml(desc));
                                } catch (TransformerException e) {
                                    // ignore
                                }
                            }
                        }
                    }
                    break;
                case XMLStreamReader.CHARACTERS:
                    if (parameterTextBuilder != null) {
                        parameterTextBuilder.append(StringEscapeUtils.escapeHtml(reader.getText()));
                    }
                    break;
                default:
                    // ignore other events
                    break;
                }
            }
        } catch (IOException | XMLStreamException e) {
            // ignore
        }
    }
}

From source file:biz.taoconsulting.oxf.processor.converter.FromPdfConverter.java

/**
 * @param xmlReceiver//from   w  w  w  . j  a  v a2 s .c  o m
 * @param doc
 */
private boolean extractPagesFromPDF(XMLReceiver xmlReceiver, PDDocument doc) {

    // This extracts all pages with the text per page
    boolean tmpReturn = true; // Benefit of the doubt
    PDFTextStripper stripper;
    try {
        stripper = new PDFTextStripper();

        AttributesImpl atts;

        // Capture the number of pages
        int pageCount = doc.getPageCount();

        //Loop through all the pages;
        for (int i = 1; i <= pageCount; i++) {
            atts = new AttributesImpl();
            atts.addAttribute("", ATT_PAGENUM, ATT_PAGENUM, ATT_CDATA, String.valueOf(i));
            stripper.setStartPage(i);
            stripper.setEndPage(i);
            String textBetweenBookmarks = stripper.getText(doc);
            xmlReceiver.startElement("", TAG_PAGE, TAG_PAGE, atts);
            textBetweenBookmarks = MassageTextResult(textBetweenBookmarks);
            xmlReceiver.characters(textBetweenBookmarks.toCharArray(), 0, textBetweenBookmarks.length());
            xmlReceiver.endElement("", TAG_PAGE, TAG_PAGE);
        }
    } catch (IOException e) {
        // If it goes wrong
        logger.error(e);
        addErrorTagToOutput(xmlReceiver, e.toString());
        tmpReturn = false;
    } catch (SAXException e) {
        // If it goes wrong
        logger.error(e);
        addErrorTagToOutput(xmlReceiver, e.toString());
        tmpReturn = false;
    }
    return tmpReturn;
}

From source file:biz.taoconsulting.oxf.processor.converter.FromPdfConverter.java

/**
 * @param atts//  www.jav  a 2s .  co m
 * @param doc
 */
private void addPageCountAttribute(AttributesImpl atts, PDDocument doc) {
    int pageCount = 0; //The number of pages in this document
    try {
        pageCount = doc.getPageCount();
    } catch (IOException e) {
        logger.error(e);
        pageCount = 0;
    }
    if (pageCount > 0) {
        atts.addAttribute("", ATT_PAGES, ATT_PAGES, ATT_CDATA, String.valueOf(pageCount));
    }

}

From source file:de.gbv.ole.Marc21ToOleBulk.java

/**
 * Add an CDATA attribute.//from   w  w w.  j  a v a  2 s  .co  m
 * 
 * @param atts      where to add
 * @param name      used for localName and qName
 * @param value     attribute value
 */
private void add(final AttributesImpl atts, final String name, final char value) {
    atts.addAttribute("", name, name, "CDATA", String.valueOf(value));
}

From source file:de.gbv.ole.Marc21ToOleBulk.java

/**
 * Add an CDATA attribute.//from  ww w .java  2s  . c  om
 * 
 * @param atts      where to add
 * @param name      used for localName and qName
 * @param value     attribute value
 */
private void add(final AttributesImpl atts, final String name, final String value) {
    atts.addAttribute("", name, name, "CDATA", value);
}

From source file:com.gargoylesoftware.htmlunit.javascript.host.html.HTMLInputElement.java

/**
 * Sets the value of the attribute {@code type}.
 * Note: this replace the DOM node with a new one.
 * @param newType the new type to set// w ww. j a  va  2s. com
 */
@JsxSetter
public void setType(String newType) {
    HtmlInput input = getDomNodeOrDie();

    final String currentType = input.getAttribute("type");

    if (!currentType.equalsIgnoreCase(newType)) {
        if (newType != null && getBrowserVersion().hasFeature(JS_INPUT_SET_TYPE_LOWERCASE)) {
            newType = newType.toLowerCase(Locale.ROOT);
        }
        final AttributesImpl attributes = readAttributes(input);
        final int index = attributes.getIndex("type");
        if (index > -1) {
            attributes.setValue(index, newType);
        } else {
            attributes.addAttribute(null, "type", "type", null, newType);
        }

        // create a new one only if we have a new type
        if (ATTRIBUTE_NOT_DEFINED != currentType || !"text".equalsIgnoreCase(newType)) {
            final HtmlInput newInput = (HtmlInput) InputElementFactory.instance.createElement(input.getPage(),
                    "input", attributes);

            if (input.wasCreatedByJavascript()) {
                newInput.markAsCreatedByJavascript();
            }

            if (input.getParentNode() == null) {
                // the input hasn't yet been inserted into the DOM tree (likely has been
                // created via document.createElement()), so simply replace it with the
                // new Input instance created in the code above
                input = newInput;
            } else {
                input.getParentNode().replaceChild(newInput, input);
            }

            input.setScriptableObject(null);
            setDomNode(newInput, true);
        } else {
            super.setAttribute("type", newType);
        }
    }
}

From source file:org.syncope.core.util.ImportExport.java

private void doExportTable(final TransformerHandler handler, final Connection conn, final String tableName)
        throws SQLException, SAXException {

    AttributesImpl atts = new AttributesImpl();

    PreparedStatement stmt = null;
    ResultSet rs = null;//w w w. java  2 s.  c  om
    try {
        stmt = conn.prepareStatement("SELECT * FROM " + tableName + " a");
        rs = stmt.executeQuery();
        for (int rowNo = 0; rs.next(); rowNo++) {
            atts.clear();

            ResultSetMetaData metaData = rs.getMetaData();
            for (int i = 0; i < metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i + 1);
                String value = rs.getString(columnName);
                if (value != null) {
                    atts.addAttribute("", "", columnName, "CDATA", value);
                }
            }

            handler.startElement("", "", tableName, atts);
            handler.endElement("", "", tableName);
        }
    } finally {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                LOG.error("While closing result set", e);
            }
        }
    }
}

From source file:gov.va.vinci.leo.descriptors.LeoAEDescriptor.java

/**
 * Generate the XML for the analysisEngine section of the deployment descriptor.
 *
 * @param thd    the xml transform handler.
 * @param isTopDescriptor   true if this is a top level descriptor, else false.
 * @throws SAXException  if there is no descriptor to output
 * @return this Leo AE Descriptor//from   w  w w  .  ja  va 2 s.  co  m
 */

public LeoAEDescriptor analysisEngineSection(TransformerHandler thd, boolean isTopDescriptor)
        throws SAXException {
    //validate we have something to output
    if (this.mAEDescriptor == null)
        throw new MissingResourceException("No Descriptor available for XML output",
                AnalysisEngineDescription.class.getCanonicalName(), "mAEDescriptor");

    AttributesImpl atts = new AttributesImpl();
    //<analysisEngine>
    if (!isTopDescriptor)
        atts.addAttribute("", "", "key", "CDATA", mAEDescriptor.getMetaData().getName());
    if (mIsAsync) {
        atts.addAttribute("", "", "async", "CDATA", "true");
    } else {
        atts.addAttribute("", "", "async", "CDATA", "false");
    } //else

    atts.addAttribute("", "", "async", "CDATA", Boolean.toString(mIsAsync));
    thd.startElement("", "", "analysisEngine", atts);
    atts.clear();

    //<scaleout .../>
    atts.addAttribute("", "", "numberOfInstances", "CDATA", Integer.toString(mNumberOfInstances));
    thd.startElement("", "", "scaleout", atts);
    thd.endElement("", "", "scaleout");
    atts.clear();

    //Handle delegate tags for aggregate engines
    if (this.isAggregate() && mIsAsync) {
        //<delegates>
        thd.startElement("", "", "delegates", atts);

        //output all the delegate engines
        for (LeoDelegate delegate : mDelegates) {
            delegate.analysisEngineSection(thd, false);
        } //for

        //</delegates>
        thd.endElement("", "", "delegates");
    } //if

    //<asyncPrimitiveErrorConfiguration> or <asyncAggregateErrorConfiguration>
    if (isTopDescriptor)
        thd.startElement("", "", "asyncPrimitiveErrorConfiguration", atts);
    else
        thd.startElement("", "", "asyncAggregateErrorConfiguration", atts);

    //<getMetadataErrors .../>
    if (!isTopDescriptor) {
        atts.addAttribute("", "", "maxRetries", "CDATA", "0");
        atts.addAttribute("", "", "timeout", "CDATA", "0");
        atts.addAttribute("", "", "errorAction", "CDATA", "terminate");
        thd.startElement("", "", "getMetadataErrors", atts);
        thd.endElement("", "", "getMetadataErrors");
        atts.clear();
    } //if

    //<processCasErrors .../>
    atts.addAttribute("", "", "thresholdCount", "CDATA", "0");
    atts.addAttribute("", "", "thresholdWindow", "CDATA", "0");
    atts.addAttribute("", "", "thresholdAction", "CDATA", "terminate");
    thd.startElement("", "", "processCasErrors", atts);
    thd.endElement("", "", "processCasErrors");
    atts.clear();

    //<collectionProcessCompleteErrors .../>
    atts.addAttribute("", "", "timeout", "CDATA", "0");
    atts.addAttribute("", "", "additionalErrorAction", "CDATA", "terminate");
    thd.startElement("", "", "collectionProcessCompleteErrors", atts);
    thd.endElement("", "", "collectionProcessCompleteErrors");
    atts.clear();

    //</asyncPrimitiveErrorConfiguration> or <asyncAggregateErrorConfiguration>
    if (isTopDescriptor)
        thd.endElement("", "", "asyncPrimitiveErrorConfiguration");
    else
        thd.endElement("", "", "asyncAggregateErrorConfiguration");

    //</analysisEngine>
    thd.endElement("", "", "analysisEngine");
    return this;
}

From source file:com.netspective.axiom.schema.column.BasicColumn.java

public void addSchemaRecordEditorDialogTemplates(TemplateElement dialogTemplate, Map jexlVars) {
    jexlVars.put("column", this);

    ForeignKey fKey = getForeignKey();/*ww w  .jav a2s .  c om*/
    if (fKey != null && fKey.getReferencedColumns().getFirst().getTable() instanceof EnumerationTable) {
        addEnumerationSchemaRecordEditorDialogTemplates(dialogTemplate, jexlVars);
        return;
    }

    TemplateProducer columnPresentationTemplates = getPresentation();
    if (columnPresentationTemplates.getInstances().size() > 0) {
        // get only the last template because if there was inheritace of a data-type we want the "final" one
        Template columnPresentationTemplate = (Template) columnPresentationTemplates.getInstances()
                .get(columnPresentationTemplates.getInstances().size() - 1);
        List copyColumnPresTmplChildren = columnPresentationTemplate.getChildren();
        for (int i = 0; i < copyColumnPresTmplChildren.size(); i++) {
            TemplateNode colTmplChildNode = (TemplateNode) copyColumnPresTmplChildren.get(i);
            if (colTmplChildNode instanceof TemplateElement) {
                TemplateElement elem = dialogTemplate.addCopyOfChildAndReplaceExpressions(
                        (TemplateElement) colTmplChildNode, jexlVars, true);
                if (elem.getElementName().equals("field")) {
                    boolean changedAttrs = false;
                    AttributesImpl attrs = new AttributesImpl(elem.getAttributes());
                    if (isPrimaryKey()
                            && (attrs.getIndex("primary-key") == -1 && attrs.getIndex("primarykey") == -1
                                    && attrs.getIndex("primary-key-generated") == -1
                                    && attrs.getIndex("primarykeygenerated") == -1)) {
                        if (this instanceof GeneratedValueColumn)
                            attrs.addAttribute(null, null, "primary-key-generated", "CDATA", "yes");
                        else
                            attrs.addAttribute(null, null, "primary-key", "CDATA", "yes");
                        if (attrs.getIndex("required") == -1) // unless required is being overidden, make the primary key field required
                            attrs.addAttribute(null, null, "required", "CDATA", "yes");
                        changedAttrs = true;
                    }

                    if (isRequiredByApp() && attrs.getIndex("required") == -1) {
                        attrs.addAttribute(null, null, "required", "CDATA", "yes");
                        changedAttrs = true;
                    }
                    if (changedAttrs)
                        elem.setAttributes(attrs);
                }
            } else if (colTmplChildNode instanceof TemplateText)
                dialogTemplate.addChild(
                        new TemplateText(dialogTemplate, ((TemplateText) colTmplChildNode).getText()));
            else
                throw new RuntimeException("This should never happen.");
        }
    }
}

From source file:DOM2SAX.java

/**
 * Writes a node using the given writer.
 * @param node node to serialize//from  w ww. j a  va  2s. co m
 * @throws SAXException In case of a problem while writing XML
 */
private void writeNode(Node node) throws SAXException {
    if (node == null) {
        return;
    }

    switch (node.getNodeType()) {
    case Node.ATTRIBUTE_NODE: // handled by ELEMENT_NODE
    case Node.DOCUMENT_FRAGMENT_NODE:
    case Node.DOCUMENT_TYPE_NODE:
    case Node.ENTITY_NODE:
    case Node.ENTITY_REFERENCE_NODE:
    case Node.NOTATION_NODE:
        // These node types are ignored!!!
        break;
    case Node.CDATA_SECTION_NODE:
        final String cdata = node.getNodeValue();
        if (lexicalHandler != null) {
            lexicalHandler.startCDATA();
            contentHandler.characters(cdata.toCharArray(), 0, cdata.length());
            lexicalHandler.endCDATA();
        } else {
            // in the case where there is no lex handler, we still
            // want the text of the cdate to make its way through.
            contentHandler.characters(cdata.toCharArray(), 0, cdata.length());
        }
        break;

    case Node.COMMENT_NODE: // should be handled!!!
        if (lexicalHandler != null) {
            final String value = node.getNodeValue();
            lexicalHandler.comment(value.toCharArray(), 0, value.length());
        }
        break;
    case Node.DOCUMENT_NODE:
        contentHandler.startDocument();
        Node next = node.getFirstChild();
        while (next != null) {
            writeNode(next);
            next = next.getNextSibling();
        }
        contentHandler.endDocument();
        break;

    case Node.ELEMENT_NODE:
        String prefix;
        List pushedPrefixes = new java.util.ArrayList();
        final AttributesImpl attrs = new AttributesImpl();
        final NamedNodeMap map = node.getAttributes();
        final int length = map.getLength();

        // Process all namespace declarations
        for (int i = 0; i < length; i++) {
            final Node attr = map.item(i);
            final String qnameAttr = attr.getNodeName();

            // Ignore everything but NS declarations here
            if (qnameAttr.startsWith(XMLNS_PREFIX)) {
                final String uriAttr = attr.getNodeValue();
                final int colon = qnameAttr.lastIndexOf(':');
                prefix = (colon > 0) ? qnameAttr.substring(colon + 1) : EMPTYSTRING;
                if (startPrefixMapping(prefix, uriAttr)) {
                    pushedPrefixes.add(prefix);
                }
            }
        }

        // Process all other attributes
        for (int i = 0; i < length; i++) {
            final Node attr = map.item(i);
            final String qnameAttr = attr.getNodeName();

            // Ignore NS declarations here
            if (!qnameAttr.startsWith(XMLNS_PREFIX)) {
                final String uriAttr = attr.getNamespaceURI();

                // Uri may be implicitly declared
                if (uriAttr != null) {
                    final int colon = qnameAttr.lastIndexOf(':');
                    prefix = (colon > 0) ? qnameAttr.substring(0, colon) : EMPTYSTRING;
                    if (startPrefixMapping(prefix, uriAttr)) {
                        pushedPrefixes.add(prefix);
                    }
                }

                // Add attribute to list
                attrs.addAttribute(attr.getNamespaceURI(), getLocalName(attr), qnameAttr, "CDATA",
                        attr.getNodeValue());
            }
        }

        // Now process the element itself
        final String qname = node.getNodeName();
        final String uri = node.getNamespaceURI();
        final String localName = getLocalName(node);

        // Uri may be implicitly declared
        if (uri != null) {
            final int colon = qname.lastIndexOf(':');
            prefix = (colon > 0) ? qname.substring(0, colon) : EMPTYSTRING;
            if (startPrefixMapping(prefix, uri)) {
                pushedPrefixes.add(prefix);
            }
        }

        // Generate SAX event to start element
        contentHandler.startElement(uri, localName, qname, attrs);

        // Traverse all child nodes of the element (if any)
        next = node.getFirstChild();
        while (next != null) {
            writeNode(next);
            next = next.getNextSibling();
        }

        // Generate SAX event to close element
        contentHandler.endElement(uri, localName, qname);

        // Generate endPrefixMapping() for all pushed prefixes
        final int nPushedPrefixes = pushedPrefixes.size();
        for (int i = 0; i < nPushedPrefixes; i++) {
            endPrefixMapping((String) pushedPrefixes.get(i));
        }
        break;

    case Node.PROCESSING_INSTRUCTION_NODE:
        contentHandler.processingInstruction(node.getNodeName(), node.getNodeValue());
        break;

    case Node.TEXT_NODE:
        final String data = node.getNodeValue();
        contentHandler.characters(data.toCharArray(), 0, data.length());
        break;
    default:
        //nop
    }
}