<commit_before>package org.pentaho.ui.xul.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.dom4j.xpath.DefaultXPath;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulContainer;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.XulLoader;
import org.pentaho.ui.xul.dom.DocumentFactory;
import org.pentaho.ui.xul.dom.dom4j.DocumentDom4J;
import org.pentaho.ui.xul.dom.dom4j.ElementDom4J;
import org.pentaho.ui.xul.util.ResourceBundleTranslator;

public abstract class AbstractXulLoader implements XulLoader {

  protected XulParser parser;

  protected String rootDir = "/";

  protected Object outerContext = null;

  protected static final Log logger = LogFactory.getLog(AbstractXulLoader.class);

  private ResourceBundle mainBundle = null;
  
  private List<Object> resourceBundleList  = new ArrayList<Object>();

  private List<ClassLoader> classloaders = new ArrayList<ClassLoader>();
  {
    classloaders.add(this.getClass().getClassLoader());
  }
  
  public AbstractXulLoader() throws XulException {

    DocumentFactory.registerDOMClass(DocumentDom4J.class);
    DocumentFactory.registerElementClass(ElementDom4J.class);

    try {
      parser = new XulParser();
    } catch (Exception e) {
      throw new XulException("Error getting XulParser Instance, probably a DOM Factory problem: " + e.getMessage(), e);
    }

  }

  /* (non-Javadoc)
   * @see org.pentaho.ui.xul.XulLoader#loadXul(org.w3c.dom.Document)
   */
  public XulDomContainer loadXul(Object xulDocument) throws IllegalArgumentException, XulException {
    Document document = (Document)xulDocument;
    try {
      xulDocument = preProcess((Document)xulDocument);

      String processedDoc = performIncludeTranslations(document.asXML());
      String localOutput = (mainBundle != null) ? ResourceBundleTranslator.translate(processedDoc, mainBundle)
          : processedDoc;
      
      SAXReader rdr = new SAXReader();
      //localOutput = localOutput.replace("UTF-8", "ISO-8859-1");
      

//      System.out.println("============ Post Processed: ============");
//      System.out.println(localOutput);
//      System.out.println("============ End Post Processed: ============");
      
      
      final Document doc = rdr.read(new StringReader(localOutput));

//      System.out.println("============ After Parse: ============");
//      System.out.println(doc.asXML());
//      System.out.println("============ After Parse: ============");
      
      
      XulDomContainer container = new XulWindowContainer(this);
      container.setOuterContext(outerContext);
      container.setResourceBundles(this.resourceBundleList);
      parser.setContainer(container);
      parser.parseDocument(doc.getRootElement());

      return container;

    } catch (Exception e) {
      throw new XulException(e);
    }
  }

  public void setRootDir(String loc) {
    if(!rootDir.equals("/")){      //lets only set this once
      return;
    }
    if (loc.lastIndexOf("/") > 0 && loc.indexOf(".xul") > -1) { //exists and not first char
      rootDir = loc.substring(0, loc.lastIndexOf("/") + 1);
    } else {
      rootDir = loc;
      if (!(loc.lastIndexOf('/') == loc.length())) { //no trailing slash, add it
        rootDir = rootDir + "/";
      }
    }
  }

  /* (non-Javadoc)
   * @see org.pentaho.ui.xul.XulLoader#loadXulFragment(org.dom4j.Document)
   */
  public XulDomContainer loadXulFragment(Object xulDocument) throws IllegalArgumentException, XulException {
    Document document = (Document)xulDocument;
    XulDomContainer container = new XulFragmentContainer(this);
    container.setResourceBundles(this.resourceBundleList);
    container.setOuterContext(outerContext);

    parser.reset();
    parser.setContainer(container);
    parser.parseDocument(document.getRootElement());

    return container;
  }

  public XulComponent createElement(String elementName) throws XulException {
    return parser.getElement(elementName);
  }

  public XulDomContainer loadXul(String resource) throws IllegalArgumentException, XulException {

    Document doc = findDocument(resource);

    setRootDir(resource);

    String resStr = resource.replace(".xul", "");
    ResourceBundle res;
    try {
      res = ResourceBundle.getBundle(resStr);
    } catch (MissingResourceException e) {
      
      URL url = null;
      try{
        url = new File(".").toURL();
      } catch(MalformedURLException ex){}
      URLClassLoader cls = URLClassLoader.newInstance(new URL[]{url});
      try{
        res = ResourceBundle.getBundle(resStr, Locale.getDefault(), cls);<commit_msg>[PDI-2840] Classpath additions passed on to container<commit_after>package org.pentaho.ui.xul.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;
import org.dom4j.xpath.DefaultXPath;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulContainer;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.XulLoader;
import org.pentaho.ui.xul.dom.DocumentFactory;
import org.pentaho.ui.xul.dom.dom4j.DocumentDom4J;
import org.pentaho.ui.xul.dom.dom4j.ElementDom4J;
import org.pentaho.ui.xul.util.ResourceBundleTranslator;

public abstract class AbstractXulLoader implements XulLoader {

  protected XulParser parser;

  protected String rootDir = "/";

  protected Object outerContext = null;

  protected static final Log logger = LogFactory.getLog(AbstractXulLoader.class);

  private ResourceBundle mainBundle = null;
  
  private List<Object> resourceBundleList  = new ArrayList<Object>();

  private List<ClassLoader> classloaders = new ArrayList<ClassLoader>();
  {
    classloaders.add(this.getClass().getClassLoader());
  }
  
  public AbstractXulLoader() throws XulException {

    DocumentFactory.registerDOMClass(DocumentDom4J.class);
    DocumentFactory.registerElementClass(ElementDom4J.class);

    try {
      parser = new XulParser();
    } catch (Exception e) {
      throw new XulException("Error getting XulParser Instance, probably a DOM Factory problem: " + e.getMessage(), e);
    }

  }

  /* (non-Javadoc)
   * @see org.pentaho.ui.xul.XulLoader#loadXul(org.w3c.dom.Document)
   */
  public XulDomContainer loadXul(Object xulDocument) throws IllegalArgumentException, XulException {
    Document document = (Document)xulDocument;
    try {
      xulDocument = preProcess((Document)xulDocument);

      String processedDoc = performIncludeTranslations(document.asXML());
      String localOutput = (mainBundle != null) ? ResourceBundleTranslator.translate(processedDoc, mainBundle)
          : processedDoc;
      
      SAXReader rdr = new SAXReader();
      //localOutput = localOutput.replace("UTF-8", "ISO-8859-1");
      

//      System.out.println("============ Post Processed: ============");
//      System.out.println(localOutput);
//      System.out.println("============ End Post Processed: ============");
      
      
      final Document doc = rdr.read(new StringReader(localOutput));

//      System.out.println("============ After Parse: ============");
//      System.out.println(doc.asXML());
//      System.out.println("============ After Parse: ============");
      
      
      XulDomContainer container = new XulWindowContainer(this);
      container.setOuterContext(outerContext);
      container.setResourceBundles(this.resourceBundleList);
      parser.setContainer(container);
      parser.parseDocument(doc.getRootElement());

      for(ClassLoader l : classloaders){
        container.registerClassLoader(l);
      }
      return container;

    } catch (Exception e) {
      throw new XulException(e);
    }
  }

  public void setRootDir(String loc) {
    if(!rootDir.equals("/")){      //lets only set this once
      return;
    }
    if (loc.lastIndexOf("/") > 0 && loc.indexOf(".xul") > -1) { //exists and not first char
      rootDir = loc.substring(0, loc.lastIndexOf("/") + 1);
    } else {
      rootDir = loc;
      if (!(loc.lastIndexOf('/') == loc.length())) { //no trailing slash, add it
        rootDir = rootDir + "/";
      }
    }
  }

  /* (non-Javadoc)
   * @see org.pentaho.ui.xul.XulLoader#loadXulFragment(org.dom4j.Document)
   */
  public XulDomContainer loadXulFragment(Object xulDocument) throws IllegalArgumentException, XulException {
    Document document = (Document)xulDocument;
    XulDomContainer container = new XulFragmentContainer(this);
    container.setResourceBundles(this.resourceBundleList);
    container.setOuterContext(outerContext);

    parser.reset();
    parser.setContainer(container);
    parser.parseDocument(document.getRootElement());

    return container;
  }

  public XulComponent createElement(String elementName) throws XulException {
    return parser.getElement(elementName);
  }

  public XulDomContainer loadXul(String resource) throws IllegalArgumentException, XulException {

    Document doc = findDocument(resource);

    setRootDir(resource);

    String resStr = resource.replace(".xul", "");
    ResourceBundle res = null;
    for(ClassLoader cl : classloaders){
      try {
        res = ResourceBundle.getBundle(resStr, Locale.getDefault(), cl);
        if(res != null){
          break;
        }
      } catch (MissingResourceException e) {}
    }
    if(res == null){
      URL url = null;
      try{
        url = new File(".").toURL();
      } catch(MalformedURLException ex){}
      URLClassLoader cls = URLClassLoader.newInstance(new URL[]{url});
      try{
        res = ResourceBundle.getBundle(resStr, Locale.getDefault(), cls);
{'fraction_non_alphanumeric': 0.13134913562644804, 'fraction_numerical': 0.004811976474781679, 'mean_word_length': 3.8668690372940158, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3633743', 'n_tokens_mistral': 3399, 'n_tokens_neox': 3333, 'n_words': 656}