KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > ConvertStyleSheets


1 import au.id.jericho.lib.html.*;
2 import java.util.*;
3 import java.io.*;
4 import java.net.*;
5
6 public class ConvertStyleSheets {
7     public static void main(String JavaDoc[] args) throws Exception JavaDoc {
8         String JavaDoc sourceUrlString="data/form.html";
9         if (args.length==0)
10           System.err.println("Using default argument of \""+sourceUrlString+'"');
11         else
12             sourceUrlString=args[0];
13         if (sourceUrlString.indexOf(':')==-1) sourceUrlString="file:"+sourceUrlString;
14         URL sourceUrl=new URL(sourceUrlString);
15         Source source=new Source(sourceUrl);
16         OutputDocument outputDocument=new OutputDocument(source);
17         source.setLogWriter(new OutputStreamWriter(System.err)); // send log messages to stderr
18
StringBuffer JavaDoc sb=new StringBuffer JavaDoc();
19         List linkStartTags=source.findAllStartTags(Tag.LINK);
20         for (Iterator i=linkStartTags.iterator(); i.hasNext();) {
21             StartTag startTag=(StartTag)i.next();
22             Attributes attributes=startTag.getAttributes();
23             String JavaDoc rel=attributes.getValue("rel");
24             if (!"stylesheet".equalsIgnoreCase(rel)) continue;
25             String JavaDoc HREF=attributes.getValue("href");
26             if (href==null) continue;
27             String JavaDoc styleSheetContent;
28             try {
29                 styleSheetContent=Util.getString(new InputStreamReader(new URL(sourceUrl,href).openStream()));
30             } catch (Exception JavaDoc ex) {
31               System.err.println(ex.toString());
32                 continue; // don't convert if URL is invalid
33
}
34             sb.setLength(0);
35             sb.append("<style");
36             Attribute typeAttribute=attributes.get("type");
37             if (typeAttribute!=null) sb.append(' ').append(typeAttribute);
38             sb.append(">\n").append(styleSheetContent).append("\n</style>");
39             outputDocument.replace(startTag,sb);
40         }
41         System.err.println("Here is the document "+sourceUrlString+" with all external stylesheets converted to inline stylesheets:\n");
42         outputDocument.writeTo(new OutputStreamWriter(System.out));
43   }
44 }
45
Popular Tags