Example usage for javax.xml XMLConstants XMLNS_ATTRIBUTE

List of usage examples for javax.xml XMLConstants XMLNS_ATTRIBUTE

Introduction

In this page you can find the example usage for javax.xml XMLConstants XMLNS_ATTRIBUTE.

Prototype

String XMLNS_ATTRIBUTE

To view the source code for javax.xml XMLConstants XMLNS_ATTRIBUTE.

Click Source Link

Document

The official XML attribute used for specifying XML Namespace declarations.

Usage

From source file:org.codice.ddf.spatial.ogc.csw.catalog.converter.CswMarshallHelper.java

static void writeValue(HierarchicalStreamWriter writer, MarshallingContext context,
        AttributeDescriptor attributeDescriptor, QName field, Serializable value) {

    String xmlValue = null;//from  w  ww.  java2 s .  c o  m
    AttributeType.AttributeFormat attrFormat = null;

    if (attributeDescriptor != null && attributeDescriptor.getType() != null) {
        attrFormat = attributeDescriptor.getType().getAttributeFormat();
    }

    if (attrFormat == null) {
        attrFormat = AttributeType.AttributeFormat.STRING;
    }

    String name = null;

    if (!StringUtils.isBlank(field.getNamespaceURI())) {
        if (!StringUtils.isBlank(field.getPrefix())) {
            name = field.getPrefix() + CswConstants.NAMESPACE_DELIMITER + field.getLocalPart();
        } else {
            name = field.getLocalPart();
        }
    } else {
        name = field.getLocalPart();
    }

    switch (attrFormat) {
    case BINARY:
        xmlValue = Base64.getEncoder().encodeToString((byte[]) value);
        break;
    case DATE:
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime((Date) value);
        xmlValue = XSD_FACTORY.newXMLGregorianCalendar(cal).toXMLFormat();
        break;
    case OBJECT:
        break;
    case GEOMETRY:
    case XML:
    default:
        xmlValue = value.toString();
        break;
    }

    // Write the node if we were able to convert it.
    if (xmlValue != null) {
        writer.startNode(name);

        if (!StringUtils.isBlank(field.getNamespaceURI())) {
            if (StringUtils.isBlank(field.getPrefix())) {
                writer.addAttribute(XMLConstants.XMLNS_ATTRIBUTE, field.getNamespaceURI());
            }
        }

        writer.setValue(xmlValue);
        writer.endNode();
    }
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.converter.GetRecordsResponseConverter.java

@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
    LOGGER.debug("Entering GetRecordsResponseConverter.marshal()");
    if (source == null || !(source instanceof CswRecordCollection)) {
        LOGGER.warn("Failed to marshal CswRecordCollection: {}", source);
        return;//from   w w w.  j a  va 2  s.c  o m
    }
    CswRecordCollection cswRecordCollection = (CswRecordCollection) source;

    for (Entry<String, String> entry : defaultCswRecordMap.getPrefixToUriMapping().entrySet()) {
        writer.addAttribute(XMLConstants.XMLNS_ATTRIBUTE + CswConstants.NAMESPACE_DELIMITER + entry.getKey(),
                entry.getValue());
    }

    long start = 1;
    String elementSet = null;
    String recordSchema = CswConstants.CSW_OUTPUT_SCHEMA;

    if (cswRecordCollection.getStartPosition() > 0) {
        start = cswRecordCollection.getStartPosition();
    }

    if (StringUtils.isNotBlank(cswRecordCollection.getOutputSchema())) {
        recordSchema = cswRecordCollection.getOutputSchema();

    }
    context.put(CswConstants.OUTPUT_SCHEMA_PARAMETER, recordSchema);

    if (cswRecordCollection.getElementSetType() != null) {
        context.put(CswConstants.ELEMENT_SET_TYPE, cswRecordCollection.getElementSetType());

        elementSet = cswRecordCollection.getElementSetType().value();
    } else if (cswRecordCollection.getElementName() != null) {
        context.put(CswConstants.ELEMENT_NAMES, cswRecordCollection.getElementName());
    }

    long nextRecord = start + cswRecordCollection.getNumberOfRecordsReturned();
    if (nextRecord > cswRecordCollection.getNumberOfRecordsMatched()) {
        nextRecord = 0;
    }
    if (!cswRecordCollection.isById()) {
        writer.addAttribute(VERSION_ATTRIBUTE, CswConstants.VERSION_2_0_2);

        writer.startNode(
                CswConstants.CSW_NAMESPACE_PREFIX + CswConstants.NAMESPACE_DELIMITER + SEARCH_STATUS_NODE_NAME);
        writer.addAttribute(TIMESTAMP_ATTRIBUTE, ISODateTimeFormat.dateTime().print(new DateTime()));
        writer.endNode();

        writer.startNode(CswConstants.CSW_NAMESPACE_PREFIX + CswConstants.NAMESPACE_DELIMITER
                + SEARCH_RESULTS_NODE_NAME);
        writer.addAttribute(NUMBER_OF_RECORDS_MATCHED_ATTRIBUTE,
                Long.toString(cswRecordCollection.getNumberOfRecordsMatched()));
        if (!ResultType.HITS.equals(cswRecordCollection.getResultType())) {
            writer.addAttribute(NUMBER_OF_RECORDS_RETURNED_ATTRIBUTE,
                    Long.toString(cswRecordCollection.getNumberOfRecordsReturned()));
        } else {
            writer.addAttribute(NUMBER_OF_RECORDS_RETURNED_ATTRIBUTE, Long.toString(0));
        }

        writer.addAttribute(NEXT_RECORD_ATTRIBUTE, Long.toString(nextRecord));
        writer.addAttribute(RECORD_SCHEMA_ATTRIBUTE, recordSchema);
        if (StringUtils.isNotBlank(elementSet)) {
            writer.addAttribute(ELEMENT_SET_ATTRIBUTE, elementSet);
        }
    }
    context.put(CswConstants.WRITE_NAMESPACES, cswRecordCollection.isDoWriteNamespaces());

    if (!ResultType.HITS.equals(cswRecordCollection.getResultType())) {
        LOGGER.debug("Transforming individual metacards.");
        for (Metacard mc : cswRecordCollection.getCswRecords()) {
            context.convertAnother(mc, transformProvider);
        }
    }
    if (!cswRecordCollection.isById()) {
        writer.endNode();
    }

}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.converter.impl.CswRecordConverter.java

private void writeValue(HierarchicalStreamWriter writer, MarshallingContext context,
        AttributeDescriptor attributeDescriptor, QName field, Serializable value) {

    String xmlValue = null;//from   w  w w. ja  v  a2 s.c  o  m

    AttributeFormat attrFormat = null;
    if (attributeDescriptor != null && attributeDescriptor.getType() != null) {
        attrFormat = attributeDescriptor.getType().getAttributeFormat();
    }
    if (attrFormat == null) {
        attrFormat = AttributeFormat.STRING;
    }
    String name = null;
    if (!StringUtils.isBlank(field.getNamespaceURI())) {
        if (!StringUtils.isBlank(field.getPrefix())) {
            name = field.getPrefix() + CswConstants.NAMESPACE_DELIMITER + field.getLocalPart();
        } else {
            name = field.getLocalPart();
        }
    } else {
        name = field.getLocalPart();
    }
    switch (attrFormat) {
    case BINARY:
        xmlValue = Base64.encodeBase64String((byte[]) value);
        break;
    case DATE:
        GregorianCalendar cal = new GregorianCalendar();
        cal.setTime((Date) value);
        xmlValue = XSD_FACTORY.newXMLGregorianCalendar(cal).toXMLFormat();
        break;
    case OBJECT:
        break;
    case GEOMETRY:
    case XML:
    default:
        xmlValue = value.toString();
        break;
    }
    // Write the node if we were able to convert it.
    if (xmlValue != null) {
        writer.startNode(name);
        if (!StringUtils.isBlank(field.getNamespaceURI())) {
            if (!StringUtils.isBlank(field.getPrefix())) {
                writeNamespace(writer, field);
            } else {
                writer.addAttribute(XMLConstants.XMLNS_ATTRIBUTE, field.getNamespaceURI());
            }
        }

        writer.setValue(xmlValue);
        writer.endNode();
    }
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.converter.impl.CswRecordConverter.java

private void writeNamespace(HierarchicalStreamWriter writer, QName field) {
    if (prefixToUriMapping == null || !prefixToUriMapping.containsKey(field.getPrefix())
            || !prefixToUriMapping.get(field.getPrefix()).equals(field.getNamespaceURI())) {
        writer.addAttribute(XMLConstants.XMLNS_ATTRIBUTE + CswConstants.NAMESPACE_DELIMITER + field.getPrefix(),
                field.getNamespaceURI());
    }//w w w .  j a va  2  s  .co m
}

From source file:org.codice.ddf.spatial.ogc.csw.catalog.converter.impl.GetRecordsResponseConverter.java

@Override
public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
    if (source == null || !(source instanceof CswRecordCollection)) {
        LOGGER.warn("Failed to marshal CswRecordCollection: {}", source);
        return;/*from   w w  w  .  java 2 s.c  o m*/
    }
    CswRecordCollection cswRecordCollection = (CswRecordCollection) source;

    for (Entry<String, String> entry : defaultCswRecordMap.getPrefixToUriMapping().entrySet()) {
        writer.addAttribute(XMLConstants.XMLNS_ATTRIBUTE + CswConstants.NAMESPACE_DELIMITER + entry.getKey(),
                entry.getValue());
    }

    long start = 1;
    String elementSet = "full";
    String recordSchema = CswConstants.CSW_OUTPUT_SCHEMA;

    GetRecordsType request = cswRecordCollection.getRequest();
    QueryType query = null;
    List<QName> elementsToWrite = null;
    ElementSetType elementSetType = ElementSetType.FULL;

    if (request != null) {
        if (request.isSetStartPosition()) {
            start = request.getStartPosition().longValue();
        }
        if (request.isSetAbstractQuery() && request.getAbstractQuery().getValue() instanceof QueryType) {
            query = (QueryType) request.getAbstractQuery().getValue();
        }
    }

    if (StringUtils.isNotBlank(cswRecordCollection.getOutputSchema())) {
        recordSchema = cswRecordCollection.getOutputSchema();

    }
    RecordConverterFactory converterFactory = null;
    for (RecordConverterFactory factory : converterFactories) {
        LOGGER.debug("Factory recordSchema == {}", factory.getOutputSchema());
        if (StringUtils.equals(factory.getOutputSchema(), recordSchema)) {
            converterFactory = factory;
        }
    }

    if (converterFactory == null) {
        throw new ConversionException("Unable to locate converter for outputSchema.");
    }

    if (cswRecordCollection.getElementSetType() != null) {
        elementSetType = cswRecordCollection.getElementSetType();
        elementSet = elementSetType.value();
        switch (elementSetType) {
        case BRIEF:
            elementsToWrite = CswRecordMetacardType.BRIEF_CSW_RECORD_FIELDS;
            break;
        case SUMMARY:
            elementsToWrite = CswRecordMetacardType.SUMMARY_CSW_RECORD_FIELDS;
            break;
        case FULL:
        default:
            elementsToWrite = CswRecordMetacardType.FULL_CSW_RECORD_FIELDS;
            break;
        }
    } else if (query != null && query.isSetElementName()) {
        elementsToWrite = query.getElementName();
    }

    long nextRecord = start + cswRecordCollection.getNumberOfRecordsReturned();
    if (nextRecord > cswRecordCollection.getNumberOfRecordsMatched()) {
        nextRecord = 0;
    }
    if (!cswRecordCollection.isById()) {
        writer.addAttribute(VERSION_ATTRIBUTE, CswConstants.VERSION_2_0_2);

        writer.startNode(
                CswConstants.CSW_NAMESPACE_PREFIX + CswConstants.NAMESPACE_DELIMITER + SEARCH_STATUS_NODE_NAME);
        writer.addAttribute(TIMESTAMP_ATTRIBUTE, ISODateTimeFormat.dateTime().print(new DateTime()));
        writer.endNode();

        writer.startNode(CswConstants.CSW_NAMESPACE_PREFIX + CswConstants.NAMESPACE_DELIMITER
                + SEARCH_RESULTS_NODE_NAME);
        writer.addAttribute(NUMBER_OF_RECORDS_MATCHED_ATTRIBUTE,
                Long.toString(cswRecordCollection.getNumberOfRecordsMatched()));
        writer.addAttribute(NUMBER_OF_RECORDS_RETURNED_ATTRIBUTE,
                Long.toString(cswRecordCollection.getNumberOfRecordsReturned()));

        writer.addAttribute(NEXT_RECORD_ATTRIBUTE, Long.toString(nextRecord));
        writer.addAttribute(RECORD_SCHEMA_ATTRIBUTE, recordSchema);
        writer.addAttribute(ELEMENT_SET_ATTRIBUTE, elementSet);
    }

    // TODO - need to pass good values here.
    RecordConverter recordConverter = converterFactory.createConverter(null,
            defaultCswRecordMap.getPrefixToUriMapping(), null, null, null, true);
    recordConverter.setFieldsToWrite(elementsToWrite);
    for (Metacard mc : cswRecordCollection.getCswRecords()) {
        String rootElementName = recordConverter.getRootElementName(elementSetType.toString());
        if (StringUtils.isNotBlank(rootElementName)) {
            writer.startNode(rootElementName);
            context.convertAnother(mc, recordConverter);
            writer.endNode();
        } else {
            context.convertAnother(mc, recordConverter);
        }
    }
    if (!cswRecordCollection.isById()) {
        writer.endNode();
    }
}

From source file:org.dhatim.delivery.dom.DOMBuilder.java

public void startElement(StartElementEvent startEvent) throws SAXException {
    Element newElement = null;/*from  ww  w. j a va  2s  .c  om*/
    int attsCount = startEvent.atts.getLength();
    Node currentNode = (Node) nodeStack.peek();

    try {
        if (startEvent.uri != null && startEvent.qName != null && !startEvent.qName.equals("")) {
            newElement = ownerDocument.createElementNS(startEvent.uri.intern(), startEvent.qName);
        } else {
            newElement = ownerDocument.createElement(startEvent.localName.intern());
        }

        currentNode.appendChild(newElement);
        if (!emptyElements.contains(startEvent.qName != null ? startEvent.qName : startEvent.localName)) {
            nodeStack.push(newElement);
        }
    } catch (DOMException e) {
        logger.error("DOMException creating start element: namespaceURI=" + startEvent.uri + ", localName="
                + startEvent.localName, e);
        throw e;
    }

    for (int i = 0; i < attsCount; i++) {
        String attNamespace = startEvent.atts.getURI(i);
        String attQName = startEvent.atts.getQName(i);
        String attLocalName = startEvent.atts.getLocalName(i);
        String attValue = startEvent.atts.getValue(i);
        try {
            if (attNamespace != null && attQName != null) {
                attNamespace = attNamespace.intern();
                if (attNamespace.equals(XMLConstants.NULL_NS_URI)) {
                    if (attQName.startsWith(XMLConstants.XMLNS_ATTRIBUTE)) {
                        attNamespace = XMLConstants.XMLNS_ATTRIBUTE_NS_URI;
                    } else if (attQName.startsWith("xml:")) {
                        attNamespace = XMLConstants.XML_NS_URI;
                    }
                }
                newElement.setAttributeNS(attNamespace, attQName, attValue);
            } else {
                newElement.setAttribute(attLocalName.intern(), attValue);
            }
        } catch (DOMException e) {
            logger.error("DOMException setting element attribute " + attLocalName + "=" + attValue
                    + "[namespaceURI=" + startEvent.uri + ", localName=" + startEvent.localName + "].", e);
            throw e;
        }
    }
}

From source file:org.opencastproject.mediapackage.XMLCatalogImpl.java

/**
 * Creates an abstract metadata container.
 * //w w  w  .  j  ava  2  s. c  o  m
 * @param id
 *          the element identifier withing the package
 * @param flavor
 *          the catalog flavor
 * @param uri
 *          the document location
 * @param size
 *          the catalog size in bytes
 * @param checksum
 *          the catalog checksum
 * @param mimeType
 *          the catalog mime type
 */
protected XMLCatalogImpl(String id, MediaPackageElementFlavor flavor, URI uri, long size, Checksum checksum,
        MimeType mimeType) {
    super(id, flavor, uri, size, checksum, mimeType);
    bindPrefix(XMLConstants.XML_NS_PREFIX, XMLConstants.XML_NS_URI);
    bindPrefix(XMLConstants.XMLNS_ATTRIBUTE, XMLConstants.XMLNS_ATTRIBUTE_NS_URI);
    bindPrefix(XSI_NS_PREFIX, XSI_NS_URI);
}

From source file:org.talend.commons.runtime.xml.XPathPrefixHandler.java

/**
 * DOC chuang Comment method "getNamespace".
 * //from ww w.ja v a 2  s  .c o m
 * @param node
 * @param parentPath
 * @return
 */
private void computeNamespace(NodeInfo info, String parentPath) {
    Node node = info.node;
    List<Node> attributes = new ArrayList<Node>();
    // return node.getNamespaceURI();
    String defaultNamespace = null;
    if (isXSDFile) {
        if (node.getNodeName().equals("xs:attribute")) { //$NON-NLS-1$
            attributes.add(node);
        }
    }
    NamedNodeMap nodeMap = node.getAttributes();
    for (int i = 0; i < nodeMap.getLength(); i++) {
        Node attr = nodeMap.item(i);
        String attrName = attr.getNodeName();
        boolean isPrefix = attrName.startsWith(XMLConstants.XMLNS_ATTRIBUTE)
                && (!isXSDFile || !attrName.equals("xmlns:xs")); //$NON-NLS-1$
        if (isPrefix) {
            if (attrName.length() == XMLConstants.XMLNS_ATTRIBUTE.length()) {
                defaultNamespace = attr.getNodeValue();
                namespaceContext.addNamespaceURI(XMLConstants.NULL_NS_URI, attr.getNodeValue());
            } else {
                int index = attrName.indexOf(':');
                String prefix = attrName.substring(index + 1);
                namespaceContext.addNamespaceURI(prefix, attr.getNodeValue());
            }
        } else if (!isXSDFile) {
            attributes.add(attr);
        }
    }

    if (defaultNamespace != null) {
        info.defaultNamespace = defaultNamespace;
    } else {
        // same as parent
        if (parentPath.equals("")) { //$NON-NLS-1$
            // no namespace
            info.defaultNamespace = ""; //$NON-NLS-1$
        } else {
            info.defaultNamespace = pathNodesMap.get(parentPath).defaultNamespace;
        }
    }

    String part[] = node.getNodeName().split(":"); //$NON-NLS-1$
    if (part.length > 1) {
        info.namespace = namespaceContext.getNamespaceURI(part[0]);
    } else {
        info.namespace = info.defaultNamespace;
    }

    collectAttributes(info, attributes);
}

From source file:org.wso2.carbon.tomcat.internal.ServerManager.java

/**
 * initialization code goes here.i.e : configuring tomcat instance using catalina-server.xml
 *///from  w w w.  jav  a2  s . c o  m
public void init() {
    bundleCtxtClassLoader = Thread.currentThread().getContextClassLoader();
    String carbonHome = System.getProperty("carbon.home");
    String catalinaHome = new File(carbonHome).getAbsolutePath() + File.separator + "lib" + File.separator
            + "tomcat";
    String catalinaXML = new File(carbonHome).getAbsolutePath() + File.separator + "repository" + File.separator
            + "conf" + File.separator + "tomcat" + File.separator + "catalina-server.xml";
    try {
        inputStream = new FileInputStream(new File(catalinaXML));
    } catch (FileNotFoundException e) {
        log.error("could not locate the file catalina-server.xml", e);
    }
    //setting catalina.base system property. tomcat configurator refers this property while tomcat instance creation.
    //you can override the property in wso2server.sh
    if (System.getProperty("catalina.base") == null) {
        System.setProperty("catalina.base",
                System.getProperty("carbon.home") + File.separator + "lib" + File.separator + "tomcat");
    }

    tomcat = new CarbonTomcat();

    if (SecretManager.getInstance().isInitialized()) {
        //creates DOM from input stream
        Element config = inputStreamToDOM(inputStream);
        //creates Secret resolver
        resolver = SecretResolverFactory.create(config, true);
        //resolves protected passwords
        resolveSecuredConfig(config, null);
        config.getAttributes()
                .removeNamedItem(XMLConstants.XMLNS_ATTRIBUTE + SecurityConstants.NS_SEPARATOR + SVNS);
        // creates new input stream from processed DOM element
        InputStream newStream = domToInputStream(config);

        tomcat.configure(catalinaHome, newStream);
    } else {
        tomcat.configure(catalinaHome, inputStream);
    }
}

From source file:org.xsystem.bpmn2.formats.xml.XMLParser3.java

protected void setNameSpace(Element elem) {
    NamedNodeMap atts = elem.getAttributes();
    for (int i = 0; i < atts.getLength(); i++) {
        Node currentAttribute = atts.item(i);
        String currentPrefix = currentAttribute.getPrefix();
        if (currentPrefix != null && currentPrefix.equals(XMLConstants.XMLNS_ATTRIBUTE)) {
            String prfx = currentAttribute.getLocalName();
            String uri = currentAttribute.getNodeValue();
            definitions.setNamespaceURI(prfx, uri);
        }//from w w  w. j  a  va2  s  .c  o m
    }
}