<commit_before>/*
 * $Id: PalgraveBookPdfFilterFactory.java,v 1.2 2014-09-08 15:03:08 aishizaki Exp $
 */

/*

Copyright (c) 2000-2014 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of his software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.plugin.palgrave;

import java.util.List;

import org.lockss.filter.pdf.SimplePdfFilterFactory;
import org.lockss.pdf.*;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.util.Logger;

public class PalgraveBookPdfFilterFactory extends SimplePdfFilterFactory {

  private static final Logger logger = Logger.getLoggerWithInitialLevel(PalgraveBookPdfFilterFactory.class.getName(), Logger.LEVEL_DEBUG3);
  
  protected static class Worker extends PdfTokenStreamWorker {
    
    protected boolean result;

    protected int beginIndex;
    
    protected int endIndex;
    
    protected int state;

    public Worker() {
      super(Direction.BACKWARD);
    }
    
    @Override
    public void setUp() throws PdfException {
      super.setUp();
      this.state = 0;
      this.result = false;
      this.beginIndex = -1;
      this.endIndex = -1;
    }

    @Override
    public void operatorCallback() throws PdfException {
      if (logger.isDebug3()) {
        logger.debug3("Worker: initial: " + state);
        logger.debug3("Worker: index: " + getIndex());
        logger.debug3("Worker: operator: " + getOpcode());
      }
      
      switch (state) {
        
        case 0: {
          if (isEndTextObject()) {
            endIndex = getIndex();
            ++state;
          }
        } break;
        
        case 1: {
          if (isShowTextGlyphPositioningStartsWith("Copyright material from www.palgraveconnect.com")) {
            ++state;
          }
          else if (isBeginTextObject()) {
            stop();
          }
        } break;
        
        case 2: {
          if (isBeginTextObject()) {
            result = true;
            beginIndex = getIndex();
            stop();
          }
        } break;
        
        default: {
          throw new PdfException("Invalid state in Worker: " + state);
        }
        
      }
      
      if (logger.isDebug3()) {
        logger.debug3("Worker: final: " + state);
        logger.debug3("Worker: result: " + result);
      }
      
    }

  }
  
  @Override
  public void transform(ArchivalUnit au, PdfDocument pdfDocument) throws PdfException {
    pdfDocument.unsetModificationDate();
    pdfDocument.unsetCreationDate();
    pdfDocument.unsetMetadata();
    PdfUtil.normalizeTrailerId(pdfDocument);
    
    Worker worker = new Worker();
    for (PdfPage pdfPage : pdfDocument.getPages()) {
      // Pages seem to be made of concatenated token streams, and the
      // target personalization is at the end -- get the last token stream
      List<PdfTokenStream> pdfTokenstreams = pdfPage.getAllTokenStreams();
      PdfTokenStream pdfTokenStream = pdfTokenstreams.get(pdfTokenstreams.size() - 1);
      worker.process(pdfTokenStream);
      if (worker.result) {
        List<PdfToken> pdfTokens = pdfTokenStream.getTokens();
        pdfTokens.subList(worker.beginIndex, worker.endIndex + 1).clear();
        pdfTokenStream.setTokens(pdfTokens);
      }
    }
  }
  
}<commit_msg>temp fix: Currently an access date appears on the right page edge - that date regularly appeared in the last token stream, so that was the only one that was checked.  Smoke Test found a book (9781137023803 - STATUTORY REGULATION AND EMPLOYMENT RELATIONS) where the access date on 4 pages ("This page intentionally left Blank") was not in the last token stream. Modified to check all token streams, instead of only the last.<commit_after>/*
 * $Id: PalgraveBookPdfFilterFactory.java,v 1.3 2015-01-12 17:47:09 aishizaki Exp $
 */

/*

Copyright (c) 2000-2014 Board of Trustees of Leland Stanford Jr. University,
all rights reserved.

Permission is hereby granted, free of charge, to any person obtaining a copy
of his software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
STANFORD UNIVERSITY BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Except as contained in this notice, the name of Stanford University shall not
be used in advertising or otherwise to promote the sale, use or other dealings
in this Software without prior written authorization from Stanford University.

*/

package org.lockss.plugin.palgrave;

import java.util.List;

import org.lockss.filter.pdf.SimplePdfFilterFactory;
import org.lockss.pdf.*;
import org.lockss.plugin.ArchivalUnit;
import org.lockss.util.Logger;

public class PalgraveBookPdfFilterFactory extends SimplePdfFilterFactory {

  private static final Logger logger = Logger.getLoggerWithInitialLevel(PalgraveBookPdfFilterFactory.class.getName(), Logger.LEVEL_DEBUG3);
  
  protected static class Worker extends PdfTokenStreamWorker {
    
    protected boolean result;

    protected int beginIndex;
    
    protected int endIndex;
    
    protected int state;

    public Worker() {
      super(Direction.BACKWARD);
    }
    
    @Override
    public void setUp() throws PdfException {
      super.setUp();
      this.state = 0;
      this.result = false;
      this.beginIndex = -1;
      this.endIndex = -1;
    }

    @Override
    public void operatorCallback() throws PdfException {
      if (logger.isDebug3()) {
        logger.debug3("Worker: initial: " + state);
        logger.debug3("Worker: index: " + getIndex());
        logger.debug3("Worker: operator: " + getOpcode());
      }
      
      switch (state) {
        
        case 0: {
          if (isEndTextObject()) {
            endIndex = getIndex();
            ++state;
          }
        } break;
        
        case 1: {
          if (isShowTextGlyphPositioningStartsWith("Copyright material from www.palgraveconnect.com")) {
            ++state;
          }
          else if (isBeginTextObject()) {
            stop();
          }
        } break;
        
        case 2: {
          if (isBeginTextObject()) {
            result = true;
            beginIndex = getIndex();
            stop();
          }
        } break;
        
        default: {
          throw new PdfException("Invalid state in Worker: " + state);
        }
        
      }
      
      if (logger.isDebug3()) {
        logger.debug3("Worker: final: " + state);
        logger.debug3("Worker: result: " + result);
      }
      
    }

  }
  
  @Override
  public void transform(ArchivalUnit au, PdfDocument pdfDocument) throws PdfException {
    pdfDocument.unsetModificationDate();
    pdfDocument.unsetCreationDate();
    pdfDocument.unsetMetadata();
    PdfUtil.normalizeTrailerId(pdfDocument);
    
    Worker worker = new Worker();
    for (PdfPage pdfPage : pdfDocument.getPages()) {
      // Pages seem to be made of concatenated token streams, and while most
      // target personalization is at the end (previously filtered the last
      // token stream), some books (9781137023803 - on pages with "Left Intentianally
      // Blank") had customization elsewhere in the token stream, so now checking all
      List<PdfTokenStream> pdfTokenstreams = pdfPage.getAllTokenStreams();
      for (int i = 0; i < pdfTokenstreams.size(); i++){
        PdfTokenStream pdfTokenStream = pdfTokenstreams.get(i);
        worker.process(pdfTokenStream);
        if (worker.result) {
          List<PdfToken> pdfTokens = pdfTokenStream.getTokens();
          pdfTokens.subList(worker.beginIndex, worker.endIndex + 1).clear();
          pdfTokenStream.setTokens(pdfTokens);
        }
      }
    }
  }
  
}
{'fraction_non_alphanumeric': 0.08116305825750444, 'fraction_numerical': 0.0111912979813827, 'mean_word_length': 2.8171656686626747, 'pattern_counts': {'":': 0, '<': 8, '<?xml version=': 0, '>': 7, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3111320', 'n_tokens_mistral': 2673, 'n_tokens_neox': 2567, 'n_words': 906}