htmlunit-2.7

aces_ = new NamespaceCollection(this);
    }
    return namespaces_;
  }
  
  public Object jsxGet_anchors()
  {
    if (anchors_ == null)
    {
      anchors_ = new HTMLCollection(this);
      String xpath;
      String xpath;
      if (getBrowserVersion().isIE()) {
        xpath = ".//a[@name or @id]";
      } else {
        xpath = ".//a[@name]";
      }
      anchors_.init(getDomNodeOrDie(), xpath);
    }
    return anchors_;
  }
  
  public Object jsxGet_applets()
  {
    if (applets_ == null)
    {
      applets_ = new HTMLCollection(this);
      applets_.init(getDomNodeOrDie(), ".//applet");
    }
    return applets_;
  }
  
  public static void jsxFunction_write(Context context, Scriptable thisObj, Object[] args, Function function)
  {
    HTMLDocument thisAsDocument = getDocument(thisObj);
    thisAsDocument.write(concatArgsAsString(args));
  }
  
  private static String concatArgsAsString(Object[] args)
  {
    StringBuilder buffer = new StringBuilder();
    for (Object arg : args) {
      buffer.append(Context.toString(arg));
    }
    return buffer.toString();
  }
  
  public static void jsxFunction_writeln(Context context, Scriptable thisObj, Object[] args, Function function)
  {
    HTMLDocument thisAsDocument = getDocument(thisObj);
    thisAsDocument.write(concatArgsAsString(args) + "\n");
  }
  
  private static HTMLDocument getDocument(Scriptable thisObj)
  {
    if (((thisObj instanceof HTMLDocument)) && ((thisObj.getPrototype() instanceof HTMLDocument))) {
      return (HTMLDocument)thisObj;
    }
    Window window = getWindow(thisObj);
    BrowserVersion browser = window.getWebWindow().getWebClient().getBrowserVersion();
    if (browser.isIE()) {
      return window.jsxGet_document();
    }
    throw Context.reportRuntimeError("Function can't be used detached from document");
  }
  
  protected void write(String content)
  {
    LOG.debug("write: " + content);
    
    HtmlPage page = (HtmlPage)getDomNodeOrDie();
    if (!page.isBeingParsed()) {
      writeInCurrentDocument_ = false;
    }
    writeBuffer_.append(content);
    if (!writeInCurrentDocument_)
    {
      LOG.debug("wrote content to buffer");
      scheduleImplicitClose();
      return;
    }
    String bufferedContent = writeBuffer_.toString();
    if (!canAlreadyBeParsed(bufferedContent))
    {
      LOG.debug("write: not enough content to parse it now");
      return;
    }
    writeBuffer_.setLength(0);
    page.writeInParsedStream(bufferedContent.toString());
  }
  
  private void scheduleImplicitClose()
  {
    if (!closePostponedAction_)
    {
      closePostponedAction_ = true;
      HtmlPage page = (HtmlPage)getDomNodeOrDie();
      page.getWebClient().getJavaScriptEngine().addPostponedAction(new PostponedAction(page)
      {
        public void execute()
          throws Exception
        {
          if (writeBuffer_.length() > 0) {
            jsxFunction_close();
          }
          closePostponedAction_ = false;
        }
      });
    }
  }
  
  private static enum PARSING_STATUS
  {
    OUTSIDE,  START,  IN_NAME,  INSIDE,  IN_STRING;
    
    private PARSING_STATUS() {}
  }
  
  private static boolean canAlreadyBeParsed(String content)
  {
    PARSING_STATUS tagState = PARSING_STATUS.OUTSIDE;
    int tagNameBeginIndex = 0;
    int scriptTagCount = 0;
    boolean tagIsOpen = true;
    char stringBoundary = '\000';
    boolean stringSkipNextChar = false;
    int index = 0;
    for (char currentChar : content.toCharArray())
    {
      switch (tagState)
      {
      case OUTSIDE: 
        if (currentChar == '<')
        {
          tagState = PARSING_STATUS.START;
          tagIsOpen = true;
        }
        else if ((currentChar == '\'') || (currentChar == '"'))
        {
          tagState = PARSING_STATUS.IN_STRING;
          stringBoundary = currentChar;
          stringSkipNextChar = false;
        }
        break;
      case START: 
        if (currentChar == '/')
        {
          tagIsOpen = false;
          tagNameBeginIndex = index + 1;
        }
        else
        {
          tagNameBeginIndex = index;
        }
        tagState = PARSING_STATUS.IN_NAME;
        break;
      case IN_NAME: 
        if ((Character.isWhitespace(currentChar)) || (currentChar == '>'))
        {
          String tagName = content.substring(tagNameBeginIndex, index);
          if (tagName.equalsIgnoreCase("script")) {
            if (tagIsOpen) {
              scriptTagCount++;
            } else if (scriptTagCount > 0) {
              scriptTagCount--;
            }
          }
          if (currentChar == '>') {
            tagState = PARSING_STATUS.OUTSIDE;
          } else {
            tagState = PARSING_STATUS.INSIDE;
          }
        }
        else if (!Character.isLetter(currentChar))
        {
          tagState = PARSING_STATUS.OUTSIDE;
        }
        break;
      case INSIDE: 
        if (currentChar == '>') {
          tagState = PARSING_STATUS.OUTSIDE;
        }
        break;
      case IN_STRING: 
        if (stringSkipNextChar) {
          stringSkipNextChar = false;
        } else if (currentChar == stringBoundary) {
          tagState = PARSING_STATUS.OUTSIDE;
        } else if (currentChar == '\\') {
          stringSkipNextChar = true;
        }
        break;
      }
      index++;
    }
    if ((scriptTagCount > 0) || (tagState != PARSING_STATUS.OUTSIDE)) {
      return false;
    }
    return true;
  }
  
  HtmlElement getLastHtmlElement(HtmlElement node)
  {
    DomNode lastChild = node.getLastChild();
    if ((lastChild == null) || (!(lastChild instanceof HtmlElement)) || ((lastChild instanceof HtmlScript))) {
      return node;
    }
    return getLastHtmlElement((HtmlElement)lastChild);
  }
  
  public String jsxGet_cookie()
  {
    HtmlPage page = getHtmlPage();
    
    URL url = page.getWebResponse().getRequestSettings().getUrl();
    url = replaceForCookieIfNecessary(url);
    
    StringBuilder buffer = new StringBuilder();
    Set<Cookie> cookies = page.getWebClient().getCookieManager().getCookies(url);
    for (Cookie cookie : cookies)
    {
      if (buffer.length() != 0) {
        buffer.append("; ");
      }
      if (!"HTMLUNIT_EMPTY_COOKIE".equals(cookie.getName()))
      {
        buffer.append(cookie.getName());
        buffer.append("=");
      }
      if (cookie.getValue().contains(" ")) {
        buffer.append('"');
      }
      buffer.append(cookie.getValue());
      if (cookie.getValue().contains(" ")) {
        buffer.append('"');
      }
    }
    return buffer.toString();
  }
  
  public String jsxGet_compatMode()
  {
    boolean strict = false;
    DocumentType docType = getPage().getDoctype();
    if (docType != null)
    {
      String publicId = docType.getPublicId();
      String systemId = docType.getSystemId();
      if (systemId != null) {
        if (systemId.equals("http://www.w3.org/TR/html4/strict.dtd")) {
          strict = true;
        } else if (systemId.equals("http://www.w3.org/TR/html4/loose.dtd"))
        {
          if ((publicId.equals("-//W3C//DTD HTML 4.01 Transitional//EN")) || ((publicId.equals("-//W3C//DTD HTML 4.0 Transitional//EN")) && (getBrowserVersion().isIE()))) {
            strict = true;
          }
        }
        else if ((systemId.equals("http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd")) || (systemId.equals("http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"))) {
          strict = true;
        }
      }
    }
    if (strict) {
      return "CSS1Compat";
    }
    return "BackCompat";
  }
  
  public void jsxSet_cookie(String newCookie)
  {
    CookieManager cookieManager = getHtmlPage().getWebClient().getCookieManager();
    if (cookieManager.isCookiesEnabled())
    {
      URL url = getHtmlPage().getWebResponse().getRequestSettings().getUrl();
      url = replaceForCookieIfNecessary(url);
      Cookie cookie = buildCookie(newCookie, url);
      cookieManager.addCookie(cookie);
      LOG.debug("Added cookie: " + cookie);
    }
    else
    {
      LOG.debug("Skipped adding cookie: " + newCookie);
    }
  }
  
  private static URL replaceForCookieIfNecessary(URL url)
  {
    String protocol = url.getProtocol();
    boolean file = "file".equals(protocol);
    if (file) {
      try
      {
        url = UrlUtils.getUrlWithNewPort(UrlUtils.getUrlWithNewHost(url, "LOCAL_FILESYSTEM"), 0);
      }
      catch (MalformedURLException e)
      {
        throw new RuntimeException(e);
      }
    }
    return url;
  }
  
  public static Cookie buildCookie(String newCookie, URL currentURL)
  {
    StringTokenizer st = new StringTokenizer(newCookie, ";");
    String value;
    String name;
    String value;
    if (newCookie.contains("="))
    {
      String nameAndValue = st.nextToken();
      String name = org.apache.commons.lang.StringUtils.substringBefore(nameAndValue, "=").trim();
      value = org.apache.commons.lang.StringUtils.substringAfter(nameAndValue, "=").trim();
    }
    else
    {
      name = "HTMLUNIT_EMPTY_COOKIE";
      value = newCookie;
    }
    Map<String, Object> atts = new HashMap();
    atts.put("domain", currentURL.getHost());
    atts.put("path", "");
    while (st.hasMoreTokens())
    {
      String token = st.nextToken();
      int indexEqual = token.indexOf("=");
      if (indexEqual > -1) {
        atts.put(token.substring(0, indexEqual).toLowerCase().trim(), token.substring(indexEqual + 1).trim());
      } else {
        atts.put(token.toLowerCase().trim(), Boolean.TRUE);
      }
    }
    String date = (String)atts.get("expires");
    Date expires = com.gargoylesoftware.htmlunit.util.StringUtils.parseHttpDate(date);
    
    String domain = (String)atts.get("domain");
    String path = (String)atts.get("path");
    boolean secure = atts.get("secure") != null;
    Cookie cookie = new Cookie(domain, name, value, path, expires, secure);
    
    return cookie;
  }
  
  public Object jsxGet_images()
  {
    if (images_ == null)
    {
      images_ = new HTMLCollection(this);
      images_.init(getDomNodeOrDie(), ".//img");
    }
    return images_;
  }
  
  public String jsxGet_URL()
  {
    return getHtmlPage().getWebResponse().getRequestSettings().getUrl().toExternalForm();
  }
  
  public String jsxGet_uniqueID()
  {
    if (uniqueID_ == null) {
      uniqueID_ = ("ms__id" + UniqueID_Counter_++);
    }
    return uniqueID_;
  }
  
  public HTMLCollection jsxGet_all()
  {
    if (all_ == null)
    {
      all_ = new HTMLCollectionTags(this);
      all_.setAvoidObjectDetection(!getBrowserVersion().isIE());
      all_.init(getDomNodeOrDie(), ".//*");
    }
    return all_;
  }
  
  public Object jsxFunction_open(String url, Object name, Object features, Object replace)
  {
    HtmlPage page = getHtmlPage();
    if (page.isBeingParsed())
    {
      LOG.warn("Ignoring call to open() during the parsing stage.");
      return null;
    }
    if (!writeInCurrentDocument_) {
      LOG.warn("Function open() called when document is already open.");
    }
    writeInCurrentDocument_ = false;
    return null;
  }
  
  public void jsxFunction_close()
    throws IOException
  {
    if (writeInCurrentDocument_)
    {
      LOG.warn("close() called when document is not open.");
    }
    else
    {
      HtmlPage page = getHtmlPage();
      URL url = page.getWebResponse().getRequestSettings().getUrl();
      WebResponse webResponse = new StringWebResponse(writeBuffer_.toString(), url);
      WebClient webClient = page.getWebClient();
      WebWindow window = page.getEnclosingWindow();
      
      webClient.loadWebResponseInto(webResponse, window);
      
      writeInCurrentDocument_ = true;
      writeBuffer_.setLength(0);
    }
  }
  
  private void implicitCloseIfNecessary()
  {
    boolean ie = getBrowserVersion().isIE();
    if ((!writeInCurrentDocument_) && (ie)) {
      try
      {
        jsxFunction_close();
      }
      catch (IOException e)
      {
        throw Context.throwAsScriptRuntimeEx(e);
      }
    }
  }
  
  public Object jsxGet_parentWindow()
  {
    return getWindow();
  }
  
  public Object jsxFunction_appendChild(Object childObject)
  {
    if ((limitAppendChildToIE()) && (!getBrowserVersion().isIE())) {
      throw Context.reportRuntimeError("Node cannot be inserted at the specified point in the hierarchy.");
    }
    return super.jsxFunction_appendChild(childObject);
  }
  
  protected boolean limitAppendChildToIE()
  {
    return true;
  }
  
  public Object jsxFunction_createElement(String tagName)
  {
    Object result = NOT_FOUND;
    if ((tagName.startsWith("<")) && (getBrowserVersion().isIE()))
    {
      Pattern p = Pattern.compile("<(\\w+)(\\s+[^>]*)?>");
      Matcher m = p.matcher(tagName);
      if (m.find())
      {
        tagName = m.group(1);
        result = super.jsxFunction_createElement(tagName);
        if ((result == NOT_FOUND) || (m.group(2) == null)) {
          return result;
        }
        HTMLElement elt = (HTMLElement)result;
        
        String attributes = m.group(2);
        Pattern pAttributes = Pattern.compile("(\\w+)\\s*=\\s*['\"]([^'\"]*)['\"]");
        Matcher mAttribute = pAttributes.matcher(attributes);
        while (mAttribute.find())
        {
          String attrName = mAttribute.group(1);
          String attrValue = mAttribute.group(2);
          elt.jsxFunction_setAttribute(attrName, attrValue);
        }
      }
    }
    else
    {
      return super.jsxFunction_createElement(tagName);
    }
    return result;
  }
  
  public Stylesheet jsxFunction_createStyleSheet(String url, int index)
  {
    Stylesheet stylesheet = new Stylesheet();
    stylesheet.setPrototype(getPrototype(Stylesheet.class));
    stylesheet.setParentScope(getWindow());
    return stylesheet;
  }
  
  public Object jsxFunction_getElementById(String id)
  {
    implicitCloseIfNecessary();
    Object result = null;
    try
    {
      boolean caseSensitive = getBrowserVersion().isFirefox();
      HtmlElement htmlElement = ((HtmlPage)getDomNodeOrDie()).getHtmlElementById(id, caseSensitive);
      Object jsElement = getScriptableFor(htmlElement);
      if (jsElement == NOT_FOUND) {
        LOG.debug("getElementById(" + id + ") cannot return a result as there isn't a JavaScript object for the HTML element " + htmlElement.getClass().getName());
      } else {
        result = jsElement;
      }
    }
    catch (ElementNotFoundException e)
    {
      BrowserVersion browser = getBrowserVersion();
      if (browser.isIE())
      {
        HTMLCollection elements = jsxFunction_getElementsByName(id);
        result = elements.get(0, elements);
        if ((result instanceof UniqueTag)) {
          return null;
        }
        LOG.warn("getElementById(" + id + ") did a getElementByName for Internet Explorer");
        return result;
      }
      LOG.debug("getElementById(" + id + "): no DOM node found with this id");
    }
    return result;
  }
  
  public HTMLCollection jsxFunction_getElementsByClassName(String className)
  {
    return ((HTMLElement)jsxGet_documentElement()).jsxFunction_getElementsByClassName(className);
  }
  
  public HTMLCollection jsxFunction_getElementsByName(String elementName)
  {
    implicitCloseIfNecessary();
    HTMLCollection collection = new HTMLCollection(this);
    String exp = ".//*[@name='" + elementName + "']";
    collection.init(getDomNodeOrDie(), exp);
    return collection;
  }
  
  protected Object getWithPreemption(String name)
  {
    HtmlPage page = (HtmlPage)getDomNodeOrNull();
    if ((page == null) || (getBrowserVersion().isFirefox())) {
      return NOT_FOUND;
    }
    return getIt(name);
  }
  
  private Object getIt(String name)
  {
    HtmlPage page = (HtmlPage)getDomNodeOrNull();
    List<HtmlElement> elements;
    List<HtmlElement> elements;
    if (getBrowserVersion().isIE()) {
      elements = page.getElementsByIdAndOrName(name);
    } else {
      elements = page.getElementsByName(name);
    }
    if (elements.isEmpty()) {
      return NOT_FOUND;
    }
    if (elements.size() == 1)
    {
      HtmlElement element = (HtmlElement)elements.get(0);
      String tagName = element.getTagName();
      if (("img".equals(tagName)) || ("form".equals(tagName)) || ("applet".equals(tagName))) {
        return getScriptableFor(element);
      }
      if ((getBrowserVersion().isIE()) && ((element instanceof BaseFrame))) {
        return ((BaseFrame)element).getEnclosedWindow().getScriptObject();
      }
      return NOT_FOUND;
    }
    HTMLCollection collection = new HTMLCollection(this);
    String xpath = ".//*[(@name = '" + name + "' and (name() = 'img' or name() = 'form'))]";
    collection.init(page, xpath);
    int size = collection.jsxGet_length();
    if (size == 1) {
      return collection.get(0, collection);
    }
    if (size > 1) {
      return collection;
    }
    return NOT_FOUND;
  }
  
  public Object getWithFallback(String name)
  {
    if (getBrowserVersion().isFirefox()) {
      return getIt(name);
    }
    return NOT_FOUND;
  }
  
  public Object jsxGet_body()
  {
    HtmlPage page = getHtmlPage();
    if ((getBrowserVersion().isIE()) && ((page.getEnclosingWindow() instanceof FrameWindow)))
    {
      HtmlPage enclosingPage = (HtmlPage)page.getEnclosingWindow().getParentWindow().getEnclosedPage();
      if ((WebClient.URL_ABOUT_BLANK.equals(page.getWebResponse().getRequestSettings().getUrl())) && (enclosingPage.getReadyState() != "complete")) {
        return null;
      }
    }
    HtmlElement body = getHtmlPage().getBody();
    if (body != null) {
      return body.getScriptObject();
    }
    return null;
  }
  
  public String jsxGet_title()
  {
    return getHtmlPage().getTitleText();
  }
  
  public void jsxSet_title(String title)
  {
    getHtmlPage().setTitleText(title);
  }
  
  public String jsxGet_bgColor()
  {
    String bgColor = getHtmlPage().getBody().getAttribute("bgColor");
    if (bgColor == DomElement.ATTRIBUTE_NOT_DEFINED) {
      bgColor = "#ffffff";
    }
    return bgColor;
  }
  
  public void jsxSet_bgColor(String bgColor)
  {
    HTMLBodyElement body = (HTMLBodyElement)getHtmlPage().getBody().getScriptObject();
    body.jsxSet_bgColor(bgColor);
  }
  
  public String jsxGet_readyState()
  {
    DomNode node = getDomNodeOrDie();
    return node.getReadyState();
  }
  
  public String jsxGet_domain()
  {
    if (domain_ == null)
    {
      URL url = getHtmlPage().getWebResponse().getRequestSettings().getUrl();
      if (url == WebClient.URL_ABOUT_BLANK)
      {
        WebWindow w = getWindow().getWebWindow();
        if ((w instanceof FrameWindow)) {
          url = ((FrameWindow)w).getEnclosingPage().getWebResponse().getRequestSettings().getUrl();
        } else {
          return null;
        }
      }
      domain_ = url.getHost();
      BrowserVersion browser = getBrowserVersion();
      if (browser.isFirefox()) {
        domain_ = domain_.toLowerCase();
      }
    }
    return domain_;
  }
  
  public void jsxSet_domain(String newDomain)
  {
    BrowserVersion browserVersion = getBrowserVersion();
    if ((WebClient.URL_ABOUT_BLANK == getPage().getWebResponse().getRequestSettings().getUrl()) && (browserVersion.isIE())) {
      throw Context.reportRuntimeError("Illegal domain value, cannot set domain from about:blank to: \"" + newDomain + "\"");
    }
    String currentDomain = jsxGet_domain();
    if (currentDomain.equalsIgnoreCase(newDomain)) {
      return;
    }
    if ((newDomain.indexOf(".") == -1) || (!currentDomain.toLowerCase().endsWith("." + newDomain.toLowerCase()))) {
      throw Context.reportRuntimeError("Illegal domain value, cannot set domain from: \"" + currentDomain + "\" to: \"" + newDomain + "\"");
    }
    if (getBrowserVersion().isFirefox()) {
      domain_ = newDomain.toLowerCase();
    } else {
      domain_ = newDomain;
    }
  }
  
  public Object jsxGet_scripts()
  {
    if (scripts_ == null)
    {
      scripts_ = new HTMLCollection(this);
      scripts_.init(getDomNodeOrDie(), ".//script");
    }
    return scripts_;
  }
  
  public Selection jsxGet_selection()
  {
    return getWindow().getSelection();
  }
  
  public Object jsxGet_frames()
  {
    return getWindow().jsxGet_frames();
  }
  
  public StyleSheetList jsxGet_styleSheets()
  {
    if (styleSheets_ == null) {
      styleSheets_ = new StyleSheetList(this);
    }
    return styleSheets_;
  }
  
  public Event jsxFunction_createEvent(String eventType)
    throws DOMException
  {
    Class<? extends Event> clazz = (Class)SUPPORTED_EVENT_TYPE_MAP.get(eventType);
    if (clazz == null) {
      Context.throwAsScriptRuntimeEx(new DOMException((short)9, "Event Type is not supported: " + eventType));
    }
    try
    {
      Event event = (Event)clazz.newInstance();
      if (getBrowserVersion().hasFeature(BrowserVersionFeatures.CREATEEVENT_INITALIZES_TARGET)) {
        event.setTarget(this);
      }
      event.setEventType(eventType);
      event.setParentScope(getWindow());
      event.setPrototype(getPrototype(clazz));
      return event;
    }
    catch (InstantiationException e)
    {
      throw Context.reportRuntimeError("Failed to instantiate event: class ='" + clazz.getName() + "' for event type of '" + eventType + "': " + e.getMessage());
    }
    catch (IllegalAccessException e)
    {
      throw Context.reportRuntimeError("Failed to instantiate event: class ='" + clazz.getName() + "' for event type of '" + eventType + "': " + e.getMessage());
    }
  }
  
  public Event jsxFunction_createEventObject()
  {
    Event event = new MouseEvent();
    event.setParentScope(getWindow());
    event.setPrototype(getPrototype(event.getClass()));
    return event;
  }
  
  public Object jsxFunction_elementFromPoint(int x, int y)
  {
    if ((getBrowserVersion().isFirefox()) && ((x <= 0) || (y <= 0))) {
      return null;
    }
    return jsxGet_body();
  }
  
  public Range jsxFunction_createRange()
  {
    Range r = new Range(this);
    r.setParentScope(getWindow());
    r.setPrototype(getPrototype(Range.class));
    return r;
  }
  
  public Object jsxFunction_createTreeWalker(Node root, int whatToShow, final Scriptable filter, boolean expandEntityReferences)
    throws DOMException
  {
    NodeFilter filterWrapper = null;
    if (filter != null) {
      filterWrapper = new NodeFilter()
      {
        private static final long serialVersionUID = -7572357836681155579L;
        
        public short acceptNode(Node n)
        {
          Object[] args = { n };
          Object response;
          Object response;
          if ((filter instanceof Callable)) {
            response = ((Callable)filter).call(Context.getCurrentContext(), filter, filter, args);
          } else {
            response = ScriptableObject.callMethod(filter, "acceptNode", args);
          }
          return (short)(int)Context.toNumber(response);
        }
      };
    }
    TreeWalker t = new TreeWalker(root, whatToShow, filterWrapper, Boolean.valueOf(expandEntityReferences));
    t.setParentScope(getWindow(this));
    t.setPrototype(staticGetPrototype(getWindow(this), TreeWalker.class));
    return t;
  }
  
  private static Scriptable staticGetPrototype(Window window, Class<? extends SimpleScriptable> javaScriptClass)
  {
    Scriptable prototype = window.getPrototype(javaScriptClass);
    if ((prototype == null) && (javaScriptClass != SimpleScriptable.class)) {
      return staticGetPrototype(window, javaScriptClass.getSuperclass());
    }
    return prototype;
  }
  
  public boolean jsxFunction_queryCommandSupported(String cmd)
  {
    boolean ff = getBrowserVersion().isFirefox();
    String mode = jsxGet_designMode();
    if (!ff) {
      return com.gargoylesoftware.htmlunit.util.StringUtils.containsCaseInsensitive(EXECUTE_CMDS_IE, cmd);
    }
    if (!"on".equals(mode))
    {
      String msg = "queryCommandSupported() called while document.designMode='" + mode + "'.";
      throw Context.reportRuntimeError(msg);
    }
    return com.gargoylesoftware.htmlunit.util.StringUtils.containsCaseInsensitive(EXECUTE_CMDS_FF, cmd);
  }
  
  public boolean jsxFunction_queryCommandEnabled(String cmd)
  {
    boolean ff = getBrowserVersion().isFirefox();
    String mode = jsxGet_designMode();
    if (!ff) {
      return com.gargoylesoftware.htmlunit.util.StringUtils.containsCaseInsensitive(EXECUTE_CMDS_IE, cmd);
    }
    if (!"on".equals(mode))
    {
      String msg = "queryCommandEnabled() called while document.designMode='" + mode + "'.";
      throw Context.reportRuntimeError(msg);
    }
    return com.gargoylesoftware.htmlunit.util.StringUtils.containsCaseInsensitive(EXECUTE_CMDS_FF, cmd);
  }
  
  public boolean jsxFunction_execCommand(String cmd, boolean userInterface, Object value)
  {
    boolean ie = getBrowserVersion().isIE();
    if (((ie) && (!com.gargoylesoftware.htmlunit.util.StringUtils.containsCaseInsensitive(EXECUTE_CMDS_IE, cmd))) || ((!ie) && (!com.gargoylesoftware.htmlunit.util.StringUtils.containsCaseInsensitive(EXECUTE_CMDS_FF, cmd))))
    {
      if (getBrowserVersion().hasFeature(BrowserVersionFeatures.EXECCOMMAND_THROWS_ON_WRONG_COMMAND)) {
        throw Context.reportRuntimeError("document.execCommand(): invalid command '" + cmd + "'");
      }
      return false;
    }
    LOG.warn("Nothing done for execCommand(" + cmd + ", ...) (feature not implemented)");
    return true;
  }
  
  public Object jsxGet_activeElement()
  {
    if (activeElement_ == null)
    {
      HtmlElement body = getHtmlPage().getBody();
      if (body != null) {
        activeElement_ = ((HTMLElement)getScriptableFor(body));
      }
    }
    return activeElement_;
  }
  
  public void setActiveElement(HTMLElement element)
  {
    activeElement_ = element;
  }
  
  public SimpleScriptable jsxGet_doctype()
  {
    if (getBrowserVersion().isIE()) {
      return null;
    }
    return super.jsxGet_doctype();
  }
  
  public boolean jsxFunction_dispatchEvent(Event event)
  {
    event.setTarget(this);
    ScriptResult result = fireEvent(event);
    return !event.isAborted(result);
  }
  
  public void jsConstructor() {}
}

/* Location:
 * Qualified Name:     com.gargoylesoftware.htmlunit.javascript.host.html.HTMLDocument
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package com.gargoylesoftware.htmlunit.javascript.host.html;

import com.gargoylesoftware.htmlunit.SgmlPage;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import org.w3c.dom.Node;

public class HTMLElement$ProxyDomNode
  extends HtmlDivision
{
  private static final long serialVersionUID = -7816775277187498538L;
  private final DomNode target_;
  private boolean append_;
  
  public HTMLElement$ProxyDomNode(SgmlPage page, DomNode target, boolean append)
  {
    super(null, "div", page, null);
    target_ = target;
    append_ = append;
  }
  
  public DomNode appendChild(Node node)
  {
    DomNode domNode = (DomNode)node;
    if (append_) {
      return target_.appendChild(domNode);
    }
    target_.insertBefore(domNode);
    return domNode;
  }
  
  public DomNode getDomNode()
  {
    return target_;
  }
  
  public boolean isAppend()
  {
    return append_;
  }
}

/* Location:
 * Qualified Name:     com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement.ProxyDomNode
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package com.gargoylesoftware.htmlunit.javascript.host.html;

import net.sourceforge.htmlunit.corejs.javascript.Context;
import net.sourceforge.htmlunit.corejs.javascript.ContextAction;
import net.sourceforge.htmlunit.corejs.javascript.Function;
import net.sourceforge.htmlunit.corejs.javascript.Scriptable;

class HTMLElement$DownloadBehaviorJob$1
  implements ContextAction
{
  HTMLElement$DownloadBehaviorJob$1(HTMLElement.DownloadBehaviorJob paramDownloadBehaviorJob, Scriptable paramScriptable, Object[] paramArrayOfObject) {}
  
  public Object run(Context cx)
  {
    HTMLElement.DownloadBehaviorJob.access$200(this$1).call(cx, val$scope, val$scope, val$args);
    return null;
  }
}

/* Location:
 * Qualified Name:     com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement.DownloadBehaviorJob.1
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package com.gargoylesoftware.htmlunit.javascript.host.html;

import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequestSettings;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine;
import com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJob;
import com.gargoylesoftware.htmlunit.javascript.host.Window;
import java.io.IOException;
import java.net.URL;
import net.sourceforge.htmlunit.corejs.javascript.Context;
import net.sourceforge.htmlunit.corejs.javascript.ContextAction;
import net.sourceforge.htmlunit.corejs.javascript.ContextFactory;
import net.sourceforge.htmlunit.corejs.javascript.Function;
import net.sourceforge.htmlunit.corejs.javascript.Scriptable;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;

final class HTMLElement$DownloadBehaviorJob
  extends JavaScriptJob
{
  private final URL url_;
  private final Function callback_;
  
  private HTMLElement$DownloadBehaviorJob(HTMLElement paramHTMLElement, URL url, Function callback)
  {
    url_ = url;
    callback_ = callback;
  }
  
  public void run()
  {
    WebClient client = this$0.getWindow().getWebWindow().getWebClient();
    final Scriptable scope = callback_.getParentScope();
    WebRequestSettings settings = new WebRequestSettings(url_);
    try
    {
      WebResponse webResponse = client.loadWebResponse(settings);
      String content = webResponse.getContentAsString();
      HTMLElement.access$100().debug("Downloaded content: " + StringUtils.abbreviate(content, 512));
      final Object[] args = { content };
      ContextAction action = new ContextAction()
      {
        public Object run(Context cx)
        {
          callback_.call(cx, scope, scope, args);
          return null;
        }
      };
      ContextFactory cf = client.getJavaScriptEngine().getContextFactory();
      cf.call(action);
    }
    catch (IOException e)
    {
      HTMLElement.access$100().error("Behavior #default#download: Cannot download " + url_, e);
    }
  }
}

/* Location:
 * Qualified Name:     com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement.DownloadBehaviorJob
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package com.gargoylesoftware.htmlunit.javascript.host.html;

class HTMLElement$1 {}

/* Location:
 * Qualified Name:     com.gargoylesoftware.htmlunit.javascript.host.html.HTMLElement.1
 * Java Class Version: 5 (49.0)
 * JD-Core Version:    0.7.1
 */
package com.gargoylesoftware.htmlunit.javascript.host.html;

import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.ScriptResult;
import com.gargoylesoftware.htmlunit.SgmlPage;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequestSettings;
import com.gargoylesoftware.htmlunit.WebResponse;
import com.gargoylesoftware.htmlunit.WebWindow;
import com.gargoylesoftware.htmlunit.html.DomAttr;
import com.gargoylesoftware.htmlunit.html.DomCharacterData;
import com.gargoylesoftware.htmlunit.html.DomComment;
import com.gargoylesoftware.htmlunit.html.DomDocumentFragment;
import com.gargoylesoftware.htmlunit.html.DomElement;
import com.gargoylesoftware.htmlunit.html.DomNode;
import com.gargoylesoftware.htmlunit.html.DomText;
import com.gargoylesoftware.htmlunit.html.HTMLParser;
import com.gargoylesoftware.htmlunit.html.HtmlAnchor;
import com.gargoylesoftware.htmlunit.html.HtmlBody;
import com.gargoylesoftware.htmlunit.html.HtmlDivision;
import com.gargoylesoftware.htmlunit.html.HtmlElement;
import com.gargoylesoftware.htmlunit.html.HtmlFrameSet;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.html.HtmlTable;
import com.gargoylesoftware.htmlunit.html.HtmlTableDataCell;
import com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine;
import com.gargoylesoftware.htmlunit.javascript.NamedNodeMap;
import com.gargoylesoftware.htmlunit.javascript.ScriptableWithFallbackGetter;
import com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJob;
import com.gargoylesoftware.htmlunit.javascript.background.JavaScriptJobManager;
import com.gargoylesoftware.htmlunit.javascript.host.Attr;
import com.gargoylesoftware.htmlunit.javascript.host.BoxObject;
import com.gargoylesoftware.htmlunit.javascript.host.Element;
import com.gargoylesoftware.htmlunit.javascript.host.Event;
import com.gargoylesoftware.htmlunit.javascript.host.EventHandler;
import com.gargoylesoftware.htmlunit.javascript.host.EventListenersContainer;
import com.gargoylesoftware.htmlunit.javascript.host.MouseEvent;
import com.gargoylesoftware.htmlunit.javascript.host.Navigator;
import com.gargoylesoftware.htmlunit.javascript.host.Screen;
import com.gargoylesoftware.htmlunit.javascript.host.TextRange;
import com.gargoylesoftware.htmlunit.javascript.host.TextRectangle;
import com.gargoylesoftware.htmlunit.javascript.host.Window;
import com.gargoylesoftware.htmlunit.javascript.host.css.CSSStyleDeclaration;
import com.gargoylesoftware.htmlunit.javascript.host.css.ComputedCSSStyleDeclaration;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import net.sourceforge.htmlunit.corejs.javascript.BaseFunction;
import net.sourceforge.htmlunit.corejs.javascript.Context;
import net.sourceforge.htmlunit.corejs.javascript.ContextAction;
import net.sourceforge.htmlunit.corejs.javascript.ContextFactory;
import net.sourceforge.htmlunit.corejs.javascript.Function;
import net.sourceforge.htmlunit.corejs.javascript.NativeArray;
import net.sourceforge.htmlunit.corejs.javascript.Scriptable;
import net.sourceforge.htmlunit.corejs.javascript.ScriptableObject;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

public class HTMLElement
  extends Element
  implements ScriptableWithFallbackGetter
{
  private static final long serialVersionUID = -6864034414262085851L;
  private static final Log LOG = LogFactory.getLog(HTMLElement.class);
  private static final int BEHAVIOR_ID_UNKNOWN = -1;
  public static final int BEHAVIOR_ID_CLIENT_CAPS = 0;
  public static final int BEHAVIOR_ID_HOMEPAGE = 1;
  public static final int BEHAVIOR_ID_DOWNLOAD = 2;
  private static final String BEHAVIOR_CLIENT_CAPS = "#default#clientCaps";
  private static final String BEHAVIOR_HOMEPAGE = "#default#homePage";
  private static final String BEHAVIOR_DOWNLOAD = "#default#download";
  static final String POSITION_BEFORE_BEGIN = "beforeBegin";
  static final String POSITION_AFTER_BEGIN = "afterBegin";
  static final String POSITION_BEFORE_END = "beforeEnd";
  static final String POSITION_AFTER_END = "afterEnd";
  private static int UniqueID_Counter_ = 1;
  private final Set<String> behaviors_ = new HashSet();
  private BoxObject boxObject_;
  private HTMLCollection all_;
  private int scrollLeft_;
  private int scrollTop_;
  private String uniqueID_;
  private Map<String, HTMLCollection> elementsByTagName_;
  private CSSStyleDeclaration style_;
  private String ch_ = "";
  private String chOff_ = "";
  private static final List<String> INNER_HTML_READONLY_IN_IE = Arrays.asList(new String[] { "col", "colgroup", "frameset", "head", "html", "style", "table", "tbody", "tfoot", "thead", "title", "tr" });
  private static final List<String> INNER_TEXT_READONLY = Arrays.asList(new String[] { "html", "table", "tbody", "tfoot", "thead", "tr" });
  private static final List<String> OUTER_HTML_READONLY = Arrays.asList(new String[] { "caption", "col", "colgroup", "frameset", "html", "tbody", "td", "tfoot", "th", "thead", "tr" });
  
  public HTMLElement()
  {
    elementsByTagName_ = new HashMap();
  }
  
  public HTMLCollection jsxGet_all()
  {
    if (all_ == null)
    {
      all_ = new HTMLCollection(this);
      all_.init(getDomNodeOrDie(), ".//*");
    }
    return all_;
  }
  
  public CSSStyleDeclaration jsxGet_style()
  {
    return style_;
  }
  
  public ComputedCSSStyleDeclaration jsxGet_currentStyle()
  {
    return getWindow().jsxFunction_getComputedStyle(this, null);
  }
  
  public void setDefaults(ComputedCSSStyleDeclaration style) {}
  
  public CSSStyleDeclaration jsxGet_runtimeStyle()
  {
    return style_;
  }
  
  public void setDomNode(DomNode domNode)
  {
    super.setDomNode(domNode);
    
    style_ = new CSSStyleDeclaration(this);
    
    HtmlElement htmlElt = (HtmlElement)domNode;
    for (DomAttr attr : htmlElt.getAttributesMap().values())
    {
      String eventName = attr.getName();
      if (eventName.startsWith("on")) {
        createEventHandler(eventName, attr.getValue());
      }
    }
  }
  
  protected void createEventHandler(String eventName, String attrValue)
  {
    HtmlElement htmlElt = getDomNodeOrDie();
    
    BaseFunction eventHandler = new EventHandler(htmlElt, eventName, attrValue);
    setEventHandler(eventName, eventHandler);
    if (((htmlElt instanceof HtmlBody)) || ((htmlElt instanceof HtmlFrameSet))) {
      getWindow().getEventListenersContainer().setEventHandlerProp(eventName.substring(2), eventHandler);
    }
  }
  
  public String jsxGet_id()
  {
    return getDomNodeOrDie().getId();
  }
  
  public void jsxSet_id(String newId)
  {
    getDomNodeOrDie().setId(newId);
  }
  
  public String jsxGet_title()
  {
    return getDomNodeOrDie().getAttribute("title");
  }
  
  public void jsxSet_title(String newTitle)
  {
    getDomNodeOrDie().setAttribute("title", newTitle);
  }
  
  public boolean jsxGet_disabled()
  {
    return getDomNodeOrDie().hasAttribute("disabled");
  }
  
  public HTMLDocument jsxGet_document()
  {
    return getWindow().jsxGet_document();
  }
  
  public void jsxSet_disabled(boolean disabled)
  {
    HtmlElement element = getDomNodeOrDie();
    if (disabled) {
      element.setAttribute("disabled", "disabled");
    } else {
      element.removeAttribute("disabled");
    }
  }
  
  public String jsxGet_namespaceURI()
  {
    if (getBrowserVersion().isIE()) {
      return getDomNodeOrDie().getNamespaceURI();
    }
    if ((getDomNodeOrDie().getPage() instanceof HtmlPage)) {
      return null;
    }
    return getDomNodeOrDie().getNamespaceURI();
  }
  
  public String jsxGet_localName()
  {
    DomNode domNode = getDomNodeOrDie();
    String localName = domNode.getLocalName();
    if ((domNode.getPage() instanceof HtmlPage))
    {
      if (domNode.getPrefix() != null) {
        localName = domNode.getPrefix() + ':' + localName;
      }
      return localName.toUpperCase();
    }
    return localName;
  }
  
  public Object getWithFallback(String name)
  {
    if (!name.equals("class"))
    {
      HtmlElement htmlElement = getDomNodeOrNull();
      if ((htmlElement != null) && (isAttributeName(name)))
      {
        String value = htmlElement.getAttribute(name);
        if (HtmlElement.ATTRIBUTE_NOT_DEFINED != value)
        {
          LOG.debug("Found attribute for evaluation of property \"" + name + "\" for of " + this);
          
          return value;
        }
      }
    }
    return NOT_FOUND;
  }
  
  protected boolean isAttributeName(String name)
  {
    return name.toLowerCase().equals(name);
  }
  
  protected String fixAttributeName(String attributeName)
  {
    if (getBrowserVersion().isIE())
    {
      if ("className".equals(attributeName)) {
        return "class";
      }
      if ("class".equals(attribute
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43

Further reading...

For more information on Java 1.5 Tiger, you may find Java 1.5 Tiger, A developer's Notebook by D. Flanagan and B. McLaughlin from O'Reilly of interest.

New!JAR listings


Copyright 2006-2019. Infinite Loop Ltd