private void updateTemplateFromEditor(PrintfTemplate template) { ArrayList params = new ArrayList(); String format = null; int text_length = editorPane.getDocument().getLength(); try { format = editorPane.getDocument().getText(0, text_length); } catch (BadLocationException ex1) { } Element section_el = editorPane.getDocument().getDefaultRootElement(); // Get number of paragraphs. int num_para = section_el.getElementCount(); for (int p_count = 0; p_count < num_para; p_count++) { Element para_el = section_el.getElement(p_count); // Enumerate the content elements int num_cont = para_el.getElementCount(); for (int c_count = 0; c_count < num_cont; c_count++) { Element content_el = para_el.getElement(c_count); AttributeSet attr = content_el.getAttributes(); // Get the name of the style applied to this content element; may be null String sn = (String) attr.getAttribute(StyleConstants.NameAttribute); // Check if style name match if (sn != null && sn.startsWith("Parameter")) { // we extract the label. JLabel l = (JLabel) StyleConstants.getComponent(attr); if (l != null) { params.add(l.getName()); } } } } template.setFormat(format); template.setTokens(params); }
/** * This will invoke the <code>startElement</code> callback in the <code>ContentHandler</code>. * * @param element <code>Element</code> used in callbacks. * @param nsAtts <code>List</code> of namespaces to declare with the element or <code>null</code>. */ private void startElement(Element element, Attributes nsAtts) throws JDOMException { String namespaceURI = element.getNamespaceURI(); String localName = element.getName(); String rawName = element.getQualifiedName(); // Allocate attribute list. AttributesImpl atts = (nsAtts != null) ? new AttributesImpl(nsAtts) : new AttributesImpl(); List attributes = element.getAttributes(); Iterator i = attributes.iterator(); while (i.hasNext()) { Attribute a = (Attribute) i.next(); atts.addAttribute( a.getNamespaceURI(), a.getName(), a.getQualifiedName(), getAttributeTypeName(a.getAttributeType()), a.getValue()); } try { contentHandler.startElement(namespaceURI, localName, rawName, atts); } catch (SAXException se) { throw new JDOMException("Exception in startElement", se); } }
/** Convert the attributes in the given XML Element into a Map of name/value pairs. */ protected static Map createAttributeMap(Element el) { Log.debug("Creating attribute map for " + el); Map attributes = new HashMap(); Iterator iter = el.getAttributes().iterator(); while (iter.hasNext()) { Attribute att = (Attribute) iter.next(); attributes.put(att.getName(), att.getValue()); } return attributes; }
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; }
/** * Creates a {@link View} for the specified <code>Element</code>. * * @param element the <code>Element</code> to create a <code>View</code> for * @return the <code>View</code> for the specified <code>Element</code> or <code>null</code> if * the type of <code>element</code> is not supported */ public View create(Element element) { View view = null; Object attr = element.getAttributes().getAttribute(StyleConstants.NameAttribute); if (attr instanceof HTML.Tag) { HTML.Tag tag = (HTML.Tag) attr; if (tag.equals(HTML.Tag.IMPLIED) || tag.equals(HTML.Tag.P)) { view = new MinParagraphView(element); } else if (tag.equals(HTML.Tag.OBJECT)) { view = new ConstObjectView(element, map); } } return (view != null ? view : super.create(element)); }
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; }
void editorPane_keyPressed(KeyEvent e) { StyledDocument doc = editorPane.getStyledDocument(); int pos = editorPane.getCaretPosition(); int code = e.getKeyCode(); Element el; switch (code) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: if (pos == 0) return; // we want to get the element to the left of position. el = doc.getCharacterElement(pos - 1); break; case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: // we want to get the element to the right of position. el = doc.getCharacterElement(pos + 1); break; default: return; // bail we don't handle it. } AttributeSet attr = el.getAttributes(); String el_name = (String) attr.getAttribute(StyleConstants.NameAttribute); int el_range = el.getEndOffset() - el.getStartOffset() - 1; if (el_name.startsWith("Parameter") && StyleConstants.getComponent(attr) != null) { try { switch (code) { case KeyEvent.VK_BACK_SPACE: case KeyEvent.VK_DELETE: doc.remove(el.getStartOffset(), el_range); break; case KeyEvent.VK_LEFT: case KeyEvent.VK_KP_LEFT: editorPane.setCaretPosition(pos - el_range); break; case KeyEvent.VK_RIGHT: case KeyEvent.VK_KP_RIGHT: editorPane.setCaretPosition(pos + (el_range)); break; } } catch (BadLocationException ex) { } } }
// 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); }
@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(); }
/** * Reads the children of an XML element and matches them to properties of a bean. * * @param ob The bean to receive the values * @param element The element the corresponds to the bean * @throws IOException If there is an error reading the document */ public void readObject(Object ob, Element element) throws IOException { // If the object is null, skip the element if (ob == null) { return; } try { BeanInfo info = (BeanInfo) beanCache.get(ob.getClass()); if (info == null) { // Get the bean info for the object info = Introspector.getBeanInfo(ob.getClass(), Object.class); beanCache.put(ob.getClass(), info); } // Get the object's properties PropertyDescriptor[] props = info.getPropertyDescriptors(); // Get the attributes of the node NamedNodeMap attrs = element.getAttributes(); // Get the children of the XML element NodeList nodes = element.getChildNodes(); int numNodes = nodes.getLength(); for (int i = 0; i < props.length; i++) { // Treat indexed properties a little differently if (props[i] instanceof IndexedPropertyDescriptor) { readIndexedProperty(ob, (IndexedPropertyDescriptor) props[i], nodes, attrs); } else { readProperty(ob, props[i], nodes, attrs); } } } catch (IntrospectionException exc) { throw new IOException( "Error getting bean info for " + ob.getClass().getName() + ": " + exc.toString()); } }
protected static Iterator getAllAttributesFrom(final Element element) { final NamedNodeMap attributes = element.getAttributes(); return new Iterator() { int attributesLength = attributes.getLength(); int attributeIndex = 0; String currentName; public boolean hasNext() { return attributeIndex < attributesLength; } public Object next() { if (!hasNext()) { throw new NoSuchElementException(); } Node current = attributes.item(attributeIndex++); currentName = current.getNodeName(); String prefix = NameImpl.getPrefixFromTagName(currentName); if (prefix.length() == 0) { return NameImpl.createFromUnqualifiedName(currentName); } else { Name attributeName = NameImpl.createFromQualifiedName(currentName, current.getNamespaceURI()); return attributeName; } } public void remove() { if (currentName == null) { throw new IllegalStateException(); } attributes.removeNamedItem(currentName); } }; }
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); } } } }
/** * 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")); } }
public static NamedNodeMap attributes(Element element) { return element.getAttributes(); }
/** * 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; }
protected void validateElement(Element element, ISchema schema, boolean isTopLevel) { String elementName = element.getNodeName(); ISchemaElement schemaElement = schema.findElement(elementName); // Validate element occurrence violations if ((schemaElement != null) && (schemaElement.getType() instanceof ISchemaComplexType)) { validateMaxElementMult(element, schemaElement); validateMinElementMult(element, schemaElement); } ISchemaElement parentSchema = null; if (!"extension".equals(elementName)) { // $NON-NLS-1$ Node parent = element.getParentNode(); parentSchema = schema.findElement(parent.getNodeName()); } else if (isTopLevel == false) { // This is an "extension" element; but, not a top level one. // It is nested within another "extension" element somewhere // e.g. "extension" element is a child element of another element // that is not a "plugin" elment // element // Report illegal element int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ELEMENT); reportIllegalElement(element, severity); return; } if (parentSchema != null) { int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ELEMENT); if (severity != CompilerFlags.IGNORE) { HashSet allowedElements = new HashSet(); computeAllowedElements(parentSchema.getType(), allowedElements); if (!allowedElements.contains(elementName)) { reportIllegalElement(element, severity); return; } } } if (schemaElement == null && parentSchema != null) { ISchemaAttribute attr = parentSchema.getAttribute(elementName); if (attr != null && attr.getKind() == IMetaAttribute.JAVA) { if (attr.isDeprecated()) reportDeprecatedAttribute(element, element.getAttributeNode("class")); // $NON-NLS-1$ validateJavaAttribute(element, element.getAttributeNode("class")); // $NON-NLS-1$ } } else { if (schemaElement != null) { validateRequiredExtensionAttributes(element, schemaElement); validateExistingExtensionAttributes(element, element.getAttributes(), schemaElement); validateInternalExtensionAttribute(element, schemaElement); if (schemaElement.isDeprecated()) { if (schemaElement instanceof ISchemaRootElement) reportDeprecatedRootElement( element, ((ISchemaRootElement) schemaElement).getDeprecatedSuggestion()); else reportDeprecatedElement(element); } if (schemaElement.hasTranslatableContent()) validateTranslatableElementContent(element); // Bug 213457 - look up elements based on the schema in which the parent is found schema = schemaElement.getSchema(); } NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) { validateElement((Element) children.item(i), schema, false); } } }
protected void validateExtensionPoint(Element element) { if (assertAttributeDefined(element, "id", CompilerFlags.ERROR)) { // $NON-NLS-1$ Attr idAttr = element.getAttributeNode("id"); // $NON-NLS-1$ double schemaVersion = getSchemaVersion(); String message = null; if (schemaVersion < 3.2 && !IdUtil.isValidSimpleID(idAttr.getValue())) message = NLS.bind(MDECoreMessages.Builders_Manifest_simpleID, idAttr.getValue()); else if (schemaVersion >= 3.2) { if (!IdUtil.isValidCompositeID(idAttr.getValue())) { message = NLS.bind(MDECoreMessages.Builders_Manifest_compositeID, idAttr.getValue()); } } if (message != null) report( message, getLine(element, idAttr.getName()), CompilerFlags.WARNING, MDEMarkerFactory.CAT_OTHER); } assertAttributeDefined(element, "name", CompilerFlags.ERROR); // $NON-NLS-1$ int severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ATTRIBUTE); NamedNodeMap attrs = element.getAttributes(); for (int i = 0; i < attrs.getLength(); i++) { Attr attr = (Attr) attrs.item(i); String name = attr.getName(); if ("name".equals(name)) { // $NON-NLS-1$ validateTranslatableString(element, attr, true); } else if (!"id".equals(name) && !"schema".equals(name) && severity != CompilerFlags.IGNORE) { // $NON-NLS-1$ //$NON-NLS-2$ reportUnknownAttribute(element, name, severity); } } severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_ELEMENT); if (severity != CompilerFlags.IGNORE) { NodeList children = element.getChildNodes(); for (int i = 0; i < children.getLength(); i++) reportIllegalElement((Element) children.item(i), severity); } // Validate the "schema" attribute of the extension point Attr attr = element.getAttributeNode(IMonitorExtensionPoint.P_SCHEMA); // Only validate the attribute if it was defined if (attr != null) { String schemaValue = attr.getValue(); IResource res = getFile().getProject().findMember(schemaValue); String errorMessage = null; // Check to see if the value specified is an extension point schema and it exists if (!(res instanceof IFile && (res.getName().endsWith(".exsd") || //$NON-NLS-1$ res.getName().endsWith(".mxsd")))) // $NON-NLS-1$ errorMessage = MDECoreMessages.ExtensionsErrorReporter_InvalidSchema; // Report an error if one was found if (errorMessage != null) { severity = CompilerFlags.getFlag(fProject, CompilerFlags.P_UNKNOWN_RESOURCE); if (severity != CompilerFlags.IGNORE) report( NLS.bind(errorMessage, schemaValue), getLine(element), severity, MDEMarkerFactory.CAT_OTHER); } } }
/** 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; }