css-validator

16:34:58.833 INFO  jd.cli.Main - Decompiling css-validator.jar
package org.w3c.css.css;

import java.util.Comparator;
import org.w3c.css.properties.css.CssProperty;

class CssCascadingOrder$CompareExplicitWeight
  implements Comparator<CssProperty>
{
  CssCascadingOrder$CompareExplicitWeight(CssCascadingOrder paramCssCascadingOrder) {}
  
  public final int compare(CssProperty property1, CssProperty property2)
  {
    int val1 = property1.getExplicitWeight();
    int val2 = property2.getExplicitWeight();
    return val1 - val2;
  }
}

/* Location:
 * Qualified Name:     org.w3c.css.css.CssCascadingOrder.CompareExplicitWeight
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.w3c.css.css;

import java.util.Comparator;
import org.w3c.css.properties.css.CssProperty;

class CssCascadingOrder$CompareOrderSpecified
  implements Comparator<CssProperty>
{
  CssCascadingOrder$CompareOrderSpecified(CssCascadingOrder paramCssCascadingOrder) {}
  
  public final int compare(CssProperty property1, CssProperty property2)
  {
    long val1 = property1.getOrderSpecified();
    long val2 = property2.getOrderSpecified();
    return (int)(val1 - val2);
  }
}

/* Location:
 * Qualified Name:     org.w3c.css.css.CssCascadingOrder.CompareOrderSpecified
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.w3c.css.css;

import java.util.Comparator;
import org.w3c.css.parser.CssSelectors;
import org.w3c.css.properties.css.CssProperty;

class CssCascadingOrder$CompareSpecificity
  implements Comparator<CssProperty>
{
  CssCascadingOrder$CompareSpecificity(CssCascadingOrder paramCssCascadingOrder) {}
  
  public final int compare(CssProperty property1, CssProperty property2)
  {
    int val1 = property1.getSelectors().getSpecificity();
    int val2 = property2.getSelectors().getSpecificity();
    return val1 - val2;
  }
}

/* Location:
 * Qualified Name:     org.w3c.css.css.CssCascadingOrder.CompareSpecificity
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.w3c.css.css;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import org.w3c.css.parser.CssSelectors;
import org.w3c.css.parser.CssStyle;
import org.w3c.css.properties.css.CssProperty;
import org.w3c.css.util.Util;

public final class CssCascadingOrder
{
  ArrayList<CssProperty> propertyData;
  int propertyCount;
  
  public CssProperty order(CssProperty property, StyleSheet style, CssSelectors selector)
  {
    propertyData = new ArrayList();
    CssProperty newProp = property;
    
    Util.verbose("CASCADING ORDER " + property.getPropertyName() + " in " + selector);
    for (CssSelectors context : style.getRules().values())
    {
      Util.verbose("######## test with " + context + " and " + selector);
      if (context.canApply(selector))
      {
        CssProperty prop = property.getPropertyInStyle(context.getStyle(), false);
        
        Util.verbose("%%%%%%%%%%%%%%%%% Found " + context);
        if (prop != null) {
          addProperty(prop);
        }
      }
    }
    if (propertyData.isEmpty())
    {
      if ((selector.getNext() != null) && (property.inherited()))
      {
        Util.verbose("Found nothing ... try the next " + selector.getNext());
        
        CssStyle s = style.getStyle(selector.getNext());
        newProp = property.getPropertyInStyle(s, true);
      }
    }
    else
    {
      Util.verbose("@@@@@@@@@@@@@@ FOUND " + propertyData.size() + " properties");
      
      newProp = getProperty(selector);
      if ((property.isSoftlyInherited()) && (selector.getNext() != null))
      {
        CssStyle s = style.getStyle(selector.getNext());
        newProp = property.getPropertyInStyle(s, true);
      }
    }
    newProp = newProp.duplicate();
    newProp.setSelectors(selector);
    
    return newProp;
  }
  
  private CssProperty getProperty(CssSelectors selector)
  {
    int propertyCount = propertyData.size();
    if (propertyCount == 1) {
      return (CssProperty)propertyData.get(0);
    }
    CssProperty[] propertyArray = new CssProperty[propertyCount];
    propertyData.toArray(propertyArray);
    
    Arrays.sort(propertyArray, 0, propertyCount, new CompareExplicitWeight());
    int old = propertyArray[0].getExplicitWeight();
    int end = 0;
    while ((end < propertyCount) && (propertyArray[end].getExplicitWeight() == old)) {
      end++;
    }
    Arrays.sort(propertyArray, 0, end, new CompareSpecificity());
    old = propertyArray[0].getSelectors().getSpecificity();
    end = 0;
    while ((end < propertyCount) && (propertyArray[end].getSelectors().getSpecificity() == old)) {
      end++;
    }
    Arrays.sort(propertyArray, 0, end, new CompareOrderSpecified());
    return propertyArray[0];
  }
  
  private void addProperty(CssProperty property)
  {
    propertyData.add(property);
  }
  
  class CompareExplicitWeight
    implements Comparator<CssProperty>
  {
    CompareExplicitWeight() {}
    
    public final int compare(CssProperty property1, CssProperty property2)
    {
      int val1 = property1.getExplicitWeight();
      int val2 = property2.getExplicitWeight();
      return val1 - val2;
    }
  }
  
  class CompareSpecificity
    implements Comparator<CssProperty>
  {
    CompareSpecificity() {}
    
    public final int compare(CssProperty property1, CssProperty property2)
    {
      int val1 = property1.getSelectors().getSpecificity();
      int val2 = property2.getSelectors().getSpecificity();
      return val1 - val2;
    }
  }
  
  class CompareOrderSpecified
    implements Comparator<CssProperty>
  {
    CompareOrderSpecified() {}
    
    public final int compare(CssProperty property1, CssProperty property2)
    {
      long val1 = property1.getOrderSpecified();
      long val2 = property2.getOrderSpecified();
      return (int)(val1 - val2);
    }
  }
}

/* Location:
 * Qualified Name:     org.w3c.css.css.CssCascadingOrder
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.w3c.css.css;

import java.io.InputStream;
import java.io.Reader;
import java.net.URL;
import org.w3c.css.util.ApplContext;

public abstract interface CssParser
{
  public abstract void reInit();
  
  public abstract StyleSheet getStyleSheet();
  
  public abstract void parseURL(ApplContext paramApplContext, URL paramURL, String paramString1, String paramString2, String paramString3, int paramInt);
  
  /**
   * @deprecated
   */
  public abstract void parseStyleElement(ApplContext paramApplContext, String paramString, URL paramURL, int paramInt);
  
  public abstract void parseStyleElement(ApplContext paramApplContext, InputStream paramInputStream, String paramString1, String paramString2, URL paramURL, int paramInt);
  
  public abstract void parseStyleElement(ApplContext paramApplContext, Reader paramReader, String paramString1, String paramString2, URL paramURL, int paramInt);
  
  /**
   * @deprecated
   */
  public abstract void parseStyleAttribute(ApplContext paramApplContext, String paramString1, String paramString2, URL paramURL, int paramInt);
  
  public abstract void parseStyleAttribute(ApplContext paramApplContext, InputStream paramInputStream, String paramString, URL paramURL, int paramInt);
}

/* Location:
 * Qualified Name:     org.w3c.css.css.CssParser
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.w3c.css.css;

import java.util.ArrayList;
import org.w3c.css.parser.AtRule;
import org.w3c.css.util.Messages;

public class CssRuleList
{
  AtRule atRule;
  String atRuleString;
  ArrayList<CssStyleRule> rulelist;
  public String pseudopage;
  String indent;
  
  public CssRuleList()
  {
    atRule = null;
    atRuleString = new String();
    rulelist = new ArrayList();
    indent = new String();
  }
  
  public void addStyleRule(CssStyleRule stylerule)
  {
    rulelist.add(stylerule);
  }
  
  public ArrayList<CssStyleRule> getStyleRules()
  {
    return rulelist;
  }
  
  public void addAtRule(AtRule atRule)
  {
    this.atRule = atRule;
    atRuleString = atRule.toString();
  }
  
  public String getAtRule()
  {
    return atRuleString;
  }
  
  public String getAtRuleEscaped()
  {
    return Messages.escapeString(atRuleString);
  }
  
  public boolean isEmpty()
  {
    return rulelist.isEmpty();
  }
  
  public String toString()
  {
    StringBuilder ret = new StringBuilder();
    if ((null != atRule) && (atRule.isEmpty()))
    {
      if (atRuleString.length() != 0)
      {
        ret.append(atRuleString);
        ret.append("\n\n");
      }
    }
    else
    {
      if (atRuleString.length() != 0)
      {
        ret.append(atRuleString);
        ret.append(" {\n\n");
      }
      for (CssStyleRule styleRule : rulelist) {
        ret.append(styleRule);
      }
      if (atRuleString.length() != 0) {
        ret.append("}\n");
      }
    }
    return ret.toString();
  }
}

/* Location:
 * Qualified Name:     org.w3c.css.css.CssRuleList
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.w3c.css.css;

import java.util.ArrayList;
import org.w3c.css.properties.css.CssProperty;
import org.w3c.css.util.Messages;

public class CssStyleRule
{
  private String indent;
  private String selectors;
  private ArrayList<CssProperty> properties;
  
  public CssStyleRule(String indent, String selectors, ArrayList<CssProperty> properties, boolean important)
  {
    this.selectors = selectors;
    this.properties = properties;
    this.indent = indent;
  }
  
  public String getSelectors()
  {
    return selectors;
  }
  
  public String getSelectorsEscaped()
  {
    return Messages.escapeString(selectors);
  }
  
  public ArrayList<CssProperty> getProperties()
  {
    return properties;
  }
  
  public String toString()
  {
    StringBuilder ret = new StringBuilder();
    if (selectors != null)
    {
      ret.append(selectors);
      ret.append(" {\n");
    }
    for (CssProperty property : properties)
    {
      ret.append(indent);
      ret.append("   ");
      ret.append(property.getPropertyName());
      ret.append(" : ");
      ret.append(property.toString());
      if (property.getImportant()) {
        ret.append(" important");
      }
      ret.append(";\n");
    }
    if (selectors != null)
    {
      ret.append(indent);
      ret.append("}\n\n");
    }
    return ret.toString();
  }
  
  public String toStringEscaped()
  {
    return Messages.escapeString(toString());
  }
}

/* Location:
 * Qualified Name:     org.w3c.css.css.CssStyleRule
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.w3c.css.css;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.Reader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.w3c.css.util.ApplContext;
import org.w3c.css.util.CssVersion;
import org.w3c.css.util.HTTPURL;
import org.w3c.css.util.Messages;
import org.w3c.css.util.Util;
import org.w3c.tools.resources.ProtocolException;
import org.w3c.www.mime.MimeType;

public class CssValidator
{
  ApplContext ac;
  PrintWriter out;
  ArrayList<String> uris = new ArrayList();
  HashMap<String, String> params;
  static boolean showCSS = false;
  
  public CssValidator()
  {
    params = new HashMap();
    params.put("profile", CssVersion.getDefault().toString());
    params.put("medium", "all");
    params.put("output", "text");
    params.put("lang", "en");
    params.put("warning", "2");
    params.put("vextwarning", "false");
  }
  
  public CssValidator(String profile, String medium, String lang, int warninglevel, boolean vextwarning, boolean followlinks)
  {
    ac = new ApplContext(lang);
    ac.setCssVersionAndProfile(profile);
    ac.setMedium(medium);
    ac.setTreatVendorExtensionsAsWarnings(vextwarning);
    ac.setWarningLevel(warninglevel);
    ac.setFollowlinks(followlinks);
  }
  
  public void setOptionsFromParams()
  {
    String profile = (String)params.get("profile");
    ac.setCssVersionAndProfile(profile);
    
    ac.setMedium((String)params.get("medium"));
    
    String vextwarn = (String)params.get("vextwarning");
    ac.setTreatVendorExtensionsAsWarnings("true".equalsIgnoreCase(vextwarn));
  }
  
  public static void main(String[] args)
    throws IOException, MalformedURLException
  {
    CssValidator style = new CssValidator();
    try
    {
      style.getParams(args);
      ac = new ApplContext((String)params.get("lang"));
      System.out.println(params);
    }
    catch (Exception e)
    {
      System.out.println("Usage: java org.w3c.css.css.CssValidator  [OPTIONS] | [URL]*");
      
      System.out.println("OPTIONS");
      System.out.println("\t-p, --printCSS");
      System.out.println("\t\tPrints the validated CSS (only with text output, the CSS is printed with other outputs)");
      
      System.out.println("\t-profile PROFILE, --profile=PROFILE");
      System.out.println("\t\tChecks the Stylesheet against PROFILE");
      System.out.println("\t\tPossible values for PROFILE are css1, css2, css21 (default), css3, svg, svgbasic, svgtiny, atsc-tv, mobile, tv");
      
      System.out.println("\t-medium MEDIUM, --medium=MEDIUM");
      System.out.println("\t\tChecks the Stylesheet using the medium MEDIUM");
      System.out.println("\t\tPossible values for MEDIUM are all (default), aural, braille, embossed, handheld, print, projection, screen, tty, tv, presentation");
      
      System.out.println("\t-output OUTPUT, --output=OUTPUT");
      System.out.println("\t\tPrints the result in the selected format");
      System.out.println("\t\tPossible values for OUTPUT are text (default), xhtml, html (same result as xhtml), soap12");
      
      System.out.println("\t-lang LANG, --lang=LANG");
      System.out.println("\t\tPrints the result in the specified language");
      System.out.println("\t\tPossible values for LANG are de, en (default), es, fr, ja, ko, nl, zh-cn, pl, it");
      
      System.out.println("\t-warning WARN, --warning=WARN");
      System.out.println("\t\tWarnings verbosity level");
      System.out.println("\t\tPossible values for WARN are -1 (no warning), 0, 1, 2 (default, all the warnings");
      
      System.out.println("\t-vextwarning true, --vextwarning=true");
      System.out.println("\t\tTreat Vendor Extensions as warnings");
      System.out.println("\t\tPossible values for vextwarning are true or false (default, is false");
      
      System.out.println();
      System.out.println("URL");
      System.out.println("\tURL can either represent a distant web resource (http://) or a local file (file:/)");
      
      System.exit(1);
    }
    style.setOptionsFromParams();
    
    String encoding = ac.getMsg().getString("output-encoding-name");
    if (encoding != null) {
      out = new PrintWriter(new OutputStreamWriter(System.out, encoding));
    } else {
      out = new PrintWriter(new OutputStreamWriter(System.out));
    }
    for (int i = 0; i < uris.size(); i++)
    {
      String uri = (String)uris.get(i);
      if (uri != null) {
        try
        {
          uri = HTTPURL.getURL(uri).toString();
          
          DocumentParser URLparser = new DocumentParser(ac, uri);
          
          style.handleRequest(ac, uri, URLparser.getStyleSheet(), (String)params.get("output"), Integer.parseInt((String)params.get("warning")), true);
        }
        catch (ProtocolException pex)
        {
          if (Util.onDebug) {
            pex.printStackTrace();
          }
        }
        catch (Exception e)
        {
          e.printStackTrace();
        }
      }
    }
  }
  
  private void handleRequest(ApplContext ac, String title, StyleSheet styleSheet, String output, int warningLevel, boolean errorReport)
    throws Exception
  {
    if (styleSheet == null) {
      throw new IOException(ac.getMsg().getServletString("process") + " " + title);
    }
    styleSheet.findConflicts(ac);
    
    StyleReport style = StyleReportFactory.getStyleReport(ac, title, styleSheet, output, warningLevel);
    if (!errorReport) {
      style.desactivateError();
    }
    style.print(out);
  }
  
  public void handleCSSStyleSheet(ApplContext ac, Reader reader, URL docref)
  {
    DocumentParser parser = null;
    try
    {
      parser = new DocumentParser(ac, reader, docref.toString(), MimeType.TEXT_CSS);
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
    StyleSheet sheet = parser.getStyleSheet();
    sheet.findConflicts(ac);
  }
  
  public void handleHTMLStyleSheet(ApplContext ac, Reader reader, URL docref)
  {
    DocumentParser parser = null;
    try
    {
      parser = new DocumentParser(ac, reader, docref.toString(), MimeType.TEXT_HTML);
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
    StyleSheet sheet = parser.getStyleSheet();
    sheet.findConflicts(ac);
  }
  
  public void handleXMLStyleSheet(ApplContext ac, Reader reader, URL docref)
  {
    DocumentParser parser = null;
    try
    {
      parser = new DocumentParser(ac, reader, docref.toString(), MimeType.APPLICATION_XML);
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
    StyleSheet sheet = parser.getStyleSheet();
    sheet.findConflicts(ac);
  }
  
  private void getParams(String[] args)
    throws Exception
  {
    Iterator<String> iterator = Arrays.asList(args).iterator();
    while (iterator.hasNext())
    {
      String paramName = "";
      String paramValue = "";
      
      String param = (String)iterator.next();
      if ((param.equals("--printCSS")) || (param.equals("-p")))
      {
        showCSS = true;
      }
      else if (param.startsWith("--"))
      {
        int separator = param.indexOf("=");
        paramName = param.substring(2, separator);
        paramValue = param.substring(separator + 1);
      }
      else if (param.startsWith("-"))
      {
        paramName = param.substring(1);
        if (iterator.hasNext()) {
          paramValue = (String)iterator.next();
        } else {
          paramValue = "";
        }
      }
      else
      {
        uris.add(param);
      }
      if ((paramName.length() != 0) && (params.containsKey(paramName)))
      {
        if (paramValue.length() == 0) {
          throw new Exception("You must specify a value for the parameter " + paramName);
        }
        params.put(paramName, paramValue);
      }
    }
  }
}

/* Location:
 * Qualified Name:     org.w3c.css.css.CssValidator
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.w3c.css.css;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import org.w3c.css.util.ApplContext;
import org.w3c.css.util.HTTPURL;
import org.w3c.css.util.Util;
import org.w3c.www.mime.MimeType;
import org.w3c.www.mime.MimeTypeFormatException;

public final class DocumentParser
{
  public static MimeType wap;
  private StyleSheet style;
  private URL htmlURL;
  private Exception exception;
  private ApplContext ac;
  
  static
  {
    try
    {
      wap = new MimeType("application/vnd.wap.xhtml+xml");
    }
    catch (MimeTypeFormatException mex)
    {
      wap = null;
    }
  }
  
  public DocumentParser(ApplContext ac, Reader reader)
    throws Exception
  {
    this(ac, reader, "urn:unknown", null);
  }
  
  public DocumentParser(ApplContext ac, Reader reader, String urlString, MimeType mediatype)
    throws Exception
  {
    htmlURL = HTTPURL.getURL(urlString);
    this.ac = ac;
    String media = ac.getMedium();
    if (mediatype == null) {
      mediatype = MimeType.TEXT_CSS;
    }
    if (mediatype.match(MimeType.TEXT_CSS) == 4)
    {
      StyleSheetParser csshandler = new StyleSheetParser();
      csshandler.parseStyleSheet(ac, reader, htmlURL);
      style = csshandler.getStyleSheet();
    }
    else if (mediatype.match(MimeType.TEXT_HTML) == 4)
    {
      TagSoupStyleSheetHandler htmlhandler = new TagSoupStyleSheetHandler(htmlURL, ac);
      
      htmlhandler.parse(reader);
      style = htmlhandler.getStyleSheet();
      if (style != null) {
        style.setType("text/html");
      }
    }
    else if ((mediatype.toString().endsWith("+xml")) || (mediatype.match(MimeType.APPLICATION_XML) == 4))
    {
      XMLStyleSheetHandler xmlhandler = new XMLStyleSheetHandler(htmlURL, ac);
      xmlhandler.parse(reader);
      style = xmlhandler.getStyleSheet();
      if (style != null) {
        style.setType("text/xml");
      }
    }
  }
  
  public DocumentParser(ApplContext ac, String urlString)
    throws Exception
  {
    htmlURL = HTTPURL.getURL(urlString);
    this.ac = ac;
    urlString = htmlURL.toString();
    String urlLower = urlString.toLowerCase();
    String media = ac.getMedium();
    String urlProtocol = htmlURL.getProtocol();
    if ((!"http".equals(urlProtocol)) && (!"https".equals(urlProtocol)))
    {
      if (urlLower.endsWith(".css"))
      {
        StyleSheetParser parser = new StyleSheetParser();
        parser.parseURL(ac, htmlURL, null, null, media, 3);
        style = parser.getStyleSheet();
      }
      else if ((urlLower.endsWith(".html")) || (urlLower.endsWith(".htm")) || (urlLower.endsWith(".shtml")) || (urlLower.endsWith("/")))
      {
        TagSoupStyleSheetHandler handler = new TagSoupStyleSheetHandler(htmlURL, ac);
        
        handler.parse(htmlURL);
        style = handler.getStyleSheet();
        if (style != null) {
          style.setType("text/html");
        }
      }
      else if ((urlLower.endsWith(".xhtml")) || (urlLower.endsWith(".xml")))
      {
        XMLStyleSheetHandler handler = new XMLStyleSheetHandler(htmlURL, ac);
        handler.parse(htmlURL);
        style = handler.getStyleSheet();
        if (style != null) {
          style.setType("text/xml");
        }
      }
      else
      {
        throw new Exception("Unknown file");
      }
    }
    else
    {
      URLConnection connection = null;
      try
      {
        boolean isXML = false;
        
        String credential = ac.getCredential();
        
        connection = HTTPURL.getConnection(htmlURL, ac);
        htmlURL = connection.getURL();
        
        String httpCL = connection.getHeaderField("Content-Location");
        if (httpCL != null) {
          htmlURL = HTTPURL.getURL(htmlURL, httpCL);
        }
        String cType = connection.getContentType();
        if (cType == null) {
          cType = "unknown/unknown";
        }
        MimeType contentType = null;
        try
        {
          contentType = new MimeType(cType);
        }
        catch (MimeTypeFormatException ex)
        {
          contentType = MimeType.TEXT_HTML;
        }
        if (Util.onDebug) {
          System.err.println("[DEBUG] content type is [" + contentType + ']');
        }
        if (contentType.match(MimeType.TEXT_HTML) == 4)
        {
          TagSoupStyleSheetHandler handler = new TagSoupStyleSheetHandler(htmlURL, ac);
          handler.parse(urlString, connection);
          style = handler.getStyleSheet();
          if (style != null) {
            style.setType("text/html");
          }
        }
        else if (contentType.match(MimeType.TEXT_CSS) == 4)
        {
          StyleSheetParser parser = new StyleSheetParser();
          parser.parseURL(ac, htmlURL, null, null, media, 3);
          style = parser.getStyleSheet();
        }
        else if ((contentType.match(MimeType.TEXT_XML) == 4) || (contentType.match(MimeType.APPLICATION_XHTML_XML) == 4) || (contentType.match(wap) == 4))
        {
          XMLStyleSheetHandler handler = new XMLStyleSheetHandler(htmlURL, ac);
          handler.parse(urlString, connection);
          style = handler.getStyleSheet();
          if (style != null) {
            style.setType("text/xml");
          }
        }
        else
        {
          throw new IOException("Unknown mime type : " + contentType);
        }
      }
      finally
      {
        try
        {
          connection.getInputStream().close();
        }
        catch (Exception e) {}
      }
    }
  }
  
  public StyleSheet getStyleSheet()
  {
    return style;
  }
}

/* Location:
 * Qualified Name:     org.w3c.css.css.DocumentParser
 * Java Class Version: 6 (50.0)
 * JD-Core Version:    0.7.1
 */
package org.w3c.css.css;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.Reader;
import java.io.StringReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import nu.validator.htmlparser.common.XmlViolationPolicy;
import nu.validator.htmlparser.sax.HtmlParser;
import org.w3c.css.parser.CssError;
import org.w3c.css.parser.Errors;
import org.w3c.css.parser.Frame;
import org.w3c.css.parser.analyzer.TokenMgrError;
import org.w3c.css.util.ApplContext;
import org.w3c.css.util.CssVersion;
import org.w3c.css.util.HTTPURL;
import org.w3c.css.util.InvalidParamException;
import org.w3c.css.util.Util;
import org.w3c.css.util.Warning;
import org.w3c.css.util.Warnings;
import org.w3c.css.util.xml.XMLCatalog;
import org.w3c.www.mime.MimeType;
import org.w3c.www.mime.MimeTypeFormatException;
import org.xml.sax.Attributes;
import org.xml.sax.ContentHandler;
import org.xml.sax.EntityResolver;
import org.xml.sax.ErrorHandler;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.XMLReader;
import org.xml.sax.ext.LexicalHandler;

public class HTMLParserStyleSheetHandler
  implements ContentHandler, LexicalHandler, ErrorHandler, EntityResolver
{
  static String XHTML_NS = "http://www.w3.org/1999/xhtml";
  private static long autoIdCount;
  String namespaceURI;
  boolean isRoot = true;
  ApplContext ac;
  URL documentURI = null;
  URL baseURI = null;
  boolean isHTML5;
  StyleSheetParser styleSheetParser = new StyleSheetParser();
  boolean inStyle = false;
  String media = null;
  String type = null;
  String title = null;
  String charset = null;
  StringBuilder text = new StringBuilder();
  Locator locator;
  static XMLCatalog catalog = new XMLCatalog();
  
  public HTMLParserStyleSheetHandler(URL baseURI, ApplContext ac)
  {
    documentURI = baseURI;
    this.baseURI = baseURI;
    this.ac = ac;
  }
  
  public void setDocumentLocator(Locator locator)
  {
    this.locator = locator;
  }
  
  public void startDocument()
    throws SAXException
  {}
  
  public void endDocument()
    throws SAXException
  {
    ac.setInput("text/xml");
  }
  
  public void startPrefixMapping(String prefix, String uri)
    throws SAXException
  {}
  
  public void endPrefixMapping(String prefix)
    throws SAXException
  {}
  
  public void characters(char[] ch, int start, int length)
    throws SAXException
  {
    if (inStyle) {
      text.append(ch, start, length);
    }
  }
  
  public void comment(char[] ch, int start, int length)
    throws SAXException
  {
    if (inStyle)
    {
      int line = locator != null ? locator.getLineNumber() : -1;
      Warning w = new Warning(baseURI.toString(), line, "style-inside-comment", 0, ac);
      
      Warnings warnings = new Warnings(ac.getWarningLevel());
      warnings.addWarning(w);
      styleSheetParser.notifyWarnings(warnings);
    }
  }
  
  public void ignorableWhitespace(char[] ch, int start, int length)
    throws SAXException
  {}
  
  public void processingInstruction(String target, String data)
    throws SAXException
  {
    HashMap<String, String> atts = getValues(data);
    if ("xml-stylesheet".equals(target))
    {
      String rel = (String)atts.get("alternate");
      String type = (String)atts.get("type");
      String href = (String)atts.get("href");
      if (Util.onDebug) {
        System.err.println("<?xml-stylesheet alternate=\"" + rel + "\" type=\"" + type + "\"" + "   href=\"" + href + "\"?>");
      }
      if ("yes".equalsIgnoreCase(rel)) {
        rel = "alternate stylesheet";
      } else {
        rel = "stylesheet";
      }
      if (href == null)
      {
        int line = -1;
        if (locator != null) {
          line = locator.getLineNumber();
        }
        CssError er = new CssError(baseURI.toString(), line, new InvalidParamException("unrecognized.link", ac));
        
        Errors ers = new Errors();
        ers.addError(er);
        styleSheetParser.notifyErrors(ers);
      }
      if (href.charAt(0) == '#') {
        return;
      }
      if (type != null)
      {
        MimeType mt = null;
        try
        {
          mt = new MimeType(type);
        }
        catch (Exception ex) {}
        if ((mt != null) && (MimeType.TEXT_CSS.match(mt) == 4))
        {
          URL url;
          try
          {
            URL url;
            if (baseURI != null) {
              url = new URL(baseURI, href);
            } else {
              url = new URL(href);
            }
          }
          catch (MalformedURLException e)
          {
            return;
          }
          if (Util.onDebug) {
            System.err.println("[HTMLParserStyleSheetHandler::initialize(): should parse CSS url: " + url.toString() + "]");
          }
          String media = (String)atts.get("media");
          if ((media == null) && (ac.getCssVersion() != CssVersion.CSS1)) {
            media = "all";
          }
          styleSheetParser.parseURL(ac, url, (String)atts.get("title"), rel, media, 3);
          if (Util.onDebug) {
            System.err.println("[parsed!]");
          }
        }
      }
    }
  }
  
  public void skippedEntity(String name)
    throws SAXException
  {}
  
  public void startElement(String namespaceURI, String localName, String qName, Attributes atts)
    throws SAXException
  {
    if (isRoot)
    {
      this.namespaceURI = namespaceURI;
      isRoot = false;
    }
    if (XHTML_NS.equals(namespaceURI))
    {
      if ("base".equals(localName))
      {
        String href = atts.getValue("href");
        if (Util.onDebug) {
          System.err.println("BASE href=\"" + href + "\"");
        }
        if (href != null) {
          try
          {
            baseURI = new URL(documentURI, href);
            documentURI = baseURI;
          }
          catch (MalformedURLException e) {}
        }
      }
      else if ("link".equals(localName))
      {
        String rel = atts.getValue("rel");
        String type = atts.getValue("type");
        String href = atts.getValue("href");
        if (Util.onDebug) {
          System.err.println("HTMLParser: link rel=\"" + rel + "\" type=\"" + type + "\"" + "   href=\"" + href + "\"");
        }
        if ((rel != null) && (rel.toLowerCase().indexOf("stylesheet") != -1))
        {
          if (href == null)
          {
            int line = -1;
            if (locator != null) {
              line = locator.getLineNumber();
            }
            CssError er = new CssError(baseURI.toString(), line, new InvalidParamException("unrecognized.link", ac));
            
            Errors ers = new Errors();
            ers.addError(er);
            styleSheetParser.notifyErrors(ers);
            return;
          }
          if (type == null)
          {
            if (!isHTML5)
            {
              int line = locator != null ? locator.getLineNumber() : -1;
              Warning w = new Warning(baseURI.toString(), line, "link-type", 0, ac);
              
              Warnings warnings = new Warnings(ac.getWarningLevel());
              warnings.addWarning(w);
              styleSheetParser.notifyWarnings(warnings);
            }
          }
          else
          {
            MimeType mt = null;
            try
            {
              mt = new MimeType(type);
            }
            catch (MimeTypeFormatException mtfe)
            {
              return;
            }
            if (MimeType.TEXT_CSS.match(mt) != 4) {
              return;
            }
          }
          URL url;
          try
          {
            URL url;
            if (baseURI != null) {
              url = new URL(baseURI, href);
            } else {
              url = new URL(href);
            }
          }
          catch (MalformedURLException e)
          {
            return;
          }
          if (Util.onDebug) {
            System.err.println("[HTMLParserStyleSheetHandler::initialize(): should parse CSS url: " + url.toString() + "]");
          }
          String media = atts.getValue("media");
          if ((media == null) && (ac.getCssVersion() != CssVersion.CSS1)) {
            media = "all";
          }
          styleSheetParser.parseURL(ac, url, atts.getValue("title"), rel, media, 3);
          if (Util.onDebug) {
            System.err.println("[parsed!]");
          }
        }
      }
      else if ("style".equals(localName))
      {
        this.media = atts.getValue("media");
        this.type = atts.getValue("type");
        title = atts.getValue("title");
        if ((this.media == null) && (ac.getCssVersion() != CssVersion.CSS1)) {
          this.media = "all";
        }
        if (Util.onDebug) {
          System.err.println("style media=\"" + this.media + "\" type=\"" + this.type + "\"" + "   title=\"" + title + "\"");
        }
        if (this.type == null)
        {
          if (!isHTML5)
          {
            int line = locator != null ? locator.getLineNumber() : -1;
            Warning w = new Warning(baseURI.toString(), line, "style-type", 0, ac);
            
            Warnings warnings = new Warnings(ac.getWarningLevel());
            warnings.addWarning(w);
            styleSheetParser.notifyWarnings(warnings);
          }
          text.setLength(0);
          inStyle = true;
        }
        else
        {
          try
          {
            MimeType mt = new MimeType(this.type);
            if (MimeType.TEXT_CSS.match(mt) == 4)
            {
              text.setLength(0);
              inStyle = true;
            }
          }
          catch (MimeTypeFormatException ex) {}
        }
      }
      else if (atts.getValue("style") != null)
      {
        String value = atts.getValue("style");
        if (value != null)
        {
          String id = atts.getValue("id");
          handleStyleAttribute(value, id);
        }
      }
    }
    else
    {
      String value = atts.getValue(XHTML_NS, "style");
      if (value != null)
      {
        String id = atts.getValue(XHTML_NS, "id");
        handleStyleAttribute(value, id);
      }
    }
  }
  
  public void endElement(String namespaceURI, String localName, String qName)
    throws SAXException
  {
    int line = 0;
    if (locator != null) {
      line = locator.getLineNumber();
    }
    if ((XHTML_NS.equals(namespaceURI)) && 
      ("style".equals(localName)) && 
      (inStyle))
    {
      inStyle = false;
      if (text.length() != 0)
      {
        if (Util.onDebug) {
          System.err.println("PARSE [" + text.toString() + "]");
        }
        styleSheetParser.parseStyleElement(ac, new StringReader(text.toString()), title, media, documentURI, line);
      }
    }
  }
  
  public void handleStyleAttribute(String value, String id)
  {
    if (id == null)
    {
      StringBuilder sb = new StringBuilder("#autoXML");
      sb.append(autoIdCount);
      
      sb.append(autoIdCount++);
      id = sb.toString();
    }
    int line = 0;
    if (locator != null) {
      line = locator.getLineNumber();
    }
    try
    {
      styleSheetParser.parseStyleAttribute(ac, new ByteArrayInputStream(value.getBytes()), id, documentURI, line);
    }
    catch (TokenMgrError ex)
    {
      CssError err = new CssError(baseURI.toString(), line, ex);
      
      Errors errs = new Errors();
      errs.addError(err);
      styleSheetParser.notifyErrors(errs);
    }
  }
  
  public StyleSheet getStyleSheet()
  {
    return styleSheetParser.getStyleSheet();
  }
  
  public void startDTD(String name, String publicId, String systemId)
    throws SAXException
  {
    isHTML5 = "html".equalsIgnoreCase(name);
  }
  
  public void endDTD()
    throws SAXException
  {}
  
  public void startEntity(String name)
    throws SAXException
  {}
  
  public void endEntity(String name)
    throws SAXException
  {}
  
  public void startCDATA()
    throws SAXException
  {}
  
  public void endCDATA()
    throws SAXException
  {}
  
  public void error(SAXParseException exception)
    throws SAXException
  {}
  
  public void fatalError(SAXParseException exception)
    throws SAXException
  {
    throw exception;
  }
  
  public void warning(SAXParseException exception)
    throws SAXException
  {}
  
  public InputSource resolveEntity(String publicId, String systemId)
    throws SAXException, IOException
  {
    String uri = null;
    if (publicId != null)
    {
      if ("-//W3C//DTD XHTML 1.0 Transitional//EN".equals(publicId))
      {
        if ((!"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd".equals(systemId)) && 
          (ac != null) && (ac.getFrame() != null)) {
          ac.getFrame().addWarning("xhtml.system_identifier.invalid");
        }
      }
      else if ("-//W3C//DTD XHTML 1.0 Strict//EN".equals(publicId))
      {
        if ((!"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd".equals(systemId)) && 
          (ac != null) && (ac.getFrame() != null)) {
          ac.getFrame().addWarning("xhtml.system_identifier.invalid");
        }
      }
      else if (("-//W3C//DTD XHTML 1.0 Frameset//EN".equals(publicId)) && 
        (!"http://www.w3.org/TR/xhtml1/DTD/xhtml1-frameset.dtd".equals(systemId)) && 
        (ac != null) && (ac.getFrame() != null)) {
        ac.getFrame().addWarning("xhtml.system_identifier.invalid");
      }
      uri = catalog.getProperty(publicId);
    }
    if ((uri == null) && (systemId != null)) {
      uri = catalog.getProperty(systemId);
    }
    if (uri != null) {
      return new InputSource(uri);
    }
    return new InputSource(new URL(baseURI, systemId).toString());
  }
  
  public void parse(InputSource source, String fileName)
    throws IOException, SAXException
  {
    XMLReader xmlParser = new HtmlParser(XmlViolationPolicy.ALLOW);
    try
    {
      xmlParser.setProperty("http://xml.org/sax/properties/lexical-handler", this);
      
      xmlParser.setFeature("http://xml.org/sax/features/validation", false);
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
    xmlParser.setContentHandler(this);
    baseURI = new URL(fileName);
    documentURI = new URL(fileName);
    source.setSystemId(fileName);
    URL ref = ac.getReferrer();
    try
    {
      ac.setReferrer(documentURI);
      xmlParser.parse(source);
    }
    finally
    {
      ac.setReferrer(ref);
    }
  }
  
  public void parse(InputStream is, String docref)
    throws IOException, SAXException
  {
    InputSource inputSource = new InputSource(is);
    try
    {
      parse(inputSource, docref);
    }
    finally
    {
      is.close();
    }
  }
  
  public void parse(Reader reader, String docref)
    throws IOException, SAXException
  {
    InputSource inputSource = new InputSource(reader);
    try
    {
      parse(inputSource, docref);
    }
    finally
    {
      reader.close();
    }
  }
  
  void parse(URL url)
    throws Exception
  {
    InputSource source = new InputSource();
    
    XMLReader xmlParser = new HtmlParser(XmlViolationPolicy.ALLOW);
    try
    {
      xmlParser.setProperty("http://xml.org/sax/properties/lexical-handler", this);
      
      xmlParser.setFeature("http://xml.org/sax/features/validation", false);
    }
    catch (Exception ex)
    {
      ex.printStackTrace();
    }
    xmlParser.setContentHandler(this);
    
    URLConnection connection = HTTPURL.getConnection(url, ac);
    InputStream in = HTTPURL.getInp
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 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93

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-2017. Infinite Loop Ltd