All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.spun.util.io.xml.XmlTranslator Maven / Gradle / Ivy

There is a newer version: 24.9.0
Show newest version
package com.spun.util.io.xml;

import com.spun.util.ObjectUtils;
import org.w3c.dom.Node;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map.Entry;

public class XmlTranslator
{
  private HashMap extractors = new HashMap();
  private HashMap       setters    = new HashMap();
  public XmlTranslator(XmlMap[] maps)
  {
    for (int i = 0; i < maps.length; i++)
    {
      String nodeName = maps[i].getNodeName();
      extractors.put(nodeName, maps[i].getExtractor());
      setters.put(nodeName, maps[i].getSettingMethod());
    }
  }
  public Object extractAndTranslateForNode(Node node, Object addToObject)
  {
    String name = node.getNodeName();
    Method method = (Method) setters.get(name);
    XmlExtractor extractor = (XmlExtractor) extractors.get(name);
    if (extractor == null)
    { throw new Error("No Extractor Found for Node '" + getNamePath(node) + "'"); }
    Object o = extractor.extractObjectForNode(node);
    this.setObject(o, addToObject, method);
    return o;
  }
  private static String getNamePath(Node node)
  {
    StringBuffer buffer = new StringBuffer(node.getNodeName());
    while (node.getParentNode() != null)
    {
      node = node.getParentNode();
      buffer.insert(0, node.getNodeName() + ".");
    }
    return buffer.toString();
  }
  private void setObject(Object o, Object addToObject, Method settingMethod)
  {
    try
    {
      settingMethod.invoke(addToObject, new Object[]{o});
    }
    catch (Exception e)
    {
      throw ObjectUtils.throwAsError(e);
    }
  }
  public String toString()
  {
    StringBuffer out = new StringBuffer();
    for (Entry entry : extractors.entrySet())
    {
      String key = entry.getKey();
      XmlExtractor value = entry.getValue();
      out.append(String.format("%s => %s\n", key, value));
    }
    return out.toString();
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy