1 25 26 package org.snipsnap.render.filter.links; 27 28 import org.radeox.util.Encoder; 29 import org.radeox.util.i18n.ResourceManager; 30 import org.radeox.util.logging.Logger; 31 import org.snipsnap.snip.Links; 32 import org.snipsnap.snip.SnipLink; 33 import org.snipsnap.util.URLEncoderDecoder; 34 35 import java.io.IOException ; 36 import java.io.Writer ; 37 import java.io.UnsupportedEncodingException ; 38 import java.util.Iterator ; 39 import java.net.URL ; 40 import java.net.InetAddress ; 41 import java.net.UnknownHostException ; 42 43 49 50 public class BackLinks { 51 private static UrlFormatter formatter = new CutLengthFormatter(); 52 private static InetAddress googleHost; 53 54 static { 55 try { 56 googleHost = InetAddress.getByName("www.google.com"); 57 } catch (UnknownHostException e) { 58 Logger.warn("unable to resolve google.com: ", e); 59 } 60 } 61 62 public static void appendTo(Writer writer, Links backLinks, int count) { 63 Iterator iterator = backLinks.iterator(); 64 65 try { 66 if (iterator.hasNext()) { 67 writer.write("<span class=\"caption\">"); 68 writer.write(ResourceManager.getString("i18n.messages", "backlinks.title")); 69 writer.write("</span>\n"); 70 writer.write("<ul class=\"list\">\n"); 71 while (iterator.hasNext() && --count >= 0) { 72 String url = (String ) iterator.next(); 73 writer.write("<li>"); 74 writer.write("<span class=\"count\">"); 75 writer.write("" + backLinks.getIntCount(url)); 76 writer.write("</span>"); 77 writer.write(" <span class=\"content\"><a HREF=\""); 78 writer.write(Encoder.escape(url)); 79 writer.write("\">"); 80 renderView(writer, url); 81 writer.write("</a></span></li>\n"); 82 } 83 writer.write("</ul>"); 84 } 85 } catch (IOException e) { 86 Logger.warn("unable write to writer", e); 87 } 88 89 } 90 91 private static void renderView(Writer writer, String url) throws IOException { 92 URL urlInfo = new URL (url); 93 String info = null; 94 try { 95 if(googleHost != null && googleHost.equals(InetAddress.getByName(urlInfo.getHost()))) { 96 info = getQuery(urlInfo.getQuery(), "q"); 97 if(info != null) { 98 info = urlInfo.getHost() + ": " + info; 99 } 100 } 101 } catch (UnknownHostException e) { 102 } 105 106 if(null == info) { 107 info = url; 108 } 109 110 writer.write(Encoder.toEntity(info.charAt(0))); 111 writer.write(Encoder.escape(SnipLink.cutLength(info.substring(1), 90))); 112 } 113 114 private static String getQuery(String query, String id) { 115 if(null != query) { 116 String vars[] = query.split("&"); 117 for(int v = 0; v < vars.length; v++) { 118 if(vars[v].startsWith(id+"=")) { 119 try { 120 String value = URLEncoderDecoder.decode(vars[v].substring(id.length()+1), "UTF-8"); 121 return value.replace('+', ' '); 122 } catch (UnsupportedEncodingException e) { 123 return null; 124 } 125 } 126 } 127 } 128 return null; 129 } 130 } | Popular Tags |