1 17 18 package org.apache.james.nntpserver.repository; 19 20 import org.apache.james.util.Base64; 21 22 import java.io.File; 23 import java.io.FileInputStream; 24 import java.io.FileOutputStream; 25 import java.io.IOException; 26 import java.util.Date; 27 import java.util.Enumeration; 28 import java.util.Properties; 29 30 42 public class ArticleIDRepository { 43 44 47 private final File root; 48 49 52 private final String articleIDDomainSuffix; 53 54 59 private int counter = 0; 60 61 ArticleIDRepository(File root,String articleIDDomainSuffix) { 62 this.root = root; 63 this.articleIDDomainSuffix = articleIDDomainSuffix; 64 } 65 66 69 String generateArticleID() { 70 int idx = Math.abs(counter++); 71 StringBuffer idBuffer = 72 new StringBuffer(256) 73 .append("<") 74 .append(Thread.currentThread().hashCode()) 75 .append(".") 76 .append(System.currentTimeMillis()) 77 .append(".") 78 .append(idx) 79 .append("@") 80 .append(articleIDDomainSuffix) 81 .append(">"); 82 return idBuffer.toString(); 83 } 84 85 90 void addArticle(String articleID,Properties prop) throws IOException { 91 if ( articleID == null ) { 92 articleID = generateArticleID(); 93 } 94 FileOutputStream fout = null; 95 try { 96 fout = new FileOutputStream(getFileFromID(articleID)); 97 prop.store(fout,new Date().toString()); 98 } finally { 99 if (fout != null) { 100 fout.close(); 101 } 102 } 103 } 104 105 113 File getFileFromID(String articleID) { 114 String b64Id; 115 try { 116 b64Id = removeCRLF(Base64.encodeAsString(articleID)); 117 } catch (Exception e) { 118 throw new RuntimeException("This shouldn't happen: " + e); 119 } 120 return new File(root, b64Id); 121 } 122 123 128 private static String removeCRLF(String str) { 129 StringBuffer buffer = new StringBuffer(); 130 for (int i = 0; i < str.length(); i++) { 131 char c = str.charAt(i); 132 if (c != '\r' && c != '\n') { 133 buffer.append(c); 134 } 135 } 136 return buffer.toString(); 137 } 138 139 146 boolean isExists(String articleID) { 147 return ( articleID == null ) ? false : getFileFromID(articleID).exists(); 148 } 149 150 160 NNTPArticle getArticle(NNTPRepository repo,String id) throws IOException { 161 File f = getFileFromID(id); 162 if ( f.exists() == false ) { 163 return null; 164 } 165 FileInputStream fin = null; 166 Properties prop = new Properties(); 167 try { 168 fin = new FileInputStream(f); 169 prop.load(fin); 170 } finally { 171 if (fin != null) { 172 fin.close(); 173 } 174 } 175 Enumeration enum = prop.keys(); 176 NNTPArticle article = null; 177 while ( article == null && enum.hasMoreElements() ) { 178 String groupName = (String)enum.nextElement(); 179 int number = Integer.parseInt(prop.getProperty(groupName)); 180 NNTPGroup group = repo.getGroup(groupName); 181 if ( group != null ) { 182 article = group.getArticle(number); 183 } 184 } 185 return article; 186 } 187 } 188 | Popular Tags |