proj_name
stringclasses
131 values
relative_path
stringlengths
30
228
class_name
stringlengths
1
68
func_name
stringlengths
1
48
masked_class
stringlengths
78
9.82k
func_body
stringlengths
46
9.61k
len_input
int64
29
2.01k
len_output
int64
14
1.94k
total
int64
55
2.05k
relevant_context
stringlengths
0
38.4k
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/frontier/WagCostAssignmentPolicy.java
WagCostAssignmentPolicy
costOf
class WagCostAssignmentPolicy extends CostAssignmentPolicy { private static final long serialVersionUID = 1L; /** * Add constant penalties for certain features of URI (and * its 'via') that make it more delayable/skippable. * * @param curi CrawlURI to be assigned a cost * * @see org.archive.crawler.frontier.CostAssignmentPolicy#costOf(org.archive.modules.CrawlURI) */ public int costOf(CrawlURI curi) {<FILL_FUNCTION_BODY>} }
int cost = 1; UURI uuri = curi.getUURI(); if (uuri.hasQuery()) { // has query string cost++; int qIndex = uuri.toString().indexOf('?'); if (curi.flattenVia().startsWith(uuri.toString().substring(0,qIndex))) { // non-query-string portion of URI is same as previous cost++; } // TODO: other potential query-related cost penalties: // - more than X query-string attributes // - calendarish terms // - query-string over certain size } // TODO: other potential path-based penalties // - new path is simply extension of via path // - many path segments // TODO: other potential hops-based penalties // - more than X hops // - each speculative hop return cost;
155
232
387
<methods>public non-sealed void <init>() ,public abstract int costOf(org.archive.modules.CrawlURI) <variables>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/frontier/precedence/BaseQueuePrecedencePolicy.java
BaseQueuePrecedencePolicy
queueReevaluate
class BaseQueuePrecedencePolicy extends QueuePrecedencePolicy implements HasKeyedProperties { private static final long serialVersionUID = 8312032856661175869L; protected KeyedProperties kp = new KeyedProperties(); public KeyedProperties getKeyedProperties() { return kp; } { setBasePrecedence(3); } public int getBasePrecedence() { return (Integer) kp.get("basePrecedence"); } /** constant precedence to assign; default is 3 (which leaves room * for a simple overlay to prioritize queues) */ public void setBasePrecedence(int precedence) { kp.put("basePrecedence", precedence); } /* (non-Javadoc) * @see org.archive.crawler.frontier.QueuePrecedencePolicy#queueCreated(org.archive.crawler.frontier.WorkQueue) */ @Override public void queueCreated(WorkQueue wq) { installProvider(wq); } /** * Install the appropriate provider helper object into the WorkQueue, * if necessary. * * @param wq target WorkQueue this policy will operate on */ protected void installProvider(WorkQueue wq) { SimplePrecedenceProvider precedenceProvider = new SimplePrecedenceProvider(calculatePrecedence(wq)); wq.setPrecedenceProvider(precedenceProvider); } /** * Calculate the precedence value for the given queue. * * @param wq WorkQueue * @return int precedence value */ protected int calculatePrecedence(WorkQueue wq) { return getBasePrecedence(); } /* (non-Javadoc) * @see org.archive.crawler.frontier.QueuePrecedencePolicy#queueReevaluate(org.archive.crawler.frontier.WorkQueue) */ @Override public void queueReevaluate(WorkQueue wq) {<FILL_FUNCTION_BODY>} }
PrecedenceProvider precedenceProvider = wq.getPrecedenceProvider(); // TODO: consider if this fails to replace provider that is // a subclass of Simple when necessary if(precedenceProvider instanceof SimplePrecedenceProvider) { // reset inside provider ((SimplePrecedenceProvider)precedenceProvider).setPrecedence( calculatePrecedence(wq)); } else { // replace provider installProvider(wq); }
609
132
741
<methods>public non-sealed void <init>() ,public abstract void queueCreated(org.archive.crawler.frontier.WorkQueue) ,public abstract void queueReevaluate(org.archive.crawler.frontier.WorkQueue) <variables>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/frontier/precedence/HighestUriQueuePrecedencePolicy.java
HighestUriPrecedenceProvider
tally
class HighestUriPrecedenceProvider extends SimplePrecedenceProvider { private static final long serialVersionUID = 5545297542888582745L; protected Histotable<Integer> enqueuedCounts = new Histotable<Integer>(); public HighestUriPrecedenceProvider(int base) { super(base); } /* (non-Javadoc) * @see org.archive.crawler.frontier.precedence.PrecedenceProvider#tally(org.archive.modules.CrawlURI, org.archive.modules.fetcher.FetchStats.Stage) */ @Override public void tally(CrawlURI curi, Stage stage) {<FILL_FUNCTION_BODY>} /* (non-Javadoc) * @see org.archive.crawler.frontier.precedence.SimplePrecedenceProvider#getPrecedence() */ @Override public int getPrecedence() { // base plus highest URI still in queue synchronized (enqueuedCounts) { Integer delta = (enqueuedCounts.size() > 0) ? enqueuedCounts.firstKey() : 0; return super.getPrecedence() + delta; } } /* * @see org.archive.crawler.frontier.precedence.PrecedenceProvider#shortReportLegend()() */ @Override public String shortReportLegend() { StringBuilder sb = new StringBuilder(); sb.append(super.shortReportLegend()); sb.append(":"); synchronized (enqueuedCounts) { for (Integer p : enqueuedCounts.keySet()) { sb.append(" p"); sb.append(p); } } return sb.toString(); } @Override public void shortReportLineTo(PrintWriter writer) { boolean betwixt = false; synchronized (enqueuedCounts) { for (Long count : enqueuedCounts.values()) { if (betwixt) writer.print(" "); writer.print(count); betwixt = true; } } } }
switch(stage) { case SCHEDULED: // enqueued synchronized (enqueuedCounts) { enqueuedCounts.tally(curi.getPrecedence()); } break; case SUCCEEDED: case DISREGARDED: case FAILED: // dequeued synchronized (enqueuedCounts) { enqueuedCounts.tally(curi.getPrecedence(), -1); } break; case RETRIED: // do nothing, already tallied break; }
618
173
791
<methods>public non-sealed void <init>() ,public int getBasePrecedence() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public void queueCreated(org.archive.crawler.frontier.WorkQueue) ,public void queueReevaluate(org.archive.crawler.frontier.WorkQueue) ,public void setBasePrecedence(int) <variables>protected org.archive.spring.KeyedProperties kp,private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/frontier/precedence/PrecedenceLoader.java
PrecedenceLoader
main
class PrecedenceLoader { public PrecedenceLoader() { } /** * Utility main for importing a text file (first argument) with lines of * the form: * * URI [whitespace] precedence * * into a BDB-JE environment (second argument, created if necessary). * * @param args command-line arguments * @throws DatabaseException * @throws IOException */ public static void main(String[] args) throws DatabaseException, IOException {<FILL_FUNCTION_BODY>} /** * Merge the precalculated precedence information in the first argument * file to the environment in the second environment (path; environment * will be created if it does not already exist). * * @param args command-line arguments * @throws DatabaseException * @throws FileNotFoundException * @throws UnsupportedEncodingException * @throws IOException */ private static void main2args(String[] args) throws DatabaseException, FileNotFoundException, UnsupportedEncodingException, IOException { File source = new File(args[0]); File env = new File(args[1]); FileUtils.ensureWriteableDirectory(env); // setup target environment EnhancedEnvironment targetEnv = PersistProcessor.setupCopyEnvironment(env); StoredClassCatalog classCatalog = targetEnv.getClassCatalog(); Database historyDB = targetEnv.openDatabase( null, PersistProcessor.URI_HISTORY_DBNAME, PersistProcessor.HISTORY_DB_CONFIG.toDatabaseConfig()); @SuppressWarnings({ "rawtypes", "unchecked" }) StoredSortedMap<String, Object> historyMap = new StoredSortedMap<String, Object>(historyDB, new StringBinding(), new SerialBinding(classCatalog, Map.class), true); int count = 0; if(source.isFile()) { // scan log, writing to database BufferedReader br = ArchiveUtils.getBufferedReader(source); Iterator<String> iter = new LineReadingIterator(br); while(iter.hasNext()) { String line = (String) iter.next(); String[] splits = line.split("\\s"); String uri = splits[0]; if(!uri.matches("\\w+:.*")) { // prepend "http://" uri = "http://"+uri; } String key = PersistProcessor.persistKeyFor(uri); int precedence = Integer.parseInt(splits[1]); @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>)historyMap.get(key); if (map==null) { map = new HashMap<String, Object>(); } map.put(A_PRECALC_PRECEDENCE, precedence); historyMap.put(key,map); count++; if(count % 100000 == 0) { System.out.print(count+"... "); } } br.close(); System.out.println(); System.out.println(count+" entries loaded"); } else { // error System.err.println("unacceptable source file"); return; } // cleanup historyDB.sync(); historyDB.close(); targetEnv.close(); System.out.println(count+" records imported from "+source+" to BDB env "+env); } }
if(args.length==2) { main2args(args); } else { System.out.println("Arguments: "); System.out.println(" source target"); System.out.println( "...where source is a file of lines 'URI precedence' "); System.out.println( "and target is a BDB env dir (created if necessary). "); return; }
910
109
1,019
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/frontier/precedence/PrecedenceProvider.java
PrecedenceProvider
shortReportMap
class PrecedenceProvider implements Reporter, FetchStats.CollectsFetchStats, Serializable { private static final long serialVersionUID = 1L; abstract public int getPrecedence(); /* (non-Javadoc) * @see org.archive.modules.fetcher.FetchStats.CollectsFetchStats#tally(org.archive.modules.CrawlURI, org.archive.modules.fetcher.FetchStats.Stage) */ public void tally(CrawlURI curi, Stage stage) { // by default do nothing; subclasses do more } /* (non-Javadoc) * @see org.archive.util.Reporter#reportTo(java.io.PrintWriter) */ @Override public void reportTo(PrintWriter writer) { writer.println(shortReportLegend()); shortReportLineTo(writer); } @Override public String shortReportLegend() { return getClass().getSimpleName(); } public String shortReportLine() { return ReportUtils.shortReportLine(this); } @Override public Map<String, Object> shortReportMap() {<FILL_FUNCTION_BODY>} @Override public void shortReportLineTo(PrintWriter writer) { writer.print(getPrecedence()); } }
Map<String,Object> data = new LinkedHashMap<String, Object>(); data.put("precedence", getPrecedence()); return data;
377
42
419
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/frontier/precedence/PreloadedUriPrecedencePolicy.java
PreloadedUriPrecedencePolicy
start
class PreloadedUriPrecedencePolicy extends BaseUriPrecedencePolicy implements Lifecycle { private static final long serialVersionUID = -1474685153995064123L; { setDefaultUriPrecedencePolicy(new BaseUriPrecedencePolicy()); } public UriPrecedencePolicy getDefaultUriPrecedencePolicy() { return (UriPrecedencePolicy) kp.get("defaultUriPrecedencePolicy"); } /** Backup URI precedence assignment policy to use. */ public void setDefaultUriPrecedencePolicy(UriPrecedencePolicy policy) { kp.put("defaultUriPrecedencePolicy",policy); } // TODO: refactor to better share code with PersistOnlineProcessor protected BdbModule bdb; @Autowired public void setBdbModule(BdbModule bdb) { this.bdb = bdb; } protected StoredSortedMap<String, ?> store; protected Database historyDb; @SuppressWarnings({ "unchecked", "rawtypes" }) public void start() {<FILL_FUNCTION_BODY>} public boolean isRunning() { return historyDb != null; } public void stop() { if(!isRunning()) { return; } // BdbModule will handle closing of DB // XXX happens at finish; move to teardown? historyDb = null; } /* (non-Javadoc) * @see org.archive.crawler.frontier.precedence.BaseUriPrecedencePolicy#uriScheduled(org.archive.crawler.datamodel.CrawlURI) */ @Override public void uriScheduled(CrawlURI curi) { int precedence = calculatePrecedence(curi); if(precedence==0) { // fall back to configured default policy getDefaultUriPrecedencePolicy().uriScheduled(curi); return; } curi.setPrecedence(precedence); } /* (non-Javadoc) * @see org.archive.crawler.frontier.precedence.BaseUriPrecedencePolicy#calculatePrecedence(org.archive.crawler.datamodel.CrawlURI) */ @Override protected int calculatePrecedence(CrawlURI curi) { mergePrior(curi); Integer preloadPrecedence = (Integer) curi.getData().get(A_PRECALC_PRECEDENCE); if(preloadPrecedence==null) { return 0; } return super.calculatePrecedence(curi) + preloadPrecedence; } /** * Merge any data from the Map stored in the URI-history store into the * current instance. * * TODO: ensure compatibility with use of PersistLoadProcessor; suppress * double-loading * @param curi CrawlURI to receive prior state data */ protected void mergePrior(CrawlURI curi) { String key = PersistProcessor.persistKeyFor(curi); @SuppressWarnings({ "rawtypes", "unchecked" }) Map<String,Map> prior = (Map<String, Map>) store.get(key); if(prior!=null) { // merge in keys curi.getData().putAll(prior); } } }
if(isRunning()) { return; } store = null; String dbName = PersistProcessor.URI_HISTORY_DBNAME; try { StoredClassCatalog classCatalog = bdb.getClassCatalog(); BdbModule.BdbConfig dbConfig = PersistProcessor.HISTORY_DB_CONFIG; historyDb = bdb.openDatabase(dbName, dbConfig, true); SerialBinding sb = new SerialBinding(classCatalog, Map.class); StoredSortedMap historyMap = new StoredSortedMap(historyDb, new StringBinding(), sb, true); store = historyMap; } catch (DatabaseException e) { throw new RuntimeException(e); }
984
198
1,182
<methods>public non-sealed void <init>() ,public int getBasePrecedence() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public void setBasePrecedence(int) ,public void uriScheduled(org.archive.modules.CrawlURI) <variables>protected org.archive.spring.KeyedProperties kp,private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/frontier/precedence/SuccessCountsQueuePrecedencePolicy.java
SuccessCountsQueuePrecedencePolicy
calculatePrecedence
class SuccessCountsQueuePrecedencePolicy extends BaseQueuePrecedencePolicy { private static final long serialVersionUID = -4469760728466350850L; // TODO: determine why this doesn't work // // /** comma-separated list of success-counts at which precedence is bumped*/ // final public static Key<List<Integer>> INCREMENT_COUNTS = // Key.make((List<Integer>)Arrays.asList(new Integer[] {100})); // // /** // * @param wq // * @return // */ // protected int calculatePrecedence(WorkQueue wq) { // // FIXME: it's inefficient to do this every time; optimizing // // should be possible via more sophisticated custom PrecedenceProvider // int precedence = wq.get(this,BASE_PRECEDENCE) - 1; // Iterator<Integer> iter = wq.get(this,INCREMENT_COUNTS).iterator(); // int increment = iter.next(); // long successes = wq.getSubstats().getFetchSuccesses(); // while(successes>0) { // successes -= increment; // precedence++; // increment = iter.hasNext() ? iter.next() : increment; // } // return precedence; // } { setIncrementCounts("100,1000"); } public String getIncrementCounts() { return (String) kp.get("incrementCounts"); } /** comma-separated list of success-counts at which precedence is bumped*/ public void setIncrementCounts(String counts) { kp.put("incrementCounts",counts); } /* (non-Javadoc) * @see org.archive.crawler.frontier.QueuePrecedencePolicy#queueReevaluate(org.archive.crawler.frontier.WorkQueue) */ @SuppressWarnings("unchecked") @Override protected int calculatePrecedence(WorkQueue wq) {<FILL_FUNCTION_BODY>} }
// FIXME: it's ridiculously inefficient to do this every time, // and optimizing will probably require inserting stateful policy // helper object into WorkQueue -- expected when URI-precedence is // also supported int precedence = getBasePrecedence() - 1; Collection<Integer> increments = CollectionUtils.collect( Arrays.asList(getIncrementCounts().split(",")), new Transformer() { public Object transform(final Object string) { return Integer.parseInt((String)string); }}); Iterator<Integer> iter = increments.iterator(); int increment = iter.next(); long successes = wq.getSubstats().getFetchSuccesses(); while(successes>=0) { successes -= increment; precedence++; increment = iter.hasNext() ? iter.next() : increment; } return precedence;
609
260
869
<methods>public non-sealed void <init>() ,public int getBasePrecedence() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public void queueCreated(org.archive.crawler.frontier.WorkQueue) ,public void queueReevaluate(org.archive.crawler.frontier.WorkQueue) ,public void setBasePrecedence(int) <variables>protected org.archive.spring.KeyedProperties kp,private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/io/NonFatalErrorFormatter.java
NonFatalErrorFormatter
format
class NonFatalErrorFormatter extends UriProcessingFormatter implements CoreAttributeConstants { public NonFatalErrorFormatter(boolean logExtraInfo) { super(logExtraInfo); } /* (non-Javadoc) * @see java.util.logging.Formatter#format(java.util.logging.LogRecord) */ public String format(LogRecord lr) {<FILL_FUNCTION_BODY>} }
// Throwable ex = lr.getThrown(); Throwable ex = (Throwable)lr.getParameters()[1]; // LocalizedError err = (LocalizedError) lr.getParameters()[1]; // Throwable ex = (Throwable)err.exception; StringWriter sw = new StringWriter(); ex.printStackTrace(new PrintWriter(sw)); return super.format(lr) + " " + sw.toString();
113
119
232
<methods>public void <init>(boolean) ,public void clear() ,public java.lang.String format(java.util.logging.LogRecord) ,public void preformat(java.util.logging.LogRecord) <variables>private static final int GUESS_AT_LINE_LENGTH,private static final java.lang.String NA,protected final ThreadLocal<java.lang.StringBuilder> bufLocal,protected final ThreadLocal<java.lang.String> cachedFormat,protected boolean logExtraInfo
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/io/RuntimeErrorFormatter.java
RuntimeErrorFormatter
format
class RuntimeErrorFormatter extends UriProcessingFormatter implements CoreAttributeConstants { public RuntimeErrorFormatter(boolean logExtraInfo) { super(logExtraInfo); } public String format(LogRecord lr) {<FILL_FUNCTION_BODY>} }
Object [] parameters = lr.getParameters(); String stackTrace = "None retrieved"; if (parameters != null) { // CrawlURI is always first parameter. CrawlURI curi = (CrawlURI)parameters[0]; if (curi != null) { Throwable t = (Throwable)curi.getData().get(A_RUNTIME_EXCEPTION); assert t != null : "Null throwable"; StringWriter sw = new StringWriter(); if (t == null) { sw.write("No exception to report."); } else { t.printStackTrace(new PrintWriter(sw)); } stackTrace = sw.toString(); } } return super.format(lr) + " " + stackTrace;
73
204
277
<methods>public void <init>(boolean) ,public void clear() ,public java.lang.String format(java.util.logging.LogRecord) ,public void preformat(java.util.logging.LogRecord) <variables>private static final int GUESS_AT_LINE_LENGTH,private static final java.lang.String NA,protected final ThreadLocal<java.lang.StringBuilder> bufLocal,protected final ThreadLocal<java.lang.String> cachedFormat,protected boolean logExtraInfo
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/io/UriErrorFormatter.java
UriErrorFormatter
format
class UriErrorFormatter extends Formatter implements CoreAttributeConstants { /* (non-Javadoc) * @see java.util.logging.Formatter#format(java.util.logging.LogRecord) */ public String format(LogRecord lr) {<FILL_FUNCTION_BODY>} }
UURI uuri = (UURI) lr.getParameters()[0]; String problem = (String) lr.getParameters()[1]; return ArchiveUtils.getLog17Date() + " " + ( (uuri ==null) ? "n/a" : uuri.toString() ) + " \"" + lr.getMessage() + "\" " + problem + "\n";
80
112
192
<methods>public abstract java.lang.String format(java.util.logging.LogRecord) ,public java.lang.String formatMessage(java.util.logging.LogRecord) ,public java.lang.String getHead(java.util.logging.Handler) ,public java.lang.String getTail(java.util.logging.Handler) <variables>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/io/UriProcessingFormatter.java
UriProcessingFormatter
format
class UriProcessingFormatter extends Formatter implements Preformatter, CoreAttributeConstants { private final static String NA = "-"; /** * Guess at line length. Used to preallocated the buffer we accumulate the * log line in. Hopefully we get it right most of the time and no need to * enlarge except in the rare case. * * <p> * In a sampling of actual Aug 2014 Archive-It crawl logs I found that a * line length 1000 characters was around the 99th percentile (only 1 in 100 * is longer than that). We put more information in the crawl log now than * was originally estimated. Exactly what goes in can depend on the * configuration as well. */ private final static int GUESS_AT_LINE_LENGTH = 1000; /** * Reusable assembly buffer. */ protected final ThreadLocal<StringBuilder> bufLocal = new ThreadLocal<StringBuilder>() { @Override protected StringBuilder initialValue() { return new StringBuilder(GUESS_AT_LINE_LENGTH); } }; protected final ThreadLocal<String> cachedFormat = new ThreadLocal<String>(); protected boolean logExtraInfo; public UriProcessingFormatter(boolean logExtraInfo) { this.logExtraInfo = logExtraInfo; } public String format(LogRecord lr) {<FILL_FUNCTION_BODY>} /** * @param str String to check. * @return Return passed string or <code>NA</code> if null. */ protected String checkForNull(String str) { return (str == null || str.length() <= 0)? NA: str; } @Override public void clear() { cachedFormat.set(null); } @Override public void preformat(LogRecord record) { cachedFormat.set(format(record)); } }
if(cachedFormat.get()!=null) { return cachedFormat.get(); } CrawlURI curi = (CrawlURI)lr.getParameters()[0]; String length = NA; String mime = null; if (curi.isHttpTransaction()) { if(curi.getContentLength() >= 0) { length = Long.toString(curi.getContentLength()); } else if (curi.getContentSize() > 0) { length = Long.toString(curi.getContentSize()); } } else { if (curi.getContentSize() > 0) { length = Long.toString(curi.getContentSize()); } } mime = MimetypeUtils.truncate(curi.getContentType()); long time = System.currentTimeMillis(); String via = curi.flattenVia(); String digest = curi.getContentDigestSchemeString(); String sourceTag = curi.containsDataKey(A_SOURCE_TAG) ? curi.getSourceTag() : null; StringBuilder buffer = bufLocal.get(); buffer.setLength(0); buffer.append(ArchiveUtils.getLog17Date(time)) .append(" ") .append(ArchiveUtils.padTo(curi.getFetchStatus(), 5)) .append(" ") .append(ArchiveUtils.padTo(length, 10)) .append(" ") .append(curi.getUURI().toString()) .append(" ") .append(checkForNull(curi.getPathFromSeed())) .append(" ") .append(checkForNull(via)) .append(" ") .append(mime) .append(" ") .append("#") // Pad threads to be 3 digits. For Igor. .append(ArchiveUtils.padTo( Integer.toString(curi.getThreadNumber()), 3, '0')) .append(" "); // arcTimeAndDuration if(curi.containsDataKey(A_FETCH_COMPLETED_TIME)) { long completedTime = curi.getFetchCompletedTime(); long beganTime = curi.getFetchBeginTime(); buffer.append(ArchiveUtils.get17DigitDate(beganTime)) .append("+") .append(Long.toString(completedTime - beganTime)); } else { buffer.append(NA); } buffer.append(" ") .append(checkForNull(digest)) .append(" ") .append(checkForNull(sourceTag)) .append(" "); Collection<String> anno = curi.getAnnotations(); if ((anno != null) && (anno.size() > 0)) { Iterator<String> iter = anno.iterator(); buffer.append(iter.next()); while (iter.hasNext()) { buffer.append(','); buffer.append(iter.next()); } } else { buffer.append(NA); } if (logExtraInfo) { buffer.append(" ").append(curi.getExtraInfo()); } buffer.append("\n"); return buffer.toString();
517
851
1,368
<methods>public abstract java.lang.String format(java.util.logging.LogRecord) ,public java.lang.String formatMessage(java.util.logging.LogRecord) ,public java.lang.String getHead(java.util.logging.Handler) ,public java.lang.String getTail(java.util.logging.Handler) <variables>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/monitor/DiskSpaceMonitor.java
DiskSpaceMonitor
checkAvailableSpace
class DiskSpaceMonitor implements ApplicationListener<ApplicationEvent> { private static final Logger logger = Logger.getLogger(DiskSpaceMonitor.class.getName()); protected List<String> monitorPaths = new ArrayList<String>(); protected long pauseThresholdMiB = 8192; protected CrawlController controller; protected ConfigPathConfigurer configPathConfigurer; protected boolean monitorConfigPaths = true; /** * @param monitorPaths List of filesystem paths that should be monitored for available space. */ public void setMonitorPaths(List<String> monitorPaths) { this.monitorPaths = monitorPaths; } public List<String> getMonitorPaths() { return this.monitorPaths; } /** * Set the minimum amount of space that must be available on all monitored paths. * If the amount falls below this pause threshold on any path the crawl will be paused. * * @param pauseThresholdMiB The desired pause threshold value. * Specified in megabytes (MiB). */ public void setPauseThresholdMiB(long pauseThresholdMiB) { this.pauseThresholdMiB = pauseThresholdMiB; } public long getPauseThresholdMiB() { return this.pauseThresholdMiB; } /** * If enabled, all the paths returned by {@link ConfigPathConfigurer#getAllConfigPaths()} * will be monitored in addition to any paths explicitly specified via * {@link #setMonitorPaths(List)}. * <p> * <code>true</code> by default. * <p> * <em>Note:</em> This is not guaranteed to contain all paths that Heritrix writes to. * It is the responsibility of modules that write to disk to register their activity * with the {@link ConfigPathConfigurer} and some may not do so. * * @param monitorConfigPaths If config paths should be monitored for usable space. */ public void setMonitorConfigPaths(boolean monitorConfigPaths){ this.monitorConfigPaths = monitorConfigPaths; } public boolean getMonitorConfigPaths(){ return this.monitorConfigPaths; } /** Autowire access to CrawlController **/ @Autowired public void setCrawlController(CrawlController controller) { this.controller = controller; } public CrawlController getCrawlController() { return this.controller; } /** Autowire access to ConfigPathConfigurer **/ @Autowired public void setConfigPathConfigurer(ConfigPathConfigurer configPathConfigurer) { this.configPathConfigurer = configPathConfigurer; } public ConfigPathConfigurer getConfigPathConfigurer() { return this.configPathConfigurer; } /** * Checks available space on {@link StatSnapshotEvent}s. */ @Override public void onApplicationEvent(ApplicationEvent event) { if (event instanceof StatSnapshotEvent) { // Check available space every time the statistics tracker // updates its sample, by default every 20 sec. for (String path : getMonitorPaths()) { checkAvailableSpace(new File(path)); } if (monitorConfigPaths) { for(ConfigPath path : configPathConfigurer.getAllConfigPaths().values()) { checkAvailableSpace(path.getFile()); } } } } /** * Probe via File.getUsableSpace to see if monitored paths have fallen below * the pause threshold. If so, request a crawl pause. * * @param path The filesystem path to check for usable space */ protected void checkAvailableSpace(File path) {<FILL_FUNCTION_BODY>} }
if (!path.exists()) { // Paths that can not be resolved will not report accurate // available space. Log and ignore. logger.fine("Ignoring non-existent path " + path.getAbsolutePath()); return; } long availBytes = path.getUsableSpace(); long thresholdBytes = getPauseThresholdMiB() * 1024 * 1024; if (availBytes < thresholdBytes && controller.isActive()) { // Enact pause controller.requestCrawlPause(); // Log issue String errorMsg = "Low Disk Pause - %d bytes (%s) available on %s, " + "this is below the minimum threshold of %d bytes (%s)"; logger.log(Level.SEVERE, String.format(errorMsg, availBytes, ArchiveUtils.formatBytesForDisplay(availBytes), path.getAbsolutePath(), thresholdBytes, ArchiveUtils.formatBytesForDisplay(thresholdBytes))); }
1,095
282
1,377
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/postprocessor/LowDiskPauseProcessor.java
LowDiskPauseProcessor
checkAvailableSpace
class LowDiskPauseProcessor extends Processor { @SuppressWarnings("unused") private static final long serialVersionUID = 3L; /** * Logger. */ private static final Logger logger = Logger.getLogger(LowDiskPauseProcessor.class.getName()); protected CrawlController controller; public CrawlController getCrawlController() { return this.controller; } @Autowired public void setCrawlController(CrawlController controller) { this.controller = controller; } /** * List of filessystem mounts whose 'available' space should be monitored * via 'df' (if available). */ protected List<String> monitorMounts = new ArrayList<String>(); public List<String> getMonitorMounts() { return this.monitorMounts; } public void setMonitorMounts(List<String> monitorMounts) { this.monitorMounts = monitorMounts; } /** * When available space on any monitored mounts falls below this threshold, * the crawl will be paused. */ protected int pauseThresholdKb = 500*1024; // 500MB public int getPauseThresholdKb() { return this.pauseThresholdKb; } public void setPauseThresholdKb(int pauseThresholdKb) { this.pauseThresholdKb = pauseThresholdKb; } /** * Available space via 'df' is rechecked after every increment of this much * content (uncompressed) is observed. */ protected int recheckThresholdKb = 200*1024; // 200MB public int getRecheckThresholdKb() { return this.recheckThresholdKb; } public void setRecheckThresholdKb(int recheckThresholdKb) { this.recheckThresholdKb = recheckThresholdKb; } protected int contentSinceCheck = 0; public static final Pattern VALID_DF_OUTPUT = Pattern.compile("(?s)^Filesystem\\s+1K-blocks\\s+Used\\s+Available\\s+Use%\\s+Mounted on\\n.*"); public static final Pattern AVAILABLE_EXTRACTOR = Pattern.compile("(?m)\\s(\\d+)\\s+\\d+%\\s+(\\S+)$"); public LowDiskPauseProcessor() { } @Override protected boolean shouldProcess(CrawlURI curi) { return true; } @Override protected void innerProcess(CrawlURI uri) { throw new AssertionError(); } /** * Notes a CrawlURI's content size in its running tally. If the * recheck increment of content has passed through since the last * available-space check, checks available space and pauses the * crawl if any monitored mounts are below the configured threshold. * * @param curi CrawlURI to process. */ @Override protected ProcessResult innerProcessResult(CrawlURI curi) { synchronized (this) { contentSinceCheck += curi.getContentSize(); if (contentSinceCheck/1024 > getRecheckThresholdKb()) { ProcessResult r = checkAvailableSpace(curi); contentSinceCheck = 0; return r; } else { return ProcessResult.PROCEED; } } } /** * Probe via 'df' to see if monitored mounts have fallen * below the pause available threshold. If so, request a * crawl pause. * @param curi Current context. */ private ProcessResult checkAvailableSpace(CrawlURI curi) {<FILL_FUNCTION_BODY>} }
try { String df = IOUtils.toString(Runtime.getRuntime().exec( "df -k").getInputStream()); Matcher matcher = VALID_DF_OUTPUT.matcher(df); if(!matcher.matches()) { logger.severe("'df -k' output unacceptable for low-disk checking"); return ProcessResult.PROCEED; } List<String> monitoredMounts = getMonitorMounts(); matcher = AVAILABLE_EXTRACTOR.matcher(df); while (matcher.find()) { String mount = matcher.group(2); if (monitoredMounts.contains(mount)) { long availKilobytes = Long.parseLong(matcher.group(1)); int thresholdKilobytes = getPauseThresholdKb(); if (availKilobytes < thresholdKilobytes ) { logger.log(Level.SEVERE, "Low Disk Pause", availKilobytes + "K available on " + mount + " (below threshold " + thresholdKilobytes + "K)"); controller.requestCrawlPause(); return ProcessResult.PROCEED; } } } } catch (IOException e) { curi.getNonFatalFailures().add(e); } return ProcessResult.PROCEED;
1,034
358
1,392
<methods>public non-sealed void <init>() ,public void doCheckpoint(org.archive.checkpointing.Checkpoint) throws java.io.IOException,public void finishCheckpoint(org.archive.checkpointing.Checkpoint) ,public static java.lang.String flattenVia(org.archive.modules.CrawlURI) ,public java.lang.String getBeanName() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public static long getRecordedSize(org.archive.modules.CrawlURI) ,public org.archive.modules.deciderules.DecideRule getShouldProcessRule() ,public long getURICount() ,public static boolean hasHttpAuthenticationCredential(org.archive.modules.CrawlURI) ,public boolean isRunning() ,public static boolean isSuccess(org.archive.modules.CrawlURI) ,public org.archive.modules.ProcessResult process(org.archive.modules.CrawlURI) throws java.lang.InterruptedException,public java.lang.String report() ,public void setBeanName(java.lang.String) ,public void setEnabled(boolean) ,public void setRecoveryCheckpoint(org.archive.checkpointing.Checkpoint) ,public void setShouldProcessRule(org.archive.modules.deciderules.DecideRule) ,public void start() ,public void startCheckpoint(org.archive.checkpointing.Checkpoint) ,public void stop() <variables>protected java.lang.String beanName,protected boolean isRunning,protected org.archive.spring.KeyedProperties kp,protected org.archive.checkpointing.Checkpoint recoveryCheckpoint,protected java.util.concurrent.atomic.AtomicLong uriCount
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/postprocessor/ReschedulingProcessor.java
ReschedulingProcessor
innerProcess
class ReschedulingProcessor extends Processor { { setRescheduleDelaySeconds(-1L); } public long getRescheduleDelaySeconds() { return (Long) kp.get("rescheduleDelaySeconds"); } /** * amount of time to wait before forcing a URI to be rescheduled * default of -1 means "don't reschedule" */ public void setRescheduleDelaySeconds(long rescheduleDelaySeconds) { kp.put("rescheduleDelaySeconds",rescheduleDelaySeconds); } public ReschedulingProcessor() { super(); } @Override protected boolean shouldProcess(CrawlURI curi) { return true; } @Override protected void innerProcess(CrawlURI curi) {<FILL_FUNCTION_BODY>} }
if(curi.isPrerequisite()) { // never resched prereqs; they get rescheduled as needed curi.setRescheduleTime(-1); return; } long rds = getRescheduleDelaySeconds(); if(rds>0) { curi.setRescheduleTime(System.currentTimeMillis()+(1000*rds)); } else { curi.setRescheduleTime(-1); }
258
146
404
<methods>public non-sealed void <init>() ,public void doCheckpoint(org.archive.checkpointing.Checkpoint) throws java.io.IOException,public void finishCheckpoint(org.archive.checkpointing.Checkpoint) ,public static java.lang.String flattenVia(org.archive.modules.CrawlURI) ,public java.lang.String getBeanName() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public static long getRecordedSize(org.archive.modules.CrawlURI) ,public org.archive.modules.deciderules.DecideRule getShouldProcessRule() ,public long getURICount() ,public static boolean hasHttpAuthenticationCredential(org.archive.modules.CrawlURI) ,public boolean isRunning() ,public static boolean isSuccess(org.archive.modules.CrawlURI) ,public org.archive.modules.ProcessResult process(org.archive.modules.CrawlURI) throws java.lang.InterruptedException,public java.lang.String report() ,public void setBeanName(java.lang.String) ,public void setEnabled(boolean) ,public void setRecoveryCheckpoint(org.archive.checkpointing.Checkpoint) ,public void setShouldProcessRule(org.archive.modules.deciderules.DecideRule) ,public void start() ,public void startCheckpoint(org.archive.checkpointing.Checkpoint) ,public void stop() <variables>protected java.lang.String beanName,protected boolean isRunning,protected org.archive.spring.KeyedProperties kp,protected org.archive.checkpointing.Checkpoint recoveryCheckpoint,protected java.util.concurrent.atomic.AtomicLong uriCount
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/postprocessor/SupplementaryLinksScoper.java
SupplementaryLinksScoper
isInScope
class SupplementaryLinksScoper extends Scoper { @SuppressWarnings("unused") private static final long serialVersionUID = -3L; private static Logger LOGGER = Logger.getLogger(SupplementaryLinksScoper.class.getName()); { setSupplementaryRule(new AcceptDecideRule()); } public DecideRule getSupplementaryRule() { return (DecideRule) kp.get("supplementaryRule"); } /** * DecideRules which if their final decision on a link is * REJECT, cause the link to be ruled out-of-scope, even * if it had previously been accepted by the main scope. */ public void setSupplementaryRule(DecideRule rule) { kp.put("supplementaryRule", rule); } public SupplementaryLinksScoper() { super(); } protected boolean shouldProcess(CrawlURI puri) { return puri instanceof CrawlURI; } protected void innerProcess(final CrawlURI puri) { CrawlURI curi = (CrawlURI)puri; // If prerequisites or no links, nothing to be done in here. if (curi.hasPrerequisiteUri() || curi.getOutLinks().isEmpty()) { return; } // Collection<CrawlURI> inScopeLinks = new HashSet<CrawlURI>(); Iterator<CrawlURI> iter = curi.getOutLinks().iterator(); while (iter.hasNext()) { CrawlURI cauri = iter.next(); if (!isInScope(cauri)) { iter.remove(); } } // for (CrawlURI cauri: curi.getOutCandidates()) { // if (isInScope(cauri)) { // inScopeLinks.add(cauri); // } // } // Replace current links collection w/ inscopeLinks. May be // an empty collection. // curi.replaceOutlinks(inScopeLinks); } protected boolean isInScope(CrawlURI caUri) {<FILL_FUNCTION_BODY>} /** * Called when a CrawlURI is ruled out of scope. * @param caUri CrawlURI that is out of scope. */ protected void outOfScope(CrawlURI caUri) { if (!LOGGER.isLoggable(Level.INFO)) { return; } LOGGER.info(caUri.getUURI().toString()); } }
// TODO: Fix filters so work on CrawlURI. CrawlURI curi = (caUri instanceof CrawlURI)? (CrawlURI)caUri: new CrawlURI(caUri.getUURI()); boolean result = false; DecideRule seq = getSupplementaryRule(); if (seq.decisionFor(curi) == DecideResult.ACCEPT) { result = true; if (LOGGER.isLoggable(Level.FINER)) { LOGGER.finer("Accepted: " + caUri); } } else { outOfScope(caUri); } return result;
689
171
860
<methods>public void <init>() ,public boolean getLogToFile() ,public org.archive.crawler.reporting.CrawlerLoggerModule getLoggerModule() ,public org.archive.modules.deciderules.DecideRule getScope() ,public boolean isRunning() ,public void setLogToFile(boolean) ,public void setLoggerModule(org.archive.crawler.reporting.CrawlerLoggerModule) ,public void setScope(org.archive.modules.deciderules.DecideRule) ,public void start() ,public void stop() <variables>protected java.util.logging.Logger fileLogger,protected boolean isRunning,protected org.archive.crawler.reporting.CrawlerLoggerModule loggerModule,protected org.archive.modules.deciderules.DecideRule scope
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/prefetch/CandidateScoper.java
CandidateScoper
innerProcessResult
class CandidateScoper extends Scoper { @SuppressWarnings("unused") private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(CandidateScoper.class.getName()); @Override protected ProcessResult innerProcessResult(CrawlURI curi) throws InterruptedException {<FILL_FUNCTION_BODY>} @Override protected boolean shouldProcess(CrawlURI uri) { return true; } @Override protected void innerProcess(CrawlURI uri) throws InterruptedException { assert false; } }
try { if (!isInScope(curi)) { // Scope rejected curi.setFetchStatus(FetchStatusCodes.S_OUT_OF_SCOPE); return ProcessResult.FINISH; } } catch (Exception e) { curi.setFetchStatus(FetchStatusCodes.S_RUNTIME_EXCEPTION); logger.log(Level.SEVERE, "problem scoping " + curi, e); return ProcessResult.FINISH; } return ProcessResult.PROCEED;
178
158
336
<methods>public void <init>() ,public boolean getLogToFile() ,public org.archive.crawler.reporting.CrawlerLoggerModule getLoggerModule() ,public org.archive.modules.deciderules.DecideRule getScope() ,public boolean isRunning() ,public void setLogToFile(boolean) ,public void setLoggerModule(org.archive.crawler.reporting.CrawlerLoggerModule) ,public void setScope(org.archive.modules.deciderules.DecideRule) ,public void start() ,public void stop() <variables>protected java.util.logging.Logger fileLogger,protected boolean isRunning,protected org.archive.crawler.reporting.CrawlerLoggerModule loggerModule,protected org.archive.modules.deciderules.DecideRule scope
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/prefetch/Preselector.java
Preselector
innerProcessResult
class Preselector extends Scoper { @SuppressWarnings("unused") private static final long serialVersionUID = 3L; { setRecheckScope(false); } public boolean getRecheckScope() { return (Boolean) kp.get("recheckScope"); } /** * Recheck if uri is in scope. This is meaningful if the scope is altered * during a crawl. URIs are checked against the scope when they are added to * queues. Setting this value to true forces the URI to be checked against * the scope when it is coming out of the queue, possibly after the scope * is altered. */ public void setRecheckScope(boolean recheck) { kp.put("recheckScope",recheck); } { setBlockAll(false); } public boolean getBlockAll() { return (Boolean) kp.get("blockAll"); } /** * Block all URIs from being processed. This is most likely to be used in * overrides to easily reject certain hosts from being processed. */ public void setBlockAll(boolean recheck) { kp.put("blockAll",recheck); } { setBlockByRegex(""); } public String getBlockByRegex() { return (String) kp.get("blockByRegex"); } /** * Block all URIs matching the regular expression from being processed. */ public void setBlockByRegex(String regex) { kp.put("blockByRegex",regex); } { setAllowByRegex(""); } public String getAllowByRegex() { return (String) kp.get("allowByRegex"); } /** * Allow only URIs matching the regular expression to be processed. */ public void setAllowByRegex(String regex) { kp.put("allowByRegex",regex); } /** * Constructor. */ public Preselector() { super(); } @Override protected boolean shouldProcess(CrawlURI puri) { return puri instanceof CrawlURI; } @Override protected void innerProcess(CrawlURI puri) { throw new AssertionError(); } @Override protected ProcessResult innerProcessResult(CrawlURI puri) {<FILL_FUNCTION_BODY>} }
CrawlURI curi = (CrawlURI)puri; // Check if uris should be blocked if (getBlockAll()) { curi.setFetchStatus(S_BLOCKED_BY_USER); return ProcessResult.FINISH; } // Check if allowed by regular expression String regex = getAllowByRegex(); if (regex != null && !regex.equals("")) { if (!TextUtils.matches(regex, curi.toString())) { curi.setFetchStatus(S_BLOCKED_BY_USER); return ProcessResult.FINISH; } } // Check if blocked by regular expression regex = getBlockByRegex(); if (regex != null && !regex.equals("")) { if (TextUtils.matches(regex, curi.toString())) { curi.setFetchStatus(S_BLOCKED_BY_USER); return ProcessResult.FINISH; } } // Possibly recheck scope if (getRecheckScope()) { if (!isInScope(curi)) { // Scope rejected curi.setFetchStatus(S_OUT_OF_SCOPE); return ProcessResult.FINISH; } } return ProcessResult.PROCEED;
643
344
987
<methods>public void <init>() ,public boolean getLogToFile() ,public org.archive.crawler.reporting.CrawlerLoggerModule getLoggerModule() ,public org.archive.modules.deciderules.DecideRule getScope() ,public boolean isRunning() ,public void setLogToFile(boolean) ,public void setLoggerModule(org.archive.crawler.reporting.CrawlerLoggerModule) ,public void setScope(org.archive.modules.deciderules.DecideRule) ,public void start() ,public void stop() <variables>protected java.util.logging.Logger fileLogger,protected boolean isRunning,protected org.archive.crawler.reporting.CrawlerLoggerModule loggerModule,protected org.archive.modules.deciderules.DecideRule scope
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/prefetch/RuntimeLimitEnforcer.java
RuntimeLimitEnforcer
innerProcessResult
class RuntimeLimitEnforcer extends Processor { @SuppressWarnings("unused") private static final long serialVersionUID = 3L; protected static Logger logger = Logger.getLogger( RuntimeLimitEnforcer.class.getName()); /** * The action that the processor takes once the runtime has elapsed. */ public static enum Operation { /** * Pauses the crawl. A change (increase) to the runtime duration will * make it pausible to resume the crawl. Attempts to resume the crawl * without modifying the run time will cause it to be immediately paused * again. */ PAUSE, /** * Terminates the job. Equivalent to using the max-time setting on the * CrawlController. */ TERMINATE, /** * Blocks each URI with an -5002 (blocked by custom processor) fetch * status code. This will cause all the URIs queued to wind up in the * crawl.log. */ BLOCK_URIS }; /** * The amount of time, in seconds, that the crawl will be allowed to run * before this processor performs it's 'end operation.' */ protected long runtimeSeconds = 24*60*60L; // 1 day public long getRuntimeSeconds() { return this.runtimeSeconds; } public void setRuntimeSeconds(long secs) { this.runtimeSeconds = secs; } /** * The action that the processor takes once the runtime has elapsed. * <p> * Operation: Pause job - Pauses the crawl. A change (increase) to the * runtime duration will make it pausible to resume the crawl. Attempts to * resume the crawl without modifying the run time will cause it to be * immediately paused again. * <p> * Operation: Terminate job - Terminates the job. Equivalent to using the * max-time setting on the CrawlController. * <p> * Operation: Block URIs - Blocks each URI with an -5002 (blocked by custom * processor) fetch status code. This will cause all the URIs queued to wind * up in the crawl.log. */ protected Operation expirationOperation = Operation.PAUSE; public Operation getExpirationOperation() { return this.expirationOperation; } public void setExpirationOperation(Operation op) { this.expirationOperation = op; } protected CrawlController controller; public CrawlController getCrawlController() { return this.controller; } @Autowired public void setCrawlController(CrawlController controller) { this.controller = controller; } protected StatisticsTracker statisticsTracker; public StatisticsTracker getStatisticsTracker() { return this.statisticsTracker; } @Autowired public void setStatisticsTracker(StatisticsTracker statisticsTracker) { this.statisticsTracker = statisticsTracker; } public RuntimeLimitEnforcer() { super(); } @Override protected boolean shouldProcess(CrawlURI puri) { return puri instanceof CrawlURI; } @Override protected void innerProcess(CrawlURI curi) { throw new AssertionError(); } @Override protected ProcessResult innerProcessResult(CrawlURI curi) throws InterruptedException {<FILL_FUNCTION_BODY>} }
CrawlController controller = getCrawlController(); StatisticsTracker stats = getStatisticsTracker(); long allowedRuntimeMs = getRuntimeSeconds() * 1000L; long currentRuntimeMs = stats.getCrawlElapsedTime(); if(currentRuntimeMs > allowedRuntimeMs){ Operation op = getExpirationOperation(); if(op != null){ if (op.equals(Operation.PAUSE)) { controller.requestCrawlPause(); } else if (op.equals(Operation.TERMINATE)){ controller.requestCrawlStop(CrawlStatus.FINISHED_TIME_LIMIT); } else if (op.equals(Operation.BLOCK_URIS)) { curi.setFetchStatus(S_BLOCKED_BY_RUNTIME_LIMIT); curi.getAnnotations().add("Runtime exceeded " + allowedRuntimeMs + "ms"); return ProcessResult.FINISH; } } else { logger.log(Level.SEVERE,"Null value for end-operation " + " when processing " + curi.toString()); } } return ProcessResult.PROCEED;
946
300
1,246
<methods>public non-sealed void <init>() ,public void doCheckpoint(org.archive.checkpointing.Checkpoint) throws java.io.IOException,public void finishCheckpoint(org.archive.checkpointing.Checkpoint) ,public static java.lang.String flattenVia(org.archive.modules.CrawlURI) ,public java.lang.String getBeanName() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public static long getRecordedSize(org.archive.modules.CrawlURI) ,public org.archive.modules.deciderules.DecideRule getShouldProcessRule() ,public long getURICount() ,public static boolean hasHttpAuthenticationCredential(org.archive.modules.CrawlURI) ,public boolean isRunning() ,public static boolean isSuccess(org.archive.modules.CrawlURI) ,public org.archive.modules.ProcessResult process(org.archive.modules.CrawlURI) throws java.lang.InterruptedException,public java.lang.String report() ,public void setBeanName(java.lang.String) ,public void setEnabled(boolean) ,public void setRecoveryCheckpoint(org.archive.checkpointing.Checkpoint) ,public void setShouldProcessRule(org.archive.modules.deciderules.DecideRule) ,public void start() ,public void startCheckpoint(org.archive.checkpointing.Checkpoint) ,public void stop() <variables>protected java.lang.String beanName,protected boolean isRunning,protected org.archive.spring.KeyedProperties kp,protected org.archive.checkpointing.Checkpoint recoveryCheckpoint,protected java.util.concurrent.atomic.AtomicLong uriCount
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/processor/CrawlMapper.java
FilePrintWriter
innerProcessResult
class FilePrintWriter extends PrintWriter { File file; public FilePrintWriter(File file) throws FileNotFoundException { super(new BufferedOutputStream(new FileOutputStream(file))); this.file = file; } public File getFile() { return file; } } /** * Whether to apply the mapping to a URI being processed itself, for example * early in processing (while its status is still 'unattempted'). */ protected boolean checkUri = true; public boolean getCheckUri() { return this.checkUri; } public void setCheckUri(boolean check) { this.checkUri = check; } /** * Whether to apply the mapping to discovered outlinks, for example after * extraction has occurred. */ protected boolean checkOutlinks = true; public boolean getCheckOutlinks() { return this.checkOutlinks; } public void setCheckOutlinks(boolean check) { this.checkOutlinks = check; } /** * Decide rules to determine if an outlink is subject to mapping. */ protected DecideRule outlinkRule = new AcceptDecideRule(); public DecideRule getOutlinkRule() { return this.outlinkRule; } public void setOutlinkRule(DecideRule rule) { this.outlinkRule = rule; } /** * Name of local crawler node; mappings to this name result in normal * processing (no diversion). */ protected String localName = "."; public String getLocalName() { return this.localName; } public void setLocalName(String name) { this.localName = name; } /** * Directory to write diversion logs. */ protected ConfigPath diversionDir = new ConfigPath("diverted URIs subdirectory","diversions"); public ConfigPath getDiversionDir() { return this.diversionDir; } public void setDiversionDir(ConfigPath path) { this.diversionDir = path; } /** * Number of timestamp digits to use as prefix of log names (grouping all * diversions from that period in a single log). Default is 10 (hourly log * rotation). * */ protected int rotationDigits = 10; public int getRotationDigits() { return this.rotationDigits; } public void setRotationDigits(int digits) { this.rotationDigits = digits; } /** * Mapping of target crawlers to logs (PrintWriters) */ protected HashMap<String,PrintWriter> diversionLogs = new HashMap<String,PrintWriter>(); /** * Truncated timestamp prefix for diversion logs; when * current time doesn't match, it's time to close all * current logs. */ protected String logGeneration = ""; protected ArrayLongFPCache cache; /** * Constructor. */ public CrawlMapper() { super(); } @Override protected boolean shouldProcess(CrawlURI puri) { return true; } @Override protected void innerProcess(CrawlURI puri) { throw new AssertionError(); } @Override protected ProcessResult innerProcessResult(CrawlURI puri) {<FILL_FUNCTION_BODY>
CrawlURI curi = (CrawlURI)puri; String nowGeneration = ArchiveUtils.get14DigitDate().substring( 0, getRotationDigits()); if(!nowGeneration.equals(logGeneration)) { updateGeneration(nowGeneration); } if (curi.getFetchStatus() <= 0 // unfetched/unsuccessful && getCheckUri()) { // apply mapping to the CrawlURI itself String target = map(curi); if(!localName.equals(target)) { // CrawlURI is mapped to somewhere other than here curi.setFetchStatus(S_BLOCKED_BY_CUSTOM_PROCESSOR); curi.getAnnotations().add("to:"+target); divertLog(curi,target); return ProcessResult.FINISH; } else { // localName means keep locally; do nothing } } if (getCheckOutlinks()) { // consider outlinks for mapping Iterator<CrawlURI> iter = curi.getOutLinks().iterator(); while(iter.hasNext()) { CrawlURI cauri = iter.next(); if (decideToMapOutlink(cauri)) { // apply mapping to the CrawlURI String target = map(cauri); if(!localName.equals(target)) { // CrawlURI is mapped to somewhere other than here iter.remove(); divertLog(cauri,target); } else { // localName means keep locally; do nothing } } } } return ProcessResult.PROCEED;
915
434
1,349
<methods>public non-sealed void <init>() ,public void doCheckpoint(org.archive.checkpointing.Checkpoint) throws java.io.IOException,public void finishCheckpoint(org.archive.checkpointing.Checkpoint) ,public static java.lang.String flattenVia(org.archive.modules.CrawlURI) ,public java.lang.String getBeanName() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public static long getRecordedSize(org.archive.modules.CrawlURI) ,public org.archive.modules.deciderules.DecideRule getShouldProcessRule() ,public long getURICount() ,public static boolean hasHttpAuthenticationCredential(org.archive.modules.CrawlURI) ,public boolean isRunning() ,public static boolean isSuccess(org.archive.modules.CrawlURI) ,public org.archive.modules.ProcessResult process(org.archive.modules.CrawlURI) throws java.lang.InterruptedException,public java.lang.String report() ,public void setBeanName(java.lang.String) ,public void setEnabled(boolean) ,public void setRecoveryCheckpoint(org.archive.checkpointing.Checkpoint) ,public void setShouldProcessRule(org.archive.modules.deciderules.DecideRule) ,public void start() ,public void startCheckpoint(org.archive.checkpointing.Checkpoint) ,public void stop() <variables>protected java.lang.String beanName,protected boolean isRunning,protected org.archive.spring.KeyedProperties kp,protected org.archive.checkpointing.Checkpoint recoveryCheckpoint,protected java.util.concurrent.atomic.AtomicLong uriCount
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/processor/HashCrawlMapper.java
HashCrawlMapper
mapString
class HashCrawlMapper extends CrawlMapper { @SuppressWarnings("unused") private static final long serialVersionUID = 2L; protected Frontier frontier; public Frontier getFrontier() { return this.frontier; } @Autowired public void setFrontier(Frontier frontier) { this.frontier = frontier; } /** * Number of crawlers among which to split up the URIs. Their names are * assumed to be 0..N-1. */ protected long crawlerCount = 1L; public long getCrawlerCount() { return this.crawlerCount; } public void setCrawlerCount(long count) { this.crawlerCount = count; } { setUsePublicSuffixesRegex(true); } public boolean getUsePublicSuffixesRegex() { return (Boolean) kp.get("usePublicSuffixesRegex"); } /** * Whether to use the PublicSuffixes-supplied reduce regex. * */ public void setUsePublicSuffixesRegex(boolean usePublicSuffixes) { kp.put("usePublicSuffixesRegex",usePublicSuffixes); } { setReducePrefixRegex(""); } public String getReducePrefixRegex() { return (String) kp.get("reducePrefixRegex"); } /** * A regex pattern to apply to the classKey, using the first match as the * mapping key. If empty (the default), use the full classKey. * */ public void setReducePrefixRegex(String regex) { kp.put("reducePrefixRegex",regex); } /** * Constructor. */ public HashCrawlMapper() { super(); } /** * Look up the crawler node name to which the given CrawlURI * should be mapped. * * @param cauri CrawlURI to consider * @return String node name which should handle URI */ protected String map(CrawlURI cauri) { // get classKey, via frontier to generate if necessary String key = frontier.getClassKey(cauri); String reduceRegex = getReduceRegex(cauri); return mapString(key, reduceRegex, getCrawlerCount()); } protected String getReduceRegex(CrawlURI cauri) { if(getUsePublicSuffixesRegex()) { return PublicSuffixes.getTopmostAssignedSurtPrefixRegex(); } else { return getReducePrefixRegex(); } } public static String mapString(String key, String reducePattern, long bucketCount) {<FILL_FUNCTION_BODY>} }
if (reducePattern != null && reducePattern.length()>0) { Matcher matcher = TextUtils.getMatcher(reducePattern,key); if(matcher.find()) { key = matcher.group(); } TextUtils.recycleMatcher(matcher); } long fp = FPGenerator.std64.fp(key); long bucket = fp % bucketCount; return Long.toString(bucket >= 0 ? bucket : -bucket);
762
128
890
<methods>public void <init>() ,public boolean getCheckOutlinks() ,public boolean getCheckUri() ,public org.archive.spring.ConfigPath getDiversionDir() ,public java.lang.String getLocalName() ,public org.archive.modules.deciderules.DecideRule getOutlinkRule() ,public int getRotationDigits() ,public boolean isRunning() ,public void setCheckOutlinks(boolean) ,public void setCheckUri(boolean) ,public void setDiversionDir(org.archive.spring.ConfigPath) ,public void setLocalName(java.lang.String) ,public void setOutlinkRule(org.archive.modules.deciderules.DecideRule) ,public void setRotationDigits(int) ,public void start() ,public void stop() <variables>protected org.archive.util.fingerprint.ArrayLongFPCache cache,protected boolean checkOutlinks,protected boolean checkUri,protected org.archive.spring.ConfigPath diversionDir,protected HashMap<java.lang.String,java.io.PrintWriter> diversionLogs,protected java.lang.String localName,protected java.lang.String logGeneration,protected org.archive.modules.deciderules.DecideRule outlinkRule,protected int rotationDigits
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/processor/LexicalCrawlMapper.java
LexicalCrawlMapper
loadMap
class LexicalCrawlMapper extends CrawlMapper { @SuppressWarnings("unused") private static final long serialVersionUID = 2L; /** * Path to map specification file. Each line should include 2 * whitespace-separated tokens: the first a key indicating the end of a * range, the second the crawler node to which URIs in the key range should * be mapped. This setting is ignored if MAP_URI is specified. */ protected ConfigPath mapPath = new ConfigPath("map specification file","lexicalcrawlmapper.config"); public ConfigPath getMapPath() { return this.mapPath; } public void setMapPath(ConfigPath path) { this.mapPath = path; } /** * URI to map specification file. Each line should include 2 * whitespace-separated tokens: the first a key indicating the end of a * range, the second the crawler node to which URIs in the key range should * be mapped. This setting takes precedence over MAP_PATH; if both are * specified, then MAP_PATH is ignored. */ protected String mapUri = ""; public String getMapUri() { return this.mapUri; } public void setMapUri(String uri) { this.mapUri = uri; } protected Frontier frontier; public Frontier getFrontier() { return this.frontier; } @Autowired public void setFrontier(Frontier frontier) { this.frontier = frontier; } /** * Mapping of classKey ranges (as represented by their start) to * crawlers (by abstract name/filename) */ protected TreeMap<String, String> map = new TreeMap<String, String>(); /** * Constructor. */ public LexicalCrawlMapper() { super(); } /** * Look up the crawler node name to which the given CrawlURI * should be mapped. * * @param cauri CrawlURI to consider * @return String node name which should handle URI */ protected String map(CrawlURI cauri) { // get classKey, via frontier to generate if necessary String classKey = frontier.getClassKey(cauri); SortedMap<String,String> tail = map.tailMap(classKey); if(tail.isEmpty()) { // wraparound tail = map; } // target node is value of nearest subsequent key return (String) tail.get(tail.firstKey()); } public void start() { super.start(); try { loadMap(); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException(e); } } /** * Retrieve and parse the mapping specification from a local path or * HTTP URL. * * @throws IOException */ protected void loadMap() throws IOException {<FILL_FUNCTION_BODY>} }
map.clear(); String uri = getMapUri(); Reader reader = null; if (uri.trim().length() == 0) { File source = getMapPath().getFile(); reader = new FileReader(source); } else { URLConnection conn = (new URL(uri)).openConnection(); reader = new InputStreamReader(conn.getInputStream()); } reader = new BufferedReader(reader); Iterator<String> iter = new RegexLineIterator( new LineReadingIterator((BufferedReader) reader), RegexLineIterator.COMMENT_LINE, RegexLineIterator.TRIMMED_ENTRY_TRAILING_COMMENT, RegexLineIterator.ENTRY); while (iter.hasNext()) { String[] entry = ((String) iter.next()).split("\\s+"); map.put(entry[0],entry[1]); } reader.close();
797
236
1,033
<methods>public void <init>() ,public boolean getCheckOutlinks() ,public boolean getCheckUri() ,public org.archive.spring.ConfigPath getDiversionDir() ,public java.lang.String getLocalName() ,public org.archive.modules.deciderules.DecideRule getOutlinkRule() ,public int getRotationDigits() ,public boolean isRunning() ,public void setCheckOutlinks(boolean) ,public void setCheckUri(boolean) ,public void setDiversionDir(org.archive.spring.ConfigPath) ,public void setLocalName(java.lang.String) ,public void setOutlinkRule(org.archive.modules.deciderules.DecideRule) ,public void setRotationDigits(int) ,public void start() ,public void stop() <variables>protected org.archive.util.fingerprint.ArrayLongFPCache cache,protected boolean checkOutlinks,protected boolean checkUri,protected org.archive.spring.ConfigPath diversionDir,protected HashMap<java.lang.String,java.io.PrintWriter> diversionLogs,protected java.lang.String localName,protected java.lang.String logGeneration,protected org.archive.modules.deciderules.DecideRule outlinkRule,protected int rotationDigits
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/reporting/AlertThreadGroup.java
AlertThreadGroup
current
class AlertThreadGroup extends ThreadGroup { protected int count; protected LinkedList<Logger> loggers = new LinkedList<Logger>(); static protected ThreadLocal<Logger> threadLogger = new ThreadLocal<Logger>(); public AlertThreadGroup(String name) { super(name); } public int getAlertCount() { return count; } public void resetAlertCount() { count = 0; } public void addLogger(Logger logger) { loggers.add(logger); } /** set alternate temporary alert logger */ public static void setThreadLogger(Logger logger) { threadLogger.set(logger); } public static AlertThreadGroup current() {<FILL_FUNCTION_BODY>} public static void publishCurrent(LogRecord record) { AlertThreadGroup atg = AlertThreadGroup.current(); if (atg == null) { Logger tlog = threadLogger.get(); if(tlog!=null) { // send to temp-registered logger boolean usePar = tlog.getUseParentHandlers(); tlog.setUseParentHandlers(false); tlog.log(record); tlog.setUseParentHandlers(usePar); } return; } atg.publish(record); } /** * Pass a record to all loggers registered with the * AlertThreadGroup. Adds thread info to the message, * if available. * * @param record */ public void publish(LogRecord record) { String orig = record.getMessage(); StringBuilder newMessage = new StringBuilder(256); Thread current = Thread.currentThread(); newMessage.append(orig).append(" (in thread '"); newMessage.append(current.getName()).append("'"); if (current instanceof SinkHandlerLogThread) { SinkHandlerLogThread tt = (SinkHandlerLogThread)current; if(tt.getCurrentProcessorName().length()>0) { newMessage.append("; in processor '"); newMessage.append(tt.getCurrentProcessorName()); newMessage.append("'"); } } newMessage.append(")"); record.setMessage(newMessage.toString()); count++; for(Logger logger : loggers) { // for the relay, suppress use of parent handlers // (otherwise endless loop a risk if any target // loggers relay through parents to topmost logger) synchronized(logger) { boolean usePar = logger.getUseParentHandlers(); logger.setUseParentHandlers(false); logger.log(record); logger.setUseParentHandlers(usePar); } } } }
Thread t = Thread.currentThread(); ThreadGroup th = t.getThreadGroup(); while ((th != null) && !(th instanceof AlertThreadGroup)) { th = th.getParent(); } return (AlertThreadGroup)th;
713
68
781
<methods>public void <init>(java.lang.String) ,public void <init>(java.lang.ThreadGroup, java.lang.String) ,public int activeCount() ,public int activeGroupCount() ,public boolean allowThreadSuspension(boolean) ,public final void checkAccess() ,public final void destroy() ,public int enumerate(java.lang.Thread[]) ,public int enumerate(java.lang.ThreadGroup[]) ,public int enumerate(java.lang.Thread[], boolean) ,public int enumerate(java.lang.ThreadGroup[], boolean) ,public final int getMaxPriority() ,public final java.lang.String getName() ,public final java.lang.ThreadGroup getParent() ,public final void interrupt() ,public final boolean isDaemon() ,public synchronized boolean isDestroyed() ,public void list() ,public final boolean parentOf(java.lang.ThreadGroup) ,public final void resume() ,public final void setDaemon(boolean) ,public final void setMaxPriority(int) ,public final void stop() ,public final void suspend() ,public java.lang.String toString() ,public void uncaughtException(java.lang.Thread, java.lang.Throwable) <variables>boolean daemon,boolean destroyed,java.lang.ThreadGroup[] groups,int maxPriority,int nUnstartedThreads,java.lang.String name,int ngroups,int nthreads,private final java.lang.ThreadGroup parent,java.lang.Thread[] threads
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/reporting/CrawlStatSnapshot.java
CrawlStatSnapshot
percentOfDiscoveredUrisCompleted
class CrawlStatSnapshot { public long timestamp; public long urisFetched; public long bytesProcessed; public long discoveredUriCount; public long queuedUriCount; public long futureUriCount; public long finishedUriCount; public long downloadedUriCount; public long downloadFailures; public long downloadDisregards; public long elapsedMilliseconds; public double docsPerSecond; public double currentDocsPerSecond; public long totalKiBPerSec; public long currentKiBPerSec; public int busyThreads; public float congestionRatio; public long deepestUri; public long averageDepth; public long novelBytes; public long novelUriCount; public long warcNovelBytes; public long warcNovelUriCount; /** * Collect all relevant snapshot samples, from the given CrawlController * and StatisticsTracker (which also provides the previous snapshot * for rate-calculations. * * @param controller * @param stats */ public void collect(CrawlController controller, StatisticsTracker stats) { // TODO: reconsider names of these methods, inline? downloadedUriCount = controller.getFrontier().succeededFetchCount(); bytesProcessed = stats.crawledBytes.getTotalBytes(); timestamp = System.currentTimeMillis(); novelBytes = stats.crawledBytes.get(CrawledBytesHistotable.NOVEL); novelUriCount = stats.crawledBytes.get(CrawledBytesHistotable.NOVELCOUNT); warcNovelBytes = stats.crawledBytes.get(CrawledBytesHistotable.WARC_NOVEL_CONTENT_BYTES); warcNovelUriCount = stats.crawledBytes.get(CrawledBytesHistotable.WARC_NOVEL_URLS); elapsedMilliseconds = stats.getCrawlElapsedTime(); discoveredUriCount = controller.getFrontier().discoveredUriCount(); finishedUriCount = controller.getFrontier().finishedUriCount(); queuedUriCount = controller.getFrontier().queuedUriCount(); futureUriCount = controller.getFrontier().futureUriCount(); downloadFailures = controller.getFrontier().failedFetchCount(); downloadDisregards = controller.getFrontier().disregardedUriCount(); busyThreads = controller.getActiveToeCount(); congestionRatio = controller.getFrontier().congestionRatio(); deepestUri = controller.getFrontier().deepestUri(); averageDepth = controller.getFrontier().averageDepth(); // overall rates docsPerSecond = (double) downloadedUriCount / (stats.getCrawlElapsedTime() / 1000d); totalKiBPerSec = (long)((bytesProcessed / 1024d) / ((stats.getCrawlElapsedTime()+1) / 1000d)); CrawlStatSnapshot lastSnapshot = stats.snapshots.peek(); if(lastSnapshot==null) { // no previous snapshot; unable to calculate current rates return; } // last sample period rates long sampleTime = timestamp - lastSnapshot.timestamp; currentDocsPerSecond = (double) (downloadedUriCount - lastSnapshot.downloadedUriCount) / (sampleTime / 1000d); currentKiBPerSec = (long) (((bytesProcessed-lastSnapshot.bytesProcessed)/1024) / (sampleTime / 1000d)); } /** * Return one line of current progress-statistics * * @return String of stats */ public String getProgressStatisticsLine() { return new PaddingStringBuffer() .append(ArchiveUtils.getLog14Date(timestamp)) .raAppend(32, discoveredUriCount) .raAppend(44, queuedUriCount) .raAppend(57, downloadedUriCount) .raAppend(74, ArchiveUtils. doubleToString(currentDocsPerSecond, 2) + "(" + ArchiveUtils.doubleToString(docsPerSecond, 2) + ")") .raAppend(85, currentKiBPerSec + "(" + totalKiBPerSec + ")") .raAppend(99, downloadFailures) .raAppend(113, busyThreads) .raAppend(126, (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024) .raAppend(140, Runtime.getRuntime().totalMemory() / 1024) .raAppend(153, ArchiveUtils.doubleToString(congestionRatio, 2)) .raAppend(165, deepestUri) .raAppend(177, averageDepth) .toString(); } public long totalCount() { return queuedUriCount + busyThreads + downloadedUriCount; } /** * This returns the number of completed URIs as a percentage of the total * number of URIs encountered (should be inverse to the discovery curve) * * @return The number of completed URIs as a percentage of the total * number of URIs encountered */ public int percentOfDiscoveredUrisCompleted() {<FILL_FUNCTION_BODY>} /** * Return true if this snapshot shows no tangible progress in * its URI counts over the supplied snapshot. May be used to * suppress unnecessary redundant reporting/checkpointing. * @param lastSnapshot * @return true if this snapshot stats are essentially same as previous given */ public boolean sameProgressAs(CrawlStatSnapshot lastSnapshot) { if(lastSnapshot==null) { return false; } return (finishedUriCount == lastSnapshot.finishedUriCount) && (queuedUriCount == lastSnapshot.queuedUriCount) && (downloadDisregards == lastSnapshot.downloadDisregards); } }
long total = discoveredUriCount; if (total == 0) { return 0; } return (int) (100 * finishedUriCount / total);
1,738
53
1,791
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/reporting/CrawlSummaryReport.java
CrawlSummaryReport
write
class CrawlSummaryReport extends Report { @Override public void write(PrintWriter writer, StatisticsTracker stats) {<FILL_FUNCTION_BODY>} @Override public String getFilename() { return "crawl-report.txt"; } }
CrawlStatSnapshot snapshot = stats.getLastSnapshot(); writer.println("crawl name: " + stats.getCrawlController().getMetadata().getJobName()); String crawlStatus = stats.getCrawlController().getCrawlExitStatus().desc; if (stats.getCrawlController().isRunning() ) { crawlStatus = StringUtils.capitalize(stats.getCrawlController().getState().toString().toLowerCase()) + " - Active"; } writer.println("crawl status: " + crawlStatus); writer.println("duration: " + ArchiveUtils.formatMillisecondsToConventional(stats.getCrawlElapsedTime())); writer.println(); // seeds summary stats.tallySeeds(); writer.println("seeds crawled: " + stats.seedsCrawled); writer.println("seeds uncrawled: " + (stats.seedsTotal - stats.seedsCrawled)); writer.println(); // hostsDistribution contains all hosts crawled plus an entry for dns. writer.println("hosts visited: " + (stats.serverCache.hostKeys().size()-1)); writer.println(); // URI totals writer.println("URIs processed: " + snapshot.finishedUriCount); writer.println("URI successes: " + snapshot.downloadedUriCount); writer.println("URI failures: " + snapshot.downloadFailures); writer.println("URI disregards: " + snapshot.downloadDisregards); writer.println(); // novel/duplicate/not-modified URI counts writer.println("novel URIs: " + stats.crawledBytes.get( CrawledBytesHistotable.NOVELCOUNT)); if(stats.crawledBytes.containsKey(CrawledBytesHistotable. DUPLICATECOUNT)) { writer.println("duplicate-by-hash URIs: " + stats.crawledBytes.get(CrawledBytesHistotable. DUPLICATECOUNT)); } if(stats.crawledBytes.containsKey(CrawledBytesHistotable. NOTMODIFIEDCOUNT)) { writer.println("not-modified URIs: " + stats.crawledBytes.get(CrawledBytesHistotable. NOTMODIFIEDCOUNT)); } writer.println(); // total bytes 'crawled' (which includes the size of // refetched-but-unwritten-duplicates and reconsidered-but-not-modified writer.println("total crawled bytes: " + snapshot.bytesProcessed + " (" + ArchiveUtils.formatBytesForDisplay(snapshot.bytesProcessed) + ") "); // novel/duplicate/not-modified byte counts writer.println("novel crawled bytes: " + stats.crawledBytes.get(CrawledBytesHistotable.NOVEL) + " (" + ArchiveUtils.formatBytesForDisplay( stats.crawledBytes.get(CrawledBytesHistotable.NOVEL)) + ")"); if(stats.crawledBytes.containsKey(CrawledBytesHistotable.DUPLICATE)) { writer.println("duplicate-by-hash crawled bytes: " + stats.crawledBytes.get(CrawledBytesHistotable.DUPLICATE) + " (" + ArchiveUtils.formatBytesForDisplay( stats.crawledBytes.get(CrawledBytesHistotable.DUPLICATE)) + ") "); } if(stats.crawledBytes.containsKey(CrawledBytesHistotable.NOTMODIFIED)) { writer.println("not-modified crawled bytes: " + stats.crawledBytes.get(CrawledBytesHistotable.NOTMODIFIED) + " (" + ArchiveUtils.formatBytesForDisplay( stats.crawledBytes.get(CrawledBytesHistotable.NOTMODIFIED)) + ") "); } writer.println(); // rates writer.println("URIs/sec: " + ArchiveUtils.doubleToString(snapshot.docsPerSecond,2)); writer.println("KB/sec: " + snapshot.totalKiBPerSec);
86
1,170
1,256
<methods>public void <init>() ,public abstract java.lang.String getFilename() ,public boolean getShouldReportAtEndOfCrawl() ,public boolean getShouldReportDuringCrawl() ,public void setShouldReportAtEndOfCrawl(boolean) ,public void setShouldReportDuringCrawl(boolean) ,public abstract void write(java.io.PrintWriter, org.archive.crawler.reporting.StatisticsTracker) <variables>private boolean shouldReportAtEndOfCrawl,private boolean shouldReportDuringCrawl
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/reporting/FrontierNonemptyReport.java
FrontierNonemptyReport
write
class FrontierNonemptyReport extends Report { @Override public void write(PrintWriter writer, StatisticsTracker stats) {<FILL_FUNCTION_BODY>} @Override public String getFilename() { return "frontier-nonempty-report.txt"; } }
if(!stats.controller.getFrontier().isRunning()) { writer.println("frontier unstarted"); } else if (stats.controller.getFrontier().isEmpty()) { writer.println("frontier empty"); } else if (stats.controller.getFrontier() instanceof WorkQueueFrontier) { ((WorkQueueFrontier)stats.controller.getFrontier()).allNonemptyReportTo(writer); } else { try { stats.controller.getFrontier().reportTo(writer); } catch (IOException e) { e.printStackTrace(); } }
88
171
259
<methods>public void <init>() ,public abstract java.lang.String getFilename() ,public boolean getShouldReportAtEndOfCrawl() ,public boolean getShouldReportDuringCrawl() ,public void setShouldReportAtEndOfCrawl(boolean) ,public void setShouldReportDuringCrawl(boolean) ,public abstract void write(java.io.PrintWriter, org.archive.crawler.reporting.StatisticsTracker) <variables>private boolean shouldReportAtEndOfCrawl,private boolean shouldReportDuringCrawl
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/reporting/FrontierSummaryReport.java
FrontierSummaryReport
write
class FrontierSummaryReport extends Report { @Override public void write(PrintWriter writer, StatisticsTracker stats) {<FILL_FUNCTION_BODY>} @Override public String getFilename() { return "frontier-summary-report.txt"; } }
if(!stats.controller.getFrontier().isRunning()) { writer.println("frontier unstarted"); } else { try { stats.controller.getFrontier().reportTo(writer); } catch (IOException e) { e.printStackTrace(); } }
86
90
176
<methods>public void <init>() ,public abstract java.lang.String getFilename() ,public boolean getShouldReportAtEndOfCrawl() ,public boolean getShouldReportDuringCrawl() ,public void setShouldReportAtEndOfCrawl(boolean) ,public void setShouldReportDuringCrawl(boolean) ,public abstract void write(java.io.PrintWriter, org.archive.crawler.reporting.StatisticsTracker) <variables>private boolean shouldReportAtEndOfCrawl,private boolean shouldReportDuringCrawl
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/reporting/HostsReport.java
HostsReport
writeReportLine
class HostsReport extends Report { private final static Logger logger = Logger.getLogger(HostsReport.class.getName()); int maxSortSize = -1; public int getMaxSortSize() { return maxSortSize; } /** * The maximum number of hosts allowed in a report while still sorting it. If the number of hosts exceeds * this value, the generated report will not be sorted. A negative signifies no limit (always sort). * A value of zero means never sort. Default -1, always sort. This matches the behavior before this * parameter was introduced. * * This value can not be overridden by a sheet. It may be safely edited at runtime. * * @param maxSortSize */ public void setMaxSortSize(int maxSortSize) { this.maxSortSize = maxSortSize; } boolean suppressEmptyHosts = false; public boolean isSuppressEmptyHosts() { return suppressEmptyHosts; } /** * If true, hosts for whom no URLs have been fetched will be suppressed in this report. * Such hosts are recorded when the crawler encounters an URL for a host but has not yet (and may never) * processed any URL for the host. This can happen for many reason's, related to scoping and queue budgeting * among others. * Default behavior is to include these non-crawled hosts. * * This value can not be overridden by a sheet. It may be safely edited at runtime. * * @param suppressEmptyHosts */ public void setSuppressEmptyHosts(boolean suppressEmptyHosts) { this.suppressEmptyHosts = suppressEmptyHosts; } @Override public void write(final PrintWriter writer, StatisticsTracker stats) { Collection<String> keys = null; DisposableStoredSortedMap<Long, String> hd = null; if (maxSortSize<0 || maxSortSize>stats.serverCache.hostKeys().size()) { hd = stats.calcReverseSortedHostsDistribution(); keys = hd.values(); } else { keys = stats.serverCache.hostKeys(); } writer.print("[#urls] [#bytes] [host] [#robots] [#remaining] [#novel-urls] [#novel-bytes] [#dup-by-hash-urls] [#dup-by-hash-bytes] [#not-modified-urls] [#not-modified-bytes]\n"); for (String key : keys) { // key is -count, value is hostname try { CrawlHost host = stats.serverCache.getHostFor(key); long fetchSuccesses = host.getSubstats().getFetchSuccesses(); if (!suppressEmptyHosts || fetchSuccesses>0) { writeReportLine(writer, fetchSuccesses, host.getSubstats().getTotalBytes(), host.fixUpName(), host.getSubstats().getRobotsDenials(), host.getSubstats().getRemaining(), host.getSubstats().getNovelUrls(), host.getSubstats().getNovelBytes(), host.getSubstats().getDupByHashUrls(), host.getSubstats().getDupByHashBytes(), host.getSubstats().getNotModifiedUrls(), host.getSubstats().getNotModifiedBytes()); } } catch (Exception e) { logger.log(Level.WARNING, "unable to tally host stats for " + key, e); } } if (hd!=null) { hd.dispose(); } } protected void writeReportLine(PrintWriter writer, Object ... fields) {<FILL_FUNCTION_BODY>} @Override public String getFilename() { return "hosts-report.txt"; } }
for(Object field : fields) { writer.print(field); writer.print(" "); } writer.print("\n");
1,113
45
1,158
<methods>public void <init>() ,public abstract java.lang.String getFilename() ,public boolean getShouldReportAtEndOfCrawl() ,public boolean getShouldReportDuringCrawl() ,public void setShouldReportAtEndOfCrawl(boolean) ,public void setShouldReportDuringCrawl(boolean) ,public abstract void write(java.io.PrintWriter, org.archive.crawler.reporting.StatisticsTracker) <variables>private boolean shouldReportAtEndOfCrawl,private boolean shouldReportDuringCrawl
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/reporting/MimetypesReport.java
MimetypesReport
write
class MimetypesReport extends Report { @Override public void write(PrintWriter writer, StatisticsTracker stats) {<FILL_FUNCTION_BODY>} @Override public String getFilename() { return "mimetype-report.txt"; } }
// header writer.print("[#urls] [#bytes] [mime-types]\n"); DisposableStoredSortedMap<Long,String> fd = stats.getReverseSortedCopy(stats.getFileDistribution()); for (Map.Entry<Long,String> entry : fd.entrySet()) { // key is -count, value is type writer.print(Math.abs(entry.getKey())); writer.print(" "); writer.print(stats.getBytesPerFileType(entry.getValue())); writer.print(" "); writer.print(entry.getValue()); writer.print("\n"); } fd.dispose();
85
187
272
<methods>public void <init>() ,public abstract java.lang.String getFilename() ,public boolean getShouldReportAtEndOfCrawl() ,public boolean getShouldReportDuringCrawl() ,public void setShouldReportAtEndOfCrawl(boolean) ,public void setShouldReportDuringCrawl(boolean) ,public abstract void write(java.io.PrintWriter, org.archive.crawler.reporting.StatisticsTracker) <variables>private boolean shouldReportAtEndOfCrawl,private boolean shouldReportDuringCrawl
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/reporting/ResponseCodeReport.java
ResponseCodeReport
write
class ResponseCodeReport extends Report { @Override public void write(PrintWriter writer, StatisticsTracker stats) {<FILL_FUNCTION_BODY>} @Override public String getFilename() { return "responsecode-report.txt"; } }
// header writer.print("[#urls] [rescode]\n"); DisposableStoredSortedMap<Long,String> scd = stats.getReverseSortedCopy(stats.getStatusCodeDistribution()); for (Map.Entry<Long,String> entry : scd.entrySet()) { writer.print(Math.abs(entry.getKey())); writer.print(" "); writer.print(entry.getValue()); writer.print("\n"); } scd.dispose();
83
149
232
<methods>public void <init>() ,public abstract java.lang.String getFilename() ,public boolean getShouldReportAtEndOfCrawl() ,public boolean getShouldReportDuringCrawl() ,public void setShouldReportAtEndOfCrawl(boolean) ,public void setShouldReportDuringCrawl(boolean) ,public abstract void write(java.io.PrintWriter, org.archive.crawler.reporting.StatisticsTracker) <variables>private boolean shouldReportAtEndOfCrawl,private boolean shouldReportDuringCrawl
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/reporting/SeedRecord.java
SeedRecord
fillWith
class SeedRecord implements CoreAttributeConstants, Serializable, IdentityCacheable { private static final long serialVersionUID = -8455358640509744478L; private static Logger logger = Logger.getLogger(SeedRecord.class.getName()); private final String uri; private int statusCode; private String disposition; private String redirectUri; /** * Create a record from the given CrawlURI and disposition string * * @param curi CrawlURI, already processed as reported to StatisticsTracker * @param disposition descriptive disposition string * */ public SeedRecord(CrawlURI curi, String disposition) { super(); this.uri = curi.getURI(); fillWith(curi,disposition); } /** * Constructor for when a CrawlURI is unavailable; such * as when considering seeds not yet passed through as * CrawlURIs. * * @param uri * @param disposition */ public SeedRecord(String uri, String disposition) { this(uri, disposition, -1, null); } /** * Create a record from the given URI, disposition, HTTP status code, * and redirect URI. * @param uri * @param disposition * @param statusCode * @param redirectUri */ public SeedRecord(String uri, String disposition, int statusCode, String redirectUri) { super(); this.uri = uri; this.statusCode = statusCode; this.disposition = disposition; this.redirectUri = redirectUri; } /** * A later/repeat report of the same seed has arrived; update with * latest. * * @param curi * @param disposition */ public void updateWith(CrawlURI curi,String disposition) { fillWith(curi, disposition); this.makeDirty(); } /** * Fill instance with given values; skips makeDirty so may be used * on initialization. * * @param curi * @param disposition */ protected void fillWith(CrawlURI curi, String disposition) {<FILL_FUNCTION_BODY>} /** * @return Returns the disposition. */ public String getDisposition() { return disposition; } /** * @return Returns the redirectUri. */ public String getRedirectUri() { return redirectUri; } /** * @return Returns the statusCode. */ public int getStatusCode() { return statusCode; } /** * @return Returns the uri. */ public String getUri() { return uri; } public int sortShiftStatusCode() { return -statusCode - Integer.MAX_VALUE; } // // IdentityCacheable support // transient private ObjectIdentityCache<?> cache; @Override public String getKey() { return uri; } @Override public void makeDirty() { cache.dirtyKey(getKey()); } @Override public void setIdentityCache(ObjectIdentityCache<?> cache) { this.cache = cache; } }
if(!this.uri.equals(curi.getURI())) { logger.warning("SeedRecord URI changed: "+uri+"->"+curi.getURI()); } this.statusCode = curi.getFetchStatus(); this.disposition = disposition; if (statusCode==301 || statusCode == 302) { for (CrawlURI cauri: curi.getOutLinks()) { if("location:".equalsIgnoreCase(cauri.getViaContext(). toString())) { redirectUri = cauri.toString(); } } } else { redirectUri = null; }
874
169
1,043
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/reporting/SeedsReport.java
SeedsReport
write
class SeedsReport extends Report { @Override public void write(PrintWriter writer, StatisticsTracker stats) {<FILL_FUNCTION_BODY>} @Override public String getFilename() { return "seeds-report.txt"; } }
// Build header. writer.print("[code] [status] [seed] [redirect]\n"); long seedsCrawled = 0; long seedsTotal = 0; DisposableStoredSortedMap<Integer, SeedRecord> seedsByCode = stats.calcSeedRecordsSortedByStatusCode(); // for (Map.Entry<Integer,SeedRecord> entry : seedsByCode.entrySet()) { Iterator<Map.Entry<Integer,SeedRecord>> iter = seedsByCode.entrySet().iterator(); while(iter.hasNext()) { Map.Entry<Integer,SeedRecord> entry = iter.next(); SeedRecord sr = entry.getValue(); writer.print(sr.getStatusCode()); writer.print(" "); seedsTotal++; if((sr.getStatusCode() > 0)) { seedsCrawled++; writer.print("CRAWLED"); } else { writer.print("NOTCRAWLED"); } writer.print(" "); writer.print(sr.getUri()); if(sr.getRedirectUri()!=null) { writer.print(" "); writer.print(sr.getRedirectUri()); } writer.print("\n"); } StoredIterator.close(iter); seedsByCode.dispose(); stats.seedsTotal = seedsTotal; stats.seedsCrawled = seedsCrawled;
83
400
483
<methods>public void <init>() ,public abstract java.lang.String getFilename() ,public boolean getShouldReportAtEndOfCrawl() ,public boolean getShouldReportDuringCrawl() ,public void setShouldReportAtEndOfCrawl(boolean) ,public void setShouldReportDuringCrawl(boolean) ,public abstract void write(java.io.PrintWriter, org.archive.crawler.reporting.StatisticsTracker) <variables>private boolean shouldReportAtEndOfCrawl,private boolean shouldReportDuringCrawl
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/reporting/SourceTagsReport.java
SourceTagsReport
write
class SourceTagsReport extends Report { @Override public void write(PrintWriter writer, StatisticsTracker stats) {<FILL_FUNCTION_BODY>} @Override public String getFilename() { return "source-report.txt"; } }
Set<String> sourceTags = stats.sourceHostDistribution.keySet(); if(sourceTags.isEmpty()) { writer.println("No source tag information. (Is 'sourceTagSeeds' enabled?)"); return; } writer.print("[source] [host] [#urls]\n"); // for each source for (String sourceKey : sourceTags) { Map<String,AtomicLong> hostCounts = (Map<String,AtomicLong>)stats.sourceHostDistribution.get(sourceKey); // sort hosts by #urls DisposableStoredSortedMap<Long,String> sortedHostCounts = stats.getReverseSortedHostCounts(hostCounts); // for each host for (Map.Entry<Long, String> entry : sortedHostCounts.entrySet()) { writer.print(sourceKey.toString()); writer.print(" "); writer.print(entry.getValue()); writer.print(" "); writer.print(Math.abs(entry.getKey())); writer.print("\n"); } sortedHostCounts.dispose(); }
80
320
400
<methods>public void <init>() ,public abstract java.lang.String getFilename() ,public boolean getShouldReportAtEndOfCrawl() ,public boolean getShouldReportDuringCrawl() ,public void setShouldReportAtEndOfCrawl(boolean) ,public void setShouldReportDuringCrawl(boolean) ,public abstract void write(java.io.PrintWriter, org.archive.crawler.reporting.StatisticsTracker) <variables>private boolean shouldReportAtEndOfCrawl,private boolean shouldReportDuringCrawl
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/BaseResource.java
BaseResource
write
class BaseResource extends ServerResource { @Override public EngineApplication getApplication() { return (EngineApplication) super.getApplication(); } protected Engine getEngine() { return getApplication().getEngine(); } protected String getStaticRef(String resource) { String rootRef = getRequest().getRootRef().toString(); return rootRef + "/engine/static/" + resource; } protected Representation render(String templateName, ViewModel viewModel) { return render(templateName, viewModel, null); } protected Representation render(String templateName, ViewModel viewModel, ObjectWrapper objectWrapper) { String baseRef = getRequest().getResourceRef().getBaseRef().toString(); if(!baseRef.endsWith("/")) { baseRef += "/"; } viewModel.put("baseRef", baseRef); viewModel.setFlashes(Flash.getFlashes(getRequest())); Template template; try { template = getApplication().getTemplateConfiguration().getTemplate(templateName); } catch (IOException e) { throw new UncheckedIOException("Error reading template " + templateName, e); } return new WriterRepresentation(MediaType.TEXT_HTML) { @Override public void write(Writer writer) throws IOException {<FILL_FUNCTION_BODY>} }; } }
try { template.process(viewModel, writer, objectWrapper); } catch (TemplateException e) { throw new RuntimeException(e); } writer.flush();
345
49
394
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/BeanBrowseResource.java
BeanBrowseResource
makeDataModel
class BeanBrowseResource extends JobRelatedResource { protected PathSharingContext appCtx; protected String beanPath; @Override public void init(Context ctx, Request req, Response res) throws ResourceException { super.init(ctx, req, res); getVariants().add(new Variant(MediaType.TEXT_HTML)); getVariants().add(new Variant(MediaType.APPLICATION_XML)); appCtx = cj.getJobContext(); beanPath = (String)req.getAttributes().get("beanPath"); if (beanPath!=null) { try { beanPath = URLDecoder.decode(beanPath,"UTF-8"); } catch (UnsupportedEncodingException e) { // inconceivable! UTF-8 required all Java impls } } else { beanPath = ""; } } @Override protected Representation post(Representation entity, Variant variant) throws ResourceException { if (appCtx == null) { throw new ResourceException(404); } // copy op? Form form = new Form(entity); beanPath = form.getFirstValue("beanPath"); String newVal = form.getFirstValue("newVal"); if(newVal!=null) { int i = beanPath.indexOf("."); String beanName = i<0?beanPath:beanPath.substring(0,i); Object namedBean = appCtx.getBean(beanName); BeanWrapperImpl bwrap = new BeanWrapperImpl(namedBean); String propPath = beanPath.substring(i+1); Object coercedVal = bwrap.convertIfNecessary(newVal, bwrap.getPropertyValue(propPath).getClass()); bwrap.setPropertyValue(propPath, coercedVal); } Reference ref = getRequest().getResourceRef(); ref.setPath(getBeansRefPath()); ref.addSegment(beanPath); getResponse().redirectSeeOther(ref); return new EmptyRepresentation(); } public String getBeansRefPath() { Reference ref = getRequest().getResourceRef(); String path = ref.getPath(); int i = path.indexOf("/beans/"); if(i>0) { return path.substring(0,i+"/beans/".length()); } if(!path.endsWith("/")) { path += "/"; } return path; } @Override public Representation get(Variant variant) throws ResourceException { if (appCtx == null) { throw new ResourceException(404); } if (variant.getMediaType() == MediaType.APPLICATION_XML) { return new WriterRepresentation(MediaType.APPLICATION_XML) { public void write(Writer writer) throws IOException { XmlMarshaller.marshalDocument(writer, "beans", makeDataModel()); } }; } else { ViewModel viewModel = new ViewModel(); viewModel.put("model", makeDataModel()); return render("Beans.ftl", viewModel); } } /** * Constructs a nested Map data structure with the information represented * by this Resource. The result is particularly suitable for use with with * {@link XmlMarshaller}. * * @return the nested Map data structure */ protected BeansModel makeDataModel(){<FILL_FUNCTION_BODY>} }
Object bean=null; String problem=null; boolean editable=false; Object target=null; if (StringUtils.isNotBlank(beanPath)) { try { int firstDot = beanPath.indexOf("."); String beanName = firstDot<0?beanPath:beanPath.substring(0,firstDot); Object namedBean = appCtx.getBean(beanName); if (firstDot < 0) { target = namedBean; bean = makePresentableMapFor(null, target, beanPath); } else { BeanWrapperImpl bwrap = new BeanWrapperImpl(namedBean); String propPath = beanPath.substring(firstDot+1); target = bwrap.getPropertyValue(propPath); Class<?> type = bwrap.getPropertyType(propPath); if(bwrap.isWritableProperty(propPath) && (bwrap.getDefaultEditor(type)!=null|| type == String.class) && !Collection.class.isAssignableFrom(type)) { editable=true; bean = makePresentableMapFor(null, target); } else { bean = makePresentableMapFor(null, target, beanPath); } } } catch (BeansException e) { problem = e.toString(); } } Collection<Object> nestedNames = new LinkedList<Object>(); Set<Object> alreadyWritten = new HashSet<Object>(); addPresentableNestedNames(nestedNames, appCtx.getBean("crawlController"), alreadyWritten); for(String name: appCtx.getBeanDefinitionNames()) { addPresentableNestedNames(nestedNames, appCtx.getBean(name), alreadyWritten); } return new BeansModel(cj.getShortName(), new Reference(getRequest().getResourceRef().getBaseRef(), "..").getTargetRef().toString(), beanPath, bean, editable, problem, target, nestedNames);
984
583
1,567
<methods>public non-sealed void <init>() ,public void init(Context, Request, Response) <variables>protected static HashSet<java.lang.String> HIDDEN_PROPS,private static final java.util.logging.Logger LOGGER,protected IdentityHashMap<java.lang.Object,java.lang.String> beanToNameMap,protected org.archive.crawler.framework.CrawlJob cj
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/EditRepresentation.java
EditRepresentation
write
class EditRepresentation extends CharacterRepresentation { protected FileRepresentation fileRepresentation; protected EnhDirectoryResource dirResource; public EditRepresentation(FileRepresentation representation, EnhDirectoryResource resource) { super(MediaType.TEXT_HTML); fileRepresentation = representation; dirResource = resource; // TODO: remove if not necessary in future? setCharacterSet(CharacterSet.UTF_8); } @Override public Reader getReader() throws IOException { StringWriter writer = new StringWriter((int)fileRepresentation.getSize()+100); write(writer); return new StringReader(writer.toString()); } protected String getStaticRef(String resource) { String rootRef = dirResource.getRequest().getRootRef().toString(); return rootRef + "/engine/static/" + resource; } @Override public void write(Writer writer) throws IOException {<FILL_FUNCTION_BODY>} public FileRepresentation getFileRepresentation() { return fileRepresentation; } }
PrintWriter pw = new PrintWriter(writer); pw.println("<!DOCTYPE html>"); pw.println("<html>"); pw.println("<head><title>"+fileRepresentation.getFile().getName()+"</title>"); pw.println("<link rel='stylesheet' href='" + getStaticRef("codemirror/codemirror.css") + "'>"); pw.println("<link rel='stylesheet' href='" + getStaticRef("codemirror/util/dialog.css") + "'>"); pw.println("<script src='" + getStaticRef("codemirror/codemirror.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/mode/xmlpure.js") + "'></script>"); pw.println("<script src='" + getStaticRef("codemirror/util/dialog.js") + "'></script>"); pw.println("<style>.CodeMirror { background: #fff; }</style>"); pw.println("</head>"); pw.println("<body style='background-color:#ddd'>"); pw.println("<form style='position:absolute;top:15px;bottom:15px;left:15px;right:15px;overflow:auto' method='POST'>"); pw.println("<textarea style='width:98%;height:90%;font-family:monospace' name='contents' id='editor'>"); StringEscapeUtils.escapeHtml(pw,fileRepresentation.getText()); pw.println("</textarea>"); pw.println("<div id='savebar'>"); pw.println("<input type='submit' value='save changes' id='savebutton'>"); pw.println(fileRepresentation.getFile()); Reference viewRef = dirResource.getRequest().getOriginalRef().clone(); viewRef.setQuery(null); pw.println("<a href='"+viewRef+"'>view</a>"); Flash.renderFlashesHTML(pw, dirResource.getRequest()); pw.println("</div>"); pw.println("</form>"); pw.println("<script>"); pw.println("var editor = document.getElementById('editor');"); pw.println("var savebar = document.getElementById('savebar');"); pw.println("var savebutton = document.getElementById('savebutton');"); pw.println("var cmopts = {"); pw.println(" mode: {name: 'xmlpure'},"); pw.println(" indentUnit: 1, lineNumbers: true, autofocus: true,"); pw.println(" onChange: function() { savebutton.disabled = false; },"); pw.println("}"); pw.println("var cm = CodeMirror.fromTextArea(editor, cmopts);"); pw.println("window.onresize = function() {"); pw.println(" cm.getScrollerElement().style.height = innerHeight - savebar.offsetHeight - 30 + 'px';"); pw.println(" cm.refresh();"); pw.println("}"); pw.println("window.onresize();"); pw.println("savebutton.disabled = true;"); pw.println("</script>"); pw.println("</body>"); pw.println("</html>");
308
965
1,273
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/EngineApplication.java
EngineApplication
createInboundRoot
class EngineApplication extends Application { protected Engine engine; private final Configuration templateConfiguration; public EngineApplication(Engine engine) { this.engine = engine; getMetadataService().addExtension("log", MediaType.TEXT_PLAIN ); getMetadataService().addExtension("cxml", MediaType.APPLICATION_XML ); setStatusService(new EngineStatusService()); templateConfiguration = new Configuration(); templateConfiguration.setClassForTemplateLoading(getClass(), ""); templateConfiguration.setObjectWrapper(ObjectWrapper.BEANS_WRAPPER); } @Override public Restlet createInboundRoot() {<FILL_FUNCTION_BODY>} public Engine getEngine() { return engine; } /** * Customize Restlet error to include back button and full stack. */ protected class EngineStatusService extends StatusService { @Override public Representation getRepresentation(Status status, Request request, Response response) { StringWriter st = new StringWriter(); PrintWriter pw = new PrintWriter(st); if(status.getCode()==404){ pw.append("<h1>Page not found</h1>\n"); pw.append("The page you are looking for does not exist. "+ "You may be able to recover by going " + "<a href='javascript:history.back();void(0);'>back</a>.\n"); } else{ pw.append("<h1>An error occurred</h1>\n"); pw.append( "You may be able to recover and try something " + "else by going " + "<a href='javascript:history.back();void(0);'>back</a>.\n"); if(status.getThrowable()!=null) { pw.append("<h2>Cause: "+ status.getThrowable().toString()+"</h2>\n"); pw.append("<pre>"); status.getThrowable().printStackTrace(pw); pw.append("</pre>"); } } pw.flush(); return new StringRepresentation(st.toString(),MediaType.TEXT_HTML); } } public Configuration getTemplateConfiguration() { return templateConfiguration; } }
Router router = new Router(getContext()); router.attach("/",new Redirector(null,"/engine",Redirector.MODE_CLIENT_TEMPORARY)); router.attach("/engine",EngineResource.class) .setMatchingMode(Template.MODE_EQUALS); router.attach("/engine/",EngineResource.class) .setMatchingMode(Template.MODE_EQUALS); Directory alljobsdir = new Directory( getContext(), engine.getJobsDir().toURI().toString()); alljobsdir.setListingAllowed(true); router.attach("/engine/jobsdir",alljobsdir); EnhDirectory anypath = new EnhDirectory( getContext(), engine.getJobsDir().toURI().toString() /*TODO: changeme*/) { @Override protected Reference determineRootRef(Request request) { String ref = "file:/"; return new Reference(ref); }}; anypath.setListingAllowed(true); anypath.setModifiable(true); anypath.setEditFilter(JobResource.EDIT_FILTER); router.attach("/engine/anypath/",anypath); EnhDirectory jobdir = new EnhDirectory( getContext(), engine.getJobsDir().toURI().toString() /*TODO: changeme*/) { @Override protected Reference determineRootRef(Request request) { try { return new Reference( EngineApplication.this.getEngine() .getJob(TextUtils.urlUnescape( (String)request.getAttributes().get("job"))) .getJobDir().getCanonicalFile().toURI().toString()); } catch (IOException e) { throw new RuntimeException(e); } }}; jobdir.setListingAllowed(true); jobdir.setModifiable(true); jobdir.setEditFilter(JobResource.EDIT_FILTER); router.attach("/engine/job/{job}/jobdir",jobdir); router.attach("/engine/job/{job}",JobResource.class); router.attach("/engine/job/{job}/report/{reportClass}",ReportGenResource.class); router.attach("/engine/job/{job}/beans",BeanBrowseResource.class); router.attach("/engine/job/{job}/beans/{beanPath}",BeanBrowseResource.class); router.attach("/engine/job/{job}/script",ScriptResource.class); // static files (won't serve directory, but will serve files in it) String resource = "clap://class/org/archive/crawler/restlet"; Directory staticDir = new Directory(getContext(),resource); router.attach("/engine/static/",staticDir); return router;
659
780
1,439
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/EngineResource.java
EngineResource
getBuiltJobs
class EngineResource extends BaseResource { @Override public void init(Context ctx, Request req, Response res) { super.init(ctx, req, res); getVariants().add(new Variant(MediaType.TEXT_HTML)); getVariants().add(new Variant(APPLICATION_XML)); } @Override protected Representation get(Variant variant) throws ResourceException { if (variant.getMediaType() == APPLICATION_XML) { return new WriterRepresentation(APPLICATION_XML) { public void write(Writer writer) throws IOException { XmlMarshaller.marshalDocument(writer, "engine", makeDataModel()); } }; } else { ViewModel viewModel = new ViewModel(); viewModel.put("fileSeparator", File.separator); viewModel.put("engine", makeDataModel()); return render("Engine.ftl", viewModel, ObjectWrapper.DEFAULT_WRAPPER); } } @Override protected Representation post(Representation entity, Variant variant) throws ResourceException { Form form = new Form(entity); String action = form.getFirstValue("action"); if("rescan".equals(action)) { getEngine().findJobConfigs(); } else if ("add".equals(action)) { String path = form.getFirstValue("addpath"); if (path==null) { Flash.addFlash(getResponse(), "Cannot add <i>null</i> path", Flash.Kind.NACK); } else { File jobFile = new File(path); String jobName = jobFile.getName(); if (!jobFile.isDirectory()) { Flash.addFlash(getResponse(), "Cannot add non-directory: <i>" + path + "</i>", Flash.Kind.NACK); } else if (getEngine().getJobConfigs().containsKey(jobName)) { Flash.addFlash(getResponse(), "Job exists: <i>" + jobName + "</i>", Flash.Kind.NACK); } else if (getEngine().addJobDirectory(new File(path))) { Flash.addFlash(getResponse(), "Added crawl job: " + "'" + path + "'", Flash.Kind.ACK); } else { Flash.addFlash(getResponse(), "Could not add job: " + "'" + path + "'", Flash.Kind.NACK); } } } else if ("create".equals(action)) { String path = form.getFirstValue("createpath"); if (path==null) { // protect against null path Flash.addFlash(getResponse(), "Cannot create <i>null</i> path.", Flash.Kind.NACK); } else if (path.indexOf(File.separatorChar) != -1) { // prevent specifying sub-directories Flash.addFlash(getResponse(), "Sub-directories disallowed: " + "<i>" + path + "</i>", Flash.Kind.NACK); } else if (getEngine().getJobConfigs().containsKey(path)) { // protect existing jobs Flash.addFlash(getResponse(), "Job exists: <i>" + path + "</i>", Flash.Kind.NACK); } else { // try to create new job dir File newJobDir = new File(getEngine().getJobsDir(),path); if (newJobDir.exists()) { // protect existing directories Flash.addFlash(getResponse(), "Directory exists: " + "<i>" + path + "</i>", Flash.Kind.NACK); } else { if (getEngine().createNewJobWithDefaults(newJobDir)) { Flash.addFlash(getResponse(), "Created new crawl job: " + "<i>" + path + "</i>", Flash.Kind.ACK); getEngine().findJobConfigs(); } else { Flash.addFlash(getResponse(), "Failed to create new job: " + "<i>" + path + "</i>", Flash.Kind.NACK); } } } } else if ("exit java process".equals(action)) { boolean cancel = false; if(!"on".equals(form.getFirstValue("im_sure"))) { Flash.addFlash( getResponse(), "You must tick \"I'm sure\" to trigger exit", Flash.Kind.NACK); cancel = true; } for(Map.Entry<String,CrawlJob> entry : getBuiltJobs().entrySet()) { if(!"on".equals(form.getFirstValue("ignore__"+entry.getKey()))) { Flash.addFlash( getResponse(), "Job '"+entry.getKey()+"' still &laquo;" +entry.getValue().getJobStatusDescription() +"&raquo;", Flash.Kind.NACK); cancel = true; } } if (!cancel) { Flash.addFlash(getResponse(), "Shutting down ... bye"); new Thread(() -> { try { Thread.sleep(1000); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } System.exit(0); }).start(); } } else if ("gc".equals(action)) { System.gc(); } // default: redirect to GET self getResponse().redirectSeeOther(getRequest().getOriginalRef()); return new EmptyRepresentation(); } protected HashMap<String, CrawlJob> getBuiltJobs() {<FILL_FUNCTION_BODY>} /** * Constructs a nested Map data structure with the information represented * by this Resource. The result is particularly suitable for use with with * {@link XmlMarshaller}. * * @return the nested Map data structure */ protected EngineModel makeDataModel() { String baseRef = getRequest().getResourceRef().getBaseRef().toString(); if(!baseRef.endsWith("/")) { baseRef += "/"; } return new EngineModel(getEngine(), baseRef); } }
HashMap<String,CrawlJob> builtJobs = new HashMap<String,CrawlJob>(); for(Map.Entry<String,CrawlJob> entry : getEngine().getJobConfigs().entrySet()) { if(entry.getValue().hasApplicationContext()) { builtJobs.put(entry.getKey(),entry.getValue()); } } return builtJobs;
1,794
112
1,906
<methods>public non-sealed void <init>() ,public org.archive.crawler.restlet.EngineApplication getApplication() <variables>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/EnhDirectory.java
EnhDirectory
handle
class EnhDirectory extends Directory { protected IOFileFilter editFilter = FileFilterUtils.falseFileFilter(); protected IOFileFilter pageFilter = FileFilterUtils.falseFileFilter(); protected IOFileFilter tailFilter = FileFilterUtils.falseFileFilter(); public EnhDirectory(Context context, Reference rootLocalReference) { super(context, rootLocalReference); // TODO Auto-generated constructor stub } public EnhDirectory(Context context, String rootUri) { super(context, rootUri); // TODO Auto-generated constructor stub } @Override public void handle(Request request, Response response) {<FILL_FUNCTION_BODY>} @Override public ServerResource create(Request request, Response response) { return new EnhDirectoryResource(); } protected abstract Reference determineRootRef(Request request); public boolean allowsEdit(File file) { return editFilter.accept(file); } public void setEditFilter(IOFileFilter fileFilter) { editFilter = fileFilter; } public boolean allowsPaging(File file) { // TODO: limit? return true; } }
synchronized (this) { Reference oldRef = getRootRef(); setRootRef(determineRootRef(request)); try { super.handle(request, response); } finally { setRootRef(oldRef); } // XXX: FileRepresentation.isAvailable() returns false for empty files generating status 204 No Content // which confuses browsers. Force it back it 200 OK. if (response.getStatus() == Status.SUCCESS_NO_CONTENT) { response.setStatus(Status.SUCCESS_OK); } }
337
169
506
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/EnhDirectoryResource.java
EnhDirectoryResource
put
class EnhDirectoryResource extends DirectoryServerResource { /** * Add EditRepresentation as a variant when appropriate. * * @see org.restlet.engine.local.DirectoryServerResource#getVariants() */ @Override public List<Variant> getVariants() { List<Variant> superVariants = super.getVariants(); if (superVariants == null) { return null; // PUT and DELETE return no content } List<Variant> variants = new LinkedList<>(superVariants); Form f = getRequest().getResourceRef().getQueryAsForm(); String format = f.getFirstValue("format"); if("textedit".equals(format)) { if(variants.isEmpty()) { // create empty placeholder file if appropriate try { File file = new File(new URI(getTargetUri())); if(getEnhDirectory().allowsEdit(file)) { file.createNewFile(); } } catch (Exception e) { throw new RuntimeException(e); } superVariants = super.getVariants(); if (superVariants == null) { return null; } variants = new LinkedList<>(superVariants); } // wrap FileRepresentations in EditRepresentations ListIterator<Variant> iter = variants.listIterator(); while(iter.hasNext()) { Variant v = iter.next(); if(v instanceof FileRepresentation) { File file = ((FileRepresentation)v).getFile(); if(getEnhDirectory().allowsEdit(file)) { iter.remove(); // any editable file for our purposes should // be XML/UTF-8 v.setCharacterSet(CharacterSet.UTF_8); iter.add(new EditRepresentation((FileRepresentation)v,this)); }; } } } else if("paged".equals(format)) { ListIterator<Variant> iter = variants.listIterator(); while(iter.hasNext()) { Variant v = iter.next(); if(v instanceof FileRepresentation) { File file = ((FileRepresentation)v).getFile(); if(getEnhDirectory().allowsPaging(file)) { iter.remove(); iter.add(new PagedRepresentation(( FileRepresentation)v, this, f.getFirstValue("pos"), f.getFirstValue("lines"), f.getFirstValue("reverse"))); }; } } } else { ListIterator<Variant> iter = variants.listIterator(); while(iter.hasNext()) { Variant v = iter.next(); v.setCharacterSet(CharacterSet.UTF_8); } } return variants; } protected EnhDirectory getEnhDirectory() { return (EnhDirectory) getDirectory(); } /** * Accept a POST used to edit or create a file. * * @see org.restlet.resource.ServerResource#post(Representation) */ @Override protected Representation post(Representation entity) throws ResourceException { // TODO: only allowPost on valid targets Form form = new Form(entity); String newContents = form.getFirstValue("contents"); File file = new File(URI.create(getTargetUri())); try { FileUtils.writeStringToFile(file, newContents,"UTF-8"); Flash.addFlash(getResponse(), "file updated"); } catch (IOException e) { // TODO report error somehow e.printStackTrace(); } // redirect to view version Reference ref = getRequest().getOriginalRef().clone(); /// ref.setQuery(null); getResponse().redirectSeeOther(ref); return new EmptyRepresentation(); } /* * XXX: We override Restlet's default PUT behaviour (see FileClientHelper.handleFilePut) as it unhelpfully changes * the file extension based on the content-type and there's no apparent way to disable that. */ @Override public Representation put(Representation entity) throws ResourceException {<FILL_FUNCTION_BODY>} }
File file = new File(URI.create(getTargetUri())); if (getTargetUri().endsWith("/") || file.isDirectory()) { return super.put(entity); } boolean created = !file.exists(); try (FileOutputStream out = new FileOutputStream(file)) { entity.write(out); } catch (FileNotFoundException e) { throw new ResourceException(Status.CLIENT_ERROR_NOT_FOUND, e); } catch (IOException e) { throw new ResourceException(Status.SERVER_ERROR_INTERNAL, e); } if (created) { getResponse().setStatus(Status.SUCCESS_CREATED); } return new EmptyRepresentation();
1,195
200
1,395
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/Flash.java
Flash
getFlashes
class Flash { /** usual types */ public enum Kind {ACK, NACK, ADVISORY} protected static long nextdrop = RandomUtils.nextLong(); protected static Map<Long,Flash> dropboxes = new LinkedHashMap<Long, Flash>() { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry(Entry<Long, Flash> eldest) { return size()>100; } }; public static void addFlash(Response response, String message) { addFlash(response, message, Kind.ACK); } public static void addFlash(Response response, String message, Kind kind) { dropboxes.put(nextdrop,new Flash(message, kind)); Series<CookieSetting> cookies = response.getCookieSettings(); CookieSetting flashdrop = null; for(CookieSetting cs : cookies) { if(cs.getName().equals("flashdrop")) { flashdrop = cs; } } if(flashdrop == null) { cookies.add(new CookieSetting("flashdrop",Long.toString(nextdrop))); } else { flashdrop.setValue(flashdrop.getValue()+","+Long.toString(nextdrop)); } nextdrop++; } public static List<Flash> getFlashes(Request request) {<FILL_FUNCTION_BODY>} public static void renderFlashesHTML(Writer writer, Request request) { PrintWriter pw = new PrintWriter(writer); for(Flash flash : getFlashes(request)) { pw.println("<div class='flash"+flash.getKind()+"'>"); pw.println(flash.getMessage()); pw.println("</div>"); } pw.flush(); } /** kind of flash, ACK NACK or ADVISORY */ protected Kind kind; /** the message to show, if any */ protected String message; /** * Create an ACK flash of default styling with the given message. * * @param message */ public Flash(String message) { this(message, Kind.ACK); } /** * Create a Flash of the given kind, message with default styling. * * @param kind * @param message */ public Flash(String message, Kind kind) { this.kind = kind; this.message = message; } /** * Indicate whether the Flash should persist. The usual and * default case is that a Flash displays once and then expires. * * @return boolean whether to discard Flash */ public boolean isExpired() { return true; } public String getMessage() { return this.message; } public Kind getKind() { return this.kind; } }
List<Flash> flashes = new LinkedList<Flash>(); Series<Cookie> cookies = request.getCookies(); String flashdrops = cookies.getFirstValue("flashdrop"); if (StringUtils.isBlank(flashdrops)) { return flashes; } for (String dropbox : flashdrops.split(",")) { if(dropbox!=null) { Flash flash = dropboxes.remove(Long.parseLong(dropbox)); if(flash!=null) { flashes.add(flash); } } } return flashes;
763
159
922
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/JobResource.java
JobResource
post
class JobResource extends BaseResource { public static final IOFileFilter EDIT_FILTER = FileUtils .getRegexFileFilter(".*\\.((c?xml)|(txt))$"); @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(JobResource.class .getName()); protected CrawlJob cj; @Override public void init(Context ctx, Request req, Response res) throws ResourceException { super.init(ctx, req, res); getVariants().add(new Variant(MediaType.TEXT_HTML)); getVariants().add(new Variant(MediaType.APPLICATION_XML)); cj = getEngine().getJob( TextUtils.urlUnescape((String) req.getAttributes().get("job"))); } @Override public Representation get(Variant variant) throws ResourceException { if (cj == null) { throw new ResourceException(404); } if (variant.getMediaType() == MediaType.APPLICATION_XML) { return new WriterRepresentation(MediaType.APPLICATION_XML) { public void write(Writer writer) throws IOException { CrawlJobModel model = makeDataModel(); model.put("heapReport", getEngine().heapReportData()); XmlMarshaller.marshalDocument(writer, "job", model); } }; } else { ViewModel viewModel = new ViewModel(); viewModel.put("heapReport", getEngine().heapReportData()); viewModel.put("job", makeDataModel()); return render("Job.ftl", viewModel); } } /** * Constructs a nested Map data structure with the information represented * by this Resource. The result is particularly suitable for use with with * {@link XmlMarshaller}. * * @return the nested Map data structure */ protected CrawlJobModel makeDataModel() { String baseRef = getRequest().getResourceRef().getBaseRef().toString(); if (!baseRef.endsWith("/")) { baseRef += "/"; } return new CrawlJobModel(cj,baseRef); } /** * Get a usable HrefPath, relative to the JobResource, for the given file. * Assumes usual helper resources ('jobdir/', 'anypath/') at the usual * locations. * * @param f * File to provide an href (suitable for clicking or redirection) * @param cj * CrawlJob for calculating jobdir-relative path if possible * @return String path suitable as href or Location header */ public static String getHrefPath(File f, CrawlJob cj) { String jobDirRelative = cj.jobDirRelativePath(f); if (jobDirRelative != null) { return "jobdir/" + jobDirRelative; } // TODO: delegate this to EngineApplication, or make // conditional on whether /anypath/ service is present? String fullPath = f.getAbsolutePath(); fullPath = fullPath.replace(File.separatorChar, '/'); return "../../anypath/" + fullPath; } @Override public Representation post(Representation entity, Variant variant) throws ResourceException {<FILL_FUNCTION_BODY>} protected void copyJob(String copyTo, boolean asProfile) throws ResourceException { try { getEngine().copy(cj, copyTo, asProfile); } catch (IOException e) { Flash.addFlash(getResponse(), "Job not copied: " + e.getMessage(), Flash.Kind.NACK); getResponse().redirectSeeOther(getRequest().getOriginalRef()); return; } // redirect to destination job page getResponse().redirectSeeOther(copyTo); } }
if (cj == null) { throw new ResourceException(404); } // copy op? Form form = new Form(entity); String copyTo = form.getFirstValue("copyTo"); if (copyTo != null) { copyJob(copyTo, "on".equals(form.getFirstValue("asProfile"))); return new EmptyRepresentation(); } AlertHandler.ensureStaticInitialization(); AlertThreadGroup.setThreadLogger(cj.getJobLogger()); String action = form.getFirstValue("action"); if ("launch".equals(action)) { String selectedCheckpoint = form.getFirstValue("checkpoint"); if (StringUtils.isNotEmpty(selectedCheckpoint)) { cj.getCheckpointService().setRecoveryCheckpointByName( selectedCheckpoint); } cj.launch(); } else if ("checkXML".equals(action)) { cj.checkXML(); } else if ("instantiate".equals(action)) { cj.instantiateContainer(); } else if ("build".equals(action) || "validate".equals(action)) { cj.validateConfiguration(); } else if ("teardown".equals(action)) { if (!cj.teardown()) { Flash.addFlash(getResponse(), "waiting for job to finish", Flash.Kind.NACK); } } else if ("pause".equals(action)) { cj.getCrawlController().requestCrawlPause(); } else if ("unpause".equals(action)) { cj.getCrawlController().requestCrawlResume(); } else if ("checkpoint".equals(action)) { String cp = cj.getCheckpointService().requestCrawlCheckpoint(); if (StringUtils.isNotEmpty(cp)) { Flash.addFlash(getResponse(), "Checkpoint <i>" + cp + "</i> saved", Flash.Kind.ACK); } else { Flash.addFlash( getResponse(), "Checkpoint not made -- perhaps no progress since last? (see logs)", Flash.Kind.NACK); } } else if ("terminate".equals(action)) { cj.terminate(); } AlertThreadGroup.setThreadLogger(null); // default: redirect to GET self getResponse().redirectSeeOther(getRequest().getOriginalRef()); return new EmptyRepresentation();
1,098
687
1,785
<methods>public non-sealed void <init>() ,public org.archive.crawler.restlet.EngineApplication getApplication() <variables>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/RateLimitGuard.java
RateLimitGuard
authenticate
class RateLimitGuard extends DigestAuthenticator { private static final int MIN_MS_BETWEEN_ATTEMPTS = 6000; private static final Logger logger = Logger.getLogger(RateLimitGuard.class.getName()); protected long lastFailureTime = 0; public RateLimitGuard(Context context, String realm, String serverKey) throws IllegalArgumentException { super(context, realm, serverKey); } @Override protected boolean authenticate(Request request, Response response) {<FILL_FUNCTION_BODY>} }
boolean succeeded = super.authenticate(request, response); String authHeader = request.getHeaders().getFirstValue("Authorization", true); if (authHeader != null && !succeeded) { logger.warning("authentication failure "+request); // wait until at least LAG has passed from last failure // holding object lock the whole time, so no other checks // can happen in parallel long now = System.currentTimeMillis(); long sleepMs = (lastFailureTime+MIN_MS_BETWEEN_ATTEMPTS)-now; if(sleepMs>0) { try { Thread.sleep(sleepMs); } catch (InterruptedException e) { // ignore } } lastFailureTime = now; } return succeeded;
158
222
380
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/ReportGenResource.java
ReportGenResource
get
class ReportGenResource extends JobRelatedResource { protected String reportClass; @Override public void init(Context ctx, Request req, Response res) throws ResourceException { super.init(ctx, req, res); getVariants().add(new Variant(MediaType.TEXT_PLAIN)); reportClass = (String)req.getAttributes().get("reportClass"); } @Override protected Representation get(Variant variant) throws ResourceException {<FILL_FUNCTION_BODY>} }
// generate report if (cj == null || cj.getCrawlController() == null) { throw new ResourceException(500); } File f = cj.getCrawlController().getStatisticsTracker().writeReportFile(reportClass); if (f==null) { throw new ResourceException(500); } // redirect String relative = JobResource.getHrefPath(f, cj); if(relative!=null) { getResponse().redirectSeeOther("../"+relative+"?m="+f.lastModified()); return new StringRepresentation(""); } else { return new StringRepresentation( "Report dumped to "+f.getAbsolutePath() +" (outside job directory)"); }
141
225
366
<methods>public non-sealed void <init>() ,public void init(Context, Request, Response) <variables>protected static HashSet<java.lang.String> HIDDEN_PROPS,private static final java.util.logging.Logger LOGGER,protected IdentityHashMap<java.lang.Object,java.lang.String> beanToNameMap,protected org.archive.crawler.framework.CrawlJob cj
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/ScriptResource.java
ScriptResource
post
class ScriptResource extends JobRelatedResource { protected static ScriptEngineManager MANAGER = new ScriptEngineManager(); // oddly, ordering is different each call to getEngineFactories, so cache protected static LinkedList<ScriptEngineFactory> FACTORIES = new LinkedList<ScriptEngineFactory>(); static { FACTORIES.addAll(MANAGER.getEngineFactories()); // Sort factories alphabetically so that they appear in the UI consistently Collections.sort(FACTORIES, new Comparator<ScriptEngineFactory>() { @Override public int compare(ScriptEngineFactory sef1, ScriptEngineFactory sef2) { return sef1.getEngineName().compareTo(sef2.getEngineName()); } }); } protected String chosenEngine = FACTORIES.isEmpty() ? "" : FACTORIES.getFirst().getNames().get(0); @Override public void init(Context ctx, Request req, Response res) throws ResourceException { super.init(ctx, req, res); getVariants().add(new Variant(MediaType.TEXT_HTML)); getVariants().add(new Variant(MediaType.APPLICATION_XML)); scriptingConsole = new ScriptingConsole(cj); } private ScriptingConsole scriptingConsole; @Override public Representation post(Representation entity, Variant variant) throws ResourceException {<FILL_FUNCTION_BODY>} @Override public Representation get(Variant variant) throws ResourceException { if (variant.getMediaType() == MediaType.APPLICATION_XML) { return new WriterRepresentation(MediaType.APPLICATION_XML) { public void write(Writer writer) throws IOException { XmlMarshaller.marshalDocument(writer,"script", makeDataModel()); } }; } else { ViewModel viewModel = new ViewModel(); viewModel.put("baseResourceRef", getRequest().getRootRef().toString() + "/engine/static/"); viewModel.put("model", makeDataModel()); viewModel.put("selectedEngine", chosenEngine); viewModel.put("staticRef", getStaticRef("")); return render("Script.ftl", viewModel); } } protected Collection<Map<String,String>> getAvailableScriptEngines() { List<Map<String,String>> engines = new LinkedList<Map<String,String>>(); for (ScriptEngineFactory f: FACTORIES) { Map<String,String> engine = new LinkedHashMap<String, String>(); engine.put("engine", f.getNames().get(0)); engine.put("language", f.getLanguageName()); engines.add(engine); } return engines; } /** * Constructs a nested Map data structure with the information represented * by this Resource. The result is particularly suitable for use with with * {@link XmlMarshaller}. * * @return the nested Map data structure */ protected ScriptModel makeDataModel() { String baseRef = getRequest().getResourceRef().getBaseRef().toString(); if(!baseRef.endsWith("/")) { baseRef += "/"; } Reference baseRefRef = new Reference(baseRef); ScriptModel model = new ScriptModel(scriptingConsole, new Reference(baseRefRef, "..").getTargetRef().toString(), getAvailableScriptEngines()); return model; } }
Form form = new Form(entity); chosenEngine = form.getFirstValue("engine"); String script = form.getFirstValue("script"); if(StringUtils.isBlank(script)) { script=""; } ScriptEngine eng = MANAGER.getEngineByName(chosenEngine); scriptingConsole.bind("scriptResource", this); scriptingConsole.execute(eng, script); scriptingConsole.unbind("scriptResource"); //TODO: log script, results somewhere; job log INFO? return get(variant);
956
168
1,124
<methods>public non-sealed void <init>() ,public void init(Context, Request, Response) <variables>protected static HashSet<java.lang.String> HIDDEN_PROPS,private static final java.util.logging.Logger LOGGER,protected IdentityHashMap<java.lang.Object,java.lang.String> beanToNameMap,protected org.archive.crawler.framework.CrawlJob cj
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/ScriptingConsole.java
ScriptingConsole
execute
class ScriptingConsole { private final CrawlJob cj; private ScriptEngine eng; private String script; private Bindings bindings; private StringWriter rawString; private StringWriter htmlString; private Throwable exception; private int linesExecuted; private List<Map<String, String>> availableGlobalVariables; public ScriptingConsole(CrawlJob job) { this.cj = job; this.bindings = new BeanLookupBindings(this.cj.getJobContext()); this.script = ""; setupAvailableGlobalVariables(); } protected void addGlobalVariable(String name, String desc) { Map<String, String> var = new LinkedHashMap<String, String>(); var.put("variable", name); var.put("description", desc); availableGlobalVariables.add(var); } private void setupAvailableGlobalVariables() { availableGlobalVariables = new LinkedList<Map<String,String>>(); addGlobalVariable("rawOut", "a PrintWriter for arbitrary text output to this page"); addGlobalVariable("htmlOut", "a PrintWriter for HTML output to this page"); addGlobalVariable("job", "the current CrawlJob instance"); addGlobalVariable("appCtx", "current job ApplicationContext, if any"); // TODO: a bit awkward to have this here, because ScriptingConsole has no ref to // ScriptResource. better to have ScriptResource call #addGlobalVariable(String, String)? addGlobalVariable("scriptResource", "the ScriptResource implementing this page, which offers utility methods"); } public void bind(String name, Object obj) { bindings.put(name, obj); } public Object unbind(String name) { return bindings.remove(name); } public void execute(ScriptEngine eng, String script) {<FILL_FUNCTION_BODY>} public CrawlJob getCrawlJob( ) { return cj; } public Throwable getException() { return exception; } public int getLinesExecuted() { return linesExecuted; } public String getRawOutput() { return rawString != null ? rawString.toString() : ""; } public String getHtmlOutput() { return htmlString != null ? htmlString.toString() : ""; } public String getScript() { return script; } public List<Map<String, String>> getAvailableGlobalVariables() { return availableGlobalVariables; } }
// TODO: update through setter rather than passing as method arguments? this.eng = eng; this.script = script; bind("job", cj); rawString = new StringWriter(); htmlString = new StringWriter(); PrintWriter rawOut = new PrintWriter(rawString); PrintWriter htmlOut = new PrintWriter(htmlString); bind("rawOut", rawOut); bind("htmlOut", htmlOut); bind("appCtx", cj.getJobContext()); exception = null; try { this.eng.eval(this.script, bindings); // TODO: should count with RE rather than creating String[]? linesExecuted = script.split("\r?\n").length; } catch (ScriptException ex) { Throwable cause = ex.getCause(); exception = cause != null ? cause : ex; } catch (RuntimeException ex) { exception = ex; } finally { rawOut.flush(); htmlOut.flush(); // TODO: are these really necessary? unbind("rawOut"); unbind("htmlOut"); unbind("appCtx"); unbind("job"); }
652
301
953
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/models/EngineModel.java
EngineModel
makeJobList
class EngineModel extends LinkedHashMap<String, Object> { public EngineModel(Engine engine, String urlBaseRef){ super(); this.put("heritrixVersion", engine.getHeritrixVersion()); this.put("heapReport", engine.heapReportData()); this.put("jobsDir", FileUtils.tryToCanonicalize(engine.getJobsDir()).getAbsolutePath()); this.put("jobsDirUrl", urlBaseRef + "jobsdir/"); List<String> actions = new LinkedList<String>(); actions.add("rescan"); actions.add("add"); actions.add("create"); this.put("availableActions", actions); this.put("jobs", makeJobList(engine, urlBaseRef)); } private List<Map<String, Object>> makeJobList(Engine engine, String urlBaseRef) {<FILL_FUNCTION_BODY>} }
List<Map<String, Object>> jobList; jobList = new ArrayList<Map<String,Object>>(); // Generate list of jobs ArrayList<Map.Entry<String,CrawlJob>> jobConfigurations = new ArrayList<Map.Entry<String,CrawlJob>>(engine.getJobConfigs().entrySet()); Collections.sort(jobConfigurations, new Comparator<Map.Entry<String, CrawlJob>>() { public int compare(Map.Entry<String, CrawlJob> cj1, Map.Entry<String, CrawlJob> cj2) { return cj1.getValue().compareTo(cj2.getValue()); } }); for(Map.Entry<String,CrawlJob> jobConfig : jobConfigurations) { CrawlJob job = jobConfig.getValue(); Map<String, Object> crawlJobModel = new LinkedHashMap<String, Object>(); crawlJobModel.put("shortName",job.getShortName()); crawlJobModel.put("url",urlBaseRef+"job/"+job.getShortName()); crawlJobModel.put("isProfile",job.isProfile()); crawlJobModel.put("launchCount",job.getLaunchCount()); crawlJobModel.put("lastLaunch",job.getLastLaunch()); crawlJobModel.put("hasApplicationContext",job.hasApplicationContext()); crawlJobModel.put("statusDescription", job.getJobStatusDescription()); crawlJobModel.put("isLaunchInfoPartial", job.isLaunchInfoPartial()); File primaryConfig = FileUtils.tryToCanonicalize(job.getPrimaryConfig()); crawlJobModel.put("primaryConfig", primaryConfig.getAbsolutePath()); crawlJobModel.put("primaryConfigUrl", urlBaseRef + "jobdir/" + primaryConfig.getName()); if (job.getCrawlController() != null) { crawlJobModel.put("crawlControllerState", job.getCrawlController().getState()); if (job.getCrawlController().getState() == State.FINISHED) { crawlJobModel.put("crawlExitStatus", job.getCrawlController().getCrawlExitStatus()); } } crawlJobModel.put("key", jobConfig.getKey()); jobList.add(crawlJobModel); } return jobList;
238
613
851
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends java.lang.String,? extends java.lang.Object>) ,public void <init>(int, float) ,public void <init>(int, float, boolean) ,public void clear() ,public boolean containsValue(java.lang.Object) ,public Set<Entry<java.lang.String,java.lang.Object>> entrySet() ,public void forEach(BiConsumer<? super java.lang.String,? super java.lang.Object>) ,public java.lang.Object get(java.lang.Object) ,public java.lang.Object getOrDefault(java.lang.Object, java.lang.Object) ,public Set<java.lang.String> keySet() ,public void replaceAll(BiFunction<? super java.lang.String,? super java.lang.Object,? extends java.lang.Object>) ,public Collection<java.lang.Object> values() <variables>final boolean accessOrder,transient Entry<java.lang.String,java.lang.Object> head,private static final long serialVersionUID,transient Entry<java.lang.String,java.lang.Object> tail
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/models/ScriptModel.java
ScriptModel
getStackTrace
class ScriptModel { private String crawlJobUrl; private Collection<Map<String, String>> availableScriptEngines; private ScriptingConsole scriptingConsole; public ScriptModel(ScriptingConsole cc, String crawlJobUrl, Collection<Map<String, String>> scriptEngines) { scriptingConsole = cc; this.crawlJobUrl = crawlJobUrl; this.availableScriptEngines = scriptEngines; } public boolean isFailure() { return scriptingConsole.getException() != null; } public String getStackTrace() {<FILL_FUNCTION_BODY>} public Throwable getException() { return scriptingConsole.getException(); } public int getLinesExecuted() { return scriptingConsole.getLinesExecuted(); } public String getRawOutput() { return scriptingConsole.getRawOutput(); } public String getHtmlOutput() { return scriptingConsole.getHtmlOutput(); } public String getScript() { return scriptingConsole.getScript(); } public String getCrawlJobShortName() { return scriptingConsole.getCrawlJob().getShortName(); } public Collection<Map<String, String>> getAvailableScriptEngines() { return availableScriptEngines; } public List<Map<String, String>> getAvailableGlobalVariables() { return scriptingConsole.getAvailableGlobalVariables(); } public String getCrawlJobUrl() { return crawlJobUrl; } }
Throwable exception = scriptingConsole.getException(); if (exception == null) return ""; StringWriter s = new StringWriter(); exception.printStackTrace(new PrintWriter(s)); return s.toString();
402
58
460
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/restlet/models/ViewModel.java
ViewModel
setFlashes
class ViewModel extends LinkedHashMap<String,Object> { public ViewModel(){ super(); } public void setFlashes(List<Flash> flashes){<FILL_FUNCTION_BODY>} }
List<Map<String,Object>> flashList = new ArrayList<Map<String,Object>>(); this.put("flashes", flashList); for(Flash flash: flashes) { Map<String, Object> flashModel = new HashMap<String, Object>(); flashModel.put("kind", flash.getKind()); flashModel.put("message", flash.getMessage()); flashList.add(flashModel); }
57
110
167
<methods>public void <init>() ,public void <init>(int) ,public void <init>(Map<? extends java.lang.String,? extends java.lang.Object>) ,public void <init>(int, float) ,public void <init>(int, float, boolean) ,public void clear() ,public boolean containsValue(java.lang.Object) ,public Set<Entry<java.lang.String,java.lang.Object>> entrySet() ,public void forEach(BiConsumer<? super java.lang.String,? super java.lang.Object>) ,public java.lang.Object get(java.lang.Object) ,public java.lang.Object getOrDefault(java.lang.Object, java.lang.Object) ,public Set<java.lang.String> keySet() ,public void replaceAll(BiFunction<? super java.lang.String,? super java.lang.Object,? extends java.lang.Object>) ,public Collection<java.lang.Object> values() <variables>final boolean accessOrder,transient Entry<java.lang.String,java.lang.Object> head,private static final long serialVersionUID,transient Entry<java.lang.String,java.lang.Object> tail
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/spring/DecideRuledSheetAssociation.java
DecideRuledSheetAssociation
compareTo
class DecideRuledSheetAssociation extends SheetAssociation implements Ordered, Comparable<DecideRuledSheetAssociation>, BeanNameAware { protected DecideRule rules; protected int order = 0; public DecideRule getRules() { return rules; } @Required public void setRules(DecideRule rules) { this.rules = rules; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } // compare on the basis of Ordered value public int compareTo(DecideRuledSheetAssociation o) {<FILL_FUNCTION_BODY>} protected String name; public void setBeanName(String name) { this.name = name; } }
int cmp = order - ((Ordered)o).getOrder(); if(cmp!=0) { return cmp; } return name.compareTo(o.name);
250
59
309
<methods>public non-sealed void <init>() ,public List<java.lang.String> getTargetSheetNames() ,public void setTargetSheetNames(List<java.lang.String>) <variables>protected List<java.lang.String> targetSheetNames
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/util/BenchmarkUriUniqFilters.java
BenchmarkUriUniqFilters
createUriUniqFilter
class BenchmarkUriUniqFilters implements UriUniqFilter.CrawlUriReceiver { // private Logger LOGGER = // Logger.getLogger(BenchmarkUriUniqFilters.class.getName()); private BufferedWriter out; // optional to dump uniq items protected String current; // current line/URI being checked /** * Test the UriUniqFilter implementation (MemUriUniqFilter, * BloomUriUniqFilter, or BdbUriUniqFilter) named in first * argument against the file of one-per-line URIs named * in the second argument. * * @param args from cmd-line * @throws IOException */ public static void main(String[] args) throws IOException { (new BenchmarkUriUniqFilters()).instanceMain(args); } public void instanceMain(String[] args) throws IOException { String testClass = args[0]; String inputFilename = args[1]; long start = System.currentTimeMillis(); UriUniqFilter uniq = createUriUniqFilter(testClass); long created = System.currentTimeMillis(); BufferedReader br = new BufferedReader(new FileReader(inputFilename)); if(args.length>2) { String outputFilename = args[2]; out = new BufferedWriter(new FileWriter(outputFilename)); } int added = 0; while((current=br.readLine())!=null) { added++; uniq.add(current,null); } uniq.close(); long finished = System.currentTimeMillis(); if(out!=null) { out.close(); } System.out.println(added+" adds"); System.out.println(uniq.count()+" retained"); System.out.println((created-start)+"ms to setup UUF"); System.out.println((finished-created)+"ms to perform all adds"); } private UriUniqFilter createUriUniqFilter(String testClass) throws IOException {<FILL_FUNCTION_BODY>} /* (non-Javadoc) * @see org.archive.crawler.datamodel.UriUniqFilter.HasUriReceiver#receive(org.archive.crawler.datamodel.CrawlURI) */ public void receive(CrawlURI item) { if(out!=null) { try { // we assume all tested filters are immediate passthrough so // we can use 'current'; a buffering filter would change this // assumption out.write(current); out.write("\n"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
UriUniqFilter uniq = null; if(BdbUriUniqFilter.class.getName().endsWith(testClass)) {; // BDB setup File tmpDir = File.createTempFile("uuf","benchmark"); tmpDir.delete(); tmpDir.mkdir(); uniq = new BdbUriUniqFilter(tmpDir, 50); } else if(BloomUriUniqFilter.class.getName().endsWith(testClass)) { // bloom setup uniq = new BloomUriUniqFilter(); } else if(MemUriUniqFilter.class.getName().endsWith(testClass)) { // mem hashset uniq = new MemUriUniqFilter(); } else if (FPUriUniqFilter.class.getName().endsWith(testClass)) { // mem fp set (open-addressing) setup uniq = new FPUriUniqFilter(new MemLongFPSet(21,0.75f)); } uniq.setDestination(this); return uniq;
719
266
985
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/util/BloomUriUniqFilter.java
BloomUriUniqFilter
afterPropertiesSet
class BloomUriUniqFilter extends SetBasedUriUniqFilter implements Serializable, InitializingBean { private static final long serialVersionUID = 1061526253773091309L; private static Logger LOGGER = Logger.getLogger(BloomUriUniqFilter.class.getName()); protected BloomFilter bloom; // package access for testing convenience public BloomFilter getBloomFilter() { return bloom; } public void setBloomFilter(BloomFilter filter) { bloom = filter; } /** * Default constructor */ public BloomUriUniqFilter() { super(); } /** * Initializer. */ public void afterPropertiesSet() {<FILL_FUNCTION_BODY>} public void forget(String canonical, CrawlURI item) { // TODO? could use in-memory exception list of currently-forgotten items LOGGER.severe("forget(\""+canonical+"\",CrawlURI) not supported"); } protected boolean setAdd(CharSequence uri) { boolean added = bloom.add(uri); // warn if bloom has reached its expected size (and its false-pos // rate will now exceed the theoretical/designed level) if( added && (count() == bloom.getExpectedInserts())) { LOGGER.warning( "Bloom has reached expected limit "+bloom.getExpectedInserts()+ "; false-positive rate will now rise above goal of "+ "1-in-(2^"+bloom.getHashCount()); } return added; } protected long setCount() { return bloom.size(); } protected boolean setRemove(CharSequence uri) { throw new UnsupportedOperationException(); } }
if(bloom==null) { // configure default bloom filter if operator hasn't already // these defaults create a bloom filter that is // 1.44*125mil*22/8 ~= 495MB in size, and at full // capacity will give a false contained indication // 1/(2^22) ~= 1 in every 4 million probes bloom = new BloomFilter64bit(125000000,22); }
466
129
595
<methods>public void <init>() ,public void add(java.lang.String, org.archive.modules.CrawlURI) ,public void addForce(java.lang.String, org.archive.modules.CrawlURI) ,public void addNow(java.lang.String, org.archive.modules.CrawlURI) ,public long addedCount() ,public void close() ,public long count() ,public void forget(java.lang.String, org.archive.modules.CrawlURI) ,public void note(java.lang.String) ,public long pending() ,public long requestFlush() ,public void setDestination(org.archive.crawler.datamodel.UriUniqFilter.CrawlUriReceiver) ,public void setProfileLog(java.io.File) <variables>private static java.util.logging.Logger LOGGER,protected java.util.concurrent.atomic.AtomicLong addedCount,protected long duplicateCount,protected long duplicatesAtLastSample,protected java.io.PrintWriter profileLog,protected org.archive.crawler.datamodel.UriUniqFilter.CrawlUriReceiver receiver
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/util/CheckpointUtils.java
CheckpointUtils
readObjectFromFile
class CheckpointUtils { public static final String SERIALIZED_CLASS_SUFFIX = ".serialized"; public static File getBdbSubDirectory(File checkpointDir) { return new File(checkpointDir, "bdbje-logs"); } public static File getClassCheckpointFile(File checkpointDir, final String suffix, Class<?> c) { return new File(checkpointDir, getClassCheckpointFilename(c, suffix)); } public static File getClassCheckpointFile(File checkpointDir, Class<?> c) { return new File(checkpointDir, getClassCheckpointFilename(c, null)); } public static String getClassCheckpointFilename(final Class<?> c) { return getClassCheckpointFilename(c, null); } public static String getClassCheckpointFilename(final Class<?> c, final String suffix) { return c.getName() + ((suffix == null)? "": "." + suffix) + SERIALIZED_CLASS_SUFFIX; } /** * Utility function to serialize an object to a file in current checkpoint * dir. Facilities * to store related files alongside the serialized object in a directory * named with a <code>.auxiliary</code> suffix. * * @param o Object to serialize. * @param dir Directory to serialize into. * @throws IOException */ public static void writeObjectToFile(final Object o, final File dir) throws IOException { writeObjectToFile(o, null, dir); } public static void writeObjectToFile(final Object o, final String suffix, final File dir) throws IOException { FileUtils.ensureWriteableDirectory(dir); ObjectOutputStream out = new ObjectOutputStream( new FileOutputStream(getClassCheckpointFile(dir, suffix, o.getClass()))); try { out.writeObject(o); } finally { out.close(); } } public static <T> T readObjectFromFile(final Class<T> c, final File dir) throws FileNotFoundException, IOException, ClassNotFoundException { return readObjectFromFile(c, null, dir); } public static <T> T readObjectFromFile(final Class<T> c, final String suffix, final File dir) throws FileNotFoundException, IOException, ClassNotFoundException {<FILL_FUNCTION_BODY>} /** * @return Instance of filename filter that will let through files ending * in '.jdb' (i.e. bdb je log files). */ public static FilenameFilter getJeLogsFilter() { return new FilenameFilter() { public boolean accept(File dir, String name) { return name != null && name.toLowerCase().endsWith(".jdb"); } }; } }
ObjectInputStream in = new ObjectInputStream( new FileInputStream(getClassCheckpointFile(dir, suffix, c))); T o = null; try { o = c.cast(in.readObject()); } finally { in.close(); } return o;
742
74
816
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/util/DiskFPMergeUriUniqFilter.java
DiskFPMergeUriUniqFilter
beginFpMerge
class DiskFPMergeUriUniqFilter extends FPMergeUriUniqFilter { protected long count = 0; protected File scratchDir; protected File currentFps; protected File newFpsFile; protected DataOutputStream newFps; protected long newCount; protected DataInputStream oldFps; public DiskFPMergeUriUniqFilter(File scratchDir) { super(); this.scratchDir = scratchDir; // TODO: Use two scratch locations, to allow IO to be split // over separate disks } /* (non-Javadoc) * @see org.archive.crawler.util.FPMergeUriUniqFilter#beginFpMerge() */ protected LongIterator beginFpMerge() {<FILL_FUNCTION_BODY>} /* (non-Javadoc) * @see org.archive.crawler.util.FPMergeUriUniqFilter#addNewFp(long) */ protected void addNewFp(long fp) { try { newFps.writeLong(fp); newCount++; } catch (IOException e) { throw new RuntimeException(e); } } /* (non-Javadoc) * @see org.archive.crawler.util.FPMergeUriUniqFilter#finishFpMerge() */ protected void finishFpMerge() { try { newFps.close(); File oldFpsFile = currentFps; currentFps = newFpsFile; if(oldFps!=null) { oldFps.close(); } if(oldFpsFile!=null) { oldFpsFile.delete(); } } catch (IOException e) { throw new RuntimeException(e); } count = newCount; } /* (non-Javadoc) * @see org.archive.crawler.datamodel.UriUniqFilter#count() */ public long count() { return count; } public class DataFileLongIterator implements LongIterator { DataInputStream in; long next; boolean nextIsValid = false; /** * Construct a long iterator reading from the given * stream. * * @param disStream DataInputStream from which to read longs */ public DataFileLongIterator(DataInputStream disStream) { this.in = disStream; } /** * Test whether any items remain; loads next item into * holding 'next' field. * * @see java.util.Iterator#hasNext() */ public boolean hasNext() { return nextIsValid ? true: lookahead(); } /** * Check if there's a next by trying to read it. * * @return true if 'next' field is filled with a valid next, false otherwise */ protected boolean lookahead() { try { next = in.readLong(); } catch (IOException e) { return false; } nextIsValid = true; return true; } /** * Return the next item. * * @see java.util.Iterator#next() */ public Long next() { if (!hasNext()) { throw new NoSuchElementException(); } // 'next' is guaranteed set by a hasNext() which returned true Long returnObj = new Long(this.next); this.nextIsValid = false; return returnObj; } /* (non-Javadoc) * @see java.util.Iterator#remove() */ public void remove() { throw new UnsupportedOperationException(); } /* (non-Javadoc) * @see it.unimi.dsi.fastutil.longs.LongIterator#nextLong() */ public long nextLong() { if (!hasNext()) { throw new NoSuchElementException(); } // 'next' is guaranteed non-null by a hasNext() which returned true this.nextIsValid = false; // after this return, 'next' needs refresh return this.next; } /* (non-Javadoc) * @see it.unimi.dsi.fastutil.longs.LongIterator#skip(int) */ public int skip(int arg0) { return 0; } } }
newFpsFile = new File(scratchDir,ArchiveUtils.get17DigitDate()+".fp"); if(newFpsFile.exists()) { throw new RuntimeException(newFpsFile+" exists"); } try { newFps = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(newFpsFile))); } catch (FileNotFoundException e) { throw new RuntimeException(e); } newCount = 0; if(currentFps==null) { return LongIterators.EMPTY_ITERATOR; } try { oldFps = new DataInputStream(new BufferedInputStream(new FileInputStream(currentFps))); } catch (FileNotFoundException e1) { throw new RuntimeException(e1); } return new DataFileLongIterator(oldFps);
1,164
214
1,378
<methods>public void <init>() ,public synchronized void add(java.lang.String, org.archive.modules.CrawlURI) ,public void addForce(java.lang.String, org.archive.modules.CrawlURI) ,public void addNow(java.lang.String, org.archive.modules.CrawlURI) ,public long addedCount() ,public void close() ,public static long createFp(java.lang.CharSequence) ,public synchronized long flush() ,public void forget(java.lang.String, org.archive.modules.CrawlURI) ,public void note(java.lang.String) ,public long pending() ,public synchronized long requestFlush() ,public void setDestination(org.archive.crawler.datamodel.UriUniqFilter.CrawlUriReceiver) ,public void setMaxPending(int) ,public void setProfileLog(java.io.File) <variables>public static final int DEFAULT_MAX_PENDING,public static final long FLUSH_DELAY_FACTOR,private static java.util.logging.Logger LOGGER,protected java.util.concurrent.atomic.AtomicLong addedCount,protected int maxPending,protected long mergeDupAtLast,protected long mergeDuplicateCount,protected long nextFlushAllowableAfter,protected long pendDupAtLast,protected long pendDuplicateCount,protected TreeSet<org.archive.crawler.util.FPMergeUriUniqFilter.PendingItem> pendingSet,protected java.io.PrintWriter profileLog,protected org.archive.util.fingerprint.ArrayLongFPCache quickCache,protected long quickDupAtLast,protected long quickDuplicateCount,protected org.archive.crawler.datamodel.UriUniqFilter.CrawlUriReceiver receiver
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/util/FPMergeUriUniqFilter.java
PendingItem
pend
class PendingItem implements Comparable<PendingItem> { long fp; CrawlURI caUri; public PendingItem(long fp, CrawlURI value) { this.fp = fp; this.caUri = value; } public int compareTo(PendingItem vs) { return (fp < vs.fp) ? -1 : ( (fp == vs.fp) ? 0 : 1); } } private static Logger LOGGER = Logger.getLogger(FPMergeUriUniqFilter.class.getName()); protected CrawlUriReceiver receiver; protected PrintWriter profileLog; // statistics protected long quickDuplicateCount = 0; protected long quickDupAtLast = 0; protected long pendDuplicateCount = 0; protected long pendDupAtLast = 0; protected long mergeDuplicateCount = 0; protected long mergeDupAtLast = 0; /** items awaiting merge * TODO: consider only sorting just pre-merge * TODO: consider using a fastutil long-&gt;Object class * TODO: consider actually writing items to disk file, * as in Najork/Heydon */ protected TreeSet<PendingItem> pendingSet = new TreeSet<PendingItem>(); /** size at which to force flush of pending items */ protected int maxPending = DEFAULT_MAX_PENDING; public static final int DEFAULT_MAX_PENDING = 10000; // TODO: increase /** * time-based throttle on flush-merge operations */ protected long nextFlushAllowableAfter = 0; public static final long FLUSH_DELAY_FACTOR = 100; /** cache of most recently seen FPs */ protected ArrayLongFPCache quickCache = new ArrayLongFPCache(); // TODO: make cache most-often seen, not just most-recent protected AtomicLong addedCount = new AtomicLong(); public FPMergeUriUniqFilter() { super(); String profileLogFile = System.getProperty(FPMergeUriUniqFilter.class.getName() + ".profileLogFile"); if (profileLogFile != null) { setProfileLog(new File(profileLogFile)); } } public void setMaxPending(int max) { maxPending = max; } public long pending() { return pendingSet.size(); } @Override public long addedCount() { return addedCount.get(); } public void setDestination(CrawlUriReceiver receiver) { this.receiver = receiver; } protected void profileLog(String key) { if (profileLog != null) { profileLog.println(key); } } /* (non-Javadoc) * @see org.archive.crawler.datamodel.UriUniqFilter#add(java.lang.String, org.archive.crawler.datamodel.CrawlURI) */ public synchronized void add(String key, CrawlURI value) { addedCount.incrementAndGet(); profileLog(key); long fp = createFp(key); if(! quickCheck(fp)) { quickDuplicateCount++; return; } pend(fp,value); if (pendingSet.size()>=maxPending) { flush(); } } /** * Place the given FP/CrawlURI pair into the pending set, awaiting * a merge to determine if it's actually accepted. * * @param fp long fingerprint * @param value CrawlURI or null, if fp only needs merging (as when * CrawlURI was already forced in */ protected void pend(long fp, CrawlURI value) {<FILL_FUNCTION_BODY>
// special case for first batch of adds if(count()==0) { if(pendingSet.add(new PendingItem(fp,null))==false) { pendDuplicateCount++; // was already present } else { // since there's no prior list to merge, push uri along right now if(value!=null) { this.receiver.receive(value); } } return; } if(pendingSet.add(new PendingItem(fp,value))==false) { pendDuplicateCount++; // was already present }
1,024
154
1,178
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/util/LogUtils.java
LogUtils
createFileLogger
class LogUtils { /** * Creates a file logger that use heritrix.properties file logger * configuration. * Change the java.util.logging.FileHandler.* properties in * heritrix.properties to change file handler properties. * Use this method if you want a class to log to its own file * rather than use default (console) logger. * @param logsDir Directory in which to write logs. * @param baseName Base name to use for log file (Will have * java.util.logging.FileHandler.pattern or '.log' for suffix). * @param logger Logger whose handler we'll replace with the * file handler created herein. */ public static FileHandler createFileLogger(File logsDir, String baseName, Logger logger) {<FILL_FUNCTION_BODY>} }
int limit = PropertyUtils.getIntProperty("java.util.logging.FileHandler.limit", 1024 * 1024 * 1024 * 1024); int count = PropertyUtils.getIntProperty("java.util.logging.FileHandler.count", 1); try { String tmp = System.getProperty("java.util.logging.FileHandler.pattern"); File logFile = new File(logsDir, baseName + ((tmp != null && tmp.length() > 0)? tmp: ".log")); FileHandler fh = new FileHandler(logFile.getAbsolutePath(), limit, count, true); // Manage the formatter to use. tmp = System.getProperty("java.util.logging.FileHandler.formatter"); if (tmp != null && tmp.length() > 0) { Constructor<?> co = Class.forName(tmp). getConstructor(new Class[] {}); Formatter f = (Formatter) co.newInstance(new Object[] {}); fh.setFormatter(f); } logger.addHandler(fh); logger.setUseParentHandlers(false); return fh; } catch (Exception e) { logger.severe("Failed customization of logger: " + e.getMessage()); return null; }
207
346
553
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/util/SetBasedUriUniqFilter.java
SetBasedUriUniqFilter
add
class SetBasedUriUniqFilter implements UriUniqFilter, Serializable { private static Logger LOGGER = Logger.getLogger(SetBasedUriUniqFilter.class.getName()); protected CrawlUriReceiver receiver; protected PrintWriter profileLog; protected long duplicateCount = 0; protected long duplicatesAtLastSample = 0; protected AtomicLong addedCount = new AtomicLong(); public SetBasedUriUniqFilter() { super(); String profileLogFile = System.getProperty(SetBasedUriUniqFilter.class.getName() + ".profileLogFile"); if (profileLogFile != null) { setProfileLog(new File(profileLogFile)); } } protected abstract boolean setAdd(CharSequence key); protected abstract boolean setRemove(CharSequence key); protected abstract long setCount(); @Override public long addedCount() { return addedCount.get(); } public long count() { return setCount(); } public long pending() { // no items pile up in this implementation return 0; } public void setDestination(CrawlUriReceiver receiver) { this.receiver = receiver; } protected void profileLog(String key) { if (profileLog != null) { profileLog.println(key); } } public void add(String key, CrawlURI value) {<FILL_FUNCTION_BODY>} public void addNow(String key, CrawlURI value) { add(key, value); } public void addForce(String key, CrawlURI value) { profileLog(key); setAdd(key); this.receiver.receive(value); } public void note(String key) { profileLog(key); setAdd(key); } public void forget(String key, CrawlURI value) { setRemove(key); } public long requestFlush() { // unnecessary; all actions with set-based uniqfilter are immediate return 0; } public void close() { if (profileLog != null) { profileLog.close(); } } public void setProfileLog(File logfile) { try { profileLog = new PrintWriter(new BufferedOutputStream( new FileOutputStream(logfile))); } catch (FileNotFoundException e) { throw new RuntimeException(e); } } }
addedCount.incrementAndGet(); profileLog(key); if (setAdd(key)) { this.receiver.receive(value); if (setCount() % 50000 == 0) { LOGGER.log(Level.FINE, "count: " + setCount() + " totalDups: " + duplicateCount + " recentDups: " + (duplicateCount - duplicatesAtLastSample)); duplicatesAtLastSample = duplicateCount; } } else { duplicateCount++; }
653
141
794
<no_super_class>
internetarchive_heritrix3
heritrix3/engine/src/main/java/org/archive/crawler/util/TopNSet.java
TopNSet
update
class TopNSet implements Serializable { private static final long serialVersionUID = 1L; protected int maxsize; protected ConcurrentMap<String, Long> set; protected volatile long smallestKnownValue; protected volatile String smallestKnownKey; protected volatile long largestKnownValue; protected volatile String largestKnownKey; public TopNSet(int size){ maxsize = size; set = CacheBuilder.newBuilder().concurrencyLevel(64).<String, Long>build().asMap(); } /** * Update the given String key with a new total value, perhaps displacing * an existing top-valued entry, and updating the fields recording max/min * keys in any case. * * @param key String key to update * @param value long new total value (*not* increment/decrement) */ public void update(String key, long value){<FILL_FUNCTION_BODY>} public String getLargest() { return largestKnownKey; } public String getSmallest() { return smallestKnownKey; } /** * After an operation invalidating the previous largest/smallest entry, * find the new largest/smallest. */ public synchronized void updateBounds(){ // freshly determine smallestKnownValue = Long.MAX_VALUE; largestKnownValue = Long.MIN_VALUE; for(String k : set.keySet()){ long v = set.get(k); if(v<smallestKnownValue){ smallestKnownValue = v; smallestKnownKey = k; } if(v>largestKnownValue){ largestKnownValue = v; largestKnownKey = k; } } } /** * Make internal map available (for checkpoint/restore purposes). * @return HashMap&lt;String,Long&gt; */ public ConcurrentMap<String, Long> getTopSet() { return set; } public int size() { return set.size(); } /** * Get descending ordered list of key,count Entries. * * @return SortedSet of Entry&lt;key, count&gt; descending-frequency */ public SortedSet<Map.Entry<?, Long>> getEntriesDescending() { TreeSet<Map.Entry<?, Long>> sorted = Histotable.getEntryByFrequencySortedSet(); sorted.addAll(getTopSet().entrySet()); return sorted; } public int getMaxSize() { return maxsize; } public void setMaxSize(int max) { maxsize = max; } }
// handle easy cases without synchronization if(set.size()<maxsize) { // need to reach maxsize before any eviction set.put(key, value); updateBounds(); return; } if(value<smallestKnownValue && !set.containsKey(key)) { // not in the running for top-N return; } set.put(key,value); synchronized(this) { if(set.size() > maxsize) { set.remove(smallestKnownKey); updateBounds(); } else if(value < smallestKnownValue || value > largestKnownValue || key.equals(smallestKnownKey) || key.equals(largestKnownKey)) { updateBounds(); } }
798
236
1,034
<no_super_class>
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/crawler/util/CrawledBytesHistotable.java
CrawledBytesHistotable
accumulate
class CrawledBytesHistotable extends Histotable<String> implements CoreAttributeConstants { private static final long serialVersionUID = 7923431123239026213L; public static final String NOTMODIFIED = "notModified"; public static final String DUPLICATE = "dupByHash"; public static final String OTHERDUPLICATE = "otherDup"; public static final String NOVEL = "novel"; public static final String NOTMODIFIEDCOUNT = "notModifiedCount"; public static final String DUPLICATECOUNT = "dupByHashCount"; public static final String OTHERDUPLICATECOUNT = "otherDupCount"; public static final String NOVELCOUNT = "novelCount"; // total size of warc response and resource record payloads (includes http // headers, does not include warc record headers) public static final String WARC_NOVEL_CONTENT_BYTES = "warcNovelContentBytes"; public static final String WARC_NOVEL_URLS = "warcNovelUrls"; public CrawledBytesHistotable() { super(); } @SuppressWarnings("unchecked") public void accumulate(CrawlURI curi) {<FILL_FUNCTION_BODY>} public String summary() { StringBuilder sb = new StringBuilder(); sb.append(ArchiveUtils.formatBytesForDisplay(getTotalBytes())); sb.append(" crawled ("); sb.append(ArchiveUtils.formatBytesForDisplay(get(NOVEL))); sb.append(" novel"); if(get(DUPLICATE)!=null) { sb.append(", "); sb.append(ArchiveUtils.formatBytesForDisplay(get(DUPLICATE))); sb.append(" "); sb.append(DUPLICATE); } if(get(NOTMODIFIED)!=null) { sb.append(", "); sb.append(ArchiveUtils.formatBytesForDisplay(get(NOTMODIFIED))); sb.append(" "); sb.append(NOTMODIFIED); } if(get(OTHERDUPLICATE)!=null) { sb.append(", "); sb.append(ArchiveUtils.formatBytesForDisplay(get(OTHERDUPLICATE))); sb.append(" "); sb.append(OTHERDUPLICATECOUNT); } sb.append(")"); return sb.toString(); } public long getTotalBytes() { return get(NOVEL) + get(DUPLICATE) + get(NOTMODIFIED) + get(OTHERDUPLICATE); } public long getTotalUrls() { return get(NOVELCOUNT) + get(DUPLICATECOUNT) + get(NOTMODIFIEDCOUNT) + get(OTHERDUPLICATECOUNT); } }
if (curi.getRevisitProfile() instanceof ServerNotModifiedRevisit) { tally(NOTMODIFIED, curi.getContentSize()); tally(NOTMODIFIEDCOUNT,1); } else if (curi.getRevisitProfile() instanceof IdenticalPayloadDigestRevisit) { tally(DUPLICATE,curi.getContentSize()); tally(DUPLICATECOUNT,1); } else if (curi.getRevisitProfile() != null) { tally(OTHERDUPLICATE, curi.getContentSize()); tally(OTHERDUPLICATECOUNT, 1); } else { tally(NOVEL,curi.getContentSize()); tally(NOVELCOUNT,1); } Map<String,Map<String,Long>> warcStats = (Map<String,Map<String,Long>>) curi.getData().get(A_WARC_STATS); if (warcStats != null) { tally(WARC_NOVEL_CONTENT_BYTES, WARCWriter.getStat(warcStats, "response", "contentBytes") + WARCWriter.getStat(warcStats, "resource", "contentBytes")); tally(WARC_NOVEL_URLS, WARCWriter.getStat(warcStats, "response", "numRecords") + WARCWriter.getStat(warcStats, "resource", "numRecords")); }
737
384
1,121
<methods>public non-sealed void <init>() ,public long add(Histotable<java.lang.String>) ,public static java.lang.String entryString(java.lang.Object) ,public java.lang.Long get(java.lang.Object) ,public static TreeSet<Entry<?,java.lang.Long>> getEntryByFrequencySortedSet() ,public long getLargestValue() ,public TreeSet<Entry<?,java.lang.Long>> getSortedByCounts() ,public Set<Entry<java.lang.String,java.lang.Long>> getSortedByKeys() ,public long getTotal() ,public long subtract(Histotable<java.lang.String>) ,public void tally(java.lang.String) ,public synchronized void tally(java.lang.String, long) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/CrawlMetadata.java
CrawlMetadata
setOperatorContactUrl
class CrawlMetadata implements UserAgentProvider, Serializable, HasKeyedProperties, HasValidator, InitializingBean { private static final long serialVersionUID = 1L; protected KeyedProperties kp = new KeyedProperties(); public KeyedProperties getKeyedProperties() { return kp; } { setRobotsPolicyName("obey"); } public String getRobotsPolicyName() { return (String) kp.get("robotsPolicyName"); } /** * Robots policy name */ @Autowired(required=false) public void setRobotsPolicyName(String policy) { kp.put("robotsPolicyName",policy); } /** Map of all available RobotsPolicies, by name, to choose from. * assembled from declared instances in configuration plus the standard * 'obey' (aka 'classic') and 'ignore' policies. */ protected Map<String,RobotsPolicy> availableRobotsPolicies = new HashMap<String,RobotsPolicy>(); public Map<String,RobotsPolicy> getAvailableRobotsPolicies() { return availableRobotsPolicies; } @Autowired(required=false) public void setAvailableRobotsPolicies(Map<String,RobotsPolicy> policies) { availableRobotsPolicies = policies; ensureStandardPoliciesAvailable(); } protected void ensureStandardPoliciesAvailable() { availableRobotsPolicies.putAll(RobotsPolicy.STANDARD_POLICIES); } /** * Get the currently-effective RobotsPolicy, as specified by the * string name and chosen from the full available map. (Setting * a different policy for some sites/URL patterns is best acheived * by establishing a setting overlay for the robotsPolicyName * property.) */ public RobotsPolicy getRobotsPolicy() { return availableRobotsPolicies.get(getRobotsPolicyName()); } protected String operator = ""; public String getOperator() { return operator; } public void setOperator(String operatorName) { this.operator = operatorName; } protected String description = ""; public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } { setUserAgentTemplate("Mozilla/5.0 (compatible; heritrix/@VERSION@ +@OPERATOR_CONTACT_URL@)"); } public String getUserAgentTemplate() { return (String) kp.get("userAgentTemplate"); } public void setUserAgentTemplate(String template) { // TODO compile pattern outside method // if(!template.matches("^.*\\+@OPERATOR_CONTACT_URL@.*$")) { // throw new IllegalArgumentException("bad user-agent: "+template); // } kp.put("userAgentTemplate",template); } { setOperatorFrom(""); } public String getOperatorFrom() { return (String) kp.get("operatorFrom"); } public void setOperatorFrom(String operatorFrom) { // TODO compile pattern outside method // if(!operatorFrom.matches("^(\\s*|\\S+@[-\\w]+\\.[-\\w\\.]+)$")) { // throw new IllegalArgumentException("bad operatorFrom: "+operatorFrom); // } kp.put("operatorFrom",operatorFrom); } { // set default to illegal value kp.put("operatorContactUrl","ENTER-A-CONTACT-HTTP-URL-FOR-CRAWL-OPERATOR"); } public String getOperatorContactUrl() { return (String) kp.get("operatorContactUrl"); } public void setOperatorContactUrl(String operatorContactUrl) {<FILL_FUNCTION_BODY>} protected String audience = ""; public String getAudience() { return audience; } public void setAudience(String audience) { this.audience = audience; } protected String organization = ""; public String getOrganization() { return organization; } public void setOrganization(String organization) { this.organization = organization; } public String getUserAgent() { String userAgent = getUserAgentTemplate(); String contactURL = getOperatorContactUrl(); userAgent = userAgent.replaceFirst("@OPERATOR_CONTACT_URL@", contactURL); userAgent = userAgent.replaceFirst("@VERSION@", Matcher.quoteReplacement(ArchiveUtils.VERSION)); return userAgent; } protected String jobName; public String getJobName() { return jobName; } public void setJobName(String jobName) { this.jobName = jobName; } public String getFrom() { return getOperatorFrom(); } public void afterPropertiesSet() { // force revalidation, throwing exception if invalid setOperatorContactUrl(getOperatorContactUrl()); ensureStandardPoliciesAvailable(); } protected static Validator VALIDATOR = new BeanFieldsPatternValidator( CrawlMetadata.class, "userAgentTemplate", "^.*@OPERATOR_CONTACT_URL@.*$", "You must supply a userAgentTemplate value that includes " + "the string \"@OPERATOR_CONTACT_URL@\" where your crawl" + "contact URL will appear.", "operatorContactUrl", "^https?://.*$", "You must supply an HTTP(S) URL which will be included " + "in your user-agent and should explain the purpose of your " + "crawl and how to contact the crawl operator in the event " + "of webmaster issues.", "operatorFrom", "^(\\s*|\\S+@[-\\w]+\\.[-\\w\\.]+)|()$", "If not blank, operatorFrom must be an email address."); public Validator getValidator() { return VALIDATOR; } }
// TODO compile pattern outside method // if(!operatorContactUrl.matches("^https?://.*$")) { // throw new IllegalArgumentException("bad operatorContactUrl: "+operatorContactUrl); // } kp.put("operatorContactUrl",operatorContactUrl);
1,600
69
1,669
<no_super_class>
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/ProcessorChain.java
ProcessorChain
stop
class ProcessorChain implements Iterable<Processor>, HasKeyedProperties, Reporter, Lifecycle { protected KeyedProperties kp = new KeyedProperties(); public KeyedProperties getKeyedProperties() { return kp; } public int size() { return getProcessors().size(); } public Iterator<Processor> iterator() { return getProcessors().iterator(); } @SuppressWarnings("unchecked") public List<Processor> getProcessors() { return (List<Processor>) kp.get("processors"); } public void setProcessors(List<Processor> processors) { kp.put("processors",processors); } protected boolean isRunning = false; public boolean isRunning() { return isRunning; } public void start() { for(Processor p : getProcessors()) { // relies on each Processor's start() being ok to call if // already running, which is part of the Lifecycle contract p.start(); } isRunning = true; } public void stop() {<FILL_FUNCTION_BODY>} /** * Compiles and returns a human readable report on the active processors. * @param writer Where to write to. * @see Processor#report() */ public void reportTo(PrintWriter writer) { writer.print( getClass().getSimpleName() + " - Processors report - " + ArchiveUtils.get12DigitDate() + "\n"); writer.print(" Number of Processors: " + size() + "\n\n"); for (Processor p: this) { writer.print(p.report()); writer.println(); } writer.println(); } public String shortReportLegend() { return ""; } public Map<String, Object> shortReportMap() { Map<String,Object> data = new LinkedHashMap<String, Object>(); data.put("processorCount", size()); data.put("processors", getProcessors()); return data; } public void shortReportLineTo(PrintWriter pw) { pw.print(size()); pw.print(" processors: "); for(Processor p : this) { pw.print(p.getBeanName()); pw.print(" "); } } public void process(CrawlURI curi, ChainStatusReceiver thread) throws InterruptedException { assert KeyedProperties.overridesActiveFrom(curi); String skipToProc = null; ploop: for(Processor curProc : this ) { if(skipToProc!=null && !curProc.getBeanName().equals(skipToProc)) { continue; } else { skipToProc = null; } if(thread!=null) { thread.atProcessor(curProc); } ArchiveUtils.continueCheck(); ProcessResult pr = curProc.process(curi); switch (pr.getProcessStatus()) { case PROCEED: continue; case FINISH: break ploop; case JUMP: skipToProc = pr.getJumpTarget(); continue; } } } public interface ChainStatusReceiver { public void atProcessor(Processor proc); } }
for(Processor p : getProcessors()) { // relies on each Processor's stop() being ok to call if // not running, which is part of the Lifecycle contract p.stop(); } isRunning = false;
1,021
74
1,095
<no_super_class>
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/ScriptedProcessor.java
ScriptedProcessor
innerProcess
class ScriptedProcessor extends Processor implements ApplicationContextAware, InitializingBean { @SuppressWarnings("unused") private static final long serialVersionUID = 3L; private static final Logger logger = Logger.getLogger(ScriptedProcessor.class.getName()); /** engine name; default "beanshell" */ protected String engineName = "beanshell"; public String getEngineName() { return this.engineName; } public void setEngineName(String name) { this.engineName = name; } protected ReadSource scriptSource = null; public ReadSource getScriptSource() { return this.scriptSource; } @Required public void setScriptSource(ReadSource source) { this.scriptSource = source; } /** * Whether each ToeThread should get its own independent script * engine, or they should share synchronized access to one * engine. Default is true, meaning each thread gets its own * isolated engine. */ protected boolean isolateThreads = true; public boolean getIsolateThreads() { return isolateThreads; } public void setIsolateThreads(boolean isolateThreads) { this.isolateThreads = isolateThreads; } protected ApplicationContext appCtx; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.appCtx = applicationContext; } transient protected ThreadLocal<ScriptEngine> threadEngine = new ThreadLocal<ScriptEngine>(); protected ScriptEngine sharedEngine; /** * Constructor. */ public ScriptedProcessor() { super(); } public void afterPropertiesSet() throws Exception { // fail at build-time if script engine not available if(null == new ScriptEngineManager().getEngineByName(engineName)) { throw new BeanInitializationException("named ScriptEngine not available"); } } protected boolean shouldProcess(CrawlURI curi) { return true; } @Override protected void innerProcess(CrawlURI curi) {<FILL_FUNCTION_BODY>} /** * Get the proper ScriptEngine instance -- either shared or local * to this thread. * @return ScriptEngine to use */ protected synchronized ScriptEngine getEngine() { if (getIsolateThreads()) { if (threadEngine.get() == null) { threadEngine.set(newEngine()); } return threadEngine.get(); } else { if (sharedEngine == null) { sharedEngine = newEngine(); } return sharedEngine; } } /** * Create a new {@link ScriptEngine} instance, preloaded with any supplied * source file and the variables 'self' (this {@link ScriptedProcessor}) and * 'context' (the {@link ApplicationContext}). * * @return the new ScriptEngine instance */ protected ScriptEngine newEngine() { ScriptEngine interpreter = new ScriptEngineManager().getEngineByName(engineName); interpreter.put("self", this); interpreter.put("context", appCtx); Reader reader = null; try { reader = getScriptSource().obtainReader(); interpreter.eval(reader); } catch (ScriptException e) { logger.log(Level.SEVERE,"script problem",e); } finally { IOUtils.closeQuietly(reader); } return interpreter; } }
// depending on previous configuration, engine may // be local to this thread or shared ScriptEngine engine = getEngine(); synchronized(engine) { // synchronization is harmless for local thread engine, // necessary for shared engine engine.put("curi",curi); engine.put("appCtx", appCtx); try { engine.eval("process(curi)"); } catch (ScriptException e) { logger.log(Level.WARNING,e.getMessage(),e); } finally { engine.put("curi", null); engine.put("appCtx", null); } }
910
166
1,076
<methods>public non-sealed void <init>() ,public void doCheckpoint(org.archive.checkpointing.Checkpoint) throws java.io.IOException,public void finishCheckpoint(org.archive.checkpointing.Checkpoint) ,public static java.lang.String flattenVia(org.archive.modules.CrawlURI) ,public java.lang.String getBeanName() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public static long getRecordedSize(org.archive.modules.CrawlURI) ,public org.archive.modules.deciderules.DecideRule getShouldProcessRule() ,public long getURICount() ,public static boolean hasHttpAuthenticationCredential(org.archive.modules.CrawlURI) ,public boolean isRunning() ,public static boolean isSuccess(org.archive.modules.CrawlURI) ,public org.archive.modules.ProcessResult process(org.archive.modules.CrawlURI) throws java.lang.InterruptedException,public java.lang.String report() ,public void setBeanName(java.lang.String) ,public void setEnabled(boolean) ,public void setRecoveryCheckpoint(org.archive.checkpointing.Checkpoint) ,public void setShouldProcessRule(org.archive.modules.deciderules.DecideRule) ,public void start() ,public void startCheckpoint(org.archive.checkpointing.Checkpoint) ,public void stop() <variables>protected java.lang.String beanName,protected boolean isRunning,protected org.archive.spring.KeyedProperties kp,protected org.archive.checkpointing.Checkpoint recoveryCheckpoint,protected java.util.concurrent.atomic.AtomicLong uriCount
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/canonicalize/BaseRule.java
BaseRule
doStripRegexMatch
class BaseRule implements CanonicalizationRule, Serializable, HasKeyedProperties { private static final long serialVersionUID = 1L; protected KeyedProperties kp = new KeyedProperties(); public KeyedProperties getKeyedProperties() { return kp; } { setEnabled(true); } public boolean getEnabled() { return (Boolean) kp.get("enabled"); } public void setEnabled(boolean enabled) { kp.put("enabled",enabled); } /** * Constructor. */ public BaseRule() { } /** * Run a regex that strips elements of a string. * * Assumes the regex has a form that wants to strip elements of the passed * string. Assumes that if a match, appending group 1 * and group 2 yields desired result. * @param url Url to search in. * @param pat * @return Original <code>url</code> else concatenization of group 1 * and group 2. */ protected String doStripRegexMatch(String url, String pat) {<FILL_FUNCTION_BODY>} /** * @param string String to check. * @return <code>string</code> if non-null, else empty string (""). */ private String checkForNull(String string) { return (string != null)? string: ""; } }
Matcher matcher = TextUtils.getMatcher(pat, url); String retVal = (matcher != null && matcher.matches())? checkForNull(matcher.group(1)) + checkForNull(matcher.group(2)): url; TextUtils.recycleMatcher(matcher); return retVal;
376
91
467
<no_super_class>
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/canonicalize/FixupQueryString.java
FixupQueryString
canonicalize
class FixupQueryString extends BaseRule { private static final long serialVersionUID = 3L; /* private static final String DESCRIPTION = "Fixup the question mark that leads off the query string. " + "This rule returns 'http://www.archive.org/index.html' if passed" + " 'http://www.archive.org/index.html?'. It will also strip '?&'" + " if '?&' is all that comprises the query string. Also strips" + " extraneous leading '&': Returns 'http://archive.org/index.html?x=y" + " if passed 'http://archive.org/index.html?&x=y." + " Will also strip '&' if last thing in query string." + " Operates on all schemes. This is a good rule to run toward the" + " end of canonicalization processing."; */ public FixupQueryString() { } public String canonicalize(String url) {<FILL_FUNCTION_BODY>} }
if (url == null || url.length() <= 0) { return url; } int index = url.lastIndexOf('?'); if (index > 0) { if (index == (url.length() - 1)) { // '?' is last char in url. Strip it. url = url.substring(0, url.length() - 1); } else if (url.charAt(index + 1) == '&') { // Next char is '&'. Strip it. if (url.length() == (index + 2)) { // Then url ends with '?&'. Strip them. url = url.substring(0, url.length() - 2); } else { // The '&' is redundant. Strip it. url = url.substring(0, index + 1) + url.substring(index + 2); } } else if (url.charAt(url.length() - 1) == '&') { // If we have a lone '&' on end of query str, // strip it. url = url.substring(0, url.length() - 1); } } return url;
269
314
583
<methods>public void <init>() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public void setEnabled(boolean) <variables>protected org.archive.spring.KeyedProperties kp,private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/canonicalize/RegexRule.java
RegexRule
canonicalize
class RegexRule extends BaseRule { private static final long serialVersionUID = -3L; protected static Logger logger = Logger.getLogger(BaseRule.class.getName()); // private static final String DESCRIPTION = "General regex rule. " + // "Specify a matching regex and a format string used outputting" + // " result if a match was found. If problem compiling regex or" + // " interpreting format, problem is logged, and this rule does" + // " nothing. See User Manual for example usage."; { setRegex(Pattern.compile("(.*)")); } public Pattern getRegex() { return (Pattern) kp.get("regex"); } /** * The regular expression to use to match. */ public void setRegex(Pattern regex) { kp.put("regex",regex); } { setFormat("$1"); } public String getFormat() { return (String) kp.get("format"); } /** * The format string to use when a match is found. */ public void setFormat(String format) { kp.put("format",format); } public RegexRule() { } public String canonicalize(String url) {<FILL_FUNCTION_BODY>} }
Pattern pattern = getRegex(); Matcher matcher = pattern.matcher(url); if (!matcher.matches()) { return url; } StringBuffer buffer = new StringBuffer(url.length() * 2); matcher.appendReplacement(buffer,getFormat()); return buffer.toString();
357
85
442
<methods>public void <init>() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public void setEnabled(boolean) <variables>protected org.archive.spring.KeyedProperties kp,private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/canonicalize/RulesCanonicalizationPolicy.java
RulesCanonicalizationPolicy
canonicalize
class RulesCanonicalizationPolicy extends UriCanonicalizationPolicy implements HasKeyedProperties { private static Logger logger = Logger.getLogger(RulesCanonicalizationPolicy.class.getName()); protected KeyedProperties kp = new KeyedProperties(); public KeyedProperties getKeyedProperties() { return kp; } { setRules(getDefaultRules()); } @SuppressWarnings("unchecked") public List<CanonicalizationRule> getRules() { return (List<CanonicalizationRule>) kp.get("rules"); } public void setRules(List<CanonicalizationRule> rules) { kp.put("rules", rules); } /** * Run the passed uuri through the list of rules. * @param before Url to canonicalize. * @return Canonicalized URL. */ public String canonicalize(String before) {<FILL_FUNCTION_BODY>} /** * A reasonable set of default rules to use, if no others are * provided by operator configuration. */ public static List<CanonicalizationRule> getDefaultRules() { List<CanonicalizationRule> rules = new ArrayList<CanonicalizationRule>(6); rules.add(new LowercaseRule()); rules.add(new StripUserinfoRule()); rules.add(new StripWWWNRule()); rules.add(new StripSessionIDs()); rules.add(new StripSessionCFIDs()); rules.add(new FixupQueryString()); return rules; } }
String canonical = before; if (logger.isLoggable(Level.FINER)) { logger.finer("Canonicalizing: "+before); } for (CanonicalizationRule rule : getRules()) { if(rule.getEnabled()) { canonical = rule.canonicalize(canonical); } if (logger.isLoggable(Level.FINER)) { logger.finer( "Rule " + rule.getClass().getName() + " " + (rule.getEnabled() ? canonical :" (disabled)")); } } return canonical;
457
175
632
<methods>public non-sealed void <init>() ,public abstract java.lang.String canonicalize(java.lang.String) <variables>
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/canonicalize/StripExtraSlashes.java
StripExtraSlashes
canonicalize
class StripExtraSlashes extends BaseRule { private static final long serialVersionUID = 1L; private static final Pattern REGEX = Pattern.compile("(^https?://.*?)//+(.*)"); public StripExtraSlashes() { super(); } public String canonicalize(String url) {<FILL_FUNCTION_BODY>} }
Matcher matcher = REGEX.matcher(url); while (matcher.matches()) { url = matcher.group(1) + "/" + matcher.group(2); matcher = REGEX.matcher(url); } return url;
97
74
171
<methods>public void <init>() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public void setEnabled(boolean) <variables>protected org.archive.spring.KeyedProperties kp,private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/canonicalize/StripSessionIDs.java
StripSessionIDs
canonicalize
class StripSessionIDs extends BaseRule { private static final long serialVersionUID = 3L; // private static final String DESCRIPTION = "Strip known session IDs. " + // "Use this rule to remove all of a set of known session IDs." + // " For example, this rule will strip JSESSIONID and its value from" + // " 'http://archive.org/index.html?" + // "JSESSIONID=DDDSSE233232333355FFSXXXXDSDSDS'. The resulting" + // " canonicalization returns 'http://archive.org/index.html'." + // " This rule strips JSESSIONID, ASPSESSIONID, PHPSESSID, and 'sid'" + // " session ids."; /** * Example: jsessionid=999A9EF028317A82AC83F0FDFE59385A. * Example: PHPSESSID=9682993c8daa2c5497996114facdc805. */ private static final String BASE_PATTERN = "(?i)^(.+)(?:(?:(?:jsessionid)|(?:phpsessid))=[0-9a-zA-Z]{32})(?:&(.*))?$"; /** * Example: sid=9682993c8daa2c5497996114facdc805. * 'sid=' can be tricky but all sid= followed by 32 byte string * so far seen have been session ids. Sid is a 32 byte string * like the BASE_PATTERN only 'sid' is the tail of 'phpsessid' * so have to have it run after the phpsessid elimination. */ private static final String SID_PATTERN = "(?i)^(.+)(?:sid=[0-9a-zA-Z]{32})(?:&(.*))?$"; /** * Example:ASPSESSIONIDAQBSDSRT=EOHBLBDDPFCLHKPGGKLILNAM. */ private static final String ASPSESSION_PATTERN = "(?i)^(.+)(?:ASPSESSIONID[a-zA-Z]{8}=[a-zA-Z]{24})(?:&(.*))?$"; public StripSessionIDs() { } public String canonicalize(String url) {<FILL_FUNCTION_BODY>} }
url = doStripRegexMatch(url, BASE_PATTERN); url = doStripRegexMatch(url, SID_PATTERN); url = doStripRegexMatch(url, ASPSESSION_PATTERN); return url;
678
69
747
<methods>public void <init>() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public void setEnabled(boolean) <variables>protected org.archive.spring.KeyedProperties kp,private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/credential/Credential.java
Credential
detachAll
class Credential implements Serializable { private static final long serialVersionUID = 2L; private static final Logger logger = Logger.getLogger(Credential.class.getName()); /** * The root domain this credential goes against: E.g. www.archive.org */ protected String domain = ""; /** * @return The domain/root URI this credential is to go against. */ public String getDomain() { return this.domain; } public void setDomain(String domain) { this.domain = domain; } /** * Constructor. */ public Credential() { } /** * @param context Context to use when searching for credential domain. * @param domain New domain. * @throws AttributeNotFoundException * @throws InvalidAttributeValueException */ /* public void setCredentialDomain(CrawlerSettings context, String domain) throws InvalidAttributeValueException, AttributeNotFoundException { setAttribute(context, new Attribute(ATTR_CREDENTIAL_DOMAIN, domain)); } */ /** * Attach this credentials avatar to the passed <code>curi</code> . * * Override if credential knows internally what it wants to attach as * payload * * @param curi CrawlURI to load with credentials. */ public void attach(CrawlURI curi) { curi.getCredentials().add(this); } /** * Detach this credential from passed curi. * * @param curi * @return True if we detached a Credential reference. */ public boolean detach(CrawlURI curi) { return curi.getCredentials().remove(this); } /** * Detach all credentials of this type from passed curi. * * @param curi * @return True if we detached references. */ public boolean detachAll(CrawlURI curi) {<FILL_FUNCTION_BODY>} /** * @param curi CrawlURI to look at. * @return True if this credential IS a prerequisite for passed * CrawlURI. */ public abstract boolean isPrerequisite(CrawlURI curi); /** * @param curi CrawlURI to look at. * @return True if this credential HAS a prerequisite for passed CrawlURI. */ public abstract boolean hasPrerequisite(CrawlURI curi); /** * Return the authentication URI, either absolute or relative, that serves * as prerequisite the passed <code>curi</code>. * * @param curi CrawlURI to look at. * @return Prerequisite URI for the passed curi. */ public abstract String getPrerequisite(CrawlURI curi); /** * @return Key that is unique to this credential type. */ public abstract String getKey(); /** * @return True if this credential is of the type that needs to be offered * on each visit to the server (e.g. Rfc2617 is such a type). */ public abstract boolean isEveryTime(); /** * @return True if this credential is to be posted. Return false if the * credential is to be GET'd or if POST'd or GET'd are not pretinent to this * credential type. */ public abstract boolean isPost(); /** * Test passed curi matches this credentials rootUri. * @param cache * @param curi CrawlURI to test. * @return True if domain for credential matches that of the passed curi. */ public boolean rootUriMatch(ServerCache cache, CrawlURI curi) { String cd = getDomain(); CrawlServer serv = cache.getServerFor(curi.getUURI()); String serverName = serv.getName(); // String serverName = controller.getServerCache().getServerFor(curi). // getName(); logger.fine("RootURI: Comparing " + serverName + " " + cd); return cd != null && serverName != null && serverName.equalsIgnoreCase(cd); } }
boolean result = false; Iterator<Credential> iter = curi.getCredentials().iterator(); while (iter.hasNext()) { Credential cred = iter.next(); if (cred.getClass() == this.getClass()) { iter.remove(); result = true; } } return result;
1,123
89
1,212
<no_super_class>
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/credential/CredentialStore.java
CredentialStore
subset
class CredentialStore implements Serializable, HasKeyedProperties { private static final long serialVersionUID = 3L; @SuppressWarnings("unused") private static Logger logger = Logger.getLogger( "org.archive.crawler.datamodel.CredentialStore"); protected KeyedProperties kp = new KeyedProperties(); public KeyedProperties getKeyedProperties() { return kp; } { setCredentials(new TreeMap<String, Credential>()); } @SuppressWarnings("unchecked") public Map<String,Credential> getCredentials() { return (Map<String,Credential>) kp.get("credentials"); } /** * Credentials used by heritrix authenticating. See * http://crawler.archive.org/proposals/auth/ for background. * * @see <a href="http://crawler.archive.org/proposals/auth/">http://crawler.archive.org/proposals/auth/</a> */ public void setCredentials(Map<String,Credential> map) { kp.put("credentials",map); } /** * List of possible credential types as a List. * * This types are inner classes of this credential type so they cannot * be created without their being associated with a credential list. */ private static final List<Class<?>> credentialTypes; // Initialize the credentialType data member. static { // Array of all known credential types. Class<?> [] tmp = {HtmlFormCredential.class, HttpAuthenticationCredential.class}; credentialTypes = Collections.unmodifiableList(Arrays.asList(tmp)); } /** * Constructor. */ public CredentialStore() { } /** * @return Unmodifable list of credential types. */ public static List<Class<?>> getCredentialTypes() { return CredentialStore.credentialTypes; } /** * @return An iterator or null. */ public Collection<Credential> getAll() { Map<String,Credential> map = getCredentials(); return map.values(); } /** * @param context Used to set context. * @param name Name to give the manufactured credential. Should be unique * else the add of the credential to the list of credentials will fail. * @return Returns <code>name</code>'d credential. */ public Credential get(/*StateProvider*/Object context, String name) { return getCredentials().get(name); } /** * Return set made up of all credentials of the passed * <code>type</code>. * * @param context Used to set context. * @param type Type of the list to return. Type is some superclass of * credentials. * @return Unmodifable sublist of all elements of passed type. */ public Set<Credential> subset(CrawlURI context, Class<?> type) { return subset(context, type, null); } /** * Return set made up of all credentials of the passed * <code>type</code>. * * @param context Used to set context. * @param type Type of the list to return. Type is some superclass of * credentials. * @param rootUri RootUri to match. May be null. In this case we return * all. Currently we expect the CrawlServer name to equate to root Uri. * Its not. Currently it doesn't distingush between servers of same name * but different ports (e.g. http and https). * @return Unmodifable sublist of all elements of passed type. */ public Set<Credential> subset(CrawlURI context, Class<?> type, String rootUri) {<FILL_FUNCTION_BODY>} }
Set<Credential> result = null; for (Credential c: getAll()) { if (!type.isInstance(c)) { continue; } if (rootUri != null) { String cd = c.getDomain(); if (cd == null) { continue; } if (!rootUri.equalsIgnoreCase(cd)) { continue; } } if (result == null) { result = new HashSet<Credential>(); } result.add(c); } return result;
1,041
146
1,187
<no_super_class>
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/credential/HtmlFormCredential.java
HtmlFormCredential
isPrerequisite
class HtmlFormCredential extends Credential { private static final long serialVersionUID = -4L; private static final Logger logger = Logger.getLogger(HtmlFormCredential.class.getName()); /** * Full URI of page that contains the HTML login form we're to apply these * credentials too: E.g. http://www.archive.org */ protected String loginUri = ""; public String getLoginUri() { return this.loginUri; } public void setLoginUri(String loginUri) { this.loginUri = loginUri; } /** * Form items. * */ protected Map<String, String> formItems = new TreeMap<String, String>(); public Map<String, String> getFormItems() { return this.formItems; } public void setFormItems(Map<String, String> formItems) { this.formItems = formItems; } public enum Method { GET, POST } /** * GET or POST. */ /** @deprecated ignored, always POST*/ protected Method httpMethod = Method.POST; /** @deprecated ignored, always POST*/ public Method getHttpMethod() { return this.httpMethod; } /** @deprecated ignored, always POST*/ public void setHttpMethod(Method method) { this.httpMethod = method; } /** * Constructor. */ public HtmlFormCredential() { } public boolean isPrerequisite(final CrawlURI curi) {<FILL_FUNCTION_BODY>} public boolean hasPrerequisite(CrawlURI curi) { return getPrerequisite(curi) != null; } public String getPrerequisite(CrawlURI curi) { return getLoginUri(); } public String getKey() { return getLoginUri(); } public boolean isEveryTime() { // This authentication is one time only. return false; } public boolean isPost() { return Method.POST.equals(getHttpMethod()); } }
boolean result = false; String curiStr = curi.getUURI().toString(); String loginUri = getPrerequisite(curi); if (loginUri != null) { try { UURI uuri = UURIFactory.getInstance(curi.getUURI(), loginUri); if (uuri != null && curiStr != null && uuri.toString().equals(curiStr)) { result = true; if (!curi.isPrerequisite()) { curi.setPrerequisite(true); logger.fine(curi + " is prereq."); } } } catch (URIException e) { logger.severe("Failed to uuri: " + curi + ", " + e.getMessage()); } } return result;
565
212
777
<methods>public void <init>() ,public void attach(org.archive.modules.CrawlURI) ,public boolean detach(org.archive.modules.CrawlURI) ,public boolean detachAll(org.archive.modules.CrawlURI) ,public java.lang.String getDomain() ,public abstract java.lang.String getKey() ,public abstract java.lang.String getPrerequisite(org.archive.modules.CrawlURI) ,public abstract boolean hasPrerequisite(org.archive.modules.CrawlURI) ,public abstract boolean isEveryTime() ,public abstract boolean isPost() ,public abstract boolean isPrerequisite(org.archive.modules.CrawlURI) ,public boolean rootUriMatch(org.archive.modules.net.ServerCache, org.archive.modules.CrawlURI) ,public void setDomain(java.lang.String) <variables>protected java.lang.String domain,private static final java.util.logging.Logger logger,private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/credential/HttpAuthenticationCredential.java
HttpAuthenticationCredential
getByRealm
class HttpAuthenticationCredential extends Credential { private static final long serialVersionUID = 4L; private static Logger logger = Logger.getLogger(HttpAuthenticationCredential.class.getName()); /** Basic/Digest Auth realm. */ protected String realm = "Realm"; public String getRealm() { return this.realm; } public void setRealm(String realm) { this.realm = realm; } /** Login. */ protected String login = "login"; public String getLogin() { return this.login; } public void setLogin(String login) { this.login = login; } /** Password. */ protected String password = "password"; public String getPassword() { return this.password; } public void setPassword(String password) { this.password = password; } /** * Constructor. */ public HttpAuthenticationCredential() { } public boolean isPrerequisite(CrawlURI curi) { // Return false. Later when we implement preemptive // rfc2617, this will change. return false; } public boolean hasPrerequisite(CrawlURI curi) { // Return false. Later when we implement preemptive // rfc2617, this will change. return false; } public String getPrerequisite(CrawlURI curi) { // Return null. Later when we implement preemptive // rfc2617, this will change. return null; } public String getKey() { return getRealm(); } public boolean isEveryTime() { return true; } public boolean isPost() { // Return false. This credential type doesn't care whether posted or // get'd. return false; } /** * Convenience method that does look up on passed set using realm for key. * * @param rfc2617Credentials Set of Rfc2617 credentials. If passed set is * not pure Rfc2617Credentials then will be ClassCastExceptions. * @param realm Realm to find in passed set. * @param context Context to use when searching the realm. * @return Credential of passed realm name else null. If more than one * credential w/ passed realm name, and there shouldn't be, we return first * found. */ public static HttpAuthenticationCredential getByRealm(Set<Credential> rfc2617Credentials, String realm, CrawlURI context) {<FILL_FUNCTION_BODY>} }
HttpAuthenticationCredential result = null; if (rfc2617Credentials == null || rfc2617Credentials.size() <= 0) { return result; } if (rfc2617Credentials != null && rfc2617Credentials.size() > 0) { for (Iterator<Credential> i = rfc2617Credentials.iterator(); i.hasNext();) { HttpAuthenticationCredential c = (HttpAuthenticationCredential)i.next(); // empty realm field means the credential can be used for any realm specified by server if (c.getRealm() == null || c.getRealm().isEmpty()) { result = c; break; } if (c.getRealm().equals(realm)) { result = c; break; } } } return result;
704
227
931
<methods>public void <init>() ,public void attach(org.archive.modules.CrawlURI) ,public boolean detach(org.archive.modules.CrawlURI) ,public boolean detachAll(org.archive.modules.CrawlURI) ,public java.lang.String getDomain() ,public abstract java.lang.String getKey() ,public abstract java.lang.String getPrerequisite(org.archive.modules.CrawlURI) ,public abstract boolean hasPrerequisite(org.archive.modules.CrawlURI) ,public abstract boolean isEveryTime() ,public abstract boolean isPost() ,public abstract boolean isPrerequisite(org.archive.modules.CrawlURI) ,public boolean rootUriMatch(org.archive.modules.net.ServerCache, org.archive.modules.CrawlURI) ,public void setDomain(java.lang.String) <variables>protected java.lang.String domain,private static final java.util.logging.Logger logger,private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/AddRedirectFromRootServerToScope.java
AddRedirectFromRootServerToScope
evaluate
class AddRedirectFromRootServerToScope extends PredicatedDecideRule { private static final long serialVersionUID = 3L; private static final Logger LOGGER = Logger.getLogger(AddRedirectFromRootServerToScope.class.getName()); private static final String SLASH = "/"; public AddRedirectFromRootServerToScope() { } @Override protected boolean evaluate(CrawlURI uri) {<FILL_FUNCTION_BODY>} }
UURI via = uri.getVia(); if (via == null) { return false; } try { String chost = uri.getUURI().getHostBasename(); if (chost == null) { return false; } String viaHost = via.getHostBasename(); if (viaHost == null) { return false; } if (chost.equals(viaHost) && uri.isLocation() && via.getPath().equals(SLASH)) { uri.setSeed(true); LOGGER.info("Adding " + uri + " to seeds via " + via); return true; } } catch (URIException e) { e.printStackTrace(); } return false;
129
204
333
<methods>public void <init>() ,public org.archive.modules.deciderules.DecideResult getDecision() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setDecision(org.archive.modules.deciderules.DecideResult) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/ContentLengthDecideRule.java
ContentLengthDecideRule
innerDecide
class ContentLengthDecideRule extends DecideRule { private static final long serialVersionUID = 3L; { setContentLengthThreshold(Long.MAX_VALUE); } public long getContentLengthThreshold() { return (Long) kp.get("contentLengthThreshold"); } /** * Content-length threshold. The rule returns ACCEPT if the content-length * is less than this threshold, or REJECT otherwise. The default is * 2^63, meaning any document will be accepted. */ public void setContentLengthThreshold(long threshold) { kp.put("contentLengthThreshold",threshold); } /** * Usual constructor. */ public ContentLengthDecideRule() { } protected DecideResult innerDecide(CrawlURI uri) {<FILL_FUNCTION_BODY>} }
if (uri.getContentLength() < getContentLengthThreshold()) { return DecideResult.ACCEPT; } return DecideResult.REJECT;
233
44
277
<methods>public void <init>() ,public boolean accepts(org.archive.modules.CrawlURI) ,public org.archive.modules.deciderules.DecideResult decisionFor(org.archive.modules.CrawlURI) ,public java.lang.String getComment() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setComment(java.lang.String) ,public void setEnabled(boolean) <variables>protected java.lang.String comment,protected org.archive.spring.KeyedProperties kp
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/DecideRule.java
DecideRule
decisionFor
class DecideRule implements Serializable, HasKeyedProperties { protected KeyedProperties kp = new KeyedProperties(); public KeyedProperties getKeyedProperties() { return kp; } { setEnabled(true); } public boolean getEnabled() { return (Boolean) kp.get("enabled"); } public void setEnabled(boolean enabled) { kp.put("enabled",enabled); } protected String comment = ""; public String getComment() { return comment; } public void setComment(String comment) { this.comment = comment; } public DecideRule() { } public DecideResult decisionFor(CrawlURI uri) {<FILL_FUNCTION_BODY>} protected abstract DecideResult innerDecide(CrawlURI uri); public DecideResult onlyDecision(CrawlURI uri) { return null; } public boolean accepts(CrawlURI uri) { return DecideResult.ACCEPT == decisionFor(uri); } }
if (!getEnabled()) { return DecideResult.NONE; } DecideResult result = innerDecide(uri); if (result == DecideResult.NONE) { return result; } return result;
288
65
353
<no_super_class>
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/DecideRuleSequence.java
DecideRuleSequence
innerDecide
class DecideRuleSequence extends DecideRule implements BeanNameAware, Lifecycle { final private static Logger LOGGER = Logger.getLogger(DecideRuleSequence.class.getName()); private static final long serialVersionUID = 3L; protected transient Logger fileLogger = null; { setLogToFile(false); } public boolean getLogToFile() { return (Boolean) kp.get("logToFile"); } /** * If enabled, log decisions to file named logs/{spring-bean-id}.log. Format * is: [timestamp] [decisive-rule-num] [decisive-rule-class] [decision] * [uri] [extraInfo] * * Relies on Spring Lifecycle to initialize the log. Only top-level * beans get the Lifecycle treatment from Spring, so bean must be top-level * for logToFile to work. (This is true of other modules that support * logToFile, and anything else that uses Lifecycle, as well.) */ public void setLogToFile(boolean enabled) { kp.put("logToFile",enabled); } /** * Whether to include the "extra info" field for each entry in crawl.log. * "Extra info" is a json object with entries "host", "via", "source" and * "hopPath". */ protected boolean logExtraInfo = false; public boolean getLogExtraInfo() { return logExtraInfo; } public void setLogExtraInfo(boolean logExtraInfo) { this.logExtraInfo = logExtraInfo; } // provided by CrawlerLoggerModule which is in heritrix-engine, inaccessible // from here, thus the need for the SimpleFileLoggerProvider interface protected SimpleFileLoggerProvider loggerModule; public SimpleFileLoggerProvider getLoggerModule() { return this.loggerModule; } @Autowired public void setLoggerModule(SimpleFileLoggerProvider loggerModule) { this.loggerModule = loggerModule; } @SuppressWarnings("unchecked") public List<DecideRule> getRules() { return (List<DecideRule>) kp.get("rules"); } public void setRules(List<DecideRule> rules) { kp.put("rules", rules); } protected ServerCache serverCache; public ServerCache getServerCache() { return this.serverCache; } @Autowired public void setServerCache(ServerCache serverCache) { this.serverCache = serverCache; } public DecideResult innerDecide(CrawlURI uri) {<FILL_FUNCTION_BODY>} protected void decisionMade(CrawlURI uri, DecideRule decisiveRule, int decisiveRuleNumber, DecideResult result) { if (fileLogger != null) { JSONObject extraInfo = null; if (logExtraInfo) { CrawlHost crawlHost = getServerCache().getHostFor(uri.getUURI()); String host = "-"; if (crawlHost != null) { host = crawlHost.fixUpName(); } extraInfo = new JSONObject(); extraInfo.put("hopPath", uri.getPathFromSeed()); extraInfo.put("via", uri.getVia()); extraInfo.put("seed", uri.getSourceTag()); extraInfo.put("host", host); } fileLogger.info(decisiveRuleNumber + " " + decisiveRule.getClass().getSimpleName() + " " + result + " " + uri + (extraInfo != null ? " " + extraInfo : "")); } } protected String beanName; public String getBeanName() { return this.beanName; } @Override public void setBeanName(String name) { this.beanName = name; } protected boolean isRunning = false; @Override public boolean isRunning() { return isRunning; } @Override public void start() { if (getLogToFile() && fileLogger == null) { // loggerModule.start() creates the log directory, and evidently // it's possible for this module to start before loggerModule, // so we need to run this here to prevent an exception loggerModule.start(); fileLogger = loggerModule.setupSimpleLog(getBeanName()); } isRunning = true; } @Override public void stop() { isRunning = false; } }
DecideRule decisiveRule = null; int decisiveRuleNumber = -1; DecideResult result = DecideResult.NONE; List<DecideRule> rules = getRules(); int max = rules.size(); for (int i = 0; i < max; i++) { DecideRule rule = rules.get(i); if (rule.onlyDecision(uri) != result) { DecideResult r = rule.decisionFor(uri); if (LOGGER.isLoggable(Level.FINEST)) { LOGGER.finest("DecideRule #" + i + " " + rule.getClass().getName() + " returned " + r + " for url: " + uri); } if (r != DecideResult.NONE) { result = r; decisiveRule = rule; decisiveRuleNumber = i; } } } decisionMade(uri, decisiveRule, decisiveRuleNumber, result); return result;
1,180
263
1,443
<methods>public void <init>() ,public boolean accepts(org.archive.modules.CrawlURI) ,public org.archive.modules.deciderules.DecideResult decisionFor(org.archive.modules.CrawlURI) ,public java.lang.String getComment() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setComment(java.lang.String) ,public void setEnabled(boolean) <variables>protected java.lang.String comment,protected org.archive.spring.KeyedProperties kp
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/ExternalGeoLocationDecideRule.java
ExternalGeoLocationDecideRule
evaluate
class ExternalGeoLocationDecideRule extends PredicatedDecideRule { private static final long serialVersionUID = 3L; private static final Logger LOGGER = Logger.getLogger(ExternalGeoLocationDecideRule.class.getName()); protected ExternalGeoLookupInterface lookup = null; public ExternalGeoLookupInterface getLookup() { return this.lookup; } public void setLookup(ExternalGeoLookupInterface lookup) { this.lookup = lookup; } /** * Country code name. */ protected List<String> countryCodes = new ArrayList<String>(); public List<String> getCountryCodes() { return this.countryCodes; } public void setCountryCodes(List<String> codes) { this.countryCodes = codes; } protected ServerCache serverCache; public ServerCache getServerCache() { return this.serverCache; } @Autowired public void setServerCache(ServerCache serverCache) { this.serverCache = serverCache; } public ExternalGeoLocationDecideRule() { } @Override protected boolean evaluate(CrawlURI uri) {<FILL_FUNCTION_BODY>} }
ExternalGeoLookupInterface impl = getLookup(); if (impl == null) { return false; } CrawlHost crawlHost = null; String host; InetAddress address; try { host = uri.getUURI().getHost(); crawlHost = serverCache.getHostFor(host); if (crawlHost.getCountryCode() != null) { return countryCodes.contains(crawlHost.getCountryCode()); } address = crawlHost.getIP(); if (address == null) { // TODO: handle transient lookup failures better address = Address.getByName(host); } crawlHost.setCountryCode((String) impl.lookup(address)); if (countryCodes.contains(crawlHost.getCountryCode())) { LOGGER.fine("Country Code Lookup: " + " " + host + crawlHost.getCountryCode()); return true; } } catch (UnknownHostException e) { LOGGER.log(Level.FINE, "Failed dns lookup " + uri, e); if (crawlHost != null) { crawlHost.setCountryCode("--"); } } catch (URIException e) { LOGGER.log(Level.FINE, "Failed to parse hostname " + uri, e); } return false;
338
358
696
<methods>public void <init>() ,public org.archive.modules.deciderules.DecideResult getDecision() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setDecision(org.archive.modules.deciderules.DecideResult) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/HopCrossesAssignmentLevelDomainDecideRule.java
HopCrossesAssignmentLevelDomainDecideRule
evaluate
class HopCrossesAssignmentLevelDomainDecideRule extends PredicatedDecideRule { private static final long serialVersionUID = 1L; private static final Logger LOGGER = Logger .getLogger(HopCrossesAssignmentLevelDomainDecideRule.class.getName()); public HopCrossesAssignmentLevelDomainDecideRule() { } protected boolean evaluate(CrawlURI uri) {<FILL_FUNCTION_BODY>} private String getAssignmentLevelSurt(UURI uuri){ String surt = uuri.getSurtForm().replaceFirst(".*://\\((.*?)\\).*", "$1"); return PublicSuffixes.reduceSurtToAssignmentLevel(surt); } }
UURI via = uri.getVia(); if (via == null) { return false; } try { // determine if this hop crosses assignment-level-domain borders String ald = getAssignmentLevelSurt(uri.getUURI()); String viaAld = getAssignmentLevelSurt(via); if (ald != null && !ald.equals(viaAld)) { if(LOGGER.isLoggable(Level.FINE)) { LOGGER.fine("rule matched for \"" + ald+"\" vs. \""+viaAld+"\""); } return true; } } catch (Exception e) { LOGGER.log(Level.WARNING,"uri="+uri+" via="+via, e); // Return false since we could not get hostname or something else // went wrong } return false;
207
249
456
<methods>public void <init>() ,public org.archive.modules.deciderules.DecideResult getDecision() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setDecision(org.archive.modules.deciderules.DecideResult) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/IpAddressSetDecideRule.java
IpAddressSetDecideRule
getHostAddress
class IpAddressSetDecideRule extends PredicatedDecideRule { private static final Logger logger = Logger.getLogger(IpAddressSetDecideRule.class.getName()); private static final long serialVersionUID = -3670434739183271441L; private Set<String> ipAddresses; /** * @return the addresses being matched */ public Set<String> getIpAddresses() { return Collections.unmodifiableSet(ipAddresses); } /** * @param ipAddresses the addresses to match */ public void setIpAddresses(Set<String> ipAddresses) { this.ipAddresses = ipAddresses; } @Override protected boolean evaluate(CrawlURI curi) { String hostAddress = getHostAddress(curi); return hostAddress != null && ipAddresses.contains(hostAddress.intern()); } transient protected ServerCache serverCache; public ServerCache getServerCache() { return this.serverCache; } @Autowired public void setServerCache(ServerCache serverCache) { this.serverCache = serverCache; } /** * from WriterPoolProcessor * * @param curi CrawlURI * @return String of IP address or null if unable to determine IP address */ protected String getHostAddress(CrawlURI curi) {<FILL_FUNCTION_BODY>} }
// if possible use the exact IP the fetcher stashed in curi if (curi.getServerIP() != null) { return curi.getServerIP(); } // otherwise, consult the cache String addr = null; try { CrawlHost crlh = getServerCache().getHostFor(curi.getUURI()); if (crlh == null) { return null; } InetAddress inetadd = crlh.getIP(); if (inetadd == null) { return null; } addr = inetadd.getHostAddress(); } catch (Exception e) { // Log error and continue (return null) logger.log(Level.WARNING, "Error looking up IP for URI "+curi.getURI(), e); } return addr;
390
215
605
<methods>public void <init>() ,public org.archive.modules.deciderules.DecideResult getDecision() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setDecision(org.archive.modules.deciderules.DecideResult) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/MatchesFilePatternDecideRule.java
MatchesFilePatternDecideRule
getRegex
class MatchesFilePatternDecideRule extends MatchesRegexDecideRule { public static enum Preset { ALL(".*(?i)(\\.(bmp|gif|jpe?g|png|svg|tiff?|aac|aiff?|m3u|m4a|midi?" + "|mp2|mp3|mp4|mpa|ogg|ra|ram|wav|wma|asf|asx|avi|flv|mov|mp4" + "|mpeg|mpg|qt|ram|rm|smil|wmv|doc|pdf|ppt|swf))$"), IMAGES(".*(?i)(\\.(bmp|gif|jpe?g|png|svg|tiff?))$"), AUDIO(".*(?i)(\\.(aac|aiff?|m3u|m4a|midi?|mp2|mp3|mp4|mpa|ogg|ra|ram|wav|wma))$"), VIDEO(".*(?i)(\\.(asf|asx|avi|flv|mov|mp4|mpeg|mpg|qt|ram|rm|smil|wmv))$"), MISC(".*(?i)(\\.(doc|pdf|ppt|swf))$"), CUSTOM(null); final private Pattern pattern; Preset(String regex) { if (regex == null) { pattern = null; } else { pattern = Pattern.compile(regex); } } public Pattern getPattern() { return pattern; } } private static final long serialVersionUID = 3L; { setUsePreset(Preset.ALL); } public Preset getUsePreset() { return (Preset) kp.get("usePreset"); } public void setUsePreset(Preset preset) { kp.put("usePreset",preset); } /** * Usual constructor. */ public MatchesFilePatternDecideRule() { } /** * Use a preset if configured to do so. * @return regex to use. */ @Override public Pattern getRegex() {<FILL_FUNCTION_BODY>} }
Preset preset = getUsePreset(); if (preset == Preset.CUSTOM) { return super.getRegex(); } return preset.getPattern();
602
51
653
<methods>public void <init>() ,public java.util.regex.Pattern getRegex() ,public void setRegex(java.util.regex.Pattern) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/MatchesListRegexDecideRule.java
MatchesListRegexDecideRule
evaluate
class MatchesListRegexDecideRule extends PredicatedDecideRule { private static final long serialVersionUID = 3L; private static final Logger logger = Logger.getLogger(MatchesListRegexDecideRule.class.getName()); { setTimeoutPerRegexSeconds(0L); } public long getTimeoutPerRegexSeconds() { return (Long) kp.get("timeout");} /** * The timeout for regular expression matching, in seconds. If set to 0 or negative then no timeout is specified and * there is no upper limit to how long the matching may take. See the corresponding test class MatchesListRegexDecideRuleTest * for a pathological example. */ public void setTimeoutPerRegexSeconds(long timeoutPerRegexSeconds) { kp.put("timeout", timeoutPerRegexSeconds);} { setRegexList(new ArrayList<Pattern>()); } @SuppressWarnings("unchecked") public List<Pattern> getRegexList() { return (List<Pattern>) kp.get("regexList"); } /** * The list of regular expressions to evalute against the URI. */ public void setRegexList(List<Pattern> patterns) { kp.put("regexList", patterns); } { setListLogicalOr(true); } public boolean getListLogicalOr() { return (Boolean) kp.get("listLogicalOr"); } /** * True if the list of regular expression should be considered as logically * AND when matching. False if the list of regular expressions should be * considered as logically OR when matching. */ public void setListLogicalOr(boolean listLogicalOr) { kp.put("listLogicalOr",listLogicalOr); } /** * Usual constructor. */ public MatchesListRegexDecideRule() { } /** * Evaluate whether given object's string version * matches configured regexes */ @Override protected boolean evaluate(CrawlURI uri) {<FILL_FUNCTION_BODY>} }
List<Pattern> regexes = getRegexList(); if(regexes.size()==0){ return false; } String str = uri.toString(); boolean listLogicOR = getListLogicalOr(); for (Pattern p: regexes) { boolean matches = false; if (getTimeoutPerRegexSeconds() <= 0) { matches = p.matcher(str).matches(); } else { InterruptibleCharSequence interruptible = new InterruptibleCharSequence(str); FutureTask<Boolean> matchesFuture = new FutureTask<>(() -> p.matcher(interruptible).matches()); ForkJoinPool.commonPool().submit(matchesFuture); try { matches = matchesFuture.get(getTimeoutPerRegexSeconds(), TimeUnit.SECONDS); } catch (TimeoutException e) { matchesFuture.cancel(true); logger.warning("Timed out after " + getTimeoutPerRegexSeconds() + " seconds waiting for '" + p + "' to match."); } catch (InterruptedException e) { matchesFuture.cancel(true); logger.warning("InterruptedException while waiting for '" + p + "' to match."); } catch (ExecutionException e) { matchesFuture.cancel(true); logger.warning("ExecutionException while waiting for '" + p + "' to match: " + e.getMessage()); } } if (logger.isLoggable(Level.FINER)) { logger.finer("Tested '" + str + "' match with regex '" + p.pattern() + " and result was " + matches); } if(matches){ if(listLogicOR){ // OR based and we just got a match, done! logger.fine("Matched: " + str); return true; } } else { if(listLogicOR == false){ // AND based and we just found a non-match, done! return false; } } } if (listLogicOR) { return false; } else { return true; }
555
533
1,088
<methods>public void <init>() ,public org.archive.modules.deciderules.DecideResult getDecision() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setDecision(org.archive.modules.deciderules.DecideResult) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/MatchesStatusCodeDecideRule.java
MatchesStatusCodeDecideRule
getLowerBound
class MatchesStatusCodeDecideRule extends PredicatedDecideRule { /** Default lower bound */ public final static Integer DEFAULT_LOWER_BOUND = new Integer(0); /** Default upper bound */ public final static Integer DEFAULT_UPPER_BOUND = new Integer(600); /** * Creates a new MatchStatusCodeDecideRule instance. Note that * this will return a rule that will return "true" for all valid * status codes (and some invalid ones, too). */ public MatchesStatusCodeDecideRule() { // set our default bounds kp.put("lowerBound", DEFAULT_LOWER_BOUND); kp.put("upperBound", DEFAULT_UPPER_BOUND); } /** * Sets the lower bound on the range of acceptable status codes. * * @param statusCode Status code */ public void setLowerBound(Integer statusCode) { kp.put("lowerBound", statusCode); } /** * Returns the lower bound on the range of acceptable status codes. * * @return Integer Status code */ public Integer getLowerBound() {<FILL_FUNCTION_BODY>} /** * Sets the upper bound on the range of acceptable status codes. * * @param statusCode Status code */ public void setUpperBound(Integer statusCode) { kp.put("upperBound", statusCode); } /** * Returns the upper bound on the range of acceptable status codes. * * @return Integer Status code */ public Integer getUpperBound() { Object value = kp.get("upperBound"); if(value != null) { return((Integer) value); } return(null); } /** * Returns "true" if the provided CrawlURI has a fetch status that falls * within this instance's specified range. * * @param uri * The URI to be evaluated * @return true If the CrawlURI has a fetch status code within the specified * range. */ @Override protected boolean evaluate(CrawlURI uri) { // by default, we'll return false boolean value = false; int statusCode = uri.getFetchStatus(); if (statusCode >= getLowerBound().intValue() && statusCode <= getUpperBound().intValue()) { value = true; } return (value); } }
Object value = kp.get("lowerBound"); if(value != null) { return((Integer) value); } return(null);
644
47
691
<methods>public void <init>() ,public org.archive.modules.deciderules.DecideResult getDecision() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setDecision(org.archive.modules.deciderules.DecideResult) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/NotMatchesStatusCodeDecideRule.java
NotMatchesStatusCodeDecideRule
evaluate
class NotMatchesStatusCodeDecideRule extends MatchesStatusCodeDecideRule { /** * Sets the upper bound on the range of acceptable status codes. */ public void setUpperBound(Integer statusCode) { kp.put("upperBound", statusCode); } /** * Returns the upper bound on the range of acceptable status codes. * * @return Integer Status code */ public Integer getUpperBound() { Object value = kp.get("upperBound"); if(value != null) { return((Integer) value); } return(null); } /** * Returns "true" if the provided CrawlURI has a fetch status that does not * fall within this instance's specified range. * * @return true If the CrawlURI has a fetch status outside the specified * range */ @Override protected boolean evaluate(CrawlURI uri) {<FILL_FUNCTION_BODY>} }
// by default, we'll return false boolean value = false; int statusCode = uri.getFetchStatus(); if (statusCode <= getLowerBound().intValue() || statusCode >= getUpperBound().intValue()) { value = true; } return (value);
261
83
344
<methods>public void <init>() ,public java.lang.Integer getLowerBound() ,public java.lang.Integer getUpperBound() ,public void setLowerBound(java.lang.Integer) ,public void setUpperBound(java.lang.Integer) <variables>public static final java.lang.Integer DEFAULT_LOWER_BOUND,public static final java.lang.Integer DEFAULT_UPPER_BOUND
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/PathologicalPathDecideRule.java
PathologicalPathDecideRule
innerDecide
class PathologicalPathDecideRule extends DecideRule { private static final long serialVersionUID = 3L; { setMaxRepetitions(2); } public int getMaxRepetitions() { return (Integer) kp.get("maxRepetitions"); } /** * Number of times the pattern should be allowed to occur. This rule returns * its decision (usually REJECT) if a path-segment is repeated more than * number of times. */ public void setMaxRepetitions(int maxRepetitions) { kp.put("maxRepetitions", maxRepetitions); } /** Constructs a new PathologicalPathFilter. */ public PathologicalPathDecideRule() { } @Override protected DecideResult innerDecide(CrawlURI uri) {<FILL_FUNCTION_BODY>} protected String constructRegex(int rep) { return (rep == 0) ? null : ".*?/(.*?/)\\1{" + rep + ",}.*"; } }
int maxRep = getMaxRepetitions(); // Pattern p = getPattern(maxRep); Matcher m = TextUtils.getMatcher(constructRegex(maxRep), uri.getUURI().toString()); try { if (m.matches()) { return DecideResult.REJECT; } else { return DecideResult.NONE; } } finally { TextUtils.recycleMatcher(m); }
273
118
391
<methods>public void <init>() ,public boolean accepts(org.archive.modules.CrawlURI) ,public org.archive.modules.deciderules.DecideResult decisionFor(org.archive.modules.CrawlURI) ,public java.lang.String getComment() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setComment(java.lang.String) ,public void setEnabled(boolean) <variables>protected java.lang.String comment,protected org.archive.spring.KeyedProperties kp
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/PrerequisiteAcceptDecideRule.java
PrerequisiteAcceptDecideRule
innerDecide
class PrerequisiteAcceptDecideRule extends DecideRule { private static final long serialVersionUID = 3L; public PrerequisiteAcceptDecideRule() { } public DecideResult innerDecide(CrawlURI uri) {<FILL_FUNCTION_BODY>} }
String hopsPath = uri.getPathFromSeed(); if (hopsPath != null && hopsPath.length() > 0 && hopsPath.charAt(hopsPath.length()-1) == Hop.PREREQ.getHopChar()) { return DecideResult.ACCEPT; } return DecideResult.NONE;
81
90
171
<methods>public void <init>() ,public boolean accepts(org.archive.modules.CrawlURI) ,public org.archive.modules.deciderules.DecideResult decisionFor(org.archive.modules.CrawlURI) ,public java.lang.String getComment() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setComment(java.lang.String) ,public void setEnabled(boolean) <variables>protected java.lang.String comment,protected org.archive.spring.KeyedProperties kp
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/ResourceNoLongerThanDecideRule.java
ResourceNoLongerThanDecideRule
evaluate
class ResourceNoLongerThanDecideRule extends PredicatedDecideRule { private static final long serialVersionUID = -8774160016195991876L; private static final Logger logger = Logger. getLogger(ResourceNoLongerThanDecideRule.class.getName()); { setUseHeaderLength(true); } public boolean getUseHeaderLength() { return (Boolean) kp.get("useHeaderLength"); } /** * Shall this rule be used as a midfetch rule? If true, this rule will * determine content length based on HTTP header information, otherwise * the size of the already downloaded content will be used. */ public void setUseHeaderLength(boolean useHeaderLength) { kp.put("useHeaderLength",useHeaderLength); } { setContentLengthThreshold(-1L); } public long getContentLengthThreshold() { return (Long) kp.get("contentLengthThreshold"); } /** * Max content-length this filter will allow to pass through. If -1, * then no limit. */ public void setContentLengthThreshold(long threshold) { kp.put("contentLengthThreshold",threshold); } // Header predictor state constants public static final int HEADER_PREDICTS_MISSING = -1; public ResourceNoLongerThanDecideRule() { } protected boolean evaluate(CrawlURI curi) {<FILL_FUNCTION_BODY>} protected boolean test(int contentlength) { return contentlength < getContentLengthThreshold(); } }
int contentlength = HEADER_PREDICTS_MISSING; // filter used as midfetch filter if (getUseHeaderLength()) { // get content-length String newContentlength = null; if (curi.getHttpResponseHeader("content-length") != null) { newContentlength = curi.getHttpResponseHeader("content-length"); } if (newContentlength != null && newContentlength.length() > 0) { try { contentlength = Integer.parseInt(newContentlength); } catch (NumberFormatException nfe) { // Ignore. } } // If no document length was reported or format was wrong, // let pass if (contentlength == HEADER_PREDICTS_MISSING) { return false; } } else { contentlength = (int) curi.getContentSize(); } return test(contentlength);
441
247
688
<methods>public void <init>() ,public org.archive.modules.deciderules.DecideResult getDecision() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setDecision(org.archive.modules.deciderules.DecideResult) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/ResponseContentLengthDecideRule.java
ResponseContentLengthDecideRule
evaluate
class ResponseContentLengthDecideRule extends PredicatedDecideRule { private static final long serialVersionUID = 1L; { setLowerBound(0l); } public long getLowerBound() { return (Long) kp.get("lowerBound"); } /** * The rule will apply if the url has been fetched and content body length * is greater than or equal to this number of bytes. Default is 0, meaning * everything will match. */ public void setLowerBound(long size) { kp.put("lowerBound", size); } { setUpperBound(Long.MAX_VALUE); } public long getUpperBound() { return (Long) kp.get("upperBound"); } /** * The rule will apply if the url has been fetched and content body length * is less than or equal to this number of bytes. Default is * {@code Long.MAX_VALUE}, meaning everything will match. */ public void setUpperBound(long bound) { kp.put("upperBound", bound); } @Override protected boolean evaluate(CrawlURI uri) {<FILL_FUNCTION_BODY>} }
// only process if curi contains evidence of fetch attempt return uri.containsDataKey(A_FETCH_BEGAN_TIME) && uri.getRecorder() != null && uri.getRecorder().getResponseContentLength() >= getLowerBound() && uri.getRecorder().getResponseContentLength() <= getUpperBound();
316
87
403
<methods>public void <init>() ,public org.archive.modules.deciderules.DecideResult getDecision() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setDecision(org.archive.modules.deciderules.DecideResult) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/ScriptedDecideRule.java
ScriptedDecideRule
getEngine
class ScriptedDecideRule extends DecideRule implements ApplicationContextAware, InitializingBean { private static final long serialVersionUID = 3L; private static final Logger logger = Logger.getLogger(ScriptedDecideRule.class.getName()); /** engine name; default "beanshell" */ protected String engineName = "beanshell"; public String getEngineName() { return this.engineName; } public void setEngineName(String name) { this.engineName = name; } protected ReadSource scriptSource = null; public ReadSource getScriptSource() { return scriptSource; } @Required public void setScriptSource(ReadSource scriptSource) { this.scriptSource = scriptSource; } /** * Whether each ToeThread should get its own independent script * engine, or they should share synchronized access to one * engine. Default is true, meaning each thread gets its own * isolated engine. */ protected boolean isolateThreads = true; public boolean getIsolateThreads() { return isolateThreads; } public void setIsolateThreads(boolean isolateThreads) { this.isolateThreads = isolateThreads; } protected ApplicationContext appCtx; public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.appCtx = applicationContext; } transient protected ThreadLocal<ScriptEngine> threadEngine = new ThreadLocal<ScriptEngine>(); transient protected ScriptEngine sharedEngine; public ScriptedDecideRule() { } public void afterPropertiesSet() throws Exception { // fail at build-time if script engine not available if(null == new ScriptEngineManager().getEngineByName(engineName)) { throw new BeanInitializationException("named ScriptEngine not available"); } } @Override public DecideResult innerDecide(CrawlURI uri) { // depending on previous configuration, engine may // be local to this thread or shared ScriptEngine engine = getEngine(); synchronized(engine) { // synchronization is harmless for local thread engine, // necessary for shared engine try { engine.put("object",uri); engine.put("appCtx", appCtx); return (DecideResult)engine.eval("decisionFor(object)"); } catch (ScriptException e) { logger.log(Level.WARNING,e.getMessage(),e); return DecideResult.NONE; } finally { engine.put("object", null); engine.put("appCtx", null); } } } /** * Get the proper ScriptEngine instance -- either shared or local * to this thread. * @return ScriptEngine to use */ protected ScriptEngine getEngine() {<FILL_FUNCTION_BODY>} /** * Create a new ScriptEngine instance, preloaded with any supplied * source file and the variables 'self' (this ScriptedDecideRule) * and 'context' (the ApplicationContext). * * @return the new Interpreter instance */ protected ScriptEngine newEngine() { ScriptEngine interpreter = new ScriptEngineManager().getEngineByName(engineName); interpreter.put("self", this); interpreter.put("context", appCtx); Reader reader = null; try { reader = getScriptSource().obtainReader(); interpreter.eval(reader); } catch (ScriptException e) { logger.log(Level.SEVERE,"script problem",e); } finally { IOUtils.closeQuietly(reader); } return interpreter; } }
if (getIsolateThreads()) { ScriptEngine engine = threadEngine.get(); if (engine == null) { engine = newEngine(); threadEngine.set(engine); } return engine; } else { // sharing the engine synchronized (this) { if (sharedEngine == null) { sharedEngine = newEngine(); } } return sharedEngine; }
963
110
1,073
<methods>public void <init>() ,public boolean accepts(org.archive.modules.CrawlURI) ,public org.archive.modules.deciderules.DecideResult decisionFor(org.archive.modules.CrawlURI) ,public java.lang.String getComment() ,public boolean getEnabled() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setComment(java.lang.String) ,public void setEnabled(boolean) <variables>protected java.lang.String comment,protected org.archive.spring.KeyedProperties kp
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/TooManyPathSegmentsDecideRule.java
TooManyPathSegmentsDecideRule
evaluate
class TooManyPathSegmentsDecideRule extends PredicatedDecideRule { private static final long serialVersionUID = 3L; @SuppressWarnings("unused") private static final Logger logger = Logger.getLogger(TooManyPathSegmentsDecideRule.class.getName()); /* default for this class is to REJECT */ { setDecision(DecideResult.REJECT); } { setMaxPathDepth(20); } public int getMaxPathDepth() { return (Integer) kp.get("maxPathDepth"); } /** * Number of path segments beyond which this rule will reject URIs. */ public void setMaxPathDepth(int maxPathDepth) { kp.put("maxPathDepth", maxPathDepth); } /** * Usual constructor. */ public TooManyPathSegmentsDecideRule() { } /** * Evaluate whether given object is over the threshold number of * path-segments. * * @param curi * @return true if the path-segments is exceeded */ @Override protected boolean evaluate(CrawlURI curi) {<FILL_FUNCTION_BODY>} }
String uriPath = curi.getUURI().getEscapedPath(); if (uriPath == null) { // no path means no segments return false; } int count = 0; int threshold = getMaxPathDepth(); for (int i = 0; i < uriPath.length(); i++) { if (uriPath.charAt(i) == '/') { count++; } if (count > threshold) { return true; } } return false;
327
133
460
<methods>public void <init>() ,public org.archive.modules.deciderules.DecideResult getDecision() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setDecision(org.archive.modules.deciderules.DecideResult) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/TransclusionDecideRule.java
TransclusionDecideRule
evaluate
class TransclusionDecideRule extends PredicatedDecideRule { private static final long serialVersionUID = -3975688876990558918L; { setMaxTransHops(2); } public int getMaxTransHops() { return (Integer) kp.get("maxTransHops"); } /** * Maximum number of non-navlink (non-'L') hops to ACCEPT. */ public void setMaxTransHops(int maxTransHops) { kp.put("maxTransHops", maxTransHops); } { setMaxSpeculativeHops(1); } public int getMaxSpeculativeHops() { return (Integer) kp.get("maxSpeculativeHops"); } /** * Maximum number of speculative ('X') hops to ACCEPT. */ public void setMaxSpeculativeHops(int maxSpeculativeHops) { kp.put("maxSpeculativeHops", maxSpeculativeHops); } /** * Usual constructor. */ public TransclusionDecideRule() { } /** * Evaluate whether given object is within the acceptable thresholds of * transitive hops. * * @param curi CrawlURI to make decision on. * @return true if the transitive hops &gt;0 and &lt;= max */ protected boolean evaluate(CrawlURI curi) {<FILL_FUNCTION_BODY>} }
String hopsPath = curi.getPathFromSeed(); if (hopsPath == null || hopsPath.length() == 0) { return false; } int allCount = 0; int nonrefCount = 0; int specCount = 0; for (int i = hopsPath.length() - 1; i >= 0; i--) { char c = hopsPath.charAt(i); if (c == Hop.NAVLINK.getHopChar() || c == Hop.SUBMIT.getHopChar() || c == Hop.MANIFEST.getHopChar()) { // end of hops counted here break; } allCount++; if (c != Hop.REFER.getHopChar()) { nonrefCount++; } if (c == Hop.SPECULATIVE.getHopChar()) { specCount++; } } // transclusion doesn't apply if there isn't at least one non-nav-hop if (allCount <= 0) { return false; } // too many speculative hops disqualify from transclusion if (specCount > getMaxSpeculativeHops()) { return false; } // transclusion applies as long as non-ref hops less than max return nonrefCount <= getMaxTransHops();
409
357
766
<methods>public void <init>() ,public org.archive.modules.deciderules.DecideResult getDecision() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setDecision(org.archive.modules.deciderules.DecideResult) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/ViaSurtPrefixedDecideRule.java
ViaSurtPrefixedDecideRule
evaluate
class ViaSurtPrefixedDecideRule extends PredicatedDecideRule { private static final long serialVersionUID = 1L; protected SurtPrefixSet surtPrefixes = new SurtPrefixSet(); public List<String> getSurtPrefixes() { return new ArrayList<String>(surtPrefixes); } @Required public void setSurtPrefixes(List<String> surtPrefixes) { this.surtPrefixes.clear(); if(surtPrefixes!=null) { for(String surt : surtPrefixes) { this.surtPrefixes.considerAsAddDirective(surt); } } } /** * Evaluate whether given object's surt form * matches one of the supplied surts * * @param uri * @return true if a surt prefix matches */ @Override protected boolean evaluate(CrawlURI uri) {<FILL_FUNCTION_BODY>} }
if (uri.getVia() != null && getSurtPrefixes() !=null){ return surtPrefixes.containsPrefixOf(SurtPrefixSet.getCandidateSurt(uri.getVia())); } else return false;
260
67
327
<methods>public void <init>() ,public org.archive.modules.deciderules.DecideResult getDecision() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setDecision(org.archive.modules.deciderules.DecideResult) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/deciderules/recrawl/IdenticalDigestDecideRule.java
IdenticalDigestDecideRule
hasIdenticalDigest
class IdenticalDigestDecideRule extends PredicatedDecideRule { private static final long serialVersionUID = 4275993790856626949L; /** default for this class is to REJECT */ { setDecision(DecideResult.REJECT); } /** * Usual constructor. */ public IdenticalDigestDecideRule() { } /** * Evaluate whether given CrawlURI's revisit profile has been set to identical digest * * @return true if CrawlURI has been flagged as an identical digest revist */ protected boolean evaluate(CrawlURI curi) { return hasIdenticalDigest(curi); } /** * Utility method for testing if a CrawlURI's revisit profile matches an identical payload digest. * * @param curi CrawlURI to test * @return true if revisit profile is set to identical payload digest, false otherwise */ public static boolean hasIdenticalDigest(CrawlURI curi) {<FILL_FUNCTION_BODY>} }
RevisitProfile revisit = curi.getRevisitProfile(); if (revisit==null) { return false; } return revisit.getProfileName().equals(WARCConstants.PROFILE_REVISIT_IDENTICAL_DIGEST);
296
72
368
<methods>public void <init>() ,public org.archive.modules.deciderules.DecideResult getDecision() ,public org.archive.modules.deciderules.DecideResult onlyDecision(org.archive.modules.CrawlURI) ,public void setDecision(org.archive.modules.deciderules.DecideResult) <variables>private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/extractor/AggressiveExtractorHTML.java
AggressiveExtractorHTML
processScript
class AggressiveExtractorHTML extends ExtractorHTML { @SuppressWarnings("unused") private static final long serialVersionUID = 3L; protected static Logger logger = Logger.getLogger(AggressiveExtractorHTML.class.getName()); public AggressiveExtractorHTML() { } protected void processScript(CrawlURI curi, CharSequence sequence, int endOfOpenTag) {<FILL_FUNCTION_BODY>} }
super.processScript(curi, sequence, endOfOpenTag); // then, proccess entire javascript code as html code // this may cause a lot of false positves processGeneralTag(curi, sequence.subSequence(0,6), sequence.subSequence(endOfOpenTag, sequence.length()));
129
79
208
<methods>public void <init>() ,public void afterPropertiesSet() ,public static java.lang.CharSequence elementContext(java.lang.CharSequence, java.lang.CharSequence) ,public boolean getExtractJavascript() ,public boolean getExtractOnlyFormGets() ,public boolean getExtractValueAttributes() ,public org.archive.modules.extractor.ExtractorJS getExtractorJS() ,public boolean getIgnoreFormActionUrls() ,public boolean getIgnoreUnexpectedHtml() ,public int getMaxAttributeNameLength() ,public int getMaxAttributeValLength() ,public int getMaxElementLength() ,public org.archive.modules.CrawlMetadata getMetadata() ,public boolean getTreatFramesAsEmbedLinks() ,public boolean innerExtract(org.archive.modules.CrawlURI) ,public static void main(java.lang.String[]) throws java.lang.Exception,public void setExtractJavascript(boolean) ,public void setExtractOnlyFormGets(boolean) ,public void setExtractValueAttributes(boolean) ,public void setExtractorJS(org.archive.modules.extractor.ExtractorJS) ,public void setIgnoreFormActionUrls(boolean) ,public void setIgnoreUnexpectedHtml(boolean) ,public void setMaxAttributeNameLength(int) ,public void setMaxAttributeValLength(int) ,public void setMaxElementLength(int) ,public void setMetadata(org.archive.modules.CrawlMetadata) ,public void setTreatFramesAsEmbedLinks(boolean) <variables>static final java.lang.String APPLET,private static final java.util.regex.Pattern ASCII_WHITESPACE,public static final java.lang.String A_FORM_OFFSETS,public static final java.lang.String A_META_ROBOTS,static final java.lang.String BASE,static final java.lang.String CLASSEXT,static final java.lang.String EACH_ATTRIBUTE_EXTRACTOR,static final java.lang.String FRAME,static final java.lang.String IFRAME,static final java.lang.String JAVASCRIPT,static final java.lang.String LINK,private static final java.lang.String MAX_ATTR_NAME_REPLACE,private static final java.lang.String MAX_ATTR_VAL_REPLACE,private static final java.lang.String MAX_ELEMENT_REPLACE,static final java.lang.String NON_HTML_PATH_EXTENSION,static final java.lang.String RELEVANT_TAG_EXTRACTOR,static final java.lang.String WHITESPACE,private java.lang.String eachAttributePattern,protected transient org.archive.modules.extractor.ExtractorJS extractorJS,private static java.util.logging.Logger logger,protected org.archive.modules.CrawlMetadata metadata,private java.lang.String relevantTagPattern,private static final long serialVersionUID
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/extractor/ContentExtractor.java
ContentExtractor
shouldProcess
class ContentExtractor extends Extractor { /** * Extracts links */ final protected void extract(CrawlURI uri) { boolean finished = innerExtract(uri); if (finished) { uri.linkExtractorFinished(); } } /** * Determines if links should be extracted from the given URI. This method * performs four checks. It first checks if the URI was processed successfully, * i.e. {@link CrawlURI#isSuccess()} returns true. * * <p> * The second check runs only if * {@link ExtractorParameters#getExtractIndependently()} is false. It checks * {@link CrawlURI#hasBeenLinkExtracted()} result. If that result is * true, then this method returns false, as some other extractor has claimed * that links are already extracted. * * <p> * Next, this method checks that the content length of the URI is greater * than zero (in other words, that there is actually content for links to be * extracted from). If the content length of the URI is zero or less, then * this method returns false. * * <p> * Finally, this method delegates to {@link #innerExtract(CrawlURI)} and * returns that result. * * @param uri * the URI to check * @return true if links should be extracted from the URI, false otherwise */ final protected boolean shouldProcess(CrawlURI uri) {<FILL_FUNCTION_BODY>} /** * Determines if otherwise valid URIs should have links extracted or not. * The given URI will have content length greater than zero. Subclasses * should implement this method to perform additional checks. For instance, * the {@link ExtractorHTML} implementation checks that the content-type of * the given URI is text/html. * * @param uri * the URI to check * @return true if links should be extracted from that URI, false otherwise */ protected abstract boolean shouldExtract(CrawlURI uri); /** * Actually extracts links. The given URI will have passed the three * checks described in {@link #shouldProcess(CrawlURI)}. Subclasses * should implement this method to discover outlinks in the URI's * content stream. For instance, {@link ExtractorHTML} extracts links * from Anchor tags and so on. * * <p>This method should only return true if extraction completed * successfully. If not (for instance, if an IO error occurred), then * this method should return false. Returning false indicates to the * pipeline that downstream extractors should attempt to extract links * themselves. Returning true indicates that downstream extractors * should be skipped. * * @param uri the URI whose links to extract * @return true if link extraction finished; false if downstream * extractors should attempt to extract links */ protected abstract boolean innerExtract(CrawlURI uri); }
if (!uri.isSuccess()) { return false; } if (!getExtractorParameters().getExtractIndependently() && uri.hasBeenLinkExtracted()) { return false; } if (uri.getContentLength() <= 0) { return false; } if (!getExtractorParameters().getExtract404s() && uri.getFetchStatus()==FetchStatusCodes.S_NOT_FOUND) { return false; } if (!shouldExtract(uri)) { return false; } return true;
784
156
940
<methods>public non-sealed void <init>() ,public static void add(org.archive.modules.CrawlURI, int, java.lang.String, org.archive.modules.extractor.LinkContext, org.archive.modules.extractor.Hop) throws URIException,public static org.archive.modules.CrawlURI addRelativeToBase(org.archive.modules.CrawlURI, int, java.lang.CharSequence, org.archive.modules.extractor.LinkContext, org.archive.modules.extractor.Hop) throws URIException,public static org.archive.modules.CrawlURI addRelativeToVia(org.archive.modules.CrawlURI, int, java.lang.String, org.archive.modules.extractor.LinkContext, org.archive.modules.extractor.Hop) throws URIException,public org.archive.modules.extractor.ExtractorParameters getExtractorParameters() ,public org.archive.modules.extractor.UriErrorLoggerModule getLoggerModule() ,public void logUriError(URIException, org.archive.net.UURI, java.lang.CharSequence) ,public java.lang.String report() ,public void setExtractorParameters(org.archive.modules.extractor.ExtractorParameters) ,public void setLoggerModule(org.archive.modules.extractor.UriErrorLoggerModule) <variables>public static final org.archive.modules.extractor.ExtractorParameters DEFAULT_PARAMETERS,private static final java.util.logging.Logger LOGGER,protected transient org.archive.modules.extractor.ExtractorParameters extractorParameters,private static final java.util.logging.Logger logger,protected transient org.archive.modules.extractor.UriErrorLoggerModule loggerModule,protected java.util.concurrent.atomic.AtomicLong numberOfLinksExtracted
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/extractor/ContentExtractorTestBase.java
ContentExtractorTestBase
defaultURI
class ContentExtractorTestBase extends ProcessorTestBase { /** * An extractor created during the setUp. */ protected Extractor extractor; /** * Sets up the {@link #extractor}. */ final public void setUp() { extractor = makeExtractor(); } @Override protected Object makeModule() { return makeExtractor(); } /** * Subclasses should return an Extractor instance to test. * * @return an Extractor instance to test */ protected abstract Extractor makeExtractor(); /** * Returns a CrawlURI for testing purposes. * * @return a CrawlURI * @throws Exception just in case */ protected CrawlURI defaultURI() throws Exception {<FILL_FUNCTION_BODY>} /** * Tests that a URI with a zero content length has no links extracted. * * @throws Exception just in case */ public void testZeroContent() throws Exception { CrawlURI uri = defaultURI(); Recorder recorder = createRecorder(""); uri.setContentType("text/plain"); uri.setRecorder(recorder); extractor.process(uri); assertEquals(0, uri.getOutLinks().size()); assertNoSideEffects(uri); } /** * Tests that a URI whose linkExtractionFinished flag has been set has * no links extracted. * * @throws Exception just in case */ public void testFinished() throws Exception { CrawlURI uri = defaultURI(); uri.linkExtractorFinished(); extractor.process(uri); assertEquals(0, uri.getOutLinks().size()); assertNoSideEffects(uri); } /** * Asserts that the given URI has no URI errors, no localized errors, and * no annotations. * * @param uri the URI to test */ protected static void assertNoSideEffects(CrawlURI uri) { assertEquals(0, uri.getNonFatalFailures().size()); assertTrue(uri.getAnnotations().isEmpty()); } @Deprecated public static Recorder createRecorder(String content) throws IOException { return createRecorder(content, Charset.defaultCharset().name()); } public static Recorder createRecorder(String content, String charset) throws IOException { File temp = File.createTempFile("test", ".tmp"); Recorder recorder = new Recorder(temp, 1024, 1024); byte[] b = content.getBytes(charset); ByteArrayInputStream bais = new ByteArrayInputStream(b); InputStream is = recorder.inputWrap(bais); recorder.markContentBegin(); for (int x = is.read(); x >= 0; x = is.read()); is.close(); return recorder; } }
UURI uuri = UURIFactory.getInstance("http://www.archive.org/start/"); return new CrawlURI(uuri, null, null, LinkContext.NAVLINK_MISC);
790
56
846
<methods>public non-sealed void <init>() <variables>
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/extractor/ExtractorCSS.java
ExtractorCSS
processStyleCode
class ExtractorCSS extends ContentExtractor { @SuppressWarnings("unused") private static final long serialVersionUID = 2L; private static Logger logger = Logger.getLogger("org.archive.crawler.extractor.ExtractorCSS"); private static String ESCAPED_AMP = "&amp"; // CSS escapes: "Parentheses, commas, whitespace characters, single // quotes (') and double quotes (") appearing in a URL must be // escaped with a backslash" protected static final String CSS_BACKSLASH_ESCAPE = "\\\\([,'\"\\(\\)\\s])"; /** * CSS URL extractor pattern. * * This pattern extracts URIs for CSS files **/ // static final String CSS_URI_EXTRACTOR = // "url[(]\\s*([\"\']?)([^\\\"\\'].*?)\\1\\s*[)]"; protected static final String CSS_URI_EXTRACTOR = "(?i)(?:@import (?:url[(]|)|url[(])\\s*([\\\"\']?)" + // G1 "([^\\\"\'].{0,"+UURI.MAX_URL_LENGTH+"}?)\\1\\s*[);]"; // G2 // GROUPS: // (G1) optional ' or " // (G2) URI /** */ public ExtractorCSS() { } @Override protected boolean shouldExtract(CrawlURI curi) { String mimeType = curi.getContentType(); if (mimeType == null) { return false; // FIXME: This check should be unnecessary } if ((mimeType.toLowerCase().indexOf("css") < 0) && (!curi.toString().toLowerCase().endsWith(".css"))) { return false; } return true; } /** * @param curi Crawl URI to process. */ public boolean innerExtract(CrawlURI curi) { try { ReplayCharSequence cs = curi.getRecorder().getContentReplayCharSequence(); numberOfLinksExtracted.addAndGet( processStyleCode(this, curi, cs)); // Set flag to indicate that link extraction is completed. return true; } catch (IOException e) { logger.log(Level.WARNING, "Problem with ReplayCharSequence: " + e.getMessage(), e); } return false; } public static long processStyleCode(Extractor ext, CrawlURI curi, CharSequence cs) {<FILL_FUNCTION_BODY>} }
long foundLinks = 0; Matcher uris = null; String cssUri; try { uris = TextUtils.getMatcher(CSS_URI_EXTRACTOR, cs); while (uris.find()) { cssUri = uris.group(2); // TODO: Escape more HTML Entities. cssUri = TextUtils.replaceAll(ESCAPED_AMP, cssUri, "&"); // Remove backslashes when used as escape character in CSS URL cssUri = TextUtils.replaceAll(CSS_BACKSLASH_ESCAPE, cssUri, "$1"); foundLinks++; int max = ext.getExtractorParameters().getMaxOutlinks(); try { addRelativeToBase(curi, max, cssUri, LinkContext.EMBED_MISC, Hop.EMBED); } catch (URIException e) { ext.logUriError(e, curi.getUURI(), cssUri); } } } catch (StackOverflowError e) { DevUtils.warnHandle(e, "ExtractorCSS StackOverflowError"); } finally { TextUtils.recycleMatcher(uris); } return foundLinks;
707
320
1,027
<methods>public non-sealed void <init>() <variables>
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/extractor/ExtractorDOC.java
ExtractorDOC
innerExtract
class ExtractorDOC extends ContentExtractor { @SuppressWarnings("unused") private static final long serialVersionUID = 3L; private static Pattern PATTERN = Pattern.compile("HYPERLINK.*?\"(.*?)\""); private static Logger logger = Logger.getLogger("org.archive.crawler.extractor.ExtractorDOC"); public ExtractorDOC() { } @Override protected boolean shouldExtract(CrawlURI uri) { String mimeType = uri.getContentType(); if (mimeType == null) { return false; } return mimeType.toLowerCase().startsWith("application/msword"); } /** * Processes a word document and extracts any hyperlinks from it. * This only extracts href style links, and does not examine the actual * text for valid URIs. * @param curi CrawlURI to process. */ protected boolean innerExtract(CrawlURI curi){<FILL_FUNCTION_BODY>} private void addLink(CrawlURI curi, String hyperlink) { try { UURI dest = UURIFactory.getInstance(curi.getUURI(), hyperlink); LinkContext lc = LinkContext.NAVLINK_MISC; addOutlink(curi, hyperlink, lc, Hop.NAVLINK); } catch (URIException e1) { logUriError(e1, curi.getUURI(), hyperlink); } numberOfLinksExtracted.incrementAndGet(); } }
int links = 0; InputStream contentStream = null; ReplayInputStream documentStream = null; SeekReader docReader = null; // Get the doc as a repositionable reader try { contentStream = curi.getRecorder().getContentReplayInputStream(); if (contentStream==null) { // TODO: note problem return false; } documentStream = new ReplayInputStream(contentStream); docReader = Doc.getText(documentStream); } catch(Exception e){ curi.getNonFatalFailures().add(e); return false; } finally { IOUtils.closeQuietly(contentStream); } CharSequence cs = new SeekReaderCharSequence(docReader, 0); Matcher m = PATTERN.matcher(cs); while (m.find()) { links++; addLink(curi, m.group(1)); } documentStream.destroy(); logger.fine(curi + " has " + links + " links."); return true;
433
281
714
<methods>public non-sealed void <init>() <variables>
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/extractor/ExtractorHTTP.java
ExtractorHTTP
addContentLocationHeaderLink
class ExtractorHTTP extends Extractor { @SuppressWarnings("unused") private static final long serialVersionUID = 3L; public ExtractorHTTP() { } /** should all HTTP URIs be used to infer a link to the site's root? */ protected boolean inferRootPage = false; public boolean getInferRootPage() { return inferRootPage; } public void setInferRootPage(boolean inferRootPage) { this.inferRootPage = inferRootPage; } @Override protected boolean shouldProcess(CrawlURI uri) { if (uri.getFetchStatus() <= 0) { return false; } FetchType ft = uri.getFetchType(); return (ft == FetchType.HTTP_GET) || (ft == FetchType.HTTP_POST); } @Override protected void extract(CrawlURI curi) { // discover headers if present addHeaderLink(curi, "Location"); addContentLocationHeaderLink(curi, "Content-Location"); addRefreshHeaderLink(curi, "Refresh"); // try /favicon.ico for every HTTP(S) URI addOutlink(curi, "/favicon.ico", LinkContext.INFERRED_MISC, Hop.INFERRED); if(getInferRootPage()) { addOutlink(curi, "/", LinkContext.INFERRED_MISC, Hop.INFERRED); } } protected void addRefreshHeaderLink(CrawlURI curi, String headerKey) { String headerValue = curi.getHttpResponseHeader(headerKey); if (headerValue != null) { // parsing logic copied from ExtractorHTML meta-refresh handling int urlIndex = headerValue.indexOf("=") + 1; if (urlIndex > 0) { String refreshUri = headerValue.substring(urlIndex); addHeaderLink(curi, headerKey, refreshUri); } } } protected void addHeaderLink(CrawlURI curi, String headerKey) { String headerValue = curi.getHttpResponseHeader(headerKey); if (headerValue != null) { addHeaderLink(curi, headerKey, headerValue); } } protected void addContentLocationHeaderLink(CrawlURI curi, String headerKey) {<FILL_FUNCTION_BODY>} protected void addHeaderLink(CrawlURI curi, String headerName, String url) { try { UURI dest = UURIFactory.getInstance(curi.getUURI(), url); LinkContext lc = HTMLLinkContext.get(headerName+":"); addOutlink(curi, dest.toString(), lc, Hop.REFER); numberOfLinksExtracted.incrementAndGet(); } catch (URIException e) { logUriError(e, curi.getUURI(), url); } } }
String headerValue = curi.getHttpResponseHeader(headerKey); if (headerValue != null) { try { UURI dest = UURIFactory.getInstance(curi.getUURI(), headerValue); addOutlink(curi, dest.toString(), LinkContext.INFERRED_MISC, Hop.INFERRED); numberOfLinksExtracted.incrementAndGet(); } catch (URIException e) { logUriError(e, curi.getUURI(), headerValue); } }
765
136
901
<methods>public non-sealed void <init>() ,public static void add(org.archive.modules.CrawlURI, int, java.lang.String, org.archive.modules.extractor.LinkContext, org.archive.modules.extractor.Hop) throws URIException,public static org.archive.modules.CrawlURI addRelativeToBase(org.archive.modules.CrawlURI, int, java.lang.CharSequence, org.archive.modules.extractor.LinkContext, org.archive.modules.extractor.Hop) throws URIException,public static org.archive.modules.CrawlURI addRelativeToVia(org.archive.modules.CrawlURI, int, java.lang.String, org.archive.modules.extractor.LinkContext, org.archive.modules.extractor.Hop) throws URIException,public org.archive.modules.extractor.ExtractorParameters getExtractorParameters() ,public org.archive.modules.extractor.UriErrorLoggerModule getLoggerModule() ,public void logUriError(URIException, org.archive.net.UURI, java.lang.CharSequence) ,public java.lang.String report() ,public void setExtractorParameters(org.archive.modules.extractor.ExtractorParameters) ,public void setLoggerModule(org.archive.modules.extractor.UriErrorLoggerModule) <variables>public static final org.archive.modules.extractor.ExtractorParameters DEFAULT_PARAMETERS,private static final java.util.logging.Logger LOGGER,protected transient org.archive.modules.extractor.ExtractorParameters extractorParameters,private static final java.util.logging.Logger logger,protected transient org.archive.modules.extractor.UriErrorLoggerModule loggerModule,protected java.util.concurrent.atomic.AtomicLong numberOfLinksExtracted
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/extractor/ExtractorImpliedURI.java
ExtractorImpliedURI
extract
class ExtractorImpliedURI extends Extractor { @SuppressWarnings("unused") private static final long serialVersionUID = 3L; private static Logger LOGGER = Logger.getLogger(ExtractorImpliedURI.class.getName()); { setRegex(Pattern.compile("^(.*)$")); } public Pattern getRegex() { return (Pattern) kp.get("regex"); } /** * Triggering regular expression. When a discovered URI matches this * pattern, the 'implied' URI will be built. The capturing groups of this * expression are available for the build replacement pattern. */ public void setRegex(Pattern regex) { kp.put("regex",regex); } { setFormat(""); } public String getFormat() { return (String) kp.get("format"); } /** * Replacement pattern to build 'implied' URI, using captured groups of * trigger expression. */ public void setFormat(String format) { kp.put("format",format); } { setRemoveTriggerUris(false); } public boolean getRemoveTriggerUris() { return (Boolean) kp.get("removeTriggerUris"); } /** * If true, all URIs that match trigger regular expression are removed * from the list of extracted URIs. Default is false. */ public void setRemoveTriggerUris(boolean remove) { kp.put("removeTriggerUris",remove); } /** * Constructor. */ public ExtractorImpliedURI() { } @Override protected boolean shouldProcess(CrawlURI uri) { return true; } /** * Perform usual extraction on a CrawlURI * * @param curi Crawl URI to process. */ @Override public void extract(CrawlURI curi) {<FILL_FUNCTION_BODY>} /** * Utility method for extracting 'implied' URI given a source uri, * trigger pattern, and build pattern. * * @param uri source to check for implied URI * @param trigger regex pattern which if matched implies another URI * @param build replacement pattern to build the implied URI * @return implied URI, or null if none */ protected static String extractImplied(CharSequence uri, Pattern trigger, String build) { if (trigger == null) { return null; } Matcher m = trigger.matcher(uri); if(m.matches()) { String result = m.replaceFirst(build); return result; } return null; } }
List<CrawlURI> links = new ArrayList<CrawlURI>(curi.getOutLinks()); int max = links.size(); for (int i = 0; i < max; i++) { CrawlURI link = links.get(i); Pattern trigger = getRegex(); String build = getFormat(); CharSequence dest = link.getUURI(); String implied = extractImplied(dest, trigger, build); if (implied != null) { try { UURI target = UURIFactory.getInstance(implied); LinkContext lc = LinkContext.INFERRED_MISC; Hop hop = Hop.INFERRED; addOutlink(curi, target, lc, hop); numberOfLinksExtracted.incrementAndGet(); boolean removeTriggerURI = getRemoveTriggerUris(); // remove trigger URI from the outlinks if configured so. if (removeTriggerURI) { if (curi.getOutLinks().remove(link)) { LOGGER.log(Level.FINE, link.getURI() + " has been removed from " + curi.getURI() + " outlinks list."); numberOfLinksExtracted.decrementAndGet(); } else { LOGGER.log(Level.FINE, "Failed to remove " + link.getURI() + " from " + curi.getURI() + " outlinks list."); } } } catch (URIException e) { LOGGER.log(Level.FINE, "bad URI", e); } } }
722
412
1,134
<methods>public non-sealed void <init>() ,public static void add(org.archive.modules.CrawlURI, int, java.lang.String, org.archive.modules.extractor.LinkContext, org.archive.modules.extractor.Hop) throws URIException,public static org.archive.modules.CrawlURI addRelativeToBase(org.archive.modules.CrawlURI, int, java.lang.CharSequence, org.archive.modules.extractor.LinkContext, org.archive.modules.extractor.Hop) throws URIException,public static org.archive.modules.CrawlURI addRelativeToVia(org.archive.modules.CrawlURI, int, java.lang.String, org.archive.modules.extractor.LinkContext, org.archive.modules.extractor.Hop) throws URIException,public org.archive.modules.extractor.ExtractorParameters getExtractorParameters() ,public org.archive.modules.extractor.UriErrorLoggerModule getLoggerModule() ,public void logUriError(URIException, org.archive.net.UURI, java.lang.CharSequence) ,public java.lang.String report() ,public void setExtractorParameters(org.archive.modules.extractor.ExtractorParameters) ,public void setLoggerModule(org.archive.modules.extractor.UriErrorLoggerModule) <variables>public static final org.archive.modules.extractor.ExtractorParameters DEFAULT_PARAMETERS,private static final java.util.logging.Logger LOGGER,protected transient org.archive.modules.extractor.ExtractorParameters extractorParameters,private static final java.util.logging.Logger logger,protected transient org.archive.modules.extractor.UriErrorLoggerModule loggerModule,protected java.util.concurrent.atomic.AtomicLong numberOfLinksExtracted
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/extractor/ExtractorJS.java
ExtractorJS
shouldExtract
class ExtractorJS extends ContentExtractor { @SuppressWarnings("unused") private static final long serialVersionUID = 3L; private static Logger LOGGER = Logger.getLogger(ExtractorJS.class.getName()); // finds strings in Javascript // (areas between paired ' or " characters, possibly backslash-quoted // on the ends, but not in the middle) protected static final String JAVASCRIPT_STRING_EXTRACTOR = "(\\\\{0,8}+(?:['\"]|u002[27]))([^'\"]{0,"+UURI.MAX_URL_LENGTH+"})(?:\\1)"; // GROUPS: // (G1) ' or " with optional leading backslashes // (G2) whitespace-free string delimited on boths ends by G1 protected long numberOfCURIsHandled = 0; protected boolean shouldExtract(CrawlURI uri) {<FILL_FUNCTION_BODY>} @Override protected boolean innerExtract(CrawlURI curi) { this.numberOfCURIsHandled++; ReplayCharSequence cs = null; try { cs = curi.getRecorder().getContentReplayCharSequence(); try { numberOfLinksExtracted.addAndGet(considerStrings(curi, cs)); } catch (StackOverflowError e) { DevUtils.warnHandle(e, "ExtractorJS StackOverflowError"); } // Set flag to indicate that link extraction is completed. return true; } catch (IOException e) { curi.getNonFatalFailures().add(e); } return false; } protected long considerStrings(CrawlURI curi, CharSequence cs) { return considerStrings(this, curi, cs, true); } public long considerStrings(Extractor ext, CrawlURI curi, CharSequence cs) { return considerStrings(ext, curi, cs, false); } public long considerStrings(Extractor ext, CrawlURI curi, CharSequence cs, boolean handlingJSFile) { long foundLinks = 0; Matcher strings = TextUtils.getMatcher(JAVASCRIPT_STRING_EXTRACTOR, cs); int startIndex = 0; while (strings.find(startIndex)) { CharSequence subsequence = cs.subSequence(strings.start(2), strings.end(2)); if (UriUtils.isPossibleUri(subsequence)) { if (considerString(ext, curi, handlingJSFile, subsequence.toString())) { foundLinks++; } } startIndex = strings.end(1); } TextUtils.recycleMatcher(strings); return foundLinks; } protected boolean considerString(Extractor ext, CrawlURI curi, boolean handlingJSFile, String candidate) { try { candidate = StringEscapeUtils.unescapeJavaScript(candidate); } catch (NestableRuntimeException e) { LOGGER.log(Level.WARNING, "problem unescaping some javascript", e); } candidate = UriUtils.speculativeFixup(candidate, curi.getUURI()); if (UriUtils.isVeryLikelyUri(candidate)) { try { int max = ext.getExtractorParameters().getMaxOutlinks(); if (handlingJSFile) { addRelativeToVia(curi, max, candidate, JS_MISC, SPECULATIVE); return true; } else { addRelativeToBase(curi, max, candidate, JS_MISC, SPECULATIVE); return true; } } catch (URIException e) { ext.logUriError(e, curi.getUURI(), candidate); } } return false; } }
String contentType = uri.getContentType(); if (contentType == null) { return false; } // If the content-type indicates js, we should process it. if (contentType.indexOf("javascript") >= 0) { return true; } if (contentType.indexOf("jscript") >= 0) { return true; } if (contentType.indexOf("ecmascript") >= 0) { return true; } if (contentType.startsWith("application/json")) { return true; } // If the filename indicates js, we should process it. if (uri.toString().toLowerCase().endsWith(".js")) { return true; } // If the viaContext indicates a script, we should process it. LinkContext context = uri.getViaContext(); if (context == null) { return false; } String s = context.toString().toLowerCase(); return s.startsWith("script");
1,048
261
1,309
<methods>public non-sealed void <init>() <variables>
internetarchive_heritrix3
heritrix3/modules/src/main/java/org/archive/modules/extractor/ExtractorMultipleRegex.java
GroupList
extract
class GroupList extends LinkedList<String> { private static final long serialVersionUID = 1L; public GroupList(MatchResult matchResult) { for (int i = 0; i <= matchResult.groupCount(); i++) { add(matchResult.group(i)); } } }; @Override public void extract(CrawlURI curi) {<FILL_FUNCTION_BODY>
// { regex name -> list of matches } Map<String, MatchList> matchLists; // uri regex Matcher matcher = TextUtils.getMatcher(getUriRegex(), curi.getURI()); if (matcher.matches()) { matchLists = new LinkedHashMap<String,MatchList>(); matchLists.put("uriRegex", new MatchList(new GroupList(matcher))); } else { TextUtils.recycleMatcher(matcher); return; // if uri regex doesn't match, we're done } ReplayCharSequence cs; try { cs = curi.getRecorder().getContentReplayCharSequence(); } catch (IOException e) { curi.getNonFatalFailures().add(e); LOGGER.log(Level.WARNING, "Failed get of replay char sequence in " + Thread.currentThread().getName(), e); TextUtils.recycleMatcher(matcher); return; } // run all the regexes on the content and cache results for (String regexName: getContentRegexes().keySet()) { String regex = getContentRegexes().get(regexName); MatchList matchList = new MatchList(regex, cs); if (matchList.isEmpty()) { TextUtils.recycleMatcher(matcher); return; // no match found for regex, so we can stop now } matchLists.put(regexName, matchList); } /* * If we have 3 regexes, the first one has 1 match, second has 12 * matches, third has 3 matches, then we have 36 combinations of * matches, thus 36 outlinks to extracted. */ int numOutlinks = 1; for (MatchList matchList: matchLists.values()) { numOutlinks *= matchList.size(); } String[] regexNames = matchLists.keySet().toArray(new String[0]); for (int i = 0; i < numOutlinks; i++) { Map<String, Object> bindings = makeBindings(matchLists, regexNames, i); buildAndAddOutlink(curi, bindings); } TextUtils.recycleMatcher(matcher);
108
587
695
<methods>public non-sealed void <init>() ,public static void add(org.archive.modules.CrawlURI, int, java.lang.String, org.archive.modules.extractor.LinkContext, org.archive.modules.extractor.Hop) throws URIException,public static org.archive.modules.CrawlURI addRelativeToBase(org.archive.modules.CrawlURI, int, java.lang.CharSequence, org.archive.modules.extractor.LinkContext, org.archive.modules.extractor.Hop) throws URIException,public static org.archive.modules.CrawlURI addRelativeToVia(org.archive.modules.CrawlURI, int, java.lang.String, org.archive.modules.extractor.LinkContext, org.archive.modules.extractor.Hop) throws URIException,public org.archive.modules.extractor.ExtractorParameters getExtractorParameters() ,public org.archive.modules.extractor.UriErrorLoggerModule getLoggerModule() ,public void logUriError(URIException, org.archive.net.UURI, java.lang.CharSequence) ,public java.lang.String report() ,public void setExtractorParameters(org.archive.modules.extractor.ExtractorParameters) ,public void setLoggerModule(org.archive.modules.extractor.UriErrorLoggerModule) <variables>public static final org.archive.modules.extractor.ExtractorParameters DEFAULT_PARAMETERS,private static final java.util.logging.Logger LOGGER,protected transient org.archive.modules.extractor.ExtractorParameters extractorParameters,private static final java.util.logging.Logger logger,protected transient org.archive.modules.extractor.UriErrorLoggerModule loggerModule,protected java.util.concurrent.atomic.AtomicLong numberOfLinksExtracted