org.w3c.dom.Node Java Examples

The following examples show how to use org.w3c.dom.Node. 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: UnmarshallerImpl.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public final Object unmarshal0( Node node, JaxBeanInfo expectedType ) throws JAXBException {
    try {
        final DOMScanner scanner = new DOMScanner();

        InterningXmlVisitor handler = new InterningXmlVisitor(createUnmarshallerHandler(null,false,expectedType));
        scanner.setContentHandler(new SAXConnector(handler,scanner));

        if(node.getNodeType() == Node.ELEMENT_NODE) {
            scanner.scan((Element)node);
        } else if(node.getNodeType() == Node.DOCUMENT_NODE) {
            scanner.scan((Document)node);
        } else {
            throw new IllegalArgumentException("Unexpected node type: "+node);
        }

        Object retVal = handler.getContext().getResult();
        handler.getContext().clearResult();
        return retVal;
    } catch( SAXException e ) {
        throw createUnmarshalException(e);
    }
}
 
Example #2
Source File: Script.java    From karate with MIT License 6 votes vote down vote up
public static ScriptValue evalXmlPathOnXmlNode(Node doc, String path) {
    NodeList nodeList;
    try {
        nodeList = XmlUtils.getNodeListByPath(doc, path);
    } catch (Exception e) {
        // hack, this happens for xpath functions that don't return nodes (e.g. count)
        String strValue = XmlUtils.getTextValueByPath(doc, path);
        return new ScriptValue(strValue);
    }
    int count = nodeList.getLength();
    if (count == 0) { // xpath / node does not exist !
        return null;
    }
    if (count == 1) {
        return nodeToValue(nodeList.item(0));
    }
    List list = new ArrayList();
    for (int i = 0; i < count; i++) {
        ScriptValue sv = nodeToValue(nodeList.item(i));
        list.add(sv.getValue());
    }
    return new ScriptValue(list);
}
 
Example #3
Source File: DomSerializer.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public DomSerializer(DOMResult domResult) {
    Node node = domResult.getNode();

    if (node == null) {
        try {
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = dbf.newDocumentBuilder();
            Document doc = db.newDocument();
            domResult.setNode(doc);
            serializer = new SaxSerializer(new Dom2SaxAdapter(doc),null,false);
        } catch (ParserConfigurationException pce) {
            throw new TxwException(pce);
        }
    } else {
        serializer = new SaxSerializer(new Dom2SaxAdapter(node),null,false);
    }
}
 
Example #4
Source File: SOFMarkerSegment.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
void updateFromNativeNode(Node node, boolean fromScratch)
    throws IIOInvalidTreeException {
    NamedNodeMap attrs = node.getAttributes();
    int value = getAttributeValue(node, attrs, "process", 0, 2, false);
    tag = (value != -1) ? value+JPEG.SOF0 : tag;
    // If samplePrecision is present, it must be 8.
    // This just checks.  We don't bother to assign the value.
    value = getAttributeValue(node, attrs, "samplePrecision", 8, 8, false);
    value = getAttributeValue(node, attrs, "numLines", 0, 65535, false);
    numLines = (value != -1) ? value : numLines;
    value = getAttributeValue(node, attrs, "samplesPerLine", 0, 65535, false);
    samplesPerLine = (value != -1) ? value : samplesPerLine;
    int numComponents = getAttributeValue(node, attrs, "numFrameComponents",
                                          1, 4, false);
    NodeList children = node.getChildNodes();
    if (children.getLength() != numComponents) {
        throw new IIOInvalidTreeException
            ("numFrameComponents must match number of children", node);
    }
    componentSpecs = new ComponentSpec [numComponents];
    for (int i = 0; i < numComponents; i++) {
        componentSpecs[i] = new ComponentSpec(children.item(i));
    }
}
 
Example #5
Source File: XMLReader.java    From archiva with Apache License 2.0 6 votes vote down vote up
/**
 * Remove namespaces from element recursively.
 */
@SuppressWarnings("unchecked")
public void removeNamespaces( Node elem )
{
    if (elem.getNodeType() == Node.ELEMENT_NODE || elem.getNodeType() == Node.ATTRIBUTE_NODE) {
        document.renameNode(elem, null, elem.getLocalName());

        Node n;

        NodeList nodeList = elem.getChildNodes();


        for (int i = 0; i < nodeList.getLength(); i++) {
            n = nodeList.item(i);
            removeNamespaces(n);
        }
    }
}
 
Example #6
Source File: ShortHistogramTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
private IIOMetadata upgradeMetadata(IIOMetadata src, BufferedImage bi) {
    String format = src.getNativeMetadataFormatName();
    System.out.println("Native format: " + format);
    Node root = src.getAsTree(format);

    // add hIST node
    Node n = lookupChildNode(root, "hIST");
    if (n == null) {
        System.out.println("Appending new hIST node...");
        Node hIST = gethISTNode(bi);
        root.appendChild(hIST);
    }

    System.out.println("Upgraded metadata tree:");
    dump(root, "");

    System.out.println("Merging metadata...");
    try {
        src.mergeTree(format, root);
    } catch (IIOInvalidTreeException e) {
        throw new RuntimeException("Test FAILED!", e);
    }
    return src;
}
 
Example #7
Source File: AspectJAutoProxyBeanDefinitionParser.java    From java-technology-stack with MIT License 6 votes vote down vote up
private void addIncludePatterns(Element element, ParserContext parserContext, BeanDefinition beanDef) {
	ManagedList<TypedStringValue> includePatterns = new ManagedList<>();
	NodeList childNodes = element.getChildNodes();
	for (int i = 0; i < childNodes.getLength(); i++) {
		Node node = childNodes.item(i);
		if (node instanceof Element) {
			Element includeElement = (Element) node;
			TypedStringValue valueHolder = new TypedStringValue(includeElement.getAttribute("name"));
			valueHolder.setSource(parserContext.extractSource(includeElement));
			includePatterns.add(valueHolder);
		}
	}
	if (!includePatterns.isEmpty()) {
		includePatterns.setSource(parserContext.extractSource(element));
		beanDef.getPropertyValues().add("includePatterns", includePatterns);
	}
}
 
Example #8
Source File: JPEGMetadata.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Merge the given DRI node into the marker sequence.
 * If there already exists a DRI marker segment, the restart interval
 * value is updated.
 * If there is no DRI segment, then a new one is created and added as
 * follows:
 * If there is an SOF segment, the new DRI segment is inserted before
 * it.
 * If there is no SOF segment, the new DRI segment is inserted before
 * the first SOS segment, if there is one.
 * If there is no SOS segment, the new DRI segment is added to the end
 * of the sequence.
 */
private void mergeDRINode(Node node) throws IIOInvalidTreeException {
    DRIMarkerSegment dri =
        (DRIMarkerSegment) findMarkerSegment(DRIMarkerSegment.class, true);
    if (dri != null) {
        dri.updateFromNativeNode(node, false);
    } else {
        DRIMarkerSegment newGuy = new DRIMarkerSegment(node);
        int firstSOF = findMarkerSegmentPosition(SOFMarkerSegment.class, true);
        int firstSOS = findMarkerSegmentPosition(SOSMarkerSegment.class, true);
        if (firstSOF != -1) {
            markerSequence.add(firstSOF, newGuy);
        } else if (firstSOS != -1) {
            markerSequence.add(firstSOS, newGuy);
        } else {
            markerSequence.add(newGuy);
        }
    }
}
 
Example #9
Source File: AbstractDOMSignatureMethod.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * This method invokes the {@link #marshalParams marshalParams}
 * method to marshal any algorithm-specific parameters.
 */
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    Element smElem = DOMUtils.createElement(ownerDoc, "SignatureMethod",
                                            XMLSignature.XMLNS, dsPrefix);
    DOMUtils.setAttribute(smElem, "Algorithm", getAlgorithm());

    if (getParameterSpec() != null) {
        marshalParams(smElem, dsPrefix);
    }

    parent.appendChild(smElem);
}
 
Example #10
Source File: DTMManagerDefault.java    From JDKSourceCode1.8 with MIT License 6 votes vote down vote up
/**
 * Method createDocumentFragment
 *
 *
 * NEEDSDOC (createDocumentFragment) @return
 */
synchronized public DTM createDocumentFragment()
{

  try
  {
    DocumentBuilderFactory dbf = JdkXmlUtils.getDOMFactory(super.overrideDefaultParser());

    DocumentBuilder db = dbf.newDocumentBuilder();
    Document doc = db.newDocument();
    Node df = doc.createDocumentFragment();

    return getDTM(new DOMSource(df), true, null, false, false);
  }
  catch (Exception e)
  {
    throw new DTMException(e);
  }
}
 
Example #11
Source File: DOMScanner.java    From jdk8u60 with GNU General Public License v2.0 6 votes vote down vote up
private void visit( Node n ) throws SAXException {
    setCurrentLocation( n );

    // if a case statement gets too big, it should be made into a separate method.
    switch(n.getNodeType()) {
    case Node.CDATA_SECTION_NODE:
    case Node.TEXT_NODE:
        String value = n.getNodeValue();
        receiver.characters( value.toCharArray(), 0, value.length() );
        break;
    case Node.ELEMENT_NODE:
        visit( (Element)n );
        break;
    case Node.ENTITY_REFERENCE_NODE:
        receiver.skippedEntity(n.getNodeName());
        break;
    case Node.PROCESSING_INSTRUCTION_NODE:
        ProcessingInstruction pi = (ProcessingInstruction)n;
        receiver.processingInstruction(pi.getTarget(),pi.getData());
        break;
    }
}
 
Example #12
Source File: XmlExtensions.java    From groovy with Apache License 2.0 6 votes vote down vote up
/**
 * Makes NodeList iterable by returning a read-only Iterator which traverses
 * over each Node.
 *
 * @param nodeList a NodeList
 * @return an Iterator for a NodeList
 * @since 1.0
 */
public static Iterator<Node> iterator(final NodeList nodeList) {
    return new Iterator<Node>() {
        private int current /* = 0 */;

        public boolean hasNext() {
            return current < nodeList.getLength();
        }

        public Node next() {
            return nodeList.item(current++);
        }

        public void remove() {
            throw new UnsupportedOperationException("Cannot remove() from a NodeList iterator");
        }
    };
}
 
Example #13
Source File: DOMBuilder.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Receive notification of character data.
 *
 * <p>The Parser will call this method to report each chunk of
 * character data.  SAX parsers may return all contiguous character
 * data in a single chunk, or they may split it into several
 * chunks; however, all of the characters in any single event
 * must come from the same external entity, so that the Locator
 * provides useful information.</p>
 *
 * <p>The application must not attempt to read from the array
 * outside of the specified range.</p>
 *
 * <p>Note that some parsers will report whitespace using the
 * ignorableWhitespace() method rather than this one (validating
 * parsers must do so).</p>
 *
 * @param ch The characters from the XML document.
 * @param start The start position in the array.
 * @param length The number of characters to read from the array.
 * @see #ignorableWhitespace
 * @see org.xml.sax.Locator
 */
public void characters(char ch[], int start, int length) throws org.xml.sax.SAXException
{
  if(isOutsideDocElem()
     && com.sun.org.apache.xml.internal.utils.XMLCharacterRecognizer.isWhiteSpace(ch, start, length))
    return;  // avoid DOM006 Hierarchy request error

  if (m_inCData)
  {
    cdata(ch, start, length);

    return;
  }

  String s = new String(ch, start, length);
  Node childNode;
  childNode =  m_currentNode != null ? m_currentNode.getLastChild(): null;
  if( childNode != null && childNode.getNodeType() == Node.TEXT_NODE ){
     ((Text)childNode).appendData(s);
  }
  else{
     Text text = m_doc.createTextNode(s);
     append(text);
  }
}
 
Example #14
Source File: TIFFBaseJPEGCompressor.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private static List<Node> getAllNodes(IIOMetadataNode root, List<Node> nodes) {
    if(nodes == null) nodes = new ArrayList<Node>();

    if(root.hasChildNodes()) {
        Node sibling = root.getFirstChild();
        while(sibling != null) {
            nodes.add(sibling);
            nodes = getAllNodes((IIOMetadataNode)sibling, nodes);
            sibling = sibling.getNextSibling();
        }
    }

    return nodes;
}
 
Example #15
Source File: MySQLBulkLoaderTest.java    From hop with Apache License 2.0 5 votes vote down vote up
@Test
public void testFieldFormatType() throws HopXmlException {
  MySQLBulkLoaderMeta lm = new MySQLBulkLoaderMeta();
  Document document = XmlHandler.loadXmlFile( this.getClass().getResourceAsStream( "transform.xml" ) );
  IHopMetadataProvider metadataProvider = null;
  Node transformNode = (Node) document.getDocumentElement();
  lm.loadXml( transformNode, metadataProvider );
  int[] codes = lm.getFieldFormatType();
  assertEquals( 3, codes[ 0 ] );
  assertEquals( 4, codes[ 1 ] );
}
 
Example #16
Source File: SessionUtil.java    From freehealth-connector with GNU Affero General Public License v3.0 5 votes vote down vote up
public static Map<String, List<String>> getMatchingAttributes(String attributeNamePattern) throws TechnicalConnectorException {
   SessionManager sessionMgr = Session.getInstance();
   if (!sessionMgr.hasValidSession()) {
      throw new TechnicalConnectorException(TechnicalConnectorExceptionValues.NO_VALID_SESSION, new Object[0]);
   } else {
      Element token = sessionMgr.getSession().getSAMLToken().getAssertion();
      NodeList attributes = extractAttributes(token);
      Map<String, List<String>> result = new HashMap();
      if (attributes != null) {
         for(int i = 0; i < attributes.getLength(); ++i) {
            Node node = attributes.item(i);
            String attributeName = node.getAttributes().getNamedItem("AttributeName").getTextContent();
            if (attributeName.matches(attributeNamePattern)) {
               if (!node.hasChildNodes()) {
                  result.put(attributeName, Arrays.asList(node.getTextContent().trim()));
               } else {
                  NodeList attributeValueNodeList = node.getChildNodes();
                  List<String> values = new ArrayList();

                  for(int index = 0; index < attributeValueNodeList.getLength(); ++index) {
                     values.add(attributeValueNodeList.item(index).getTextContent().trim());
                  }

                  result.put(attributeName, values);
               }
            }
         }
      }

      return result;
   }
}
 
Example #17
Source File: XSDocumentInfo.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Initialize namespace support by collecting all of the namespace
 * declarations in the root's ancestors. This is necessary to
 * support schemas fragments, i.e. schemas embedded in other
 * documents. See,
 *
 * https://jaxp.dev.java.net/issues/show_bug.cgi?id=43
 *
 * Requires the DOM to be created with namespace support enabled.
 */
private void initNamespaceSupport(Element schemaRoot) {
    fNamespaceSupport = new SchemaNamespaceSupport();
    fNamespaceSupport.reset();

    Node parent = schemaRoot.getParentNode();
    while (parent != null && parent.getNodeType() == Node.ELEMENT_NODE
            && !parent.getNodeName().equals("DOCUMENT_NODE"))
    {
        Element eparent = (Element) parent;
        NamedNodeMap map = eparent.getAttributes();
        int length = (map != null) ? map.getLength() : 0;
        for (int i = 0; i < length; i++) {
            Attr attr = (Attr) map.item(i);
            String uri = attr.getNamespaceURI();

            // Check if attribute is an ns decl -- requires ns support
            if (uri != null && uri.equals("http://www.w3.org/2000/xmlns/")) {
                String prefix = attr.getLocalName().intern();
                if (prefix == "xmlns") prefix = "";
                // Declare prefix if not set -- moving upwards
                if (fNamespaceSupport.getURI(prefix) == null) {
                    fNamespaceSupport.declarePrefix(prefix,
                            attr.getValue().intern());
                }
            }
        }
        parent = parent.getParentNode();
    }
}
 
Example #18
Source File: XCalWriterTest.java    From biweekly with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@Test
public void write_existing_dom_element() throws Exception {
	Document document = XmlUtils.toDocument("<root><a /><b /></root>");
	Node element = document.getFirstChild().getFirstChild();
	XCalWriter writer = new XCalWriter(element);

	ical.setProductId("value");
	writer.write(ical);

	writer.close();

	//@formatter:off
	String xml =
	"<root>" +
		"<a>" +
			"<icalendar xmlns=\"" + XCAL_NS + "\">" +
				"<vcalendar>" +
					"<properties>" +
						"<version><text>2.0</text></version>" +
						"<prodid><text>value</text></prodid>" +
					"</properties>" +
				"</vcalendar>" +
			"</icalendar>" +
		"</a>" +
		"<b />" +
	"</root>";
	Document expected = XmlUtils.toDocument(xml);
	//@formatter:on

	assertXMLEqual(expected, document);
}
 
Example #19
Source File: ByteArrayCodec.java    From oodt with Apache License 2.0 5 votes vote down vote up
public Object decode(Node node) {
	String encodedValue;
	if (node.getFirstChild() != null && node.getFirstChild().getNodeType() == Node.CDATA_SECTION_NODE) {
	  encodedValue = node.getFirstChild().getNodeValue();
	} else {
	  encodedValue = XML.text(node);
	}
	if (encodedValue.length() <= 0) {
	  return new byte[0];
	}
	return Base64.decode(encodedValue.getBytes());
}
 
Example #20
Source File: XMLRipperInput.java    From AndroidRipper with GNU Affero General Public License v3.0 5 votes vote down vote up
public ArrayList<ActivityDescription> loadActivityDescriptionList(InputStream is) {
	ArrayList<ActivityDescription> ret = new ArrayList<ActivityDescription>();
	
	NodeList nList = null;
	try {

		DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
		DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
		Document doc = dBuilder.parse(is);

		doc.getDocumentElement().normalize();

		nList = doc.getElementsByTagName(ACTIVITY);
		
		for (int i = 0; i < nList.getLength(); i++) {

			Node nNode = nList.item(i);

			if (nNode.getNodeType() == Node.ELEMENT_NODE) {
				Element eElement = (Element) nNode;
				ActivityDescription ad = this.inputActivityDescription(eElement);
				ret.add(ad);
			}
		}

	} catch (Exception e) {
		e.printStackTrace();
		//System.out.println(e.getMessage());
	}
	
	return ret;
}
 
Example #21
Source File: DOM2TO.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private String getNodeTypeFromCode(short code) {
    String retval = null;
    switch (code) {
    case Node.ATTRIBUTE_NODE :
        retval = "ATTRIBUTE_NODE"; break;
    case Node.CDATA_SECTION_NODE :
        retval = "CDATA_SECTION_NODE"; break;
    case Node.COMMENT_NODE :
        retval = "COMMENT_NODE"; break;
    case Node.DOCUMENT_FRAGMENT_NODE :
        retval = "DOCUMENT_FRAGMENT_NODE"; break;
    case Node.DOCUMENT_NODE :
        retval = "DOCUMENT_NODE"; break;
    case Node.DOCUMENT_TYPE_NODE :
        retval = "DOCUMENT_TYPE_NODE"; break;
    case Node.ELEMENT_NODE :
        retval = "ELEMENT_NODE"; break;
    case Node.ENTITY_NODE :
        retval = "ENTITY_NODE"; break;
    case Node.ENTITY_REFERENCE_NODE :
        retval = "ENTITY_REFERENCE_NODE"; break;
    case Node.NOTATION_NODE :
        retval = "NOTATION_NODE"; break;
    case Node.PROCESSING_INSTRUCTION_NODE :
        retval = "PROCESSING_INSTRUCTION_NODE"; break;
    case Node.TEXT_NODE:
        retval = "TEXT_NODE"; break;
    }
    return retval;
}
 
Example #22
Source File: BeanDefinitionParserDelegate.java    From blog_demos with Apache License 2.0 5 votes vote down vote up
/**
 * Parse a qualifier element.
 */
public void parseQualifierElement(Element ele, AbstractBeanDefinition bd) {
	String typeName = ele.getAttribute(TYPE_ATTRIBUTE);
	if (!StringUtils.hasLength(typeName)) {
		error("Tag 'qualifier' must have a 'type' attribute", ele);
		return;
	}
	this.parseState.push(new QualifierEntry(typeName));
	try {
		AutowireCandidateQualifier qualifier = new AutowireCandidateQualifier(typeName);
		qualifier.setSource(extractSource(ele));
		String value = ele.getAttribute(VALUE_ATTRIBUTE);
		if (StringUtils.hasLength(value)) {
			qualifier.setAttribute(AutowireCandidateQualifier.VALUE_KEY, value);
		}
		NodeList nl = ele.getChildNodes();
		for (int i = 0; i < nl.getLength(); i++) {
			Node node = nl.item(i);
			if (isCandidateElement(node) && nodeNameEquals(node, QUALIFIER_ATTRIBUTE_ELEMENT)) {
				Element attributeEle = (Element) node;
				String attributeName = attributeEle.getAttribute(KEY_ATTRIBUTE);
				String attributeValue = attributeEle.getAttribute(VALUE_ATTRIBUTE);
				if (StringUtils.hasLength(attributeName) && StringUtils.hasLength(attributeValue)) {
					BeanMetadataAttribute attribute = new BeanMetadataAttribute(attributeName, attributeValue);
					attribute.setSource(extractSource(attributeEle));
					qualifier.addMetadataAttribute(attribute);
				}
				else {
					error("Qualifier 'attribute' tag must have a 'name' and 'value'", attributeEle);
					return;
				}
			}
		}
		bd.addQualifier(qualifier);
	}
	finally {
		this.parseState.pop();
	}
}
 
Example #23
Source File: DOMKeyValue.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public void marshal(Node parent, String dsPrefix, DOMCryptoContext context)
    throws MarshalException
{
    Document ownerDoc = DOMUtils.getOwnerDocument(parent);

    // create KeyValue element
    Element kvElem = DOMUtils.createElement(ownerDoc, "KeyValue",
                                            XMLSignature.XMLNS, dsPrefix);
    marshalPublicKey(kvElem, ownerDoc, dsPrefix, context);

    parent.appendChild(kvElem);
}
 
Example #24
Source File: XteeSchemaCodePrinter.java    From j-road with Apache License 2.0 5 votes vote down vote up
private String findXteeTitle(SchemaProperty prop) throws IOException {
  String xteeTitle = null;
  try {
    String localPart = prop.getName().getLocalPart();
    Node propNode = ((SchemaTypeImpl) prop.getContainerType()).getParseObject().getDomNode();
    Node node = propNode;

    if (StringUtils.equals(localPart, "item") || StringUtils.equals(localPart, "all")) {
      while (true) {
        if (StringUtils.equals(node.getLocalName(), "element")) {
          localPart = node.getAttributes().getNamedItem("name").getNodeValue();
          break;
        }
        node = node.getParentNode();
        if (node == null) {
          node = findFirstNode(propNode.getChildNodes(), "element", localPart);
          break;
        }
      }
    } else {
      node = findFirstNode(node.getChildNodes(), "element", localPart);
    }
    if (node != null) {
      xteeTitle = clearString(getXmlObjectValue(findFirstNode(node.getChildNodes(), "title", null, false)));
      if (xteeTitle == null) {
        xteeTitle = StringUtils.capitalize(node.getAttributes().getNamedItem("name").getNodeValue());
      }
    }
  } catch (Exception e) {
    throw new IOException(e);
  }

  return xteeTitle;
}
 
Example #25
Source File: ZipFileMetaTest.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private Node getTestNode() throws KettleXMLException {
  String xml = "<step>" + Const.CR
    + "<name>Zip file</name>" + Const.CR
    + "<type>ZipFile</type>" + Const.CR
    + "<description/>" + Const.CR
    + "<distribute>Y</distribute>" + Const.CR
    + "<custom_distribution/>" + Const.CR
    + "<copies>1</copies>" + Const.CR
    + "<partitioning>" + Const.CR
    + "  <method>none</method>" + Const.CR
    + "  <schema_name/>" + Const.CR
    + "</partitioning>" + Const.CR
    + "<sourcefilenamefield>Files</sourcefilenamefield>" + Const.CR
    + "<targetfilenamefield>ZipFile</targetfilenamefield>" + Const.CR
    + "<baseFolderField>BaseFolder</baseFolderField>" + Const.CR
    + "<operation_type>move</operation_type>" + Const.CR
    + "<addresultfilenames>Y</addresultfilenames>" + Const.CR
    + "<overwritezipentry>Y</overwritezipentry>" + Const.CR
    + "<createparentfolder>Y</createparentfolder>" + Const.CR
    + "<keepsourcefolder>Y</keepsourcefolder>" + Const.CR
    + "<movetofolderfield/>" + Const.CR
    + "<cluster_schema/>" + Const.CR
    + "<remotesteps>" + Const.CR
    + "  <input></input>" + Const.CR
    + "  <output></output>" + Const.CR
    + "</remotesteps>" + Const.CR
    + "<GUI>" + Const.CR
    + "  <xloc>608</xloc>" + Const.CR
    + "  <yloc>48</yloc>" + Const.CR
    + "  <draw>Y</draw>" + Const.CR
    + "</GUI>" + Const.CR
    + "</step>" + Const.CR;
  return XMLHandler.loadXMLString( xml, "step" );
}
 
Example #26
Source File: DomViewerWindow.java    From LoboBrowser with MIT License 5 votes vote down vote up
private void addAttributes(final Node node) {
  final NamedNodeMap attributes = node.getAttributes();
  for (int i = 0; i < attributes.getLength(); i++) {
    final Node attr = attributes.item(i);
    textArea.append(" ");
    textArea.append(attr.getNodeName());
    textArea.append("=\"");
    textArea.append(attr.getNodeValue());
    textArea.append("\"");
  }
}
 
Example #27
Source File: XPathImpl.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private XObject eval(String expression, Object contextItem)
    throws javax.xml.transform.TransformerException {
    com.sun.org.apache.xpath.internal.XPath xpath = new com.sun.org.apache.xpath.internal.XPath( expression,
        null, prefixResolver, com.sun.org.apache.xpath.internal.XPath.SELECT );
    com.sun.org.apache.xpath.internal.XPathContext xpathSupport = null;
    if ( functionResolver != null ) {
        JAXPExtensionsProvider jep = new JAXPExtensionsProvider(
                functionResolver, featureSecureProcessing, featureManager );
        xpathSupport = new com.sun.org.apache.xpath.internal.XPathContext( jep );
    } else {
        xpathSupport = new com.sun.org.apache.xpath.internal.XPathContext();
    }

    XObject xobj = null;

    xpathSupport.setVarStack(new JAXPVariableStack(variableResolver));

    // If item is null, then we will create a a Dummy contextNode
    if ( contextItem instanceof Node ) {
        xobj = xpath.execute (xpathSupport, (Node)contextItem,
                prefixResolver );
    } else {
        xobj = xpath.execute ( xpathSupport, DTM.NULL, prefixResolver );
    }

    return xobj;
}
 
Example #28
Source File: XMLFile.java    From netbeans with Apache License 2.0 5 votes vote down vote up
protected final String getTextContent(String xpath) {
    Node node = getNode(xpath);
    if (node == null) {
        return null;
    }
    return node.getTextContent();
}
 
Example #29
Source File: SalesforceDeleteMeta.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private void readData( Node stepnode ) throws KettleXMLException {
  try {
    setDeleteField( XMLHandler.getTagValue( stepnode, "DeleteField" ) );

    setBatchSize( XMLHandler.getTagValue( stepnode, "batchSize" ) );
    setRollbackAllChangesOnError(
      "Y".equalsIgnoreCase( XMLHandler.getTagValue( stepnode, "rollbackAllChangesOnError" ) ) );
  } catch ( Exception e ) {
    throw new KettleXMLException( "Unable to load step info from XML", e );
  }
}
 
Example #30
Source File: JavaxXmlDeserializer.java    From attic-polygene-java with Apache License 2.0 5 votes vote down vote up
@Override
public <T> T fromXml( ModuleDescriptor module, ValueType valueType, Node state )
{
    Optional<Element> stateElement = JavaxXml.firstChildElementNamed( state, settings.getRootTagName() );
    if( stateElement.isPresent() )
    {
        Optional<Node> stateNode = JavaxXml.firstStateChildNode( stateElement.get() );
        return doDeserialize( module, valueType, stateNode.orElse( null ) );
    }
    return null;
}