<commit_before>/*
 * $Id: TestHighWireMetadataExtractor.java,v 1.2 2009-10-27 22:22:31 dshr Exp $
 */

/*

Copyright (c) 2000-2003 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 this 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.highwire;

import java.io.*;
import java.util.*;
import java.util.regex.*;

import org.lockss.test.*;
import org.lockss.util.*;
import org.lockss.config.*;
import org.lockss.daemon.*;
import org.lockss.crawler.*;
import org.lockss.repository.*;
import org.lockss.extractor.*;
import org.lockss.plugin.*;
import org.lockss.plugin.base.*;
import org.lockss.plugin.simulated.*;

public class TestHighWireMetadataExtractor extends LockssTestCase {
  static Logger log = Logger.getLogger("TestHighWireMetadataExtractor");

  private SimulatedArchivalUnit sau;
  private MockLockssDaemon theDaemon;
  private CrawlManager crawlMgr;
  private static int exceptionCount;
  private static final int DEFAULT_MAX_DEPTH = 1000;
  private static final int DEFAULT_FILESIZE = 3000;
  private static int fileSize = DEFAULT_FILESIZE;
  private static int maxDepth=DEFAULT_MAX_DEPTH;
  private static int urlCount = 28;
  private static int testExceptions = 3;

  private static final Map<String, String> tagMap =
    new HashMap<String, String>();
  static {
    tagMap.put("citation_journal_title", "JOURNAL %1 %2 %3");
    tagMap.put("citation_issn", "%1-%2-%3");

    tagMap.put("citation_authors", "AUTHOR %1 %2 %3");
    tagMap.put("citation_title", "TITLE %1 %2 %3");
    tagMap.put("citation_date", "%1/%2/%3");
    tagMap.put("citation_volume", "%1%2%3");
    tagMap.put("citation_issue", "%3%2%1");
    tagMap.put("citation_firstpage", "%2%1%3");
    tagMap.put("citation_id", "%1%2%3/%3%2%1/%2%1%3");
    tagMap.put("citation_mjid", "MJID;%1%2%3/%3%2%1/%2%1%3");
    tagMap.put("citation_doi", "10.1152/ajprenal.%1%2%3.2004");
    tagMap.put("citation_abstract_html_url", "http://www.example.com/cgi/content/abstract/%1%2%3/%3%2%1/%2%1%3");
    tagMap.put("citation_fulltext_html_url", "http://www.example.com/cgi/content/full/%1%2%3/%3%2%1/%2%1%3");
    tagMap.put("citation_pdf_url", "http://www.example.com/cgi/reprint/%1%2%3/%3%2%1/%2%1%3.pdf");
    tagMap.put("citation_pmid", "%3%2%1");

    tagMap.put("dc.Contributor", "AUTHOR %1 %2 %3");
    tagMap.put("dc.Title", "TITLE %1 %2 %3");
    tagMap.put("dc.Identifier", "10.1152/ajprenal.%1%2%3.2004");
    tagMap.put("dc.Date", "%1/%2/%3");
  };

  public static void main(String[] args) throws Exception {
    TestHighWireMetadataExtractor test = new TestHighWireMetadataExtractor();
    if (args.length>0) {
      try {
        maxDepth = Integer.parseInt(args[0]);
      } catch (NumberFormatException ex) { }
    }

    test.setUp(maxDepth);
    test.testExtraction();
    test.tearDown();
  }

  public void setUp() throws Exception {
    super.setUp();
    this.setUp(DEFAULT_MAX_DEPTH);
  }

  public void setUp(int max) throws Exception {

    String tempDirPath = getTempDir().getAbsolutePath() + File.separator;
    String auId = "org|lockss|plugin|highwire|TestHighWireMetadataExtractor$MySimulatedPlugin.root~" +
      PropKeyEncoder.encode(tempDirPath);
    Properties props = new Properties();
    props.setProperty(NewContentCrawler.PARAM_MAX_CRAWL_DEPTH, ""+max);
    maxDepth=max;
    props.setProperty(LockssRepositoryImpl.PARAM_CACHE_LOCATION, tempDirPath);

    props.setProperty("org.lockss.au." + auId + "." +
                      SimulatedPlugin.AU_PARAM_ROOT, tempDirPath);
    // the simulated Content's depth will be (AU_PARAM_DEPTH + 1)
    props.setProperty("org.lockss.au." + auId + "." +
                      SimulatedPlugin.AU_PARAM_DEPTH, "3");
    props.setProperty("org.lockss.au." + auId + "." +
                      SimulatedPlugin.AU_PARAM_BRANCH, "3");
    props.setProperty("org.lockss.au." + auId + "." +
                      SimulatedPlugin.AU_PARAM_NUM_FILES, "7");
    props.setProperty("org.lockss.au." + auId + "." +
                      SimulatedPlugin.AU_PARAM_FILE_TYPES, "" +
                      (SimulatedContentGenerator.FILE_TYPE_PDF +
		       SimulatedContentGenerator.FILE_TYPE_HTML));
    props.setProperty("org.lockss.au." + auId + "." +
                      SimulatedPlugin.AU_PARAM_BIN_FILE_SIZE, ""+fileSize);

    theDaemon = getMockLockssDaemon();
    theDaemon.getAlertManager();
    theDaemon.getPluginManager().setLoadablePluginsReady(true);
    theDaemon.setDaemonInited(true);
    theDaemon.getPluginManager().startService();
    crawlMgr = theDaemon.getCrawlManager();

    ConfigurationUtil.setCurrentConfigFromProps(props);

    sau =
        (SimulatedArchivalUnit)theDaemon.getPluginManager().getAllAus().get(0);
    theDaemon.getLockssRepository(sau).startService();
    theDaemon.setNodeManager(new MockNodeManager(), sau);
  }

  public void tearDown() throws Exception {
    sau.deleteContentTree();
    theDaemon.stopDaemon();
    super.tearDown();
  }

  public void testExtraction() throws Exception {
    createContent();

    // get the root of the simContent
    String simDir = sau.getSimRoot();

    crawlContent();

    exceptionCount = 0;
    int count = 0;
    for (Iterator it = sau.getArticleIterator(); it.hasNext(); ) {
	BaseCachedUrl cu = (BaseCachedUrl)it.next();
	assertNotNull(cu);
	assertTrue(cu instanceof CachedUrl);
	log.debug3("count " + count + " url " + cu.getUrl());
	MetadataExtractor me = cu.getMetadataExtractor();
	log.debug3("Extractor: " + me.toString());
	assertTrue(me instanceof
		   HighWireMetadataExtractorFactory.HighWireMetadataExtractor);
	Metadata md = me.extract(cu);
	assertNotNull(md);
	checkMetadata(md);
	count++;
    }
    log.debug("Article count is " + count);
    assertEquals(urlCount, count);
  }

  private void createContent() {
    log.debug("Generating tree of size 3x1x2 with "+fileSize<commit_msg>Better unit test.<commit_after>/*
 * $Id: TestHighWireMetadataExtractor.java,v 1.3 2009-12-09 05:13:03 dshr Exp $
 */

/*

Copyright (c) 2000-2003 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 this 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.highwire;

import java.io.*;
import java.util.*;
import java.util.regex.*;

import org.lockss.test.*;
import org.lockss.util.*;
import org.lockss.config.*;
import org.lockss.daemon.*;
import org.lockss.crawler.*;
import org.lockss.repository.*;
import org.lockss.extractor.*;
import org.lockss.plugin.*;
import org.lockss.plugin.base.*;
import org.lockss.plugin.simulated.*;

public class TestHighWireMetadataExtractor extends LockssTestCase {
  static Logger log = Logger.getLogger("TestHighWireMetadataExtractor");

  private SimulatedArchivalUnit sau;
  private MockLockssDaemon theDaemon;
  private CrawlManager crawlMgr;
  private static int exceptionCount;
  private static final int DEFAULT_MAX_DEPTH = 1000;
  private static final int DEFAULT_FILESIZE = 3000;
  private static int fileSize = DEFAULT_FILESIZE;
  private static int maxDepth=DEFAULT_MAX_DEPTH;
  private static int urlCount = 28;
  private static int testExceptions = 3;

  private static final Map<String, String> tagMap =
    new HashMap<String, String>();
  static {
    tagMap.put("citation_journal_title", "JOURNAL %1 %2 %3");
    tagMap.put("citation_issn", "%1-%2-%3");

    tagMap.put("citation_authors", "AUTHOR %1 %2 %3");
    tagMap.put("citation_title", "TITLE %1 %2 %3");
    tagMap.put("citation_date", "%1/%2/%3");
    tagMap.put("citation_volume", "%1%2%3");
    tagMap.put("citation_issue", "%3%2%1");
    tagMap.put("citation_firstpage", "%2%1%3");
    tagMap.put("citation_id", "%1%2%3/%3%2%1/%2%1%3");
    tagMap.put("citation_mjid", "MJID;%1%2%3/%3%2%1/%2%1%3");
    tagMap.put("citation_doi", "10.1152/ajprenal.%1%2%3.2004");
    tagMap.put("citation_abstract_html_url", "http://www.example.com/cgi/content/abstract/%1%2%3/%3%2%1/%2%1%3");
    tagMap.put("citation_fulltext_html_url", "http://www.example.com/cgi/content/full/%1%2%3/%3%2%1/%2%1%3");
    tagMap.put("citation_pdf_url", "http://www.example.com/cgi/reprint/%1%2%3/%3%2%1/%2%1%3.pdf");
    tagMap.put("citation_pmid", "%3%2%1");

    tagMap.put("dc.Contributor", "AUTHOR %1 %2 %3");
    tagMap.put("dc.Title", "TITLE %1 %2 %3");
    tagMap.put("dc.Identifier", "10.1152/ajprenal.%1%2%3.2004");
    tagMap.put("dc.Date", "%1/%2/%3");
  };

  public static void main(String[] args) throws Exception {
    TestHighWireMetadataExtractor test = new TestHighWireMetadataExtractor();
    if (args.length>0) {
      try {
        maxDepth = Integer.parseInt(args[0]);
      } catch (NumberFormatException ex) { }
    }

    test.setUp(maxDepth);
    test.testExtraction();
    test.tearDown();
  }

  public void setUp() throws Exception {
    super.setUp();
    this.setUp(DEFAULT_MAX_DEPTH);
  }

  public void setUp(int max) throws Exception {

    String tempDirPath = getTempDir().getAbsolutePath() + File.separator;
    String auId = "org|lockss|plugin|highwire|TestHighWireMetadataExtractor$MySimulatedPlugin.root~" +
      PropKeyEncoder.encode(tempDirPath);
    Properties props = new Properties();
    props.setProperty(NewContentCrawler.PARAM_MAX_CRAWL_DEPTH, ""+max);
    maxDepth=max;
    props.setProperty(LockssRepositoryImpl.PARAM_CACHE_LOCATION, tempDirPath);

    props.setProperty("org.lockss.au." + auId + "." +
                      SimulatedPlugin.AU_PARAM_ROOT, tempDirPath);
    // the simulated Content's depth will be (AU_PARAM_DEPTH + 1)
    props.setProperty("org.lockss.au." + auId + "." +
                      SimulatedPlugin.AU_PARAM_DEPTH, "3");
    props.setProperty("org.lockss.au." + auId + "." +
                      SimulatedPlugin.AU_PARAM_BRANCH, "3");
    props.setProperty("org.lockss.au." + auId + "." +
                      SimulatedPlugin.AU_PARAM_NUM_FILES, "7");
    props.setProperty("org.lockss.au." + auId + "." +
                      SimulatedPlugin.AU_PARAM_FILE_TYPES, "" +
                      (SimulatedContentGenerator.FILE_TYPE_PDF +
		       SimulatedContentGenerator.FILE_TYPE_HTML));
    props.setProperty("org.lockss.au." + auId + "." +
                      SimulatedPlugin.AU_PARAM_BIN_FILE_SIZE, ""+fileSize);

    theDaemon = getMockLockssDaemon();
    theDaemon.getAlertManager();
    theDaemon.getPluginManager().setLoadablePluginsReady(true);
    theDaemon.setDaemonInited(true);
    theDaemon.getPluginManager().startService();
    crawlMgr = theDaemon.getCrawlManager();

    ConfigurationUtil.setCurrentConfigFromProps(props);

    sau =
        (SimulatedArchivalUnit)theDaemon.getPluginManager().getAllAus().get(0);
    theDaemon.getLockssRepository(sau).startService();
    theDaemon.setNodeManager(new MockNodeManager(), sau);
  }

  public void tearDown() throws Exception {
    sau.deleteContentTree();
    theDaemon.stopDaemon();
    super.tearDown();
  }

  public void testExtraction() throws Exception {
    createContent();

    // get the root of the simContent
    String simDir = sau.getSimRoot();

    crawlContent();

    exceptionCount = 0;
    int count = 0;
    for (Iterator it = sau.getArticleIterator(); it.hasNext(); ) {
	BaseCachedUrl cu = (BaseCachedUrl)it.next();
	assertNotNull(cu);
	assertTrue(cu instanceof CachedUrl);
	log.debug3("count " + count + " url " + cu.getUrl());
	MetadataExtractor me = cu.getMetadataExtractor();
	log.debug3("Extractor: " + me.toString());
	assertTrue(me instanceof
		   HighWireMetadataExtractorFactory.HighWireMetadataExtractor);
	Metadata md = me.extract(cu);
	assertNotNull(md);
	checkMetadata(md);
	count++;
    }
    log.debug("Article count is " + count);
    assertEquals(urlCount, count);
  }

  String goodDOI = "10.1152/ajprenal.13.4.123";
  String goodVolume = "13";
  String goodIssue = "4";
  String goodStartPage = "123";
  String goodISSN = "1234-5678";
  String goodDate = "4/1/2000";
  String goodAuthor = "<NAME>";
  String goodTitle = "Spurious Results";
  String goodAbsUrl = "http://www.example.com/cgi/content/abstract/13/4/123";
  String goodPdfUrl = "http://www.example.com/cgi/content/reprint/13/4/123";
  String goodHtmUrl = "http://www.example.com/cgi/content/full/13/4/123";
  String[] dublinCoreField = {
    "dc.Identifier",
    "dc.Date",
    "dc.Contributor",
    "dc.Title",
  };
  String[] dublinCoreValue = {
    goodDOI,
    goodDate,
    goodAuthor,
    goodTitle,
  };
  String goodContent =
    "<HTML><HEAD><TITLE>" + goodTitle + "</TITLE></HEAD><BODY>\n" + 
    "<meta name=\"citation_journal_title\"" + 
      " content=\"Bogus\">\n" +	
    "<meta name=\"citation_authors\"" + 
      " content=\"" + goodAuthor + "\">\n" + 
    "<meta name=\"citation_title\" content=\"" + goodTitle + "\">\n" +
    "<meta name=\"citation_date\" content=\"" + goodDate + "\">\n" +
    "<meta name=\"citation_volume\"" +
      " content=\"" + goodVolume + "\">\n" +
    "<meta name=\"citation_issue\" content=\"" + goodIssue + "\">\n" +
    "<meta name=\"citation_issn\" content=\"" + goodISSN + "\">\n" +
    "<meta name=\"citation_firstpage\"" +
      " content=\"" + goodStartPage + "\">\n" +
    "<meta name=\"citation_pdf_url\"" +
      " content=\"" + goodPdfUrl + "\">\n" +
    "<meta name=\"citation_abstract_html_url\"" +
      " content=\"" + goodAbsUrl + "\">\n" +
    "<meta name=\"citation_doi\"" + " content=\"" + goodDOI + "\">\n" +
    "<meta name=\"citation_id\"" + " content=\"13/4/123\">\n" +
    "<meta name=\"citation_mjid\"" + " content=\"MJID;13/4/123\">\n" +
    "<meta name=\"citation_pmid\"" + " content=\"13.4.123\">\n" +
    "<meta name=\"dc.Contributor\"" + " content=\"" + goodAuthor + "\">\n" +
    "<meta name=\"dc.Title\"" + " content=\"" + goodTitle + "\">\n" +
    "<meta name=\"dc.Identifier\"" + " content=\"" + goodDOI + "\">\n" +
      "<meta name=\"dc.Date\"" + " content=\"" + goodDate + "\">\n";

  public void testExtractFromGoodContent() throws Exception {
    String url = "http://www.example.com/vol1/issue2/art3/";
    MockCachedUrl cu = new MockCachedUrl(url, sau);
    cu.setContent(goodContent);
    cu.setContentSize(goodContent.length());
    MetadataExtractorFactory mef = new HighWireMetadataExtractorFactory();
    MetadataExtractor me = mef.createMetadataExtractor("text/html");
    assertNotNull(me);
    log.debug3("Extractor: " + me.toString());
    assertTrue(me instanceof HighWireMetadataExtractorFactory.HighWireMetadataExtractor);
    Metadata md = me.extract(cu);
    assertNotNull(md);
    assertEquals(goodDOI, md.getDOI());
    assertEquals(goodVolume, md.getVolume());
    assertEquals(goodIssue, md.getIssue());
    assertEquals(goodStartPage, md.getStartPage());
    assertEquals(goodISSN, md.getISSN());
    for (int i = 1; i < dublinCoreField.length; i++) {
      assertEquals(dublinCoreValue[i], md.getProperty(dublinCoreField[i]));
    }
  }

  String badContent =
    "<HTML><HEAD><TITLE>" + goodTitle + "</TITLE></HEAD><BODY>\n" + 
    "<meta name=\"foo\"" +  " content=\"bar\">\n" +
    "  <div id=\"issn\">" +
    "<!-- FILE: /data/templates/www.example.com/bogus/issn.inc -->MUMBLE: " +
    goodISSN + " </div>\n";

  public void testExtractFromBadContent() throws Exception {
    String url = "http://www.example.com/vol1/issue2/art3/";
    MockCachedUrl cu = new MockCachedUrl(url, sau);
    cu.setContent(badContent);
    cu.setContentSize(badContent.length());
    MetadataExtractorFactory mef = new HighWireMetadataExtractorFactory();
    MetadataExtractor me = mef.createMetadataExtractor("text/html");
    assertNotNull(me);
    log.debug3("Extractor: " + me.toString());
    assertTrue(me instanceof HighWireMetadataExtractorFactory.HighWireMetadataExtractor);
    Metadata md = me.extract(cu);
    assertNotNull(md);
    assertNull(md.getDOI());
    assertNull(md.getVolume());
    assertNull(md.getIssue());
    assertNull(md.getStartPage());
    assertNull(md.getISSN());
    for (int i = 1; i < dublinCoreField.length; i++) {
      assertNull(md.getProperty(dublinCoreField[i]));
    }
    assertEquals(1, md.size());
    assertEquals("bar", md.getProperty("foo"));
  }

  private void createContent() {
    log.debug("Generating tree of size 3x1x2 with "+fileSize
{'fraction_non_alphanumeric': 0.14519173723100157, 'fraction_numerical': 0.021088398683997627, 'mean_word_length': 3.891057768398839, 'pattern_counts': {'":': 0, '<': 44, '<?xml version=': 0, '>': 44, 'https://': 0, 'lorem ipsum': 0, 'www.': 12, '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': '3439490', 'n_tokens_mistral': 6254, 'n_tokens_neox': 5918, 'n_words': 1323}