File: FileNewsrc.java

package info (click to toggle)
libgnuinet-java 1.1-3
  • links: PTS
  • area: main
  • in suites: sarge
  • size: 1,368 kB
  • ctags: 1,710
  • sloc: java: 12,475; sh: 5,408; makefile: 218; xml: 126
file content (598 lines) | stat: -rw-r--r-- 14,520 bytes parent folder | download
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
/*
 * $Id: FileNewsrc.java,v 1.4 2004/07/28 09:37:21 dog Exp $
 * Copyright (C) 2002 The Free Software Foundation
 * 
 * This file is part of GNU inetlib, a library.
 * 
 * GNU inetlib is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * GNU inetlib is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * As a special exception, if you link this library with other files to
 * produce an executable, this library does not by itself cause the
 * resulting executable to be covered by the GNU General Public License.
 * This exception does not however invalidate any other reasons why the
 * executable file might be covered by the GNU General Public License.
 */

package gnu.inet.nntp;

import java.io.BufferedReader;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * A .newsrc configuration on a filesystem.
 *
 * @author <a href='mailto:dog@gnu.org'>Chris Burdess</a>
 * @version $Revision: 1.4 $ $Date: 2004/07/28 09:37:21 $
 */
public class FileNewsrc implements Newsrc
{

  private static final String NEWSRC_ENCODING = "US-ASCII";

  protected File file;

  protected List subs = null;
  protected List groups = null;
  protected Map lines = null;
  protected boolean dirty;
  protected boolean debug;

  /**
   * Constructor.
   * @param file the disk file
   * @param debug for debugging information on stderr
   */
  public FileNewsrc (File file, boolean debug)
  {
    this.file = file;
    this.debug = debug;
  }

  public void close ()
  {
    if (!dirty)
      {
        return;
      }
    save ();
  }
  
  /**
   * Load the file.
   */
  void load ()
  {
    long fs = file.length ();
    long max = (long) Integer.MAX_VALUE;
    int bs = (int) (fs > max ? max : fs);
    
    groups = new LinkedList ();
    lines = new HashMap (bs / 20);
    subs = new LinkedList ();
    
    // Load
    try
      {
        long t1 = System.currentTimeMillis ();
        if (debug)
          {
            System.err.println ("DEBUG: nntp: newsrc loading " +
                                file.getPath ());
          }
        
        FileInputStream fr = new FileInputStream (file);
        InputStreamReader ir = new InputStreamReader (fr, NEWSRC_ENCODING);
        BufferedReader reader = new BufferedReader (ir, bs);
        String line = reader.readLine ();
        while (line != null)
          {
            int cp = line.indexOf (':');
            if (cp > -1)
              {
                // Subscribed newsgroup
                String name = line.substring (0, cp);
                groups.add (name);
                subs.add (name);
                cp++;
                if (cp < line.length ())
                  {
                    String tail = line.substring (cp).trim ();
                    if (tail.length() > 0)
                      {
                        lines.put (name, tail);
                      }
                  }
              }
            else
              {
                int pp = line.indexOf ('!');
                if (pp > -1)
                  {
                    // Unsubscribed newsgroup
                    String name = line.substring (0, pp);
                    groups.add (name);
                    pp++;
                    if (pp < line.length ())
                      {
                        String tail = line.substring (pp).trim ();
                        if (tail.length () > 0)
                          {
                            lines.put (name, tail);
                          }
                      }
                  }
                // else ignore - comments etc will not be saved!
              }
            line = reader.readLine ();
          }
        reader.close ();
        long t2 = System.currentTimeMillis ();
        if (debug)
          {
            System.err.println ("DEBUG: nntp: newsrc load: " +
                                groups.size () + " groups in " +
                                (t2 - t1) + "ms");
          }
      }
    catch (FileNotFoundException e)
      {
      }
    catch (IOException e)
      {
        System.err.println ("WARNING: nntp: unable to read newsrc file");
        if (debug)
          {
            e.printStackTrace (System.err);
          }
      }
    catch (SecurityException e)
      {
        System.err.println ("WARNING: nntp: " +
                            "no read permission on newsrc file");
      }
    dirty = false;
  }
  
  /**
   * Save the file.
   */
  void save ()
  {
    try
      {
        long t1 = System.currentTimeMillis ();
        if (debug)
          {
            System.err.println ("DEBUG: nntp: newsrc saving " +
                                file.getPath ());
          }

        int bs = (groups.size() * 20);    // guess an average line length
        FileOutputStream fw = new FileOutputStream (file);
        BufferedOutputStream writer = new BufferedOutputStream (fw, bs);
        for (Iterator i = groups.iterator (); i.hasNext ();)
          {
            String group = (String) i.next ();
            StringBuffer buffer = new StringBuffer (group);
            if (subs.contains (group))
              {
                buffer.append (':');
              }
            else
              {
                buffer.append ('!');
              }
            Object r = lines.get (group);
            if (r instanceof String)
              {
                buffer.append ((String) r);
              }
            else
              {
                RangeList ranges = (RangeList) r;
                if (ranges != null)
                  {
                    buffer.append (ranges.toString ());
                  }
              }
            buffer.append ('\n');

            byte[] bytes = buffer.toString ().getBytes (NEWSRC_ENCODING);
            writer.write (bytes);
          }
        writer.flush ();
        writer.close ();

        long t2 = System.currentTimeMillis ();
        if (debug)
          {
            System.err.println("DEBUG: nntp: newsrc save: " +
                               groups.size () + " groups in " +
                               (t2 - t1) + "ms");
          }
      }
    catch (IOException e)
      {
        System.err.println ("WARNING: nntp: unable to save newsrc file");
        if (debug)
          {
            e.printStackTrace (System.err);
          }
      }
    dirty = false;
  }

  /**
   * Returns an iterator over the names of the currently subscribed
   * newsgroups.
   */
  public Iterator list ()
  {
    if (subs == null)
      {
        load ();
      }
    return subs.iterator ();
  }

  public boolean isSubscribed (String newsgroup)
  {
    if (subs == null)
      {
        load ();
      }
    return (subs.contains (newsgroup));
  }

  public void setSubscribed (String newsgroup, boolean flag)
  {
    if (subs == null)
      {
        load ();
      }
    if (flag && !groups.contains (newsgroup))
      {
        groups.add (newsgroup);
      }
    boolean subscribed = subs.contains (newsgroup);
    if (flag && !subscribed)
      {
        subs.add (newsgroup);
        dirty = true;
      }
    else if (!flag && subscribed)
      {
        subs.remove (newsgroup);
        dirty = true;
      }
  }

  public boolean isSeen (String newsgroup, int article)
  {
    if (subs == null)
      {
        load ();
      }
    Object value = lines.get (newsgroup);
    if (value instanceof String)
      {
        value = new RangeList ((String) value);
      }
    RangeList ranges = (RangeList) value;
    if (ranges != null)
      {
        return ranges.isSeen (article);
      }
    return false;
  }

  public void setSeen (String newsgroup, int article, boolean flag)
  {
    if (subs == null)
      {
        load ();
      }
    Object value = lines.get (newsgroup);
    if (value instanceof String)
      {
        value = new RangeList ((String) value);
      }
    RangeList ranges = (RangeList) value;
    if (ranges == null)
      {
        ranges = new RangeList ();
        lines.put (newsgroup, ranges);
        dirty = true;
      }
    if (ranges.isSeen (article) != flag)
      {
        ranges.setSeen (article, flag);
        dirty = true;
      }
  }

  /**
   * A RangeList holds a series of ranges that are ordered and
   * non-overlapping.
   */
  static class RangeList
  {

    List seen;

    RangeList ()
    {
      seen = new ArrayList ();
    }

    RangeList (String line)
    {
      this ();
      try
        {
          // Parse the line at comma delimiters.
          int start = 0;
          int end = line.indexOf (',');
          while (end > start)
            {
              String token = line.substring (start, end);
              addToken (token);
              start = end + 1;
              end = line.indexOf (',', start);
            }
          addToken (line.substring (start));
        }
      catch (NumberFormatException e)
        {
          System.err.println ("ERROR: nntp: bad newsrc format: " + line);
        }
    }

    /*
     * Used during initial parse.
     */
    private void addToken (String token) throws NumberFormatException
    {
      int hp = token.indexOf ('-');
      if (hp > -1)
        {
          // Range
          String fs = token.substring (0, hp);
          String ts = token.substring (hp + 1);
          int from = Integer.parseInt (fs);
          int to = Integer.parseInt (ts);
          if (from > -1 && to > -1)
            {
              insert (from, to);
            }
        }
      else
        {
          // Single number
          int number = Integer.parseInt (token);
          if (number > -1)
            {
              insert (number);
            }
        }
    }

    /**
     * Indicates whether the specified article is seen.
     */
    public boolean isSeen (int num)
    {
      int len = seen.size ();
      Range[] r = new Range[len];
      seen.toArray (r);
      for (int i = 0; i < len; i++)
        {
          if (r[i].contains (num))
            {
              return true;
            }
        }
      return false;
    }

    /**
     * Sets whether the specified article is seen.
     */
    public void setSeen (int num, boolean flag)
    {
      if (flag)
        {
          insert (num);
        }
      else
        {
          remove (num);
        }
    }

    /*
     * Find the index within seen to insert the specified article.
     * The range object at the returned index may already contain num.
     */
    int indexOf (int num)
    {
      int len = seen.size ();
      Range[] r = new Range[len];
      seen.toArray (r);
      for (int i = 0; i < len; i++)
        {
          if (r[i].contains (num))
            {
              return i;
            }
          if (r[i].from > num)
            {
              return i;
            }
          if (r[i].to == num - 1)
            {
              return i;
            }
        }
      return len;
    }

    void insert (int start, int end)
    {
      Range range = new Range (start, end);
      int i1 = indexOf (range.from);
      // range is at end
      if (i1 == seen.size ())
        {
          seen.add (range);
          return;
        }
      Range r1 = (Range) seen.get (i1);
      // range is before r1
      if (range.to < r1.from)
        {
          seen.add (i1, range);
          return;
        }
      // range is a subset of r1
      if (r1.from <= range.from && r1.to >= range.to)
        {
          return;
        }
      // range is a superset of r1
      int i2 = indexOf (range.to);
      Range r2 = (Range) seen.get (i2);
      System.err.println ("r2 " + r2 + " i2 " + i2);
      // remove all ranges between
      for (int i = i2; i >= i1; i--)
        {
          seen.remove (i);
        }
      // merge
      int f = (range.from < r1.from) ? range.from : r1.from;
      int t = (range.to > r2.to) ? range.to : r2.to;
      range = new Range (f, t);
      seen.add (i1, range);
    }

    void insert (int num)
    {
      insert (num, num);
    }

    void remove (int num)
    {
      int i = indexOf (num);
      Range r = (Range) seen.get (i);
      seen.remove (i);
      // num == r
      if ((r.from == r.to) && (r.to == num))
        {
          return;
        }
      // split r
      if (r.to > num)
        {
          Range r2 = new Range (num + 1, r.to);
          seen.add (i, r2);
        }
      if (r.from < num)
        {
          Range r2 = new Range (r.from, num - 1);
          seen.add (i, r2);
        }
    }

    public String toString ()
    {
      StringBuffer buf = new StringBuffer ();
      int len = seen.size ();
      for (int i = 0; i < len; i++)
        {
          Range range = (Range) seen.get (i);
          if (i > 0)
            {
              buf.append (',');
            }
          buf.append (range.toString ());
        }
      return buf.toString ();
    }

  }

  /**
   * A range is either a single integer or a range between two integers.
   */
  static class Range
  {
    int from;
    int to;

    public Range (int i)
    {
      from = to = i;
    }

    public Range (int f, int t)
    {
      if (f > t)
        {
          from = t;
          to = f;
        }
      else
        {
          from = f;
          to = t;
        }
    }

    public boolean contains (int num)
    {
      return (num >= from && num <= to);
    }

    public String toString ()
    {
      if (from != to)
        {
          return new StringBuffer ()
            .append (from)
            .append ('-')
            .append (to)
            .toString ();
        }
      else
        {
          return Integer.toString (from);
        }
    }

  }

}