//
// DataMapProperties.java - Use mappings from properties
//

package nyangau.jmsadapter;

//...simports:0:
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
import java.util.Properties;
import java.util.Enumeration;
import java.io.InputStream;
import java.io.IOException;
import java.net.URL;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
//...e

public class DataMapProperties extends DataMap
  {
  protected String props;
  protected String xml;
//...sDataMapProperties:2:
public DataMapProperties(Node eDataMap)
  throws FlowProcessorException
  {
  super(eDataMap);
  NamedNodeMap nnmDataMap = eDataMap.getAttributes();
  Node aProps = nnmDataMap.getNamedItem("properties");
  props = ( aProps != null ) ? aProps.getNodeValue() : null;
  Node aXml = nnmDataMap.getNamedItem("xml");
  xml = ( aXml != null ) ? aXml.getNodeValue() : null;
  }
//...e
//...smap:2:
//...saddMaplets:2:
// I thought I could do one of
//   mapped.putAll(p);
//   mapped.putAll((Map<String,String>)p);
// but the type mechanism causes compiler errors.
// I even have problems trying to use Enumeration<String>.

protected void addMaplets(Map<String,String> mapped, Properties p)
  {
  for ( Enumeration ep = p.propertyNames(); ep.hasMoreElements(); )
    {
    String n = (String) ep.nextElement();
    mapped.put(n, p.getProperty(n));
    }
  }
//...e

public void map(Set<String> unmapped, Map<String,String> mapped)
  throws FlowProcessorException
  {
  // Read properties file
  if ( props != null )
    {
    Properties p = new Properties();
    try
      {
      InputStream is = new URL(props).openStream();
      p.load(is);
      }
    catch ( IOException e )
      {
      throw new FlowProcessorException("can't fetch properties from "+props, e);
      }
    addMaplets(mapped, p);
    }

  // Read XML properties file
  if ( xml != null )
    {
    Properties p = new Properties();
    try
      {
      InputStream is = new URL(xml).openStream();
      p.loadFromXML(is);
      }
    catch ( IOException e )
      {
      throw new FlowProcessorException("can't fetch XML properties from "+xml, e);
      }
    addMaplets(mapped, p);
    }

  if ( unmapped.size() < mapped.size() )
    {
    for ( String s : unmapped )
      if ( mapped.get(s) != null )
        unmapped.remove(s);
    }
  else
    for ( String s : mapped.keySet() )
      unmapped.remove(s);
  }
//...e
  }
