org.w3c.dom.Element Java Examples

The following examples show how to use org.w3c.dom.Element. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: AIMLParser.java    From BotLibre with Eclipse Public License 1.0 6 votes vote down vote up
public boolean appendHTML(String tag, Element child, boolean multiStar, boolean[] srai, boolean isTemplate, StringWriter writer, Network network) {
	writer.write("<");
	writer.write(tag);
	NamedNodeMap attributes = child.getAttributes();
	for (int index = 0; index < attributes.getLength(); index++) {
		Node attribute = attributes.item(index);
		writer.write(" ");
		writer.write(attribute.getNodeName());
		writer.write("=\\\"");
		writer.write(attribute.getNodeValue());
		writer.write("\\\"");
	}
	if (!child.hasChildNodes()) {
		writer.write("/>");
	} else {
		writer.write(">");
		if (appendNestedText((Element)child, multiStar, srai, writer, network)) {
			isTemplate = true;						
		}
		writer.write("</");
		writer.write(tag);
		writer.write(">");
	}
	return isTemplate;
}
 
Example #2
Source File: XAdESCRLSource.java    From dss with GNU Lesser General Public License v2.1 6 votes vote down vote up
private void collectValues(final String revocationValuesPath, RevocationOrigin revocationOrigin) {
	if (revocationValuesPath == null) {
		return;
	}

	final NodeList revocationValuesNodeList = DomUtils.getNodeList(signatureElement, revocationValuesPath);
	for (int i = 0; i < revocationValuesNodeList.getLength(); i++) {
		final Element revocationValuesElement = (Element) revocationValuesNodeList.item(i);
		final NodeList crlValueNodes = DomUtils.getNodeList(revocationValuesElement, xadesPaths.getCurrentCRLValuesChildren());
		for (int ii = 0; ii < crlValueNodes.getLength(); ii++) {
			try {
				final Element crlValueEl = (Element) crlValueNodes.item(ii);
				if (crlValueEl != null) {
					CRLBinary crlBinary = CRLUtils.buildCRLBinary(Utils.fromBase64(crlValueEl.getTextContent()));
					addBinary(crlBinary, revocationOrigin);
				}
			} catch (Exception e) {
				LOG.warn("Unable to build CRLBinary from an obtained element with origin {}", revocationOrigin);
			}
		}
	}
}
 
Example #3
Source File: ConfigBeanDefinitionParser.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Create a {@link RootBeanDefinition} for the advisor described in the supplied. Does <strong>not</strong>
 * parse any associated '{@code pointcut}' or '{@code pointcut-ref}' attributes.
 */
private AbstractBeanDefinition createAdvisorBeanDefinition(Element advisorElement, ParserContext parserContext) {
	RootBeanDefinition advisorDefinition = new RootBeanDefinition(DefaultBeanFactoryPointcutAdvisor.class);
	advisorDefinition.setSource(parserContext.extractSource(advisorElement));

	String adviceRef = advisorElement.getAttribute(ADVICE_REF);
	if (!StringUtils.hasText(adviceRef)) {
		parserContext.getReaderContext().error(
				"'advice-ref' attribute contains empty value.", advisorElement, this.parseState.snapshot());
	}
	else {
		advisorDefinition.getPropertyValues().add(
				ADVICE_BEAN_NAME, new RuntimeBeanNameReference(adviceRef));
	}

	if (advisorElement.hasAttribute(ORDER_PROPERTY)) {
		advisorDefinition.getPropertyValues().add(
				ORDER_PROPERTY, advisorElement.getAttribute(ORDER_PROPERTY));
	}

	return advisorDefinition;
}
 
Example #4
Source File: JupiterBeanDefinitionParser.java    From Jupiter with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("SameParameterValue")
private static void addPropertyReferenceArray(
        RootBeanDefinition definition, Element element, String elementTypeName, String propertyName, boolean required) {
    String[] refArray = Strings.split(element.getAttribute(propertyName), ',');
    List<RuntimeBeanReference> refBeanList = Lists.newArrayListWithCapacity(refArray.length);
    for (String ref : refArray) {
        ref = ref.trim();
        if (required) {
            checkAttribute(propertyName, ref);
        }
        if (!Strings.isNullOrEmpty(ref)) {
            refBeanList.add(new RuntimeBeanReference(ref));
        }
    }

    if (!refBeanList.isEmpty()) {
        ManagedArray managedArray = new ManagedArray(elementTypeName, refBeanList.size());
        managedArray.addAll(refBeanList);
        definition.getPropertyValues().addPropertyValue(propertyName, managedArray);
    }
}
 
Example #5
Source File: Helper.java    From packagedrone with Eclipse Public License 1.0 6 votes vote down vote up
public static void addBundleRequirement ( final Set<String> context, final Element requires, final ArtifactInformation a )
{
    final String id = a.getMetaData ().get ( new MetaKey ( "osgi", "name" ) );
    if ( id == null )
    {
        return;
    }

    final String version = a.getMetaData ().get ( new MetaKey ( "osgi", "version" ) );

    final String key = String.format ( "%s.feature.group-%s", id, version );
    if ( !context.add ( key ) )
    {
        return;
    }

    final Element p = requires.getOwnerDocument ().createElement ( "required" );
    requires.appendChild ( p );

    p.setAttribute ( "namespace", "org.eclipse.equinox.p2.iu" );
    p.setAttribute ( "name", id );
    p.setAttribute ( "range", String.format ( "[%1$s,%1$s]", version ) );
}
 
Example #6
Source File: BPELProcessFragments.java    From container with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a BPEL assign activity that reads the property values from a NodeInstance Property response and sets the
 * given variables
 *
 * @param assignName                          the name of the assign activity
 * @param nodeInstancePropertyResponseVarName the name of the variable holding the property data
 * @param propElement2BpelVarNameMap          a Map from DOM Elements (representing Node Properties) to BPEL
 *                                            variable names
 * @return a String containing a BPEL assign activity
 * @throws IOException is thrown when reading internal files fail
 */
public String createAssignFromInstancePropertyToBPELVariableAsString(final String assignName,
                                                                     final String nodeInstancePropertyResponseVarName,
                                                                     final Map<Element, String> propElement2BpelVarNameMap) throws IOException {
    final String template = ResourceAccess.readResourceAsString(getClass().getClassLoader().getResource("core-bpel/BpelCopyFromPropertyVarToNodeInstanceProperty.xml"));

    String assignString =
        "<bpel:assign name=\"" + assignName + "\" xmlns:bpel=\"" + BPELPlan.bpelNamespace + "\" >";

    // <!-- $PropertyVarName, $NodeInstancePropertyRequestVarName,
    // $NodeInstancePropertyLocalName, $NodeInstancePropertyNamespace -->
    for (final Element propElement : propElement2BpelVarNameMap.keySet()) {
        String copyString = template.replace("$PropertyVarName", propElement2BpelVarNameMap.get(propElement));
        copyString = copyString.replace("$NodeInstancePropertyRequestVarName", nodeInstancePropertyResponseVarName);
        copyString = copyString.replace("$NodeInstancePropertyLocalName", propElement.getLocalName());
        copyString = copyString.replace("$NodeInstancePropertyNamespace", propElement.getNamespaceURI());
        assignString += copyString;
    }

    assignString += "</bpel:assign>";

    BPELProcessFragments.LOG.debug("Generated following assign string:");
    BPELProcessFragments.LOG.debug(assignString);

    return assignString;
}
 
Example #7
Source File: PropFindContent.java    From cosmo with Apache License 2.0 6 votes vote down vote up
/**
 * toXML.
 * {@inheritDoc}
 * @param doc - The document.
 * @return The element.
 */
public Element toXml(Document doc) {
    Element propfind = DomUtil.createElement(doc, XML_PROPFIND, NAMESPACE);

    if (propertyNames.isEmpty()) {
        // allprop
        Element allprop =
            DomUtil.createElement(doc, XML_ALLPROP, NAMESPACE);
        propfind.appendChild(allprop);
    }
    else {
        for (DavPropertyName propname: propertyNames) {
            Element name =
                DomUtil.createElement(doc, propname.getName(),
                                      propname.getNamespace());

            Element prop = DomUtil.createElement(doc, XML_PROP, NAMESPACE);
            prop.appendChild(name);

            propfind.appendChild(prop);
        }
    }

    return propfind;
}
 
Example #8
Source File: PomReader.java    From ant-ivy with Apache License 2.0 6 votes vote down vote up
private List<PomPluginElement> getPlugins(Element parent) {
    Element buildElement = getFirstChildElement(parent, "build");
    Element pluginsElement = getFirstChildElement(buildElement, PLUGINS);

    if (pluginsElement == null) {
        return Collections.emptyList();
    }
    NodeList children = pluginsElement.getChildNodes();
    List<PomPluginElement> plugins = new LinkedList<>();
    for (int i = 0; i < children.getLength(); i++) {
        Node node = children.item(i);
        if (node instanceof Element && PLUGIN.equals(node.getNodeName())) {
            plugins.add(new PomPluginElement((Element) node));
        }
    }
    return plugins;
}
 
Example #9
Source File: Utils.java    From onpc with GNU General Public License v3.0 6 votes vote down vote up
public static List<Element> getElements(final Element e, final String name)
{
    List<Element> retValue = new ArrayList<>();
    for (Node object = e.getFirstChild(); object != null; object = object.getNextSibling())
    {
        if (object instanceof Element)
        {
            final Element en = (Element) object;
            if (name == null || name.equals(en.getTagName()))
            {
                retValue.add(en);
            }
        }
    }
    return retValue;
}
 
Example #10
Source File: FilePreferencesXmlSupport.java    From phoebus with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Import Map from the specified input stream, which is assumed to contain a map
 * document as per the prefs DTD. This is used as the internal (undocumented)
 * format for FileSystemPrefs. The key-value pairs specified in the XML document
 * will be put into the specified Map. (If this Map is empty, it will contain
 * exactly the key-value pairs int the XML-document when this method returns.)
 *
 * @throws IOException
 *             if reading from the specified output stream results in an
 *             <tt>IOException</tt>.
 * @throws InvalidPreferencesFormatException
 *             Data on input stream does not constitute a valid XML document
 *             with the mandated document type.
 */
static void importMap(InputStream is, Map m) throws IOException, InvalidPreferencesFormatException {
    try {
        Document doc = loadPrefsDoc(is);
        Element xmlMap = doc.getDocumentElement();
        // check version
        String mapVersion = xmlMap.getAttribute("MAP_XML_VERSION");
        if (mapVersion.compareTo(MAP_XML_VERSION) > 0)
            throw new InvalidPreferencesFormatException("Preferences map file format version " + mapVersion
                    + " is not supported. This java installation can read" + " versions " + MAP_XML_VERSION
                    + " or older. You may need" + " to install a newer version of JDK.");

        NodeList entries = xmlMap.getChildNodes();
        for (int i = 0, numEntries = entries.getLength(); i < numEntries; i++) {
            Element entry = (Element) entries.item(i);
            m.put(entry.getAttribute("key"), entry.getAttribute("value"));
        }
    } catch (SAXException e) {
        throw new InvalidPreferencesFormatException(e);
    }
}
 
Example #11
Source File: BusinessContentEncryptor.java    From freehealth-connector with GNU Affero General Public License v3.0 6 votes vote down vote up
public static byte[] encrypt(Document doc, Crypto crypto, String detailId) throws TechnicalConnectorException, TransformerException, UnsupportedEncodingException {
   NodeList nodes = doc.getElementsByTagNameNS("urn:be:cin:encrypted", "EncryptedKnownContent");
   String content = toStringOmittingXmlDeclaration(nodes);
   SignatureBuilder builder = SignatureBuilderFactory.getSignatureBuilder(AdvancedElectronicSignatureEnumeration.XAdES);
   Map<String, Object> options = new HashMap();
   List<String> tranforms = new ArrayList();
   tranforms.add("http://www.w3.org/2000/09/xmldsig#base64");
   tranforms.add("http://www.w3.org/2001/10/xml-exc-c14n#");
   options.put("transformerList", tranforms);
   options.put("baseURI", detailId);
   options.put("encapsulate", true);
   options.put("encapsulate-transformer", new EncapsulationTransformer() {
      public Node transform(Node signature) {
         Element result = signature.getOwnerDocument().createElementNS("urn:be:cin:encrypted", "Xades");
         result.setTextContent(Base64.encodeBase64String(ConnectorXmlUtils.toByteArray(signature)));
         return result;
      }
   });
   byte[] encryptedKnowContent = builder.sign(Session.getInstance().getSession().getEncryptionCredential(), content.getBytes("UTF-8"), options);
   return seal(crypto, encryptedKnowContent);
}
 
Example #12
Source File: BundleMvnAntTask.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
/**
 * Set an attribute on the named target element. The target element must exist
 * and be a child of the project-element.
 *
 * @param el
 *          The element owning the target element to be updated.
 * @param name
 *          The name of the target-element to set an attribute for.
 * @param attrName
 *          The name of the attribute to set.
 * @param attrValue
 *          The new attribute value.
 */
private void setTargetAttr(final Element el, final String name, final String attrName, final String attrValue) {
  final NodeList propertyNL = el.getElementsByTagName("target");
  boolean found = false;
  for (int i = 0; i<propertyNL.getLength(); i++) {
    final Element target = (Element) propertyNL.item(i);
    if (name.equals(target.getAttribute("name"))) {
      log("Setting <target name=\"" +name +"\" attrName =\"" +attrValue +"\" ...>.", Project.MSG_DEBUG);
      target.setAttribute(attrName, attrValue);
      found = true;
      break;
    }
  }
  if (!found) {
    throw new BuildException("No <property name=\"" +name +"\" ...> in XML document " +el);
  }
}
 
Example #13
Source File: BaseDefinitionReader.java    From arcusplatform with Apache License 2.0 6 votes vote down vote up
protected T buildModel(Element root) {
   B builder = builder();
   builder
      .withName(root.getAttribute("name"))
      .withNamespace(root.getAttribute("namespace"))
      .withVersion(root.getAttribute("version"));
   
   NodeList nodes = root.getElementsByTagNameNS(schemaURI, "description");
   if (nodes.getLength() > 0)
   {
      Element description = (Element)nodes.item(0);
      builder.withDescription(readDescription(description));
   }
   else {
      logger.warn("No description was given for the capability {}", root.getAttribute("name"));
   }

   populateDefinitionSpecificData(builder, root);

   builder.withMethods(buildMethods(root.getElementsByTagNameNS(schemaURI, "method")));
   builder.withEvents(buildEvents(root.getElementsByTagNameNS(schemaURI, "event")));
   return builder.build();
}
 
Example #14
Source File: ElementProxy.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method creates an Element in a given namespace with a given localname.
 * It uses the {@link ElementProxy#getDefaultPrefix} method to decide whether
 * a particular prefix is bound to that namespace.
 * <BR />
 * This method was refactored out of the constructor.
 *
 * @param doc
 * @param namespace
 * @param localName
 * @return The element created.
 */
public static Element createElementForFamily(Document doc, String namespace, String localName) {
    Element result = null;
    String prefix = ElementProxy.getDefaultPrefix(namespace);

    if (namespace == null) {
        result = doc.createElementNS(null, localName);
    } else {
        if ((prefix == null) || (prefix.length() == 0)) {
            result = doc.createElementNS(namespace, localName);
            result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns", namespace);
        } else {
            result = doc.createElementNS(namespace, prefix + ":" + localName);
            result.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:" + prefix, namespace);
        }
    }

    return result;
}
 
Example #15
Source File: TmfXmlStateAttributeAndLocationCuTest.java    From tracecompass with Eclipse Public License 2.0 6 votes vote down vote up
/**
 * Test the compilation of a invalid state attribute strings, except
 * locations
 *
 * @throws SAXException
 *             Exception thrown by parser
 * @throws IOException
 *             Exception thrown by parser
 * @throws ParserConfigurationException
 *             Exception thrown by parser
 */
@Test
public void testInvalidStateAttributeCompilation() throws SAXException, IOException, ParserConfigurationException {
    String[] invalidStrings = { "<stateAttribute type=\"constant\" />",
            "<stateAttribute type=\"eventField\" />",
            "<stateAttribute type=\"query\" />",
            "<stateAttribute type=\"query\" ><stateAttribute type=\"constant\" /></stateAttribute>",
            "<stateAttribute type=\"location\" value=\"undefined\" />"
    };

    for (String invalidString : invalidStrings) {
        Element xmlElement = TmfXmlTestUtils.getXmlElement(TmfXmlStrings.STATE_ATTRIBUTE, invalidString);
        assertNotNull(xmlElement);
        assertNull(invalidString, TmfXmlStateValueCu.compileAttribute(ANALYSIS_DATA, xmlElement));
    }
}
 
Example #16
Source File: XMLCipher.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Encrypts a <code>NodeList</code> (the contents of an
 * <code>Element</code>) and replaces its parent <code>Element</code>'s
 * content with this the resulting <code>EncryptedType</code> within the
 * context <code>Document</code>, that is, the <code>Document</code>
 * specified when one calls
 * {@link #getInstance(String) getInstance}.
 *
 * @param element the <code>NodeList</code> to encrypt.
 * @return the context <code>Document</code> with the encrypted
 *   <code>NodeList</code> having replaced the content of the source
 *   <code>Element</code>.
 * @throws Exception
 */
private Document encryptElementContent(Element element) throws /* XMLEncryption */Exception {
    if (log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "Encrypting element content...");
    }
    if (null == element) {
        log.log(java.util.logging.Level.SEVERE, "Element unexpectedly null...");
    }
    if (cipherMode != ENCRYPT_MODE && log.isLoggable(java.util.logging.Level.FINE)) {
        log.log(java.util.logging.Level.FINE, "XMLCipher unexpectedly not in ENCRYPT_MODE...");
    }

    if (algorithm == null) {
        throw new XMLEncryptionException("XMLCipher instance without transformation specified");
    }
    encryptData(contextDocument, element, true);

    Element encryptedElement = factory.toElement(ed);

    removeContent(element);
    element.appendChild(encryptedElement);

    return contextDocument;
}
 
Example #17
Source File: DOMSignatureProperties.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);
    Element propsElem = DOMUtils.createElement(ownerDoc,
                                               "SignatureProperties",
                                               XMLSignature.XMLNS,
                                               dsPrefix);

    // set attributes
    DOMUtils.setAttributeID(propsElem, "Id", id);

    // create and append any properties
    for (SignatureProperty property : properties) {
        ((DOMSignatureProperty)property).marshal(propsElem, dsPrefix,
                                                 context);
    }

    parent.appendChild(propsElem);
}
 
Example #18
Source File: DOMUtil.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
public static List<Element> getChildElements(Element e) {
    List<Element> r = new ArrayList<Element>();
    NodeList l = e.getChildNodes();
    for(int i=0;i<l.getLength();i++) {
        Node n = l.item(i);
        if(n.getNodeType()==Node.ELEMENT_NODE)
            r.add((Element)n);
    }
    return r;
}
 
Example #19
Source File: TestXMLDocumentHelper.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
/**
 * Tests whether an instance can be created wrapping a new document.
 */
@Test
public void testInitForNewDocument() throws ConfigurationException
{
    final XMLDocumentHelper helper = XMLDocumentHelper.forNewDocument(ELEMENT);
    final Document doc = helper.getDocument();
    final Element rootElement = doc.getDocumentElement();
    assertEquals("Wrong root element name", ELEMENT,
            rootElement.getNodeName());
    final NodeList childNodes = rootElement.getChildNodes();
    assertEquals("Got child nodes", 0, childNodes.getLength());
    assertNull("Got a public ID", helper.getSourcePublicID());
    assertNull("Got a system ID", helper.getSourceSystemID());
}
 
Example #20
Source File: XmlParser.java    From android-uiconductor with Apache License 2.0 5 votes vote down vote up
/** Convert xml node to nodeContext. Nodes in meaningless layer will be filtered out. */
private void initBounds(List<Element> roots) throws UicdXMLFormatException {
  int xmlLayerIndex = 0;
  for (Element root : roots) {
    initBoundsFromRoot(root, xmlLayerIndex);
    filterMeaninglessLayers(xmlLayerIndex);
    xmlLayerIndex++;
  }
}
 
Example #21
Source File: BeanDefinitionParserDelegate.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
/**
 * Parse constructor-arg sub-elements of the given bean element.
 */
public void parseConstructorArgElements(Element beanEle, BeanDefinition bd) {
	NodeList nl = beanEle.getChildNodes();
	for (int i = 0; i < nl.getLength(); i++) {
		Node node = nl.item(i);
		if (isCandidateElement(node) && nodeNameEquals(node, CONSTRUCTOR_ARG_ELEMENT)) {
			parseConstructorArgElement((Element) node, bd);
		}
	}
}
 
Example #22
Source File: Utils.java    From dr-elephant with Apache License 2.0 5 votes vote down vote up
/**
 * Given a configuration element, extract the params map.
 *
 * @param confElem the configuration element
 * @return the params map or an empty map if one can't be found
 */
public static Map<String, String> getConfigurationParameters(Element confElem) {
  Map<String, String> paramsMap = new HashMap<String, String>();
  Node paramsNode = confElem.getElementsByTagName("params").item(0);
  if (paramsNode != null) {
    NodeList paramsList = paramsNode.getChildNodes();
    for (int j = 0; j < paramsList.getLength(); j++) {
      Node paramNode = paramsList.item(j);
      if (paramNode != null && !paramsMap.containsKey(paramNode.getNodeName())) {
        paramsMap.put(paramNode.getNodeName(), paramNode.getTextContent());
      }
    }
  }
  return paramsMap;
}
 
Example #23
Source File: DOMConfigurator.java    From cacheonix-core with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
    * Delegates unrecognized content to created instance if
    * it supports UnrecognizedElementParser and catches and
   *  logs any exception.
    * @since 1.2.15
    * @param instance instance, may be null.
    * @param element element, may not be null.
    * @param props properties
    */
 private static void quietParseUnrecognizedElement(final Object instance,
                                        final Element element,
                                        final Properties props) {
    try {
        parseUnrecognizedElement(instance, element, props);
    } catch (Exception ex) {
        LogLog.error("Error in extension content: ", ex);
    }
}
 
Example #24
Source File: ConfigBeanDefinitionParser.java    From java-technology-stack with MIT License 5 votes vote down vote up
/**
 * Parses the supplied {@code <advisor>} element and registers the resulting
 * {@link org.springframework.aop.Advisor} and any resulting {@link org.springframework.aop.Pointcut}
 * with the supplied {@link BeanDefinitionRegistry}.
 */
private void parseAdvisor(Element advisorElement, ParserContext parserContext) {
	AbstractBeanDefinition advisorDef = createAdvisorBeanDefinition(advisorElement, parserContext);
	String id = advisorElement.getAttribute(ID);

	try {
		this.parseState.push(new AdvisorEntry(id));
		String advisorBeanName = id;
		if (StringUtils.hasText(advisorBeanName)) {
			parserContext.getRegistry().registerBeanDefinition(advisorBeanName, advisorDef);
		}
		else {
			advisorBeanName = parserContext.getReaderContext().registerWithGeneratedName(advisorDef);
		}

		Object pointcut = parsePointcutProperty(advisorElement, parserContext);
		if (pointcut instanceof BeanDefinition) {
			advisorDef.getPropertyValues().add(POINTCUT, pointcut);
			parserContext.registerComponent(
					new AdvisorComponentDefinition(advisorBeanName, advisorDef, (BeanDefinition) pointcut));
		}
		else if (pointcut instanceof String) {
			advisorDef.getPropertyValues().add(POINTCUT, new RuntimeBeanReference((String) pointcut));
			parserContext.registerComponent(
					new AdvisorComponentDefinition(advisorBeanName, advisorDef));
		}
	}
	finally {
		this.parseState.pop();
	}
}
 
Example #25
Source File: TransformBase64Decode.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
void traverseElement(org.w3c.dom.Element node, StringBuilder sb) {
    Node sibling = node.getFirstChild();
    while (sibling != null) {
        switch (sibling.getNodeType()) {
        case Node.ELEMENT_NODE:
            traverseElement((Element)sibling, sb);
            break;
        case Node.TEXT_NODE:
            sb.append(((Text)sibling).getData());
        }
        sibling = sibling.getNextSibling();
    }
}
 
Example #26
Source File: BaseConfigurationService.java    From sakai with Educational Community License v2.0 5 votes vote down vote up
protected void saveServletClientMappings(Document document) {
	  
	  Element clientElement = document.getElementById("saveciteClients");
	  
	  if(clientElement == null) {
		  NodeList mapNodes = document.getElementsByTagName("map");
		  if(mapNodes != null) {
			  for(int i = 0; i < mapNodes.getLength(); i++) {
				  Element mapElement = (Element) mapNodes.item(i);
				  if(mapElement.hasAttribute("id") && mapElement.getAttribute("id").equals("saveciteClients")) {
					  clientElement = mapElement;
					  break;
				  }
			  }
		  }
	  }
	  
	  if(clientElement != null) {
		  try {
			  XStream xstream = new XStream();
			  TransformerFactory transFactory = TransformerFactory.newInstance();
			  Transformer transformer = transFactory.newTransformer();
			  StringWriter buffer = new StringWriter();
			  transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			  transformer.transform(new DOMSource(clientElement),
			        new StreamResult(buffer));
			  String str = buffer.toString();
//			  DOMImplementationLS domImplLS = (DOMImplementationLS) document.getImplementation();
//			  LSSerializer serializer = domImplLS.createLSSerializer();
//			  String str = serializer.writeToString(clientElement);
			  this.saveciteClients = (Map<String, List<Map<String, String>>>) xstream.fromXML(str);
		  } catch(Exception e) {
			  log.warn("Exception trying to read saveciteClients from config XML", e);
		  }
	  }
	
  }
 
Example #27
Source File: AuthorizationNsHandler.java    From peer-os with Apache License 2.0 5 votes vote down vote up
@Override
public ComponentMetadata decorate( Node node, ComponentMetadata cm, ParserContext pc )
{
    if ( node instanceof Element )
    {
        parseElement( ( Element ) node, pc );
    }

    return cm;
}
 
Example #28
Source File: PrivateKeyResolver.java    From hottub with GNU General Public License v2.0 5 votes vote down vote up
/**
 * This method returns whether the KeyResolverSpi is able to perform the requested action.
 *
 * @param element
 * @param BaseURI
 * @param storage
 * @return whether the KeyResolverSpi is able to perform the requested action.
 */
public boolean engineCanResolve(Element element, String BaseURI, StorageResolver storage) {
    if (XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_X509DATA)
        || XMLUtils.elementIsInSignatureSpace(element, Constants._TAG_KEYNAME)) {
        return true;
    }

    return false;
}
 
Example #29
Source File: MessageListDeserializer.java    From mq-http-java-sdk with MIT License 5 votes vote down vote up
public List<Message> deserialize(Document doc) {
    NodeList list = doc.getElementsByTagName(Constants.MESSAGE_TAG);
    if (list != null && list.getLength() > 0) {
        List<Message> results = new ArrayList<Message>();

        for (int i = 0; i < list.getLength(); i++) {
            Message msg = parseMessage((Element) list.item(i));
            results.add(msg);
        }
        return results;
    }
    return null;
}
 
Example #30
Source File: XmlElement.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private Optional<String> findAndCompareNode(
        XmlElement otherElement,
        List<Node> otherElementChildren,
        XmlElement childNode) {

    Optional<String> message = Optional.absent();
    for (Node potentialNode : otherElementChildren) {
        if (potentialNode.getNodeType() == Node.ELEMENT_NODE) {
            XmlElement otherChildNode = new XmlElement((Element) potentialNode, mDocument);
            if (childNode.getType() == otherChildNode.getType()) {
                // check if this element uses a key.
                if (childNode.getType().getNodeKeyResolver().getKeyAttributesNames()
                        .isEmpty()) {
                    // no key... try all the other elements, if we find one equal, we are done.
                    message = childNode.compareTo(otherChildNode);
                    if (!message.isPresent()) {
                        return Optional.absent();
                    }
                } else {
                    // key...
                    if (childNode.getKey() == null) {
                        // other key MUST also be null.
                        if (otherChildNode.getKey() == null) {
                            return childNode.compareTo(otherChildNode);
                        }
                    } else {
                        if (childNode.getKey().equals(otherChildNode.getKey())) {
                            return childNode.compareTo(otherChildNode);
                        }
                    }
                }
            }
        }
    }
    return message.isPresent()
            ? message
            : Optional.of(String.format("Child %1$s not found in document %2$s",
                    childNode.getId(),
                    otherElement.printPosition()));
}