Example usage for org.xml.sax Attributes getIndex

List of usage examples for org.xml.sax Attributes getIndex

Introduction

In this page you can find the example usage for org.xml.sax Attributes getIndex.

Prototype

public int getIndex(String qName);

Source Link

Document

Look up the index of an attribute by XML qualified (prefixed) name.

Usage

From source file:io.wcm.handler.url.rewriter.impl.UrlExternalizerTransformer.java

@Override
public void startElement(String nsUri, String name, String raw, Attributes attrs) throws SAXException {

    // check if for this element an attribute for rewriting is configured
    String rewriteAttr = transformerConfig.getElementAttributeNames().get(name);
    if (rewriteAttr == null) {
        log.trace("Rewrite element {}: Skip - No rewrite attribute configured.", name);
        super.startElement(nsUri, name, raw, attrs);
        return;/*from   w  ww  . ja v  a2 s .c o m*/
    }

    // validate URL handler
    if (urlHandler == null) {
        log.warn("Rewrite element {}: Skip - Unable to get URL handler/Integrator handler instance.", name);
        super.startElement(nsUri, name, raw, attrs);
        return;
    }

    // check if attribute exists
    int attributeIndex = attrs.getIndex(rewriteAttr);
    if (attributeIndex < 0) {
        log.trace("Rewrite element {}: Skip - Attribute does not exist: {}", name, rewriteAttr);
        super.startElement(nsUri, name, raw, attrs);
        return;
    }

    // rewrite URL
    String url = attrs.getValue(attributeIndex);
    if (StringUtils.isEmpty(url)) {
        log.trace("Rewrite element {}: Skip - URL is empty.", name);
        super.startElement(nsUri, name, raw, attrs);
        return;
    }

    // remove escaping
    url = StringEscapeUtils.unescapeHtml4(url);

    // externalize URL (if it is not already externalized)
    String rewrittenUrl = urlHandler.get(url).buildExternalResourceUrl();

    if (StringUtils.equals(url, rewrittenUrl)) {
        log.debug("Rewrite element {}: Skip - URL is already externalized: {}", name, url);
        super.startElement(nsUri, name, raw, attrs);
        return;
    }

    // set new attribute value
    log.debug("Rewrite element {}: Rewrite URL {} to {}", name, url, rewrittenUrl);
    AttributesImpl newAttrs = new AttributesImpl(attrs);
    newAttrs.setValue(attributeIndex, rewrittenUrl);
    super.startElement(nsUri, name, raw, newAttrs);
}

From source file:jp.gr.java_conf.petit_lycee.subsonico.MethodConstants.java

public void startElement(String namespaceURI, String localName, String qName,
        org.xml.sax.Attributes attributes) {

    ResponseElement elem = null;/*from   w  w  w  .  j a v  a 2s.co m*/

    //element????
    //(error????)
    if (qName.equals("subsonic-response")) {
        //set response data
        response.setStatus(attributes.getValue("status"));
        response.setVersion(attributes.getValue("version"));
        if (!"ok".equals(response.getStatus())) {
            subsEx = new SubsonicException();
        }
    } else if (qName.equals("error")) {
        if (subsEx != null)
            setValues(subsEx, attributes);

    } else if (qName.equals("directory")) {
        Directory p = new Directory();
        p.setDir(true);
        elem = p;

    } else if (qName.equals("index")) {
        elem = new Index();

    } else if (qName.equals("child")) {
        int spam = attributes.getIndex("isDir");
        if (spam >= 0 && attributes.getValue(spam).equals("true")) {
            elem = new Directory();
        } else {
            elem = new Media();
        }

    } else if (qName.equals("artist")) {
        elem = new Directory();
    } else if (qName.equals("song")) {
        elem = new Media();
    } else if (qName.equals("license")) {
        elem = new License();
    }

    if (elem != null) {
        setValues(elem, attributes);
        if (elem instanceof Entry) {
            Entry etr = (Entry) elem;
            ArrayList<Entry> list = stack.peek();
            list.add(etr);
            stack.push(etr.children);
        }
    }
}

From source file:nl.armatiek.xslweb.pipeline.PipelineHandler.java

private String getAttribute(Attributes attr, String name, String defaultValue) {
    int index = -1;
    return ((index = attr.getIndex(name)) >= 0) ? attr.getValue(index) : defaultValue;
}

From source file:nl.nn.adapterframework.extensions.sap.jco2.IdocXmlHandler.java

public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
    //log.debug("startElement("+localName+")");
    if (doc == null) {
        log.debug("creating Idoc [" + localName + "]");
        doc = JCoIDoc.createDocument(sapSystem.getIDocRepository(), localName);
        IDoc.Segment segment = doc.getRootSegment();
        segmentStack.add(segment);/*  w ww  . j a  v a 2 s .c  o  m*/
    } else {
        if (attributes.getIndex("SEGMENT") >= 0) {
            if (localName.startsWith("EDI_DC")) {
                parsingEdiDcHeader = true;
            } else {
                log.debug("creating segment [" + localName + "]");
                IDoc.Segment parentSegment = (IDoc.Segment) segmentStack.get(segmentStack.size() - 1);
                IDoc.Segment segment = parentSegment.addChild(localName);
                segmentStack.add(segment);
            }
        } else {
            currentField = localName;
        }
    }
}

From source file:nl.nn.adapterframework.extensions.sap.jco3.IdocXmlHandler.java

public void startElement(String uri, String localName, String qName, Attributes attributes)
        throws SAXException {
    //log.debug("startElement("+localName+")");
    if (doc == null) {
        log.debug("creating Idoc [" + localName + "]");
        try {//from w ww  .  j  av a2s . c  om
            doc = JCoIDoc.getIDocFactory().createIDocDocument(sapSystem.getIDocRepository(), localName);
        } catch (IDocMetaDataUnavailableException e) {
            throw new SAXException("could not create idoc document, idoc meta data unavailable", e);
        } catch (JCoException e) {
            throw new SAXException("could not create idoc document", e);
        }
        IDocSegment segment = doc.getRootSegment();
        segmentStack.add(segment);
    } else {
        if (attributes.getIndex("SEGMENT") >= 0) {
            if (localName.startsWith("EDI_DC")) {
                parsingEdiDcHeader = true;
            } else {
                log.debug("creating segment [" + localName + "]");
                IDocSegment parentSegment = (IDocSegment) segmentStack.get(segmentStack.size() - 1);
                IDocSegment segment;
                try {
                    segment = parentSegment.addChild(localName);
                } catch (IDocIllegalTypeException e) {
                    throw new SAXException("could not parse segment, idoc illegal type", e);
                } catch (IDocMetaDataUnavailableException e) {
                    throw new SAXException("could not parse segment, idoc meta data unavailable", e);
                }
                segmentStack.add(segment);
            }
        } else {
            currentField = localName;
        }
    }
}

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

/**
 * Handle select elements. Sets up some instance variables for
 * following option elements.//from  w w w  .  java  2 s  .c  o m
 */
protected void startSelectElement(String uri, String name, String raw, Attributes attr) throws SAXException {

    // this.values = request.getParameterValues(@name)
    String aName = getName(attr.getValue("name"));
    String fixed = attr.getValue(this.fixedName);
    this.values = null;
    if (getLogger().isDebugEnabled())
        getLogger().debug("startSelectElement " + name + " attributes " + this.printAttributes(attr));
    if (aName != null && !(this.fixed || (fixed != null && BooleanUtils.toBoolean(fixed)))) {
        if (attr.getIndex("multiple") > -1) {
            this.values = this.getValues(aName);
        } else {
            Object val = this.getNextValue(aName);
            if (val != null) {
                this.values = new Object[1];
                this.values[0] = val;
            } else {
                this.values = null;
            }
        }
        attr = this.normalizeAttributes(attr);
    }
    this.relayStartElement(uri, name, raw, attr);
}

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

private String getAttribute(Attributes attr, String name, String defaultValue) {
    return (attr.getIndex(name) >= 0) ? attr.getValue(name) : defaultValue;
}

From source file:org.apache.cocoon.woody.transformation.WidgetReplacingPipe.java

public void startElement(String namespaceURI, String localName, String qName, Attributes attributes)
        throws SAXException {
    elementNestingCounter++;/* w  ww .ja  va2  s .com*/

    if (inWidgetElement) {
        if (elementNestingCounter == widgetElementNesting + 1 && Constants.WI_NS.equals(namespaceURI)
                && STYLING_EL.equals(localName)) {
            gotStylingElement = true;
        }
        saxBuffer.startElement(namespaceURI, localName, qName, attributes);
    } else if (Constants.WT_NS.equals(namespaceURI)) {
        if (localName.equals(WIDGET) || localName.equals(REPEATER_WIDGET)) {
            checkContextWidgetAvailable(qName);
            inWidgetElement = true;
            widgetElementNesting = elementNestingCounter;
            gotStylingElement = false;
            saxBuffer = new SaxBuffer();
            // retrieve widget here, but its XML will only be streamed in the endElement call
            widget = getWidget(attributes);
            repeaterWidget = localName.equals(REPEATER_WIDGET);
            if (repeaterWidget && !(widget instanceof Repeater)) {
                throw new SAXException(
                        "WoodyTemplateTransformer: the element \"repeater-widget\" can only be used for repeater widgets.");
            }
        } else if (localName.equals(WIDGET_LABEL)) {
            checkContextWidgetAvailable(qName);
            Widget widget = getWidget(attributes);
            widget.generateLabel(contentHandler);
        } else if (localName.equals(REPEATER_WIDGET_LABEL)) {
            checkContextWidgetAvailable(qName);
            Widget widget = getWidget(attributes);
            if (!(widget instanceof Repeater)) {
                throw new SAXException(
                        "WoodyTemplateTransformer: the element \"repeater-widget-label\" can only be used for repeater widgets.");
            }
            String widgetId = attributes.getValue("widget-id");
            if (widgetId == null || widgetId.length() == 0) {
                throw new SAXException(
                        "WoodyTemplateTransformer: the element \"repeater-widget-label\" requires a \"widget-id\" attribute.");
            }
            ((Repeater) widget).generateWidgetLabel(widgetId, contentHandler);
        } else if (localName.equals(REPEATER_SIZE)) {
            checkContextWidgetAvailable(qName);
            Widget widget = getWidget(attributes);
            if (!(widget instanceof Repeater))
                throw new SAXException(
                        "WoodyTemplateTransformer: the element \"repeater-size\" can only be used for repeater widgets.");
            contentHandler.startPrefixMapping(Constants.WI_PREFIX, Constants.WI_NS);
            ((Repeater) widget).generateSize(contentHandler);
            contentHandler.endPrefixMapping(Constants.WI_PREFIX);
        } else if (localName.equals(FORM_TEMPLATE_EL)) {
            if (contextWidget != null) {
                throw new SAXException("Detected nested wt:form-template elements, this is not allowed.");
            }
            contentHandler.startPrefixMapping(Constants.WI_PREFIX, Constants.WI_NS);

            // ====> Retrieve the form

            // first look for the form using the location attribute, if any
            String formJXPath = attributes.getValue(LOCATION);
            if (formJXPath != null) {
                // remove the location attribute
                AttributesImpl attrsCopy = new AttributesImpl(attributes);
                attrsCopy.removeAttribute(attributes.getIndex(LOCATION));
                attributes = attrsCopy;
            }
            contextWidget = pipeContext.findForm(formJXPath);

            // ====> Determine the Locale
            //TODO pull this locale stuff also up in the Config object?

            String localeAttr = attributes.getValue("locale");
            if (localeAttr != null) { // first use value of locale attribute if any
                localeAttr = pipeContext.translateText(localeAttr);
                pipeContext.setLocale(I18nUtils.parseLocale(localeAttr));
            } else if (pipeContext.getLocaleParameter() != null) { // then use locale specified as transformer parameter, if any
                pipeContext.setLocale(pipeContext.getLocaleParameter());
            } else { // use locale specified in bizdata supplied for form
                Object locale = null;
                try {
                    locale = pipeContext.evaluateExpression("/locale");
                } catch (JXPathException e) {
                }
                if (locale != null) {
                    pipeContext.setLocale((Locale) locale);
                } else {
                    // final solution: use locale defined in the server machine
                    pipeContext.setLocale(Locale.getDefault());
                }
            }

            String[] namesToTranslate = { "action" };
            Attributes transAtts = translateAttributes(attributes, namesToTranslate);
            contentHandler.startElement(Constants.WI_NS, FORM_TEMPLATE_EL,
                    Constants.WI_PREFIX_COLON + FORM_TEMPLATE_EL, transAtts);

        } else if (localName.equals(CONTINUATION_ID)) {
            // Insert the continuation id
            // FIXME(SW) we could avoid costly JXPath evaluation if we had the objectmodel here.
            Object idObj = pipeContext.evaluateExpression("$continuation/id");
            if (idObj == null) {
                throw new SAXException("No continuation found");
            }

            String id = idObj.toString();
            contentHandler.startPrefixMapping(Constants.WI_PREFIX, Constants.WI_NS);
            contentHandler.startElement(Constants.WI_NS, CONTINUATION_ID,
                    Constants.WI_PREFIX_COLON + CONTINUATION_ID, attributes);
            contentHandler.characters(id.toCharArray(), 0, id.length());
            contentHandler.endElement(Constants.WI_NS, CONTINUATION_ID,
                    Constants.WI_PREFIX_COLON + CONTINUATION_ID);
            contentHandler.endPrefixMapping(Constants.WI_PREFIX);
        } else {
            throw new SAXException("WoodyTemplateTransformer: Unsupported element: " + localName);
        }
    } else {
        super.startElement(namespaceURI, localName, qName, attributes);
    }
}

From source file:org.apache.struts.config.ConfigRuleSet.java

public void begin(Attributes attributes) throws Exception {
    if (attributes.getIndex("key") == -1) {
        super.begin(attributes);

        return;/* w  ww  . j  ava  2 s .co  m*/
    }

    if (attributes.getIndex("property") != -1) {
        throw new IllegalArgumentException(
                "<set-property> accepts only one of 'key' or 'property' attributes.");
    }

    Object topOfStack = digester.peek();

    if (topOfStack instanceof BaseConfig) {
        BaseConfig config = (BaseConfig) topOfStack;

        config.setProperty(attributes.getValue("key"), attributes.getValue("value"));
    } else {
        throw new IllegalArgumentException(
                "'key' attribute of <set-property> only applicable to subclasses of BaseConfig; "
                        + "object on top of stack is " + topOfStack + " [key: " + attributes.getValue("key")
                        + ", value: " + attributes.getValue("value") + "]");
    }
}

From source file:org.betaconceptframework.astroboa.engine.jcr.io.contenthandler.ImportContentHandler.java

private String getValueForAttribute(String attributeName, Attributes atts) {

    final int index = atts.getIndex(attributeName);

    if (index > -1) {
        return atts.getValue(index);
    }/*from  w  w  w  .  j a  va  2 s .  co  m*/

    return null;
}