<commit_before>/*
 * $Id: GenericFileCachedUrlSet.java,v 1.37 2003-04-29 02:21:00 tal Exp $
 */

/*

Copyright (c) 2002 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;

import java.io.*;
import java.util.*;
import java.security.*;
import java.net.MalformedURLException;

import org.lockss.app.*;
import org.lockss.daemon.*;
import org.lockss.hasher.*;
import org.lockss.repository.*;
import org.lockss.util.*;
import org.lockss.poller.PollManager;
import org.lockss.protocol.*;
import org.lockss.plugin.*;
import org.lockss.plugin.base.*;
import org.lockss.state.*;

/**
 * This is an abstract CachedUrlSet implementation which uses the {@link LockssRepository}.
 *
 * @author  Emil Aalto
 * @version 0.0
 */
public class GenericFileCachedUrlSet extends BaseCachedUrlSet {
  private static final int BYTES_PER_MS_DEFAULT = 100;
  static final double TIMEOUT_INCREASE = 1.5;

  private Exception lastException = null;
  private LockssRepository repository;
  private NodeManager nodeManager;
  protected static Logger logger = Logger.getLogger("CachedUrlSet");

 // int contentNodeCount = 0;
  long totalNodeSize = 0;

  public GenericFileCachedUrlSet(ArchivalUnit owner, CachedUrlSetSpec spec) {
    super(owner, spec);
    LockssRepositoryService repService = (LockssRepositoryService)
        LockssDaemon.getManager(LockssDaemon.LOCKSS_REPOSITORY_SERVICE);
    repository = repService.getLockssRepository(owner);
    NodeManagerService nodeService = (NodeManagerService)
        LockssDaemon.getManager(LockssDaemon.NODE_MANAGER_SERVICE);
    nodeManager = nodeService.getNodeManager(owner);
  }

  public boolean isLeaf() {
    try {
      return repository.getNode(getUrl()).isLeaf();
    } catch (MalformedURLException mue) {
      logger.error("Bad url in spec: " + getUrl());
      throw new LockssRepository.RepositoryStateException("Bad url in spec: "
							  +getUrl());
    }
  }

  public Iterator flatSetIterator() {
    if (spec instanceof SingleNodeCachedUrlSetSpec) {
      return CollectionUtil.EMPTY_ITERATOR;
    }
    TreeSet flatSet = new TreeSet(new UrlComparator());
    String prefix = spec.getUrl();
    try {
      RepositoryNode intNode = repository.getNode(prefix);
      Iterator children = intNode.listNodes(spec, false);
      while (children.hasNext()) {
        RepositoryNode child = (RepositoryNode)children.next();
        if (child.isLeaf()) {
          CachedUrl newUrl =
	    ((BaseArchivalUnit)au).cachedUrlFactory(this, child.getNodeUrl());
          flatSet.add(newUrl);
        } else {
	  CachedUrlSetSpec rSpec =
	    new RangeCachedUrlSetSpec(child.getNodeUrl());
          CachedUrlSet newSet = ((BaseArchivalUnit)au).makeCachedUrlSet(rSpec);
          flatSet.add(newSet);
        }
      }
    } catch (MalformedURLException mue) {
      logger.error("Bad url in spec: "+prefix);
      throw new RuntimeException("Bad url in spec: "+prefix);
    }
    return flatSet.iterator();
  }

  /**
   * This returns an iterator over all nodes in the CachedUrlSet.  This
   * includes the node itself if either it's got a RangedCachedUrlSetSpec with
   * no range or a SingleNodeCachedUrlSetSpec
   * @return an {@link Iterator}
   */
  public Iterator contentHashIterator() {
    return new CUSIterator();
  }

  public CachedUrlSetHasher getContentHasher(MessageDigest hasher) {
    return contentHasherFactory(this, hasher);
  }

  public CachedUrlSetHasher getNameHasher(MessageDigest hasher) {
    return nameHasherFactory(this, hasher);
  }

  public void storeActualHashDuration(long elapsed, Exception err) {
    //only store estimate if it was a full hash (not ranged or single node)
    if ((spec instanceof SingleNodeCachedUrlSetSpec) ||
        ((spec instanceof RangeCachedUrlSetSpec) &&
         (((RangeCachedUrlSetSpec)spec).getLowerBound()!=null))) {
      return;
    }
    // don't adjust for exceptions, except time-out exceptions
    long lastDuration = nodeManager.getNodeState(this).getAverageHashDuration();
    lastException = err;
    if (err!=null) {
      if (err instanceof HashService.Timeout) {
        // increment current estimate by 50%, so as to avoid future timeouts
        if (lastDuration > 0) {
          nodeManager.hashFinished(this,
                                   (long)(Math.max(elapsed, lastDuration) *
					  TIMEOUT_INCREASE));
        }
      }
    } else {
      //average with current estimate to minimize effect of extreme results
      if (lastDuration > 0) {
        lastDuration = (lastDuration + elapsed) / 2;
      }
      else {
        lastDuration = elapsed;
      }
      nodeManager.hashFinished(this, lastDuration);
    }
  }

  public long estimatedHashDuration() {
    long lastDuration = nodeManager.getNodeState(this).getAverageHashDuration();
    if (lastDuration>0) return lastDuration;<commit_msg>Yet another fix to expired bahavior.<commit_after>/*
 * $Id: GenericFileCachedUrlSet.java,v 1.38 2003-04-30 04:55:39 tal Exp $
 */

/*

Copyright (c) 2002 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;

import java.io.*;
import java.util.*;
import java.security.*;
import java.net.MalformedURLException;

import org.lockss.app.*;
import org.lockss.daemon.*;
import org.lockss.hasher.*;
import org.lockss.repository.*;
import org.lockss.util.*;
import org.lockss.poller.PollManager;
import org.lockss.protocol.*;
import org.lockss.plugin.*;
import org.lockss.plugin.base.*;
import org.lockss.state.*;

/**
 * This is an abstract CachedUrlSet implementation which uses the {@link LockssRepository}.
 *
 * @author  <NAME>
 * @version 0.0
 */
public class GenericFileCachedUrlSet extends BaseCachedUrlSet {
  private static final int BYTES_PER_MS_DEFAULT = 100;
  static final double TIMEOUT_INCREASE = 1.5;

  private Exception lastException = null;
  private LockssRepository repository;
  private NodeManager nodeManager;
  protected static Logger logger = Logger.getLogger("CachedUrlSet");

 // int contentNodeCount = 0;
  long totalNodeSize = 0;

  public GenericFileCachedUrlSet(ArchivalUnit owner, CachedUrlSetSpec spec) {
    super(owner, spec);
    LockssRepositoryService repService = (LockssRepositoryService)
        LockssDaemon.getManager(LockssDaemon.LOCKSS_REPOSITORY_SERVICE);
    repository = repService.getLockssRepository(owner);
    NodeManagerService nodeService = (NodeManagerService)
        LockssDaemon.getManager(LockssDaemon.NODE_MANAGER_SERVICE);
    nodeManager = nodeService.getNodeManager(owner);
  }

  public boolean isLeaf() {
    try {
      return repository.getNode(getUrl()).isLeaf();
    } catch (MalformedURLException mue) {
      logger.error("Bad url in spec: " + getUrl());
      throw new LockssRepository.RepositoryStateException("Bad url in spec: "
							  +getUrl());
    }
  }

  public Iterator flatSetIterator() {
    if (spec instanceof SingleNodeCachedUrlSetSpec) {
      return CollectionUtil.EMPTY_ITERATOR;
    }
    TreeSet flatSet = new TreeSet(new UrlComparator());
    String prefix = spec.getUrl();
    try {
      RepositoryNode intNode = repository.getNode(prefix);
      Iterator children = intNode.listNodes(spec, false);
      while (children.hasNext()) {
        RepositoryNode child = (RepositoryNode)children.next();
        if (child.isLeaf()) {
          CachedUrl newUrl =
	    ((BaseArchivalUnit)au).cachedUrlFactory(this, child.getNodeUrl());
          flatSet.add(newUrl);
        } else {
	  CachedUrlSetSpec rSpec =
	    new RangeCachedUrlSetSpec(child.getNodeUrl());
          CachedUrlSet newSet = ((BaseArchivalUnit)au).makeCachedUrlSet(rSpec);
          flatSet.add(newSet);
        }
      }
    } catch (MalformedURLException mue) {
      logger.error("Bad url in spec: "+prefix);
      throw new RuntimeException("Bad url in spec: "+prefix);
    }
    return flatSet.iterator();
  }

  /**
   * This returns an iterator over all nodes in the CachedUrlSet.  This
   * includes the node itself if either it's got a RangedCachedUrlSetSpec with
   * no range or a SingleNodeCachedUrlSetSpec
   * @return an {@link Iterator}
   */
  public Iterator contentHashIterator() {
    return new CUSIterator();
  }

  public CachedUrlSetHasher getContentHasher(MessageDigest hasher) {
    return contentHasherFactory(this, hasher);
  }

  public CachedUrlSetHasher getNameHasher(MessageDigest hasher) {
    return nameHasherFactory(this, hasher);
  }

  public void storeActualHashDuration(long elapsed, Exception err) {
    //only store estimate if it was a full hash (not ranged or single node)
    if ((spec instanceof SingleNodeCachedUrlSetSpec) ||
        ((spec instanceof RangeCachedUrlSetSpec) &&
         (((RangeCachedUrlSetSpec)spec).getLowerBound()!=null))) {
      return;
    }
    // don't adjust for exceptions, except time-out exceptions
    long lastDuration =
      nodeManager.getNodeState(this).getAverageHashDuration();
    long newEst;

    lastException = err;
    if (err!=null) {
      if (err instanceof HashService.Timeout) {
        // timed out - Guess 50% longer next time
	newEst = (long)(Math.max(elapsed, lastDuration) * TIMEOUT_INCREASE);
      } else {
	// other error - don't update estimate
	return;
      }
    } else {
      //average with current estimate to minimize effect of extreme results
      if (lastDuration > 0) {
        newEst = (lastDuration + elapsed) / 2;
      }
      else {
        newEst = elapsed;
      }
    }
    nodeManager.hashFinished(this, newEst);
  }

  public long estimatedHashDuration() {
    long lastDuration = nodeManager.getNodeState(this).getAverageHashDuration();
    if (lastDuration>0) return lastDuration;
{'fraction_non_alphanumeric': 0.08594647841077, 'fraction_numerical': 0.00582827121983254, 'mean_word_length': 3.722093023255814, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 1, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '820575', 'n_tokens_mistral': 3499, 'n_tokens_neox': 3379, 'n_words': 1111}