void removeNamespace(Namespace namespace) { Namespace current = getNodeNamespace(); // Do not remove in-use namespace if (namespace.is(current)) return; NamedNodeMap attrs = this.dom.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { XmlNode attr = XmlNode.createImpl(attrs.item(i)); if (namespace.is(attr.getNodeNamespace())) return; } // TODO I must confess I am not sure I understand the spec fully. See ECMA357 13.4.4.31 String existingPrefix = getExistingPrefixFor(namespace); if (existingPrefix != null) { if (namespace.isUnspecifiedPrefix()) { // we should remove any namespace with this URI from scope; we do this by declaring a // namespace with the same // prefix as the existing prefix and setting its URI to the default namespace declareNamespace(existingPrefix, getDefaultNamespace().getUri()); } else { if (existingPrefix.equals(namespace.getPrefix())) { declareNamespace(existingPrefix, getDefaultNamespace().getUri()); } } } else { // the argument namespace is not declared in this scope, so do nothing. } }
XmlNode[] getAttributes() { NamedNodeMap attrs = this.dom.getAttributes(); // TODO Or could make callers handle null? if (attrs == null) throw new IllegalStateException("Must be element."); XmlNode[] rv = new XmlNode[attrs.getLength()]; for (int i = 0; i < attrs.getLength(); i++) { rv[i] = createImpl(attrs.item(i)); } return rv; }
private static Command parseCommand(Node n) { NamedNodeMap atts = n.getAttributes(); String name = atts.getNamedItem("name").getNodeValue(); String desc = atts.getNamedItem("description").getNodeValue(); String command = atts.getNamedItem("command").getNodeValue(); Command com = new Command(name, desc, command); NodeList children = n.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { Node child = children.item(i); if (!child.getNodeName().equals("Argument")) continue; NamedNodeMap childAtts = child.getAttributes(); String childName = childAtts.getNamedItem("name").getNodeValue(); String childDesc = childAtts.getNamedItem("description").getNodeValue(); String childVal = ""; if (childAtts.getNamedItem("default") != null) childVal = childAtts.getNamedItem("default").getNodeValue(); Argument arg = new Argument(childName, childDesc, childVal); com.addArgument(arg); } return com; }
/** * Counts the attributenode for an element (xmlns attributes ignored) * * @param attributesR attributesMap * @return number of attributes */ private int countAttributes(NamedNodeMap attributesR) { int cntAttributes = 0; for (int i = 0; i < attributesR.getLength(); i++) { if (!attributesR.item(i).getNodeName().startsWith(XMLConstants.XMLNS_ATTRIBUTE)) { cntAttributes++; } } return cntAttributes; }
/** Возвращает имя метода. */ public String getName() { /** Получаем атрибуты узла метода. */ NamedNodeMap attributes = node.getAttributes(); /** Получаем узел аттрибута. */ Node nameAttrib = attributes.getNamedItem("name"); /** Возвращаем значение атрибута. */ return nameAttrib.getNodeValue(); }
protected Element copyElementToName(Element element, String tagName) { Element newElement = element.getOwnerDocument().createElement(tagName); NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Node attribute = attrs.item(i); newElement.setAttribute(attribute.getNodeName(), attribute.getNodeValue()); } for (int i = 0; i < element.getChildNodes().getLength(); i++) { newElement.appendChild(element.getChildNodes().item(i).cloneNode(true)); } return newElement; }
public static Map<String, String> getAttrList(Node node) { Map<String, String> map = new HashMap<String, String>(); NamedNodeMap list = node.getAttributes(); if (list != null) for (int i = 0; i < list.getLength(); i++) { Attr attr = (Attr) list.item(i); map.put(attr.getName(), attr.getValue()); } return map; }
private static Category parseCategory(Node n) { NamedNodeMap atts = n.getAttributes(); String name = atts.getNamedItem("name").getNodeValue(); String desc = atts.getNamedItem("description").getNodeValue(); Category cat = new Category(name, desc); NodeList children = n.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { parseNode(children.item(i), cat); } return cat; }
/** * Retrieves default values from xml. * * @param list the configuration list */ private static void parseDefaults(NodeList list) { for (int i = 0; i < list.getLength(); ++i) { NamedNodeMap mapping = list.item(i).getAttributes(); String attribute = mapping.getNamedItem("attribute").getNodeValue(); String value = mapping.getNamedItem("value").getNodeValue(); try { Default field = Default.fromString(attribute); DEFAULTS.put(field, value); } catch (IllegalArgumentException exc) { logger.warn("Unrecognized default attribute: " + attribute); } } }
/** * Populates LOCALES list with contents of xml. * * @param list the configuration list */ private static void parseLocales(NodeList list) { for (int i = 0; i < list.getLength(); ++i) { Node node = list.item(i); NamedNodeMap attributes = node.getAttributes(); String label = ((Attr) attributes.getNamedItem("label")).getValue(); String code = ((Attr) attributes.getNamedItem("isoCode")).getValue(); String dictLocation = ((Attr) attributes.getNamedItem("dictionaryUrl")).getValue(); try { LOCALES.add(new Locale(label, code, new URL(dictLocation))); } catch (MalformedURLException exc) { logger.warn( "Unable to parse dictionary location of " + label + " (" + dictLocation + ")", exc); } } }
public void validateContent(IProgressMonitor monitor) { Element element = getDocumentRoot(); if (element == null) return; String elementName = element.getNodeName(); if (!"plugin".equals(elementName) && !"fragment".equals(elementName)) { // $NON-NLS-1$ //$NON-NLS-2$ reportIllegalElement(element, CompilerFlags.ERROR); } else { int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_DEPRECATED); if (severity != CompilerFlags.IGNORE) { NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { reportUnusedAttribute(element, attrs.item(i).getNodeName(), severity); } } NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { if (monitor.isCanceled()) break; Element child = (Element) children.item(i); String name = child.getNodeName(); if (name.equals("extension")) { // $NON-NLS-1$ validateExtension(child); } else if (name.equals("extension-point")) { // $NON-NLS-1$ validateExtensionPoint(child); } else { if (!name.equals("runtime") && !name.equals("requires")) { // $NON-NLS-1$ //$NON-NLS-2$ severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ELEMENT); if (severity != CompilerFlags.IGNORE) reportIllegalElement(child, severity); } else { severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_DEPRECATED); if (severity != CompilerFlags.IGNORE) reportUnusedElement(child, severity); } } } IExtensions extensions = fModel.getExtensions(); if (extensions != null && extensions.getExtensions().length == 0 && extensions.getExtensionPoints().length == 0) report( MDECoreMessages.Builders_Manifest_useless_file, -1, IMarker.SEVERITY_WARNING, MDEMarkerFactory.P_USELESS_FILE, MDEMarkerFactory.CAT_OTHER); } }
protected static XmlConfigurator parse(Element root_element) throws java.io.IOException { XmlConfigurator configurator = null; final LinkedList<ProtocolConfiguration> prot_data = new LinkedList<ProtocolConfiguration>(); /** * CAUTION: crappy code ahead ! I (bela) am not an XML expert, so the code below is pretty * amateurish... But it seems to work, and it is executed only on startup, so no perf loss on * the critical path. If somebody wants to improve this, please be my guest. */ try { String root_name = root_element.getNodeName(); if (!"config".equals(root_name.trim().toLowerCase())) throw new IOException("the configuration does not start with a <config> element"); NodeList prots = root_element.getChildNodes(); for (int i = 0; i < prots.getLength(); i++) { Node node = prots.item(i); if (node.getNodeType() != Node.ELEMENT_NODE) continue; Element tag = (Element) node; String protocol = tag.getTagName(); Map<String, String> params = new HashMap<String, String>(); NamedNodeMap attrs = tag.getAttributes(); int attrLength = attrs.getLength(); for (int a = 0; a < attrLength; a++) { Attr attr = (Attr) attrs.item(a); String name = attr.getName(); String value = attr.getValue(); params.put(name, value); } ProtocolConfiguration cfg = new ProtocolConfiguration(protocol, params); prot_data.add(cfg); } configurator = new XmlConfigurator(prot_data); } catch (Exception x) { if (x instanceof java.io.IOException) throw (java.io.IOException) x; else { IOException tmp = new IOException(); tmp.initCause(x); throw tmp; } } return configurator; }
// DOM input public void declareNamespace(Element element) { NamedNodeMap attrs = element.getAttributes(); int size = attrs.getLength(); for (int i = 0; i < size; i++) { Attr attr = (Attr) attrs.item(i); String qName = attr.getName(); if (qName.startsWith("xmlns:")) { String uri = attr.getValue(); String prefix = qName.substring("xmlns:".length()); declareNamespace(prefix, uri); } else if (qName.startsWith("xmlns")) { String uri = attr.getValue(); declareNamespace("", uri); } } }
private void addNamespaces(Namespaces rv, Element element) { if (element == null) throw new RuntimeException("element must not be null"); String myDefaultNamespace = toUri(element.lookupNamespaceURI(null)); String parentDefaultNamespace = ""; if (element.getParentNode() != null) { parentDefaultNamespace = toUri(element.getParentNode().lookupNamespaceURI(null)); } if (!myDefaultNamespace.equals(parentDefaultNamespace) || !(element.getParentNode() instanceof Element)) { rv.declare(Namespace.create("", myDefaultNamespace)); } NamedNodeMap attributes = element.getAttributes(); for (int i = 0; i < attributes.getLength(); i++) { Attr attr = (Attr) attributes.item(i); if (attr.getPrefix() != null && attr.getPrefix().equals("xmlns")) { rv.declare(Namespace.create(attr.getLocalName(), attr.getValue())); } } }
@Test public void testgetAttributesWithNamedNodeMap() throws Exception { // builderFactory = DocumentBuilderFactory.newInstance(); builderFactory.setNamespaceAware(true); File f = new File(System.getProperty("user.dir"), "src/test/resources/sample-springbeans.xml"); DocumentBuilder builder = builderFactory.newDocumentBuilder(); Document doc = builder.parse(f); Element root = doc.getDocumentElement(); // System.out.println("* current impl: " + doc.getClass().getName()); // id, class Map<String, String> actualMap = new HashMap<String, String>(); NodeList list = root.getChildNodes(); for (int i = 0; i < list.getLength(); i++) { Node node = list.item(i); if (node instanceof Element) { Element elem = (Element) node; if (elem.getTagName().equals("beans:bean")) { // System.out.println("bean[" + elem.getAttribute("id") + "]"); NamedNodeMap map = elem.getAttributes(); String valueId = null; String valueClass = null; for (int x = 0; x < map.getLength(); x++) { Node attr = map.item(x); if (attr.getNodeName().equals("id")) valueId = attr.getNodeValue(); if (attr.getNodeName().equals("class")) valueClass = attr.getNodeValue(); } if (valueId != null && valueClass != null) actualMap.put(valueId, valueClass); } } } Map<String, String> expected = new HashMap<String, String>(); expected.put("authenticationManager", "org.springframework.security.providers.ProviderManager"); expected.put( "daoAuthenticationProvider", "org.springframework.security.providers.dao.DaoAuthenticationProvider"); expected.put( "loggerListener", "org.springframework.security.event.authentication.LoggerListener"); Assert.assertEquals("Attributes with NamedNodeMap", expected, actualMap); }
private void validateExistingExtensionAttributes( Element element, NamedNodeMap attrs, ISchemaElement schemaElement) { for (int i = 0; i < attrs.getLength(); i++) { Attr attr = (Attr) attrs.item(i); ISchemaAttribute attInfo = schemaElement.getAttribute(attr.getName()); if (attInfo == null) { HashSet allowedElements = new HashSet(); computeAllowedElements(schemaElement.getType(), allowedElements); if (allowedElements.contains(attr.getName())) { validateJavaAttribute(element, attr); } else { int flag = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ATTRIBUTE); if (flag != CompilerFlags.IGNORE) reportUnknownAttribute(element, attr.getName(), flag); } } else { validateExtensionAttribute(element, attr, attInfo); } } }
@Override protected AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) { BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(SpringJolokiaConfigHolder.class); Map<String, String> config = new HashMap<String, String>(); NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Attr attr = (Attr) attrs.item(i); String name = attr.getName(); if (skipMap.contains(name)) { continue; } config.put(name, attr.getValue()); } builder.addPropertyValue("config", config); String order = element.getAttribute("order"); if (StringUtils.hasText(order)) { builder.addPropertyValue("order", Integer.parseInt(order)); } return builder.getBeanDefinition(); }
/** * @param node * @param indent */ public static String toString(Node node, int indent) { StringBuffer str = new StringBuffer(); for (int i = 0; i < indent; ++i) str.append(" "); str.append(node); if (node.hasAttributes()) { NamedNodeMap attrs = node.getAttributes(); for (int j = 0; j < attrs.getLength(); ++j) { Node attr = attrs.item(j); // str.append(toString(attr,indent+2)); str.append(" "); str.append(attr); } } str.append("\n"); ++indent; for (Node child = node.getFirstChild(); child != null; child = child.getNextSibling()) { str.append(toString(child, indent)); // str.append("\n"); } return str.toString(); }
private static void parseXML() { try { Document doc = DocumentBuilderFactory.newInstance() .newDocumentBuilder() .parse(CommandBuilder.class.getResourceAsStream("/CommandMap.xml")); NodeList nodes = doc.getElementsByTagName("CommandMap"); for (int i = 0; i < nodes.getLength(); i++) { Node n = nodes.item(i); NamedNodeMap atts = n.getAttributes(); String rootCommand = atts.getNamedItem("rootCommand").getNodeValue(); rootNode = new Category(rootCommand, ""); NodeList children = n.getChildNodes(); for (int p = 0; p < children.getLength(); p++) { parseNode(children.item(p), rootNode); } } } catch (Exception e) { e.printStackTrace(); } }
private void processPanelLayout(Session session, Element element, HashMap additionalInformation) { String nodeName = element.getNodeName(); String panelName = nodeName; NamedNodeMap tNodeMap = element.getAttributes(); for (int i = 0; i < tNodeMap.getLength(); i++) { Node node = tNodeMap.item(i); String name = node.getNodeName(); if (name.equals("dividerFractions")) { String value = node.getNodeValue(); String[] tokens = value.split(","); double[] divs = new double[tokens.length]; try { for (int j = 0; j < tokens.length; j++) { divs[j] = Double.parseDouble(tokens[j]); } session.setDividerFractions(divs); } catch (NumberFormatException e) { log.error("Error parsing divider locations", e); } } } }
void invalidateNamespacePrefix() { if (!(dom instanceof Element)) throw new IllegalStateException(); String prefix = this.dom.getPrefix(); QName after = QName.create(this.dom.getNamespaceURI(), this.dom.getLocalName(), null); renameNode(after); NamedNodeMap attrs = this.dom.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { if (attrs.item(i).getPrefix().equals(prefix)) { createImpl(attrs.item(i)) .renameNode( QName.create(attrs.item(i).getNamespaceURI(), attrs.item(i).getLocalName(), null)); } } }
public static int size(NamedNodeMap namedNodeMap) { return namedNodeMap.getLength(); }
/** * Constructs an attribute element from an existing XML block. * * @param element representing a DOM tree element. * @exception SAMLException if there is an error in the sender or in the element definition. */ public Attribute(Element element) throws SAMLException { // make sure that the input xml block is not null if (element == null) { SAMLUtilsCommon.debug.message("Attribute: Input is null."); throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput")); } // Make sure this is an Attribute. String tag = null; tag = element.getLocalName(); if ((tag == null) || (!tag.equals("Attribute"))) { SAMLUtilsCommon.debug.message("Attribute: wrong input"); throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("wrongInput")); } int i = 0; // handle attributes NamedNodeMap atts = element.getAttributes(); int attrCount = atts.getLength(); for (i = 0; i < attrCount; i++) { Node att = atts.item(i); if (att.getNodeType() == Node.ATTRIBUTE_NODE) { String attName = att.getLocalName(); if (attName == null) { attName = att.getNodeName(); } if (attName == null || attName.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message("Attribute:" + "Attribute Name is either null or empty."); } continue; // throw new SAMLRequesterException( // SAMLUtilsCommon.bundle.getString("nullInput")); } if (attName.equals("AttributeName")) { this._attributeName = ((Attr) att).getValue().trim(); } else if (attName.equals("AttributeNamespace")) { this._attributeNameSpace = ((Attr) att).getValue().trim(); } } } // AttributeName is required if (_attributeName == null || _attributeName.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message("Attribute: " + "AttributeName is required attribute"); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingAttribute")); } // AttributeNamespace is required if (_attributeNameSpace == null || _attributeNameSpace.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message("Attribute: " + "AttributeNamespace is required attribute"); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingAttribute")); } // handle the children of Attribute element NodeList nodes = element.getChildNodes(); int nodeCount = nodes.getLength(); if (nodeCount > 0) { for (i = 0; i < nodeCount; i++) { Node currentNode = nodes.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { String tagName = currentNode.getLocalName(); String tagNS = currentNode.getNamespaceURI(); if ((tagName == null) || tagName.length() == 0 || tagNS == null || tagNS.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message( "Attribute:" + " The tag name or tag namespace of child" + " element is either null or empty."); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput")); } if (tagName.equals("AttributeValue") && tagNS.equals(SAMLConstants.assertionSAMLNameSpaceURI)) { if (_attributeValue == null) { _attributeValue = new ArrayList(); } if (!(_attributeValue.add((Element) currentNode))) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message( "Attribute: failed to " + "add to the attribute value list."); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("addListError")); } } else { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message("Attribute:" + "wrong element:" + tagName); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("wrongInput")); } } // end of if (currentNode.getNodeType() == Node.ELEMENT_NODE) } // end of for loop } // end of if (nodeCount > 0) if (_attributeValue == null || _attributeValue.isEmpty()) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message( "Attribute: " + "should contain at least one AttributeValue."); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingElement")); } }
/** updates the XMl with hashcode for the files */ protected BudgetSubAwards updateXML( byte xmlContents[], Map fileMap, BudgetSubAwards budgetSubAwardBean, Budget budget) throws Exception { javax.xml.parsers.DocumentBuilderFactory domParserFactory = javax.xml.parsers.DocumentBuilderFactory.newInstance(); javax.xml.parsers.DocumentBuilder domParser = domParserFactory.newDocumentBuilder(); ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(xmlContents); org.w3c.dom.Document document = domParser.parse(byteArrayInputStream); byteArrayInputStream.close(); String namespace = null; String formName = null; if (document != null) { Node node; Element element = document.getDocumentElement(); NamedNodeMap map = element.getAttributes(); String namespaceHolder = element.getNodeName().substring(0, element.getNodeName().indexOf(':')); node = map.getNamedItem("xmlns:" + namespaceHolder); namespace = node.getNodeValue(); FormMappingInfo formMappingInfo = new FormMappingLoader().getFormInfo(namespace); formName = formMappingInfo.getFormName(); budgetSubAwardBean.setNamespace(namespace); budgetSubAwardBean.setFormName(formName); } String xpathEmptyNodes = "//*[not(node()) and local-name(.) != 'FileLocation' and local-name(.) != 'HashValue']"; String xpathOtherPers = "//*[local-name(.)='ProjectRole' and local-name(../../.)='OtherPersonnel' and count(../NumberOfPersonnel)=0]"; removeAllEmptyNodes(document, xpathEmptyNodes, 0); removeAllEmptyNodes(document, xpathOtherPers, 1); removeAllEmptyNodes(document, xpathEmptyNodes, 0); changeDataTypeForNumberOfOtherPersons(document); List<String> fedNonFedSubAwardForms = getFedNonFedSubawardForms(); NodeList budgetYearList = XPathAPI.selectNodeList(document, "//*[local-name(.) = 'BudgetYear']"); for (int i = 0; i < budgetYearList.getLength(); i++) { Node bgtYearNode = budgetYearList.item(i); String period = getValue(XPathAPI.selectSingleNode(bgtYearNode, "BudgetPeriod")); if (fedNonFedSubAwardForms.contains(namespace)) { Element newBudgetYearElement = copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName()); bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode); } else { Element newBudgetYearElement = copyElementToName((Element) bgtYearNode, bgtYearNode.getNodeName() + period); bgtYearNode.getParentNode().replaceChild(newBudgetYearElement, bgtYearNode); } } Node oldroot = document.removeChild(document.getDocumentElement()); Node newroot = document.appendChild(document.createElement("Forms")); newroot.appendChild(oldroot); org.w3c.dom.NodeList lstFileName = document.getElementsByTagName("att:FileName"); org.w3c.dom.NodeList lstFileLocation = document.getElementsByTagName("att:FileLocation"); org.w3c.dom.NodeList lstMimeType = document.getElementsByTagName("att:MimeType"); org.w3c.dom.NodeList lstHashValue = document.getElementsByTagName("glob:HashValue"); if ((lstFileName.getLength() != lstFileLocation.getLength()) || (lstFileLocation.getLength() != lstHashValue.getLength())) { // throw new RuntimeException("Tag occurances mismatch in XML File"); } org.w3c.dom.Node fileNode, hashNode, mimeTypeNode; org.w3c.dom.NamedNodeMap fileNodeMap, hashNodeMap; String fileName; byte fileBytes[]; String contentId; List attachmentList = new ArrayList(); for (int index = 0; index < lstFileName.getLength(); index++) { fileNode = lstFileName.item(index); Node fileNameNode = fileNode.getFirstChild(); fileName = fileNameNode.getNodeValue(); fileBytes = (byte[]) fileMap.get(fileName); if (fileBytes == null) { throw new RuntimeException("FileName mismatch in XML and PDF extracted file"); } String hashVal = GrantApplicationHash.computeAttachmentHash(fileBytes); hashNode = lstHashValue.item(index); hashNodeMap = hashNode.getAttributes(); Node temp = document.createTextNode(hashVal); hashNode.appendChild(temp); hashNode = hashNodeMap.getNamedItem("glob:hashAlgorithm"); hashNode.setNodeValue(S2SConstants.HASH_ALGORITHM); fileNode = lstFileLocation.item(index); fileNodeMap = fileNode.getAttributes(); fileNode = fileNodeMap.getNamedItem("att:href"); contentId = fileNode.getNodeValue(); String encodedContentId = cleanContentId(contentId); fileNode.setNodeValue(encodedContentId); mimeTypeNode = lstMimeType.item(0); String contentType = mimeTypeNode.getFirstChild().getNodeValue(); BudgetSubAwardAttachment budgetSubAwardAttachmentBean = new BudgetSubAwardAttachment(); budgetSubAwardAttachmentBean.setAttachment(fileBytes); budgetSubAwardAttachmentBean.setContentId(encodedContentId); budgetSubAwardAttachmentBean.setContentType(contentType); budgetSubAwardAttachmentBean.setBudgetId(budgetSubAwardBean.getBudgetId()); budgetSubAwardAttachmentBean.setSubAwardNumber(budgetSubAwardBean.getSubAwardNumber()); attachmentList.add(budgetSubAwardAttachmentBean); } budgetSubAwardBean.setBudgetSubAwardAttachments(attachmentList); javax.xml.transform.Transformer transformer = javax.xml.transform.TransformerFactory.newInstance().newTransformer(); transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes"); ByteArrayOutputStream bos = new ByteArrayOutputStream(); javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(bos); javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(document); transformer.transform(source, result); budgetSubAwardBean.setSubAwardXmlFileData(new String(bos.toByteArray())); bos.close(); return budgetSubAwardBean; }
private static String xgetAt(NamedNodeMap namedNodeMap, String elementName) { Attr a = (Attr) namedNodeMap.getNamedItem(elementName); return a.getValue(); }
/** * @param list * @param parent * @exception NumberFormatException * @exception DicomException */ void addAttributesFromNodeToList(AttributeList list, Node parent) throws NumberFormatException, DicomException { if (parent != null) { Node node = parent.getFirstChild(); while (node != null) { String elementName = node.getNodeName(); NamedNodeMap attributes = node.getAttributes(); if (attributes != null) { Node vrNode = attributes.getNamedItem("vr"); Node groupNode = attributes.getNamedItem("group"); Node elementNode = attributes.getNamedItem("element"); if (vrNode != null && groupNode != null && elementNode != null) { String vrString = vrNode.getNodeValue(); String groupString = groupNode.getNodeValue(); String elementString = elementNode.getNodeValue(); if (vrString != null && groupString != null && elementString != null) { byte[] vr = vrString.getBytes(); int group = Integer.parseInt(groupString, 16); int element = Integer.parseInt(elementString, 16); AttributeTag tag = new AttributeTag(group, element); if ((group % 2 == 0 && element == 0) || (group == 0x0008 && element == 0x0001) || (group == 0xfffc && element == 0xfffc)) { // System.err.println("ignoring group length or length to end or dataset trailing // padding "+tag); } else { if (vrString.equals("SQ")) { SequenceAttribute a = new SequenceAttribute(tag); // System.err.println("Created "+a); if (node.hasChildNodes()) { Node childNode = node.getFirstChild(); while (childNode != null) { String childNodeName = childNode.getNodeName(); // System.err.println("childNodeName = "+childNodeName); if (childNodeName != null && childNodeName.equals("Item")) { // should check item number, but ignore for now :( // System.err.println("Adding item to sequence"); AttributeList itemList = new AttributeList(); addAttributesFromNodeToList(itemList, childNode); a.addItem(itemList); } // else may be a #text element in between childNode = childNode.getNextSibling(); } } // System.err.println("Sequence Attribute is "+a); list.put(tag, a); } else { Attribute a = AttributeFactory.newAttribute(tag, vr); // System.err.println("Created "+a); if (node.hasChildNodes()) { Node childNode = node.getFirstChild(); while (childNode != null) { String childNodeName = childNode.getNodeName(); // System.err.println("childNodeName = "+childNodeName); if (childNodeName != null && childNodeName.equals("value")) { // should check value number, but ignore for now :( String value = childNode.getTextContent(); // System.err.println("Value value = "+value); if (value != null) { value = StringUtilities.removeLeadingOrTrailingWhitespaceOrISOControl( value); // just in case a.addValue(value); } } // else may be a #text element in between childNode = childNode.getNextSibling(); } } // System.err.println("Attribute is "+a); list.put(tag, a); } } } } } node = node.getNextSibling(); } } }
private Object deserialize(Node node, boolean setProperty, boolean popBean) throws Exception { Object object = null; currentType = null; currentNode = node; currentName = node.getNodeName(); boolean isNull = false; NamedNodeMap attrs = node.getAttributes(); String arrayType = null; for (int i = 0; i < attrs.getLength(); i++) { String nodeName = attrs.item(i).getNodeName(); String nodeValue = attrs.item(i).getNodeValue(); if (nodeName.equals(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":" + Constants.ATTR_TYPE)) currentType = new StringBuffer(nodeValue).delete(0, nodeValue.indexOf(':') + 1).toString(); else if (nodeName.equals( NamespaceConstants.NSPREFIX_SOAP_ENCODING + ":" + Constants.ATTR_ARRAY_TYPE)) arrayType = new StringBuffer(nodeValue).delete(0, nodeValue.indexOf(':') + 1).toString(); else if (nodeName.equals(NamespaceConstants.NSPREFIX_SCHEMA_XSI + ":null")) isNull = nodeValue.equals("true"); } Class cls = null; if (currentType != null) cls = getXsdTypeClass(currentType); // Handle array, Vector, ArrayList, LinkedList, Hashtable, // Properties, and HashMap data types if ((cls != null) && ((cls == java.lang.reflect.Array.class) || (cls == Vector.class) || (cls == ArrayList.class) || (cls == LinkedList.class) || (cls == Hashtable.class) || (cls == Properties.class) || (cls == HashMap.class) || (cls == SortedMap.class))) { parentNode = currentNode; String name = node.getNodeName(); // Handle arrays if (cls == java.lang.reflect.Array.class) { int a = arrayType.indexOf("["); int b = arrayType.indexOf("]"); String s = arrayType.substring(a + 1, b); int arrayLen = Integer.valueOf(s).intValue(); arrayType = arrayType.substring(0, a); // check if the array element is a standard Java class Class arrayClass = getXsdTypeClass(arrayType); // otherwise try to get the class of the bean if (arrayClass == null) arrayClass = getClassOfBean((ClassLoader) classLoaderStrategy, arrayType); object = java.lang.reflect.Array.newInstance(arrayClass, arrayLen); } else { // Construct the list or map type Constructor ct = cls.getConstructor((Class[]) null); object = ct.newInstance((Object[]) null); } // deserialize the elements of the array, list, or map NodeList childNodes = node.getChildNodes(); int arrayIndex = -1; Node childNode = null; Object nodeObj = null; for (int i = 0; i < childNodes.getLength(); i++) { childNode = childNodes.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE) { if ((cls == java.lang.reflect.Array.class) || (cls == Vector.class) || (cls == ArrayList.class) || (cls == LinkedList.class)) { nodeObj = deserialize(childNode, false, true); if (nodeObj != null) { if (cls == java.lang.reflect.Array.class) java.lang.reflect.Array.set(object, ++arrayIndex, nodeObj); else ((List) object).add(nodeObj); } } else if ((cls == Hashtable.class) || (cls == Properties.class) || (cls == HashMap.class) || (cls == SortedMap.class)) { if (childNode.getLocalName().equals("item")) { NodeList htNodes = childNode.getChildNodes(); if (htNodes.getLength() == 2) { Object hashKey = deserialize(htNodes.item(0), false, false); Object hashValue = deserialize(htNodes.item(1), false, true); ((Map) object).put(hashKey, hashValue); } } } } } setBeanProperty(name, object); // Handle everything else (primitives & POJOs) } else { // recurse on each of the child nodes NodeList childNodes = node.getChildNodes(); if ((childNodes != null) && (childNodes.getLength() > 0)) { for (int i = 0; i < childNodes.getLength(); i++) { Node childNode = childNodes.item(i); if (childNode.getNodeType() == Node.ELEMENT_NODE) { if (currentType != null) createObject( node, currentName, currentPackage, currentType, childNode.getNodeValue(), setProperty); parentNode = node; object = deserialize(childNode, true, true); } else if ((childNode.getNodeType() == Node.TEXT_NODE) && (currentType != null)) { object = createObject( node, currentName, currentPackage, currentType, childNode.getNodeValue(), setProperty); } currentType = null; } } else { if (!isNull) object = createObject(node, currentName, currentPackage, currentType, null, setProperty); } if (node.getParentNode() != parentNode) { parentNode = node.getParentNode(); if (popBean) { Object bean = popBeanOffStack(); if (bean != null) object = bean; } } } return object; }
private Object createObject( Node node, String name, String classPackage, String type, String value, boolean setProperty) { Bean parentBean = null; if (beansStack.size() > 0) parentBean = (Bean) beansStack.peek(); Object object = null; // param is either an XSD type or a bean, // check if it can be converted to an XSD type XSDatatype dt = null; try { dt = DatatypeFactory.getTypeByName(type); } catch (DatatypeException dte) { // the type is not a valid XSD data type } // convert null value to default if ((dt != null) && (value == null)) { Class objType = dt.getJavaObjectType(); if (objType == String.class) value = ""; else if ((objType == java.math.BigInteger.class) || (objType == Long.class) || (objType == Integer.class) || (objType == Short.class) || (objType == Byte.class)) value = "0"; else if ((objType == java.math.BigDecimal.class) || (objType == Double.class) || (objType == Float.class)) value = "0.0"; else if (objType == Boolean.class) value = "false"; else if (objType == java.util.Date.class) value = DateUtils.getCurrentDate(); else if (objType == java.util.Calendar.class) value = DateUtils.getCurrentDateTime(); } // check whether the type was converted to an XSD datatype if ((dt != null) && dt.isValid(value, null)) { // create and return an XSD Java object (e.g. String, Integer, Boolean, etc) object = dt.createJavaObject(value, null); if (object instanceof java.util.Calendar) { // check that the object is truly a Calendar // because DatatypeFactory converts xsd:date // types to GregorianCalendar instead of Date. if (type.equals("date")) { java.text.DateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd"); try { object = df.parse(value); } catch (java.text.ParseException pe) { object = new java.util.Date(); } } } } else { // Create a bean object if (topLevelBean == null) topLevelBean = parentBean; object = pushBeanOnStack(classPackage, type); // Check fields to see if this property is the 'value' for the object Field[] fields = object.getClass().getDeclaredFields(); for (int i = 0; i < fields.length; i++) { if (fields[i].isAnnotationPresent(ObjectXmlAsValue.class)) { try { StringBuffer fieldName = new StringBuffer(fields[i].getName()); char c = fieldName.charAt(0); if (c >= 'a' && c <= 'z') { c += 'A' - 'a'; } fieldName.setCharAt(0, c); fieldName.insert(0, "set"); Method method = object .getClass() .getMethod(fieldName.toString(), new Class[] {fields[i].getType()}); method.invoke(object, value); break; } catch (Exception e) { System.err.println(e.getMessage()); } } } NamedNodeMap nodeAttrs = node.getAttributes(); // iterate attributes and set field values for property attributes for (int i = 0; i < nodeAttrs.getLength(); i++) { String nodePrefix = nodeAttrs.item(i).getPrefix(); if (nodePrefix.equals(nsPrefix)) { String nodeName = nodeAttrs.item(i).getLocalName(); String nodeValue = nodeAttrs.item(i).getNodeValue(); try { Field field = object.getClass().getDeclaredField(nodeName); if (field.isAnnotationPresent(ObjectXmlAsAttribute.class)) { StringBuffer fieldName = new StringBuffer(field.getName()); char c = fieldName.charAt(0); if (c >= 'a' && c <= 'z') { c += 'A' - 'a'; } fieldName.setCharAt(0, c); fieldName.insert(0, "set"); Method method = object.getClass().getMethod(fieldName.toString(), new Class[] {field.getType()}); if (field.getType() == String.class) method.invoke(object, nodeValue); else if (field.getType() == Boolean.TYPE) method.invoke(object, StringUtils.strToBool(nodeValue, "true")); else if (field.getType() == Byte.TYPE) method.invoke(object, Byte.valueOf(nodeValue).byteValue()); else if (field.getType() == Character.TYPE) method.invoke(object, Character.valueOf(nodeValue.charAt(0))); else if (field.getType() == Double.TYPE) method.invoke(object, Double.valueOf(nodeValue).doubleValue()); else if (field.getType() == Float.TYPE) method.invoke(object, Float.valueOf(nodeValue).floatValue()); else if (field.getType() == Integer.TYPE) method.invoke(object, Integer.valueOf(nodeValue).intValue()); else if (field.getType() == Long.TYPE) method.invoke(object, Long.valueOf(nodeValue).longValue()); else if (field.getType() == Short.TYPE) method.invoke(object, Short.valueOf(nodeValue).shortValue()); } } catch (Exception e) { System.err.println(e.getMessage()); } } } } if ((parentBean != null) && (setProperty)) { parentBean.setProperty(name, object); } return object; }
/** * Constructs an attribute designator element from an existing XML block. * * @param element representing a DOM tree element. * @exception SAMLException if that there is an error in the sender or in the element definition. */ public AttributeDesignator(Element element) throws SAMLException { // make sure that the input xml block is not null if (element == null) { SAMLUtilsCommon.debug.message("AttributeDesignator: Input is null."); throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput")); } // Make sure this is an AttributeDesignator. String tag = null; tag = element.getLocalName(); if ((tag == null) || (!tag.equals("AttributeDesignator"))) { SAMLUtilsCommon.debug.message("AttributeDesignator: wrong input"); throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("wrongInput")); } // handle attributes int i = 0; NamedNodeMap atts = ((Node) element).getAttributes(); int attrCount = atts.getLength(); for (i = 0; i < attrCount; i++) { Node att = atts.item(i); if (att.getNodeType() == Node.ATTRIBUTE_NODE) { String attName = att.getLocalName(); if (attName == null || attName.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message( "AttributeDesignator:" + "Attribute Name is either null or empty."); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("nullInput")); } if (attName.equals("AttributeName")) { _attributeName = ((Attr) att).getValue().trim(); } else if (attName.equals("AttributeNamespace")) { _attributeNameSpace = ((Attr) att).getValue().trim(); } } } // AttributeName is required if (_attributeName == null || _attributeName.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message( "AttributeDesignator: " + "AttributeName is required attribute"); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingAttribute")); } // AttributeNamespace is required if (_attributeNameSpace == null || _attributeNameSpace.length() == 0) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message( "AttributeDesignator: " + "AttributeNamespace is required attribute"); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("missingAttribute")); } // handle the children of AttributeDesignator element // Since AttributeDesignator does not have any child element_node, // we will throw exception if we found any such child. NodeList nodes = element.getChildNodes(); int nodeCount = nodes.getLength(); if (nodeCount > 0) { for (i = 0; i < nodeCount; i++) { Node currentNode = nodes.item(i); if (currentNode.getNodeType() == Node.ELEMENT_NODE) { if (SAMLUtilsCommon.debug.messageEnabled()) { SAMLUtilsCommon.debug.message("AttributeDesignator: illegal input!"); } throw new SAMLRequesterException(SAMLUtilsCommon.bundle.getString("wrongInput")); } } } }
/** * Process a track element. This should return a single track, but could return multiple tracks * since the uniqueness of the track id is not enforced. * * @param session * @param element * @param additionalInformation * @return */ private List<Track> processTrack( Session session, Element element, HashMap additionalInformation) { String id = getAttribute(element, SessionAttribute.ID.getText()); // TODo -- put in utility method, extacts attributes from element **Definitely need to do this HashMap<String, String> tAttributes = new HashMap(); HashMap<String, String> drAttributes = null; NamedNodeMap tNodeMap = element.getAttributes(); for (int i = 0; i < tNodeMap.getLength(); i++) { Node node = tNodeMap.item(i); String value = node.getNodeValue(); if (value != null && value.length() > 0) { tAttributes.put(node.getNodeName(), value); } } if (element.hasChildNodes()) { drAttributes = new HashMap(); Node childNode = element.getFirstChild(); Node sibNode = childNode.getNextSibling(); String sibName = sibNode.getNodeName(); if (sibName.equals(SessionElement.DATA_RANGE.getText())) { NamedNodeMap drNodeMap = sibNode.getAttributes(); for (int i = 0; i < drNodeMap.getLength(); i++) { Node node = drNodeMap.item(i); String value = node.getNodeValue(); if (value != null && value.length() > 0) { drAttributes.put(node.getNodeName(), value); } } } } // Get matching tracks. List<Track> matchedTracks = trackDictionary.get(id); if (matchedTracks == null) { log.info("Warning. No tracks were found with id: " + id + " in session file"); } else { for (final Track track : matchedTracks) { // Special case for sequence & gene tracks, they need to be removed before being placed. if (version >= 4 && track == geneTrack || track == seqTrack) { igv.removeTracks(Arrays.asList(track)); } track.restorePersistentState(tAttributes); if (drAttributes != null) { DataRange dr = track.getDataRange(); dr.restorePersistentState(drAttributes); track.setDataRange(dr); } } trackDictionary.remove(id); } NodeList elements = element.getChildNodes(); process(session, elements, additionalInformation); return matchedTracks; }