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
|
|---|---|---|---|---|---|---|---|---|---|
google_gson
|
gson/metrics/src/main/java/com/google/gson/metrics/NonUploadingCaliperRunner.java
|
NonUploadingCaliperRunner
|
run
|
class NonUploadingCaliperRunner {
private NonUploadingCaliperRunner() {}
private static String[] concat(String first, String... others) {
if (others.length == 0) {
return new String[] {first};
} else {
String[] result = new String[others.length + 1];
result[0] = first;
System.arraycopy(others, 0, result, 1, others.length);
return result;
}
}
public static void run(Class<?> c, String[] args) {<FILL_FUNCTION_BODY>}
}
|
// Disable result upload; Caliper uploads results to webapp by default, see
// https://github.com/google/caliper/issues/356
CaliperMain.main(c, concat("-Cresults.upload.options.url=", args));
| 152
| 68
| 220
|
<no_super_class>
|
google_gson
|
gson/metrics/src/main/java/com/google/gson/metrics/ParseBenchmark.java
|
JacksonStreamParser
|
parse
|
class JacksonStreamParser implements Parser {
@Override
public void parse(char[] data, Document document) throws Exception {<FILL_FUNCTION_BODY>}
}
|
JsonFactory jsonFactory =
new JsonFactoryBuilder()
.configure(JsonFactory.Feature.CANONICALIZE_FIELD_NAMES, false)
.build();
com.fasterxml.jackson.core.JsonParser jp =
jsonFactory.createParser(new CharArrayReader(data));
int depth = 0;
do {
JsonToken token = jp.nextToken();
switch (token) {
case START_OBJECT:
case START_ARRAY:
depth++;
break;
case END_OBJECT:
case END_ARRAY:
depth--;
break;
case FIELD_NAME:
jp.currentName();
break;
case VALUE_STRING:
jp.getText();
break;
case VALUE_NUMBER_INT:
case VALUE_NUMBER_FLOAT:
jp.getLongValue();
break;
case VALUE_TRUE:
case VALUE_FALSE:
jp.getBooleanValue();
break;
case VALUE_NULL:
// Do nothing; nextToken() will advance in stream
break;
default:
throw new IllegalArgumentException("Unexpected token " + token);
}
} while (depth > 0);
jp.close();
| 44
| 327
| 371
|
<no_super_class>
|
google_gson
|
gson/metrics/src/main/java/com/google/gson/metrics/SerializationBenchmark.java
|
SerializationBenchmark
|
timeObjectSerialization
|
class SerializationBenchmark {
private Gson gson;
private BagOfPrimitives bag;
@Param private boolean pretty;
public static void main(String[] args) {
NonUploadingCaliperRunner.run(SerializationBenchmark.class, args);
}
@BeforeExperiment
void setUp() throws Exception {
this.gson = pretty ? new GsonBuilder().setPrettyPrinting().create() : new Gson();
this.bag = new BagOfPrimitives(10L, 1, false, "foo");
}
public void timeObjectSerialization(int reps) {<FILL_FUNCTION_BODY>}
}
|
for (int i = 0; i < reps; ++i) {
gson.toJson(bag);
}
| 170
| 34
| 204
|
<no_super_class>
|
google_gson
|
gson/proto/src/main/java/com/google/gson/protobuf/ProtoTypeAdapter.java
|
Builder
|
serialize
|
class Builder {
private final Set<Extension<FieldOptions, String>> serializedNameExtensions;
private final Set<Extension<EnumValueOptions, String>> serializedEnumValueExtensions;
private EnumSerialization enumSerialization;
private CaseFormat protoFormat;
private CaseFormat jsonFormat;
private Builder(
EnumSerialization enumSerialization,
CaseFormat fromFieldNameFormat,
CaseFormat toFieldNameFormat) {
this.serializedNameExtensions = new HashSet<>();
this.serializedEnumValueExtensions = new HashSet<>();
setEnumSerialization(enumSerialization);
setFieldNameSerializationFormat(fromFieldNameFormat, toFieldNameFormat);
}
@CanIgnoreReturnValue
public Builder setEnumSerialization(EnumSerialization enumSerialization) {
this.enumSerialization = requireNonNull(enumSerialization);
return this;
}
/**
* Sets the field names serialization format. The first parameter defines how to read the format
* of the proto field names you are converting to JSON. The second parameter defines which
* format to use when serializing them.
*
* <p>For example, if you use the following parameters: {@link CaseFormat#LOWER_UNDERSCORE},
* {@link CaseFormat#LOWER_CAMEL}, the following conversion will occur:
*
* <pre>{@code
* PROTO <-> JSON
* my_field myField
* foo foo
* n__id_ct nIdCt
* }</pre>
*/
@CanIgnoreReturnValue
public Builder setFieldNameSerializationFormat(
CaseFormat fromFieldNameFormat, CaseFormat toFieldNameFormat) {
this.protoFormat = fromFieldNameFormat;
this.jsonFormat = toFieldNameFormat;
return this;
}
/**
* Adds a field proto annotation that, when set, overrides the default field name
* serialization/deserialization. For example, if you add the '{@code serialized_name}'
* annotation and you define a field in your proto like the one below:
*
* <pre>
* string client_app_id = 1 [(serialized_name) = "appId"];
* </pre>
*
* ...the adapter will serialize the field using '{@code appId}' instead of the default ' {@code
* clientAppId}'. This lets you customize the name serialization of any proto field.
*/
@CanIgnoreReturnValue
public Builder addSerializedNameExtension(
Extension<FieldOptions, String> serializedNameExtension) {
serializedNameExtensions.add(requireNonNull(serializedNameExtension));
return this;
}
/**
* Adds an enum value proto annotation that, when set, overrides the default <b>enum</b> value
* serialization/deserialization of this adapter. For example, if you add the ' {@code
* serialized_value}' annotation and you define an enum in your proto like the one below:
*
* <pre>
* enum MyEnum {
* UNKNOWN = 0;
* CLIENT_APP_ID = 1 [(serialized_value) = "APP_ID"];
* TWO = 2 [(serialized_value) = "2"];
* }
* </pre>
*
* ...the adapter will serialize the value {@code CLIENT_APP_ID} as "{@code APP_ID}" and the
* value {@code TWO} as "{@code 2}". This works for both serialization and deserialization.
*
* <p>Note that you need to set the enum serialization of this adapter to {@link
* EnumSerialization#NAME}, otherwise these annotations will be ignored.
*/
@CanIgnoreReturnValue
public Builder addSerializedEnumValueExtension(
Extension<EnumValueOptions, String> serializedEnumValueExtension) {
serializedEnumValueExtensions.add(requireNonNull(serializedEnumValueExtension));
return this;
}
public ProtoTypeAdapter build() {
return new ProtoTypeAdapter(
enumSerialization,
protoFormat,
jsonFormat,
serializedNameExtensions,
serializedEnumValueExtensions);
}
}
/**
* Creates a new {@link ProtoTypeAdapter} builder, defaulting enum serialization to {@link
* EnumSerialization#NAME} and converting field serialization from {@link
* CaseFormat#LOWER_UNDERSCORE} to {@link CaseFormat#LOWER_CAMEL}.
*/
public static Builder newBuilder() {
return new Builder(EnumSerialization.NAME, CaseFormat.LOWER_UNDERSCORE, CaseFormat.LOWER_CAMEL);
}
private static final FieldDescriptor.Type ENUM_TYPE = FieldDescriptor.Type.ENUM;
private static final ConcurrentMap<String, ConcurrentMap<Class<?>, Method>> mapOfMapOfMethods =
new MapMaker().makeMap();
private final EnumSerialization enumSerialization;
private final CaseFormat protoFormat;
private final CaseFormat jsonFormat;
private final Set<Extension<FieldOptions, String>> serializedNameExtensions;
private final Set<Extension<EnumValueOptions, String>> serializedEnumValueExtensions;
private ProtoTypeAdapter(
EnumSerialization enumSerialization,
CaseFormat protoFormat,
CaseFormat jsonFormat,
Set<Extension<FieldOptions, String>> serializedNameExtensions,
Set<Extension<EnumValueOptions, String>> serializedEnumValueExtensions) {
this.enumSerialization = enumSerialization;
this.protoFormat = protoFormat;
this.jsonFormat = jsonFormat;
this.serializedNameExtensions = serializedNameExtensions;
this.serializedEnumValueExtensions = serializedEnumValueExtensions;
}
@Override
public JsonElement serialize(Message src, Type typeOfSrc, JsonSerializationContext context) {<FILL_FUNCTION_BODY>
|
JsonObject ret = new JsonObject();
final Map<FieldDescriptor, Object> fields = src.getAllFields();
for (Map.Entry<FieldDescriptor, Object> fieldPair : fields.entrySet()) {
final FieldDescriptor desc = fieldPair.getKey();
String name = getCustSerializedName(desc.getOptions(), desc.getName());
if (desc.getType() == ENUM_TYPE) {
// Enum collections are also returned as ENUM_TYPE
if (fieldPair.getValue() instanceof Collection) {
// Build the array to avoid infinite loop
JsonArray array = new JsonArray();
@SuppressWarnings("unchecked")
Collection<EnumValueDescriptor> enumDescs =
(Collection<EnumValueDescriptor>) fieldPair.getValue();
for (EnumValueDescriptor enumDesc : enumDescs) {
array.add(context.serialize(getEnumValue(enumDesc)));
ret.add(name, array);
}
} else {
EnumValueDescriptor enumDesc = ((EnumValueDescriptor) fieldPair.getValue());
ret.add(name, context.serialize(getEnumValue(enumDesc)));
}
} else {
ret.add(name, context.serialize(fieldPair.getValue()));
}
}
return ret;
| 1,496
| 318
| 1,814
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/bdb/AutoKryo.java
|
AutoKryo
|
newInstance
|
class AutoKryo extends Kryo {
protected ArrayList<Class<?>> registeredClasses = new ArrayList<Class<?>>();
@Override
protected void handleUnregisteredClass(@SuppressWarnings("rawtypes") Class type) {
System.err.println("UNREGISTERED FOR KRYO "+type+" in "+registeredClasses.get(0));
super.handleUnregisteredClass(type);
}
public void autoregister(Class<?> type) {
if (registeredClasses.contains(type)) {
return;
}
registeredClasses.add(type);
try {
invokeStatic(
"autoregisterTo",
type,
new Class[]{ ((Class<?>)AutoKryo.class), },
new Object[] { this, });
} catch (Exception e) {
register(type);
}
}
protected static final ReflectionFactory REFLECTION_FACTORY = ReflectionFactory.getReflectionFactory();
protected static final Object[] INITARGS = new Object[0];
protected static final Map<Class<?>, Constructor<?>> CONSTRUCTOR_CACHE = new ConcurrentHashMap<Class<?>, Constructor<?>>();
@Override
public <T> T newInstance(Class<T> type) {<FILL_FUNCTION_BODY>}
protected Object invokeStatic(String method, Class<?> clazz, Class<?>[] types, Object[] args) throws Exception {
return clazz.getMethod(method, types).invoke(null, args);
}
}
|
SerializationException ex = null;
try {
return super.newInstance(type);
} catch (SerializationException se) {
ex = se;
}
try {
Constructor<?> constructor = CONSTRUCTOR_CACHE.get(type);
if(constructor == null) {
constructor = REFLECTION_FACTORY.newConstructorForSerialization(
type, Object.class.getDeclaredConstructor( new Class[0] ) );
constructor.setAccessible( true );
CONSTRUCTOR_CACHE.put(type, constructor);
}
Object inst = constructor.newInstance( INITARGS );
return (T) inst;
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
throw ex;
| 409
| 302
| 711
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/bdb/DisposableStoredSortedMap.java
|
DisposableStoredSortedMap
|
dispose
|
class DisposableStoredSortedMap<K,V> extends StoredSortedMap<K,V> {
final private static Logger LOGGER =
Logger.getLogger(DisposableStoredSortedMap.class.getName());
protected Database db;
public DisposableStoredSortedMap(Database db, EntryBinding<K> arg1, EntityBinding<V> arg2, boolean arg3) {
super(db, arg1, arg2, arg3);
this.db = db;
}
public DisposableStoredSortedMap(Database db, EntryBinding<K> arg1, EntityBinding<V> arg2, PrimaryKeyAssigner arg3) {
super(db, arg1, arg2, arg3);
this.db = db;
}
public DisposableStoredSortedMap(Database db, EntryBinding<K> arg1, EntryBinding<V> arg2, boolean arg3) {
super(db, arg1, arg2, arg3);
this.db = db;
}
public DisposableStoredSortedMap(Database db, EntryBinding<K> arg1, EntryBinding<V> arg2, PrimaryKeyAssigner arg3) {
super(db, arg1, arg2, arg3);
this.db = db;
}
public void dispose() {<FILL_FUNCTION_BODY>}
}
|
String name = null;
try {
if(this.db!=null) {
name = this.db.getDatabaseName();
this.db.close();
this.db.getEnvironment().removeDatabase(null, name);
this.db = null;
}
} catch (DatabaseException e) {
LOGGER.log(Level.WARNING, "Error closing db " + name, e);
}
| 371
| 121
| 492
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/bdb/KryoBinding.java
|
KryoBinding
|
getBuffer
|
class KryoBinding<K> implements EntryBinding<K> {
protected Class<K> baseClass;
protected AutoKryo kryo = new AutoKryo();
protected ThreadLocal<WeakReference<ObjectBuffer>> threadBuffer = new ThreadLocal<WeakReference<ObjectBuffer>>() {
@Override
protected WeakReference<ObjectBuffer> initialValue() {
return new WeakReference<ObjectBuffer>(new ObjectBuffer(kryo,16*1024,Integer.MAX_VALUE));
}
};
/**
* Constructor. Save parameters locally, as superclass
* fields are private.
*
* @param baseClass is the base class for serialized objects stored using
* this binding
*/
public KryoBinding(Class<K> baseClass) {
this.baseClass = baseClass;
kryo.autoregister(baseClass);
// TODO: reevaluate if explicit registration should be required
kryo.setRegistrationOptional(true);
}
public Kryo getKryo() {
return kryo;
}
private ObjectBuffer getBuffer() {<FILL_FUNCTION_BODY>}
/**
* Copies superclass simply to allow different source for FastOoutputStream.
*
* @see com.sleepycat.bind.serial.SerialBinding#entryToObject
*/
public void objectToEntry(K object, DatabaseEntry entry) {
entry.setData(getBuffer().writeObjectData(object));
}
@Override
public K entryToObject(DatabaseEntry entry) {
return getBuffer().readObjectData(entry.getData(), baseClass);
}
}
|
WeakReference<ObjectBuffer> ref = threadBuffer.get();
ObjectBuffer ob = ref.get();
if (ob == null) {
ob = new ObjectBuffer(kryo,16*1024,Integer.MAX_VALUE);
threadBuffer.set(new WeakReference<ObjectBuffer>(ob));
}
return ob;
| 430
| 91
| 521
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/bdb/StoredQueue.java
|
StoredQueue
|
hookupDatabase
|
class StoredQueue<E extends Serializable> extends AbstractQueue<E> {
@SuppressWarnings("unused")
private static final Logger logger =
Logger.getLogger(StoredQueue.class.getName());
protected transient StoredSortedMap<Long,E> queueMap; // Long -> E
protected transient Database queueDb; // Database
protected AtomicLong tailIndex; // next spot for insert
protected transient volatile E peekItem = null;
/**
* Create a StoredQueue backed by the given Database.
*
* The Class of values to be queued may be provided; there is only a
* benefit when a primitive type is specified. A StoredClassCatalog
* must be provided if a primitive type is not supplied.
*
* @param db
* @param clsOrNull
* @param classCatalog
*/
public StoredQueue(Database db, Class<E> clsOrNull, StoredClassCatalog classCatalog) {
hookupDatabase(db, clsOrNull, classCatalog);
tailIndex = new AtomicLong(queueMap.isEmpty() ? 0L : queueMap.lastKey()+1);
}
/**
* @param db
* @param clsOrNull
* @param classCatalog
*/
public void hookupDatabase(Database db, Class<E> clsOrNull, StoredClassCatalog classCatalog) {<FILL_FUNCTION_BODY>}
@Override
public Iterator<E> iterator() {
return queueMap.values().iterator();
}
@Override
public int size() {
try {
return Math.max(0,
(int)(tailIndex.get()
- queueMap.firstKey()));
} catch (IllegalStateException ise) {
return 0;
} catch (NoSuchElementException nse) {
return 0;
} catch (NullPointerException npe) {
return 0;
}
}
@Override
public boolean isEmpty() {
if(peekItem!=null) {
return false;
}
try {
return queueMap.isEmpty();
} catch (IllegalStateException de) {
return true;
}
}
public boolean offer(E o) {
long targetIndex = tailIndex.getAndIncrement();
queueMap.put(targetIndex, o);
return true;
}
public synchronized E peek() {
if(peekItem == null) {
if(queueMap.isEmpty()) {
return null;
}
peekItem = queueMap.remove(queueMap.firstKey());
}
return peekItem;
}
public synchronized E poll() {
E head = peek();
peekItem = null;
return head;
}
/**
* A suitable DatabaseConfig for the Database backing a StoredQueue.
* (However, it is not necessary to use these config options.)
*
* @return DatabaseConfig suitable for queue
*/
public static BdbModule.BdbConfig databaseConfig() {
BdbModule.BdbConfig dbConfig = new BdbModule.BdbConfig();
dbConfig.setTransactional(false);
dbConfig.setAllowCreate(true);
return dbConfig;
}
public void close() {
try {
queueDb.sync();
queueDb.close();
} catch (DatabaseException e) {
throw new RuntimeException(e);
}
}
}
|
EntryBinding<E> valueBinding = TupleBinding.getPrimitiveBinding(clsOrNull);
if(valueBinding == null) {
valueBinding = new SerialBinding<E>(classCatalog, clsOrNull);
}
queueDb = db;
queueMap = new StoredSortedMap<Long,E>(
db,
TupleBinding.getPrimitiveBinding(Long.class),
valueBinding,
true);
| 908
| 112
| 1,020
|
<methods>public boolean add(E) ,public boolean addAll(Collection<? extends E>) ,public void clear() ,public E element() ,public E remove() <variables>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/checkpointing/Checkpoint.java
|
Checkpoint
|
saveWriter
|
class Checkpoint implements InitializingBean {
private final static Logger LOGGER =
Logger.getLogger(Checkpoint.class.getName());
/** format for serial numbers */
public static final DecimalFormat INDEX_FORMAT = new DecimalFormat("00000");
/** Name of file written with timestamp into valid checkpoints */
public static final String VALIDITY_STAMP_FILENAME = "valid";
protected String name;
protected String shortName;
protected boolean success = false;
/**
* Checkpoints directory; either an absolute path, or relative to the
* CheckpointService's checkpointsDirectory (which will be inserted as
* the COnfigPath base before the Checkpoint is consulted).
*/
protected ConfigPath checkpointDir =
new ConfigPath("checkpoint directory","");
public ConfigPath getCheckpointDir() {
return checkpointDir;
}
@Required // if used in Spring context
public void setCheckpointDir(ConfigPath checkpointsDir) {
this.checkpointDir = checkpointsDir;
}
public Checkpoint() {
}
/**
* Use immediately after instantiation to fill-in a Checkpoint
* created outside Spring configuration.
*
* @param checkpointsDir
* @param nextCheckpointNumber
* @throws IOException
*/
public void generateFrom(ConfigPath checkpointsDir, int nextCheckpointNumber) throws IOException {
getCheckpointDir().setBase(checkpointsDir);
getCheckpointDir().setPath(
"cp"
+ INDEX_FORMAT.format(nextCheckpointNumber)
+ "-"
+ ArchiveUtils.get14DigitDate());
org.archive.util.FileUtils.ensureWriteableDirectory(getCheckpointDir().getFile());
afterPropertiesSet();
}
public void afterPropertiesSet() {
name = checkpointDir.getFile().getName();
shortName = name.substring(0, name.indexOf("-"));
}
public void setSuccess(boolean b) {
success = b;
}
public boolean getSuccess() {
return success;
}
public String getName() {
return name;
}
public String getShortName() {
return shortName;
}
public void writeValidity(String stamp) {
if(!success) {
return;
}
File valid = new File(checkpointDir.getFile(), VALIDITY_STAMP_FILENAME);
try {
FileUtils.writeStringToFile(valid, stamp);
} catch (IOException e) {
valid.delete();
}
}
public void saveJson(String beanName, JSONObject json) {
try {
File targetFile = new File(getCheckpointDir().getFile(),beanName);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("saving json to " + targetFile);
}
FileUtils.writeStringToFile(
targetFile,
json.toString());
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"unable to save checkpoint JSON state of "+beanName,e);
setSuccess(false);
}
}
public JSONObject loadJson(String beanName) {
File sourceFile = new File(getCheckpointDir().getFile(),beanName);
try {
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("reading json from " + sourceFile);
}
return new JSONObject(FileUtils.readFileToString(sourceFile));
} catch (JSONException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public BufferedWriter saveWriter(String beanName, String extraName) throws IOException {<FILL_FUNCTION_BODY>}
public BufferedReader loadReader(String beanName, String extraName) throws IOException {
File sourceFile = new File(getCheckpointDir().getFile(),beanName+"-"+extraName);
return new BufferedReader(new FileReader(sourceFile));
}
public static boolean hasValidStamp(File checkpointDirectory) {
return (new File(checkpointDirectory,Checkpoint.VALIDITY_STAMP_FILENAME)).exists();
}
protected boolean forgetAllButLatest = false;
public void setForgetAllButLatest(boolean b) {
this.forgetAllButLatest = b;
}
public boolean getForgetAllButLatest() {
return forgetAllButLatest;
}
}
|
try {
File targetFile = new File(getCheckpointDir().getFile(),beanName+"-"+extraName);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("opening for writing: " + targetFile);
}
return new BufferedWriter(new FileWriter(targetFile));
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"unable to save checkpoint writer state "+extraName+" of "+beanName,e);
setSuccess(false);
throw e;
}
| 1,303
| 160
| 1,463
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/io/Arc2Warc.java
|
Arc2Warc
|
transform
|
class Arc2Warc {
protected RecordIDGenerator generator = new UUIDGenerator();
private static void usage(HelpFormatter formatter, Options options,
int exitCode) {
formatter.printHelp("java org.archive.io.arc.Arc2Warc " +
"[--force] ARC_INPUT WARC_OUTPUT", options);
System.exit(exitCode);
}
private static String getRevision() {
return Warc2Arc.parseRevision("$Revision$");
}
public void transform(final File arc, final File warc, final boolean force)
throws IOException {
FileUtils.assertReadable(arc);
if (warc.exists() && !force) {
throw new IOException("Target WARC already exists. " +
"Will not overwrite.");
}
ARCReader reader = ARCReaderFactory.get(arc, false, 0);
transform(reader, warc);
}
protected void transform(final ARCReader reader, final File warc)
throws IOException {<FILL_FUNCTION_BODY>}
protected void write(final WARCWriter writer, final ARCRecord r)
throws IOException {
WARCRecordInfo recordInfo = new WARCRecordInfo();
recordInfo.setUrl(r.getHeader().getUrl());
recordInfo.setContentStream(r);
recordInfo.setContentLength(r.getHeader().getLength());
recordInfo.setEnforceLength(true);
// convert ARC date to WARC-Date format
String arcDateString = r.getHeader().getDate();
String warcDateString = DateTimeFormat.forPattern("yyyyMMddHHmmss")
.withZone(DateTimeZone.UTC)
.parseDateTime(arcDateString)
.toString(ISODateTimeFormat.dateTimeNoMillis());
recordInfo.setCreate14DigitDate(warcDateString);
ANVLRecord ar = new ANVLRecord();
String ip = (String)r.getHeader()
.getHeaderValue((ARCConstants.IP_HEADER_FIELD_KEY));
if (ip != null && ip.length() > 0) {
ar.addLabelValue(WARCConstants.NAMED_FIELD_IP_LABEL, ip);
r.getMetaData();
}
recordInfo.setExtraHeaders(ar);
// enable reconstruction of ARC from transformed WARC
// TODO: deferred for further analysis (see HER-1750)
// ar.addLabelValue("ARC-Header-Line", r.getHeaderString());
// If contentBody > 0, assume http headers. Make the mimetype
// be application/http. Otherwise, give it ARC mimetype.
if (r.getHeader().getContentBegin() > 0) {
recordInfo.setType(WARCRecordType.response);
recordInfo.setMimetype(WARCConstants.HTTP_RESPONSE_MIMETYPE);
recordInfo.setRecordId(generator.getRecordID());
} else {
recordInfo.setType(WARCRecordType.resource);
recordInfo.setMimetype(r.getHeader().getMimetype());
recordInfo.setRecordId(((WARCWriterPoolSettings)writer.settings).getRecordIDGenerator().getRecordID());
}
writer.writeRecord(recordInfo);
}
/**
* Command-line interface to Arc2Warc.
*
* @param args Command-line arguments.
* @throws ParseException Failed parse of the command line.
* @throws IOException
* @throws java.text.ParseException
*/
@SuppressWarnings("unchecked")
public static void main(String [] args)
throws ParseException, IOException, java.text.ParseException {
Options options = new Options();
options.addOption(new Option("h","help", false,
"Prints this message and exits."));
options.addOption(new Option("f","force", false,
"Force overwrite of target file."));
PosixParser parser = new PosixParser();
CommandLine cmdline = parser.parse(options, args, false);
List<String> cmdlineArgs = cmdline.getArgList();
Option [] cmdlineOptions = cmdline.getOptions();
HelpFormatter formatter = new HelpFormatter();
// If no args, print help.
if (cmdlineArgs.size() <= 0) {
usage(formatter, options, 0);
}
// Now look at options passed.
boolean force = false;
for (int i = 0; i < cmdlineOptions.length; i++) {
switch(cmdlineOptions[i].getId()) {
case 'h':
usage(formatter, options, 0);
break;
case 'f':
force = true;
break;
default:
throw new RuntimeException("Unexpected option: " +
+ cmdlineOptions[i].getId());
}
}
// If no args, print help.
if (cmdlineArgs.size() != 2) {
usage(formatter, options, 0);
}
(new Arc2Warc()).transform(new File(cmdlineArgs.get(0)),
new File(cmdlineArgs.get(1)), force);
}
}
|
WARCWriter writer = null;
// No point digesting. Digest is available after reading of ARC which
// is too late for inclusion in WARC.
reader.setDigest(false);
try {
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream(warc));
// Get the body of the first ARC record as a String so can dump it
// into first record of WARC.
final Iterator<ArchiveRecord> i = reader.iterator();
ARCRecord firstRecord = (ARCRecord)i.next();
ByteArrayOutputStream baos =
new ByteArrayOutputStream((int)firstRecord.getHeader().
getLength());
firstRecord.dump(baos);
// Add ARC first record content as an ANVLRecord.
ANVLRecord ar = new ANVLRecord();
ar.addLabelValue("Filedesc", baos.toString());
List<String> metadata = new ArrayList<String>(1);
metadata.add(ar.toString());
// Now create the writer. If reader was compressed, lets write
// a compressed WARC.
writer = new WARCWriter(
new AtomicInteger(),
bos,
warc,
new WARCWriterPoolSettingsData(
"", "", -1, reader.isCompressed(), null, metadata, generator));
// Write a warcinfo record with description about how this WARC
// was made.
writer.writeWarcinfoRecord(warc.getName(),
"Made from " + reader.getReaderIdentifier() + " by " +
this.getClass().getName() + "/" + getRevision());
for (; i.hasNext();) {
write(writer, (ARCRecord)i.next());
}
} finally {
if (reader != null) {
reader.close();
}
if (writer != null) {
// I don't want the close being logged -- least, not w/o log of
// an opening (and that'd be a little silly for simple script
// like this). Currently, it logs at level INFO so that close
// of files gets written to log files. Up the log level just
// for the close.
Logger l = Logger.getLogger(writer.getClass().getName());
Level oldLevel = l.getLevel();
l.setLevel(Level.WARNING);
try {
writer.close();
} finally {
l.setLevel(oldLevel);
}
}
}
| 1,359
| 683
| 2,042
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/io/CrawlerJournal.java
|
CrawlerJournal
|
close
|
class CrawlerJournal implements Closeable {
private static final Logger LOGGER = Logger.getLogger(
CrawlerJournal.class.getName());
/** prefix for error lines*/
public static final String LOG_ERROR = "E ";
/** prefix for timestamp lines */
public static final String LOG_TIMESTAMP = "T ";
/**
* Stream on which we record frontier events.
*/
protected Writer out = null;
/** line count */
protected long lines = 0;
/** number of lines between timestamps */
protected int timestamp_interval = 0; // 0 means no timestamps
/**
* File we're writing journal to.
* Keep a reference in case we want to rotate it off.
*/
protected File gzipFile = null;
/**
* Create a new crawler journal at the given location
*
* @param path Directory to make thejournal in.
* @param filename Name to use for journal file.
* @throws IOException
*/
public CrawlerJournal(String path, String filename)
throws IOException {
this.gzipFile = new File(path, filename);
this.out = initialize(gzipFile);
}
/**
* Create a new crawler journal at the given location
*
* @param file path at which to make journal
* @throws IOException
*/
public CrawlerJournal(File file) throws IOException {
this.gzipFile = file;
this.out = initialize(gzipFile);
}
protected Writer initialize(final File f) throws FileNotFoundException, IOException {
FileUtils.moveAsideIfExists(f);
return new OutputStreamWriter(new GZIPOutputStream(
new FastBufferedOutputStream(new FileOutputStream(f),32*1024)));
}
/**
* Write a line
* @param strs
*/
public synchronized void writeLine(String... strs) {
try {
for(String s : strs) {
this.out.write(s);
}
this.out.write("\n");
noteLine();
} catch (IOException e) {
LOGGER.log(
Level.SEVERE,
"problem writing journal line: "+StringUtils.join(strs),
e);
}
}
/**
* Count and note a line
*
* @throws IOException
*/
protected void noteLine() throws IOException {
lines++;
considerTimestamp();
}
/**
* Write a timestamp line if appropriate
*
* @throws IOException
*/
protected void considerTimestamp() throws IOException {
if(timestamp_interval > 0 && lines % timestamp_interval == 0) {
out.write(LOG_TIMESTAMP);
out.write(ArchiveUtils.getLog14Date());
out.write("\n");
}
}
/**
* Flush and close the underlying IO objects.
*/
public void close() {<FILL_FUNCTION_BODY>}
/**
* Note a serious error vioa a special log line
*
* @param err
*/
public synchronized void seriousError(String err) {
writeLine(LOG_ERROR+ArchiveUtils.getLog14Date()+" "+err+"\n");
}
/**
* Handle a checkpoint by rotating the current log to a checkpoint-named
* file and starting a new log.
*/
public synchronized void rotateForCheckpoint(Checkpoint checkpointInProgress) {
if (this.out == null || !this.gzipFile.exists()) {
return;
}
close();
File newName = new File(this.gzipFile.getParentFile(),
this.gzipFile.getName() + "." + checkpointInProgress.getName());
try {
FileUtils.moveAsideIfExists(newName);
if (checkpointInProgress.getForgetAllButLatest()) {
// merge any earlier checkpointed files into new checkpoint
// file, taking advantage of the legality of concatenating gzips
File[] oldCheckpointeds = this.gzipFile.getParentFile().listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
String regex = "^" + Pattern.quote(gzipFile.getName()) + "\\.cp\\d{5}-\\d{14}$";
return TextUtils.matches(regex, name);
}
});
Arrays.sort(oldCheckpointeds);
for (int i = 1; i < oldCheckpointeds.length; i++) {
FileUtils.appendTo(oldCheckpointeds[0], oldCheckpointeds[i]);
oldCheckpointeds[i].delete();
}
if (oldCheckpointeds.length > 0) {
FileUtils.appendTo(oldCheckpointeds[0], this.gzipFile);
this.gzipFile.delete();
oldCheckpointeds[0].renameTo(newName);
} else {
this.gzipFile.renameTo(newName);
}
} else {
this.gzipFile.renameTo(newName);
}
// Open new gzip file.
this.out = initialize(this.gzipFile);
} catch (IOException ioe) {
LOGGER.log(Level.SEVERE,"Problem rotating recovery journal", ioe);
}
}
}
|
if (this.out == null) {
return;
}
try {
this.out.flush();
this.out.close();
this.out = null;
} catch (IOException e) {
LOGGER.log(Level.SEVERE,"problem closing journal", e);
}
| 1,402
| 80
| 1,482
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/io/Warc2Arc.java
|
Warc2Arc
|
transform
|
class Warc2Arc {
private static void usage(HelpFormatter formatter, Options options,
int exitCode) {
formatter.printHelp("java org.archive.io.arc.Warc2Arc " +
"[--force] [--prefix=PREFIX] [--suffix=SUFFIX] WARC_INPUT " +
"OUTPUT_DIR",
options);
System.exit(exitCode);
}
protected static String parseRevision(final String version) {
final String ID = "$Revision: ";
int index = version.indexOf(ID);
return (index < 0)? version:
version.substring(index + ID.length(), version.length() - 1).trim();
}
private static String getRevision() {
return parseRevision("$Revision$");
}
public void transform(final File warc, final File dir, final String prefix,
final String suffix, final boolean force)
throws IOException, java.text.ParseException {<FILL_FUNCTION_BODY>}
protected void transform(final WARCReader reader, final ARCWriter writer)
throws IOException, java.text.ParseException {
// No point digesting. Digest is available after reading of ARC which
// is too late for inclusion in WARC.
reader.setDigest(false);
// I don't want the close being logged -- least, not w/o log of
// an opening (and that'd be a little silly for simple script
// like this). Currently, it logs at level INFO so that close
// of files gets written to log files. Up the log level just
// for the close.
Logger l = Logger.getLogger(writer.getClass().getName());
Level oldLevel = l.getLevel();
try {
l.setLevel(Level.WARNING);
for (final Iterator<ArchiveRecord> i = reader.iterator(); i.hasNext();) {
WARCRecord r = (WARCRecord)i.next();
if (!isARCType(r.getHeader().getMimetype())) {
continue;
}
if (r.getHeader().getContentBegin() <= 0) {
// Otherwise, because length include Header-Line and
// Named Fields, these will end up in the ARC unless there
// is a non-zero content begin.
continue;
}
String ip = (String)r.getHeader().
getHeaderValue((WARCConstants.HEADER_KEY_IP));
long length = r.getHeader().getLength();
int offset = r.getHeader().getContentBegin();
// This mimetype is not exactly what you'd expect to find in
// an ARC though technically its 'correct'. To get right one,
// need to parse the HTTP Headers. That's messy. Not doing for
// now.
String mimetype = r.getHeader().getMimetype();
// Clean out ISO time string '-', 'T', ':', and 'Z' characters.
String t = r.getHeader().getDate().replaceAll("[-T:Z]", "");
long time = ArchiveUtils.getSecondsSinceEpoch(t).getTime();
writer.write(r.getHeader().getUrl(), mimetype, ip, time,
(int)(length - offset), r);
}
} finally {
if (reader != null) {
reader.close();
}
if (writer != null) {
try {
writer.close();
} finally {
l.setLevel(oldLevel);
}
}
}
}
protected boolean isARCType(final String mimetype) {
// Comparing mimetypes, especially WARC types can be problematic since
// they have whitespace. For now, ignore.
if (mimetype == null || mimetype.length() <= 0) {
return false;
}
String cleaned = mimetype.toLowerCase().trim();
if (cleaned.equals(WARCConstants.HTTP_RESPONSE_MIMETYPE) ||
cleaned.equals("text/dns")) {
return true;
}
return false;
}
/**
* Command-line interface to Arc2Warc.
*
* @param args Command-line arguments.
* @throws ParseException Failed parse of the command line.
* @throws IOException
* @throws java.text.ParseException
*/
public static void main(String [] args)
throws ParseException, IOException, java.text.ParseException {
Options options = new Options();
options.addOption(new Option("h","help", false,
"Prints this message and exits."));
options.addOption(new Option("f","force", false,
"Force overwrite of target file."));
options.addOption(new Option("p","prefix", true,
"Prefix to use on created ARC files, else uses default."));
options.addOption(new Option("s","suffix", true,
"Suffix to use on created ARC files, else uses default."));
PosixParser parser = new PosixParser();
CommandLine cmdline = parser.parse(options, args, false);
@SuppressWarnings("unchecked")
List<String> cmdlineArgs = cmdline.getArgList();
Option [] cmdlineOptions = cmdline.getOptions();
HelpFormatter formatter = new HelpFormatter();
// If no args, print help.
if (cmdlineArgs.size() < 0) {
usage(formatter, options, 0);
}
// Now look at options passed.
boolean force = false;
String prefix = "WARC2ARC";
String suffix = null;
for (int i = 0; i < cmdlineOptions.length; i++) {
switch(cmdlineOptions[i].getId()) {
case 'h':
usage(formatter, options, 0);
break;
case 'f':
force = true;
break;
case 'p':
prefix = cmdlineOptions[i].getValue();
break;
case 's':
suffix = cmdlineOptions[i].getValue();
break;
default:
throw new RuntimeException("Unexpected option: " +
+ cmdlineOptions[i].getId());
}
}
// If no args, print help.
if (cmdlineArgs.size() != 2) {
usage(formatter, options, 0);
}
(new Warc2Arc()).transform(new File(cmdlineArgs.get(0).toString()),
new File(cmdlineArgs.get(1).toString()), prefix, suffix, force);
}
}
|
FileUtils.assertReadable(warc);
FileUtils.assertReadable(dir);
WARCReader reader = WARCReaderFactory.get(warc);
List<String> metadata = new ArrayList<String>();
metadata.add("Made from " + reader.getReaderIdentifier() + " by " +
this.getClass().getName() + "/" + getRevision());
ARCWriter writer =
new ARCWriter(
new AtomicInteger(),
new WriterPoolSettingsData(
prefix,
suffix,
-12,
reader.isCompressed(),
Arrays.asList(new File [] {dir}),
metadata));
transform(reader, writer);
| 1,719
| 181
| 1,900
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/net/ClientFTP.java
|
ClientFTP
|
disconnect
|
class ClientFTP extends FTPClient implements ProtocolCommandListener {
private final Logger logger = Logger.getLogger(this.getClass().getName());
// Records the conversation on the ftp control channel. The format is based on "curl -v".
protected StringBuilder controlConversation;
protected Socket dataSocket;
/**
* Constructs a new <code>ClientFTP</code>.
*/
public ClientFTP() {
controlConversation = new StringBuilder();
addProtocolCommandListener(this);
}
/**
* Opens a data connection.
*
* @param command
* the data command (eg, RETR or LIST)
* @param path
* the path of the file to retrieve
* @return the socket to read data from, or null if server says not found,
* permission denied, etc
* @throws IOException
* if a network error occurs
*/
public Socket openDataConnection(int command, String path)
throws IOException {
try {
dataSocket = _openDataConnection_(command, path);
if (dataSocket != null) {
recordAdditionalInfo("Opened data connection to "
+ dataSocket.getInetAddress().getHostAddress() + ":"
+ dataSocket.getPort());
}
return dataSocket;
} catch (IOException e) {
if (getPassiveHost() != null) {
recordAdditionalInfo("Failed to open data connection to "
+ getPassiveHost() + ":" + getPassivePort() + ": "
+ e.getMessage());
} else {
recordAdditionalInfo("Failed to open data connection: "
+ e.getMessage());
}
throw e;
}
}
public void closeDataConnection() {
if (dataSocket != null) {
String dataHostPort = dataSocket.getInetAddress().getHostAddress()
+ ":" + dataSocket.getPort();
try {
dataSocket.close();
recordAdditionalInfo("Closed data connection to "
+ dataHostPort);
} catch (IOException e) {
recordAdditionalInfo("Problem closing data connection to "
+ dataHostPort + ": " + e.getMessage());
}
}
}
protected void _connectAction_() throws IOException {
try {
recordAdditionalInfo("Opening control connection to "
+ getRemoteAddress().getHostAddress() + ":"
+ getRemotePort());
super._connectAction_();
} catch (IOException e) {
recordAdditionalInfo("Failed to open control connection to "
+ getRemoteAddress().getHostAddress() + ":"
+ getRemotePort() + ": " + e.getMessage());
throw e;
}
}
public void disconnect() throws IOException {<FILL_FUNCTION_BODY>}
public String getControlConversation() {
return controlConversation.toString();
}
protected void recordControlMessage(String linePrefix, String message) {
for (String line: new IterableLineIterator(new StringReader(message))) {
controlConversation.append(linePrefix);
controlConversation.append(line);
controlConversation.append(NETASCII_EOL);
if (logger.isLoggable(Level.FINEST)) {
logger.finest(linePrefix + line);
}
}
}
public void protocolCommandSent(ProtocolCommandEvent event) {
recordControlMessage("> ", event.getMessage());
}
public void protocolReplyReceived(ProtocolCommandEvent event) {
recordControlMessage("< ", event.getMessage());
}
// for noting things like successful/unsuccessful connection to data port
private void recordAdditionalInfo(String message) {
recordControlMessage("* ", message);
}
// XXX see https://issues.apache.org/jira/browse/NET-257
@Override
public String[] getReplyStrings() {
return _replyLines.toArray(new String[0]);
}
}
|
String remoteHostPort = getRemoteAddress().getHostAddress() + ":"
+ getRemotePort();
super.disconnect();
recordAdditionalInfo("Closed control connection to " + remoteHostPort);
| 1,015
| 52
| 1,067
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/net/ClientSFTP.java
|
ClientSFTP
|
getLsFileMap
|
class ClientSFTP {
private final Logger logger = Logger.getLogger(getClass().getName());
protected StringBuilder controlConversation;
protected Socket dataSocket;
protected Session session = null;
protected Channel channel = null;
protected ChannelSftp channelSFTP = null;
public ClientSFTP() {
this.controlConversation = new StringBuilder();
this.logger.setUseParentHandlers(true);
}
public String getControlConversation() {
return this.controlConversation.toString();
}
public void connect(String username, String host, int port, String password) throws SocketException, IOException {
JSch jSch = new JSch();
try {
session = jSch.getSession(username, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();
this.logger.info("Connected to SFTP server " + host + ":" + port);
this.controlConversation.append("Connected to SFTP server " + host + ":" + port);
} catch (Exception exception) {
this.logger.info("Unable to connect to SFTP server : " + exception.toString());
this.controlConversation.append("Unable to connect to SFTP server : " + exception.toString());
session.disconnect();
}
}
public ChannelSftp openSFTPChannel() throws JSchException {
channel = session.openChannel("sftp");
channel.connect();
channelSFTP = (ChannelSftp) channel;
this.logger.info("*** SFTP Channel created. ***");
boolean bool = channelSFTP.isConnected();
if (bool)
this.logger.info("channelSftp connected ");
return channelSFTP;
}
public boolean isConnected() {
if (channelSFTP != null) {
return channelSFTP.isConnected();
}
return false;
}
public ChannelSftp getChannelSftp() {
return channelSFTP;
}
public void exit() {
session.disconnect();
}
public boolean isDirectory(String paramString) throws Exception {
SftpATTRS sftpATTRS = channelSFTP.stat(paramString);
return sftpATTRS.isDir();
}
public void disconnect() {
if (channelSFTP != null) {
channelSFTP.exit();
this.logger.info("channelSftp exit....");
}
if (session != null) {
session.disconnect();
this.logger.info("session disconnect....");
}
channelSFTP = null;
}
@SuppressWarnings("unchecked")
public Map<String, Boolean> getLsFileMap(String paramString) throws Exception {<FILL_FUNCTION_BODY>}
protected boolean mkdir(String paramString) throws Exception {
this.logger.info("channelSftp mkdir: " + paramString);
channelSFTP.mkdir(paramString);
return true;
}
public boolean cd(String paramString) throws Exception {
this.logger.info("channelSftp cd : " + paramString);
channelSFTP.cd(paramString);
return true;
}
protected boolean put(FileInputStream paramFileInputStream, String paramString) throws Exception {
this.logger.info("channelSftp put: " + paramString);
channelSFTP.put(paramFileInputStream, paramString);
return true;
}
protected boolean downRemoteSingleFile(String src, String dest) throws Exception {
FileOutputStream fileOutputStream = new FileOutputStream(dest);
channelSFTP.get(src, fileOutputStream);
this.logger.info("channelSftp download file: " + src);
return true;
}
protected boolean rm(String paramString) throws Exception {
channelSFTP.rm(paramString);
return true;
}
}
|
Map<String, Boolean> hashMap = new HashMap<>();
Vector<ChannelSftp.LsEntry> vector = channelSFTP.ls(paramString);
for(ChannelSftp.LsEntry lsEntry : vector) {
String str = lsEntry.getFilename();
if (!".".equals(str)) {
if (!"..".equals(str)) {
String str1 = paramString + "/" + str;
boolean bool = isDirectory(str1);
this.logger.info("fileName : " + str);
hashMap.put(str, Boolean.valueOf(bool));
}
}
}
return hashMap;
| 1,004
| 177
| 1,181
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/net/UURI.java
|
UURI
|
readObjectData
|
class UURI extends UsableURI implements CustomSerialization {
private static final long serialVersionUID = -8946640480772772310L;
public UURI(String fixup, boolean b, String charset) throws URIException {
super(fixup, b, charset);
}
public UURI(UsableURI base, UsableURI relative) throws URIException {
super(base, relative);
}
/* needed for kryo serialization */
protected UURI() {
super();
}
@Override
public void writeObjectData(Kryo kryo, ByteBuffer buffer) {
StringSerializer.put(buffer, toCustomString());
}
@Override
public void readObjectData(Kryo kryo, ByteBuffer buffer) {<FILL_FUNCTION_BODY>}
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.writeUTF(toCustomString());
}
private void readObject(ObjectInputStream stream) throws IOException,
ClassNotFoundException {
parseUriReference(stream.readUTF(), true);
}
}
|
try {
parseUriReference(StringSerializer.get(buffer), true);
} catch (URIException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
| 286
| 52
| 338
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/net/UURIFactory.java
|
UURIFactory
|
makeOne
|
class UURIFactory extends UsableURIFactory {
private static final long serialVersionUID = -7969477276065915936L;
/**
* The single instance of this factory.
*/
private static final UURIFactory factory = new UURIFactory();
/**
* @param uri URI as string.
* @return An instance of UURI
* @throws URIException
*/
public static UURI getInstance(String uri) throws URIException {
return (UURI) UURIFactory.factory.create(uri);
}
/**
* @param base Base uri to use resolving passed relative uri.
* @param relative URI as string.
* @return An instance of UURI
* @throws URIException
*/
public static UURI getInstance(UURI base, String relative)
throws URIException {
return (UURI) UURIFactory.factory.create(base, relative);
}
@Override
protected UURI makeOne(String fixedUpUri, boolean escaped, String charset)
throws URIException {
return new UURI(fixedUpUri, escaped, charset);
}
@Override
protected UsableURI makeOne(UsableURI base, UsableURI relative) throws URIException {<FILL_FUNCTION_BODY>}
}
|
// return new UURI(base, relative);
return new UURI(base, relative);
| 340
| 26
| 366
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/spring/BeanFieldsPatternValidator.java
|
PropertyPatternRule
|
test
|
class PropertyPatternRule {
protected String propertyName;
protected Pattern requiredPattern;
protected String errorMessage;
public PropertyPatternRule(String name, String pat, String msg) {
propertyName = name;
requiredPattern = Pattern.compile(pat);
errorMessage = msg.replace("@@", pat);
}
public void test(BeanWrapperImpl wrapper, Errors errors) {<FILL_FUNCTION_BODY>}
}
|
Matcher m = requiredPattern.matcher(
(CharSequence)wrapper.getPropertyValue(propertyName));
if(!m.matches()) {
errors.rejectValue(propertyName, null, errorMessage);
}
| 124
| 65
| 189
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/spring/ConfigFile.java
|
ConfigFile
|
obtainWriter
|
class ConfigFile extends ConfigPath implements ReadSource, WriteTarget {
private static final long serialVersionUID = 1L;
public ConfigFile() {
super();
}
public ConfigFile(String name, String path) {
super(name, path);
}
public Reader obtainReader() {
try {
if(!getFile().exists()) {
getFile().createNewFile();
}
if (configurer != null) {
configurer.snapshotToLaunchDir(getFile());
}
return new InputStreamReader(
new FileInputStream(getFile()),
"UTF-8");
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public Writer obtainWriter() {
return obtainWriter(false);
}
public Writer obtainWriter(boolean append) {<FILL_FUNCTION_BODY>}
}
|
try {
return new OutputStreamWriter(
new FileOutputStream(getFile(), append),
"UTF-8");
} catch (IOException e) {
throw new RuntimeException(e);
}
| 268
| 62
| 330
|
<methods>public void <init>() ,public void <init>(java.lang.String, java.lang.String) ,public org.archive.spring.ConfigPath getBase() ,public java.io.File getFile() ,public java.lang.String getName() ,public java.lang.String getPath() ,public org.archive.spring.ConfigPath merge(org.archive.spring.ConfigPath) ,public void setBase(org.archive.spring.ConfigPath) ,public void setConfigurer(org.archive.spring.ConfigPathConfigurer) ,public void setName(java.lang.String) ,public void setPath(java.lang.String) <variables>protected org.archive.spring.ConfigPath base,protected org.archive.spring.ConfigPathConfigurer configurer,protected java.lang.String name,protected java.lang.String path,private static final long serialVersionUID
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/spring/ConfigPath.java
|
ConfigPath
|
getFile
|
class ConfigPath implements Serializable {
private static final long serialVersionUID = 1L;
protected String name;
protected String path;
protected ConfigPath base;
public ConfigPath() {
super();
}
public ConfigPath(String name, String path) {
super();
this.name = name;
this.path = path;
}
public ConfigPath getBase() {
return base;
}
public void setBase(ConfigPath base) {
this.base = base;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPath() {
return path;
}
@Required
public void setPath(String path) {
this.path = path;
}
public File getFile() {<FILL_FUNCTION_BODY>}
/**
* To maintain ConfigPath's 'base' and object-identity, this merge
* should be used to updated ConfigPath properties in other beans,
* rather than discarding the old value.
*
* @param newvals ConfigPath to merge into this one
* @return this
*/
public ConfigPath merge(ConfigPath newvals) {
if(newvals.name!=null) {
setName(newvals.getName());
}
if(newvals.path!=null) {
setPath(newvals.getPath());
}
return this;
}
protected ConfigPathConfigurer configurer;
public void setConfigurer(ConfigPathConfigurer configPathConfigurer) {
this.configurer = configPathConfigurer;
}
}
|
String interpolatedPath;
if (configurer != null) {
interpolatedPath = configurer.interpolate(path);
} else {
interpolatedPath = path;
}
return base == null || interpolatedPath.startsWith("/")
? new File(interpolatedPath)
: new File(base.getFile(), interpolatedPath);
| 521
| 108
| 629
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/spring/ConfigPathConfigurer.java
|
ConfigPathConfigurer
|
fixupPaths
|
class ConfigPathConfigurer
implements
BeanPostProcessor,
ApplicationListener<ApplicationEvent>,
ApplicationContextAware,
Ordered {
private static final Logger logger =
Logger.getLogger(ConfigPathConfigurer.class.getName());
protected Map<String,Object> allBeans = new HashMap<String,Object>();
//// BEAN PROPERTIES
/** 'home' directory for all other paths to be resolved
* relative to; defaults to directory of primary XML config file */
protected ConfigPath path;
public ConfigPath getPath() {
return path;
}
//// BEANPOSTPROCESSOR IMPLEMENTATION
/**
* Remember all beans for later fixup.
* @see org.springframework.beans.factory.config.BeanPostProcessor#postProcessAfterInitialization(java.lang.Object, java.lang.String)
*/
public Object postProcessAfterInitialization(Object bean, String beanName)
throws BeansException {
allBeans.put(beanName,bean);
return bean;
}
// APPLICATIONLISTENER IMPLEMENTATION
/**
* Fix all beans with ConfigPath properties that lack a base path
* or a name, to use a job-implied base path and name.
*/
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof ContextRefreshedEvent) {
for(String beanName: allBeans.keySet()) {
fixupPaths(allBeans.get(beanName), beanName);
}
allBeans.clear(); // forget
}
// ignore all others
}
/**
* Find any ConfigPath properties in the passed bean; ensure that
* if they have a null 'base', that is replaced with the job home
* directory. Also, remember all ConfigPaths so fixed-up for later
* reference.
*
* @param bean
* @param beanName
* @return Same bean as passed in, fixed as necessary
*/
protected Object fixupPaths(Object bean, String beanName) {<FILL_FUNCTION_BODY>}
protected void fixupConfigPath(ConfigPath cp, String patchName) {
if(cp.getBase()==null && cp != path) {
cp.setBase(path);
}
if(StringUtils.isEmpty(cp.getName())) {
cp.setName(patchName);
}
cp.setConfigurer(this);
remember(patchName, cp);
}
//// APPLICATIONCONTEXTAWARE IMPLEMENTATION
protected PathSharingContext appCtx;
/**
* Remember ApplicationContext, and if possible primary
* configuration file's home directory.
*
* Requires appCtx be a PathSharingContext
*
* @see org.springframework.context.ApplicationContextAware#setApplicationContext(org.springframework.context.ApplicationContext)
*/
public void setApplicationContext(ApplicationContext appCtx) throws BeansException {
this.appCtx = (PathSharingContext)appCtx;
String basePath;
if(appCtx instanceof PathSharingContext) {
basePath = this.appCtx.getConfigurationFile().getParent();
} else {
basePath = ".";
}
path = new ConfigPath("job base",basePath);
path.setConfigurer(this);
}
// REMEMBERED CONFIGPATHS
protected Map<String,ConfigPath> allConfigPaths = new HashMap<String,ConfigPath>();
protected void remember(String key, ConfigPath cp) {
allConfigPaths.put(key, cp);
}
public Map<String,ConfigPath> getAllConfigPaths() {
return allConfigPaths;
}
// noop
public Object postProcessBeforeInitialization(Object bean, String beanName)
throws BeansException {
return bean;
}
/**
* Act as late as possible.
*
* @see org.springframework.core.Ordered#getOrder()
*/
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
public void snapshotToLaunchDir(File readFile) throws IOException {
if(appCtx.getCurrentLaunchDir()==null|| !appCtx.getCurrentLaunchDir().exists()) {
logger.log(Level.WARNING, "launch directory unavailable to snapshot "+readFile);
return;
}
FileUtils.copyFileToDirectory(readFile, appCtx.getCurrentLaunchDir());
}
protected String interpolate(String rawPath) {
if (appCtx.getCurrentLaunchId() != null) {
return rawPath.replace("${launchId}", appCtx.getCurrentLaunchId());
} else {
return rawPath;
}
}
}
|
BeanWrapperImpl wrapper = new BeanWrapperImpl(bean);
for(PropertyDescriptor d : wrapper.getPropertyDescriptors()) {
if (d.getPropertyType().isAssignableFrom(ConfigPath.class)
|| d.getPropertyType().isAssignableFrom(ConfigFile.class)) {
Object value = wrapper.getPropertyValue(d.getName());
if (value != null && value instanceof ConfigPath) {
String patchName = beanName+"."+d.getName();
fixupConfigPath((ConfigPath) value,patchName);
}
} else if (Iterable.class.isAssignableFrom(d.getPropertyType())) {
Iterable<?> iterable = (Iterable<?>) wrapper.getPropertyValue(d.getName());
if (iterable != null) {
int i = 0;
for (Object candidate : iterable) {
if(candidate!=null && candidate instanceof ConfigPath) {
String patchName = beanName+"."+d.getName()+"["+i+"]";
fixupConfigPath((ConfigPath) candidate,patchName);
}
i++;
}
}
}
}
return bean;
| 1,391
| 329
| 1,720
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/spring/HeritrixLifecycleProcessor.java
|
HeritrixLifecycleProcessor
|
onRefresh
|
class HeritrixLifecycleProcessor extends DefaultLifecycleProcessor implements BeanNameAware {
protected String name;
@Override
public void onRefresh() {<FILL_FUNCTION_BODY>}
@Override
public void setBeanName(String name) {
this.name = name;
}
public String getBeanName() {
return name;
}
}
|
// do nothing: we do not want to auto-start
| 106
| 17
| 123
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/spring/KeyedProperties.java
|
KeyedProperties
|
withOverridesDo
|
class KeyedProperties extends ConcurrentSkipListMap<String,Object> {
private static final long serialVersionUID = 2L;
private static final Logger logger = Logger.getLogger(KeyedProperties.class.getName());
/** the alternate global property-paths leading to this map
* TODO: consider if deterministic ordered list is important */
protected TreeSet<String> externalPaths = new TreeSet<String>();
/**
* Add a path by which the outside world can reach this map
* @param path String path
*/
public void addExternalPath(String path) {
externalPaths.add(path);
}
/**
* Get the given value, checking override maps if appropriate.
*
* @param key
* @return discovered override, or local value
*/
public Object get(String key) {
ArrayList<OverlayContext> overlays = threadOverrides.get();
for(int i = overlays.size()-1; i>=0; i--) {
OverlayContext ocontext = overlays.get(i);
for(int j = ocontext.getOverlayNames().size()-1; j>=0; j--) {
String name = ocontext.getOverlayNames().get(j);
Map<String,Object> m = ocontext.getOverlayMap(name);
if (m != null) {
for(String ok : getOverrideKeys(key)) {
Object val = m.get(ok);
if(val!=null) {
return val;
}
}
} else {
logger.warning("sheet '" + name + "' should apply but there is no such sheet!");
}
}
}
return super.get(key);
}
/**
* Compose the complete keys (externalPath + local key name) to use
* for checking for contextual overrides.
*
* @param key local key to compose
* @return List of full keys to check
*/
protected List<String> getOverrideKeys(String key) {
ArrayList<String> keys = new ArrayList<String>(externalPaths.size());
for(String path : externalPaths) {
keys.add(path+"."+key);
}
return keys;
}
//
// CLASS SERVICES
//
/**
* ThreadLocal (contextual) collection of pushed override maps
*/
protected static ThreadLocal<ArrayList<OverlayContext>> threadOverrides =
new ThreadLocal<ArrayList<OverlayContext>>() {
protected ArrayList<OverlayContext> initialValue() {
return new ArrayList<OverlayContext>();
}
};
/**
* Add an override map to the stack
*/
static public void pushOverrideContext(OverlayContext ocontext) {
threadOverrides.get().add(ocontext);
}
/**
* Remove last-added override map from the stack
* @return Map removed
*/
static public OverlayContext popOverridesContext() {
// TODO maybe check that pop is as expected
return threadOverrides.get().remove(threadOverrides.get().size()-1);
}
static public void clearAllOverrideContexts() {
threadOverrides.get().clear();
}
static public void loadOverridesFrom(OverlayContext ocontext) {
assert ocontext.haveOverlayNamesBeenSet();
pushOverrideContext(ocontext);
}
static public boolean clearOverridesFrom(OverlayContext ocontext) {
return threadOverrides.get().remove(ocontext);
}
static public void withOverridesDo(OverlayContext ocontext, Runnable todo) {<FILL_FUNCTION_BODY>}
public static boolean overridesActiveFrom(OverlayContext ocontext) {
return threadOverrides.get().contains(ocontext);
}
}
|
try {
loadOverridesFrom(ocontext);
todo.run();
} finally {
clearOverridesFrom(ocontext);
}
| 1,101
| 53
| 1,154
|
<methods>public void <init>() ,public void <init>(Comparator<? super java.lang.String>) ,public void <init>(Map<? extends java.lang.String,? extends java.lang.Object>) ,public void <init>(SortedMap<java.lang.String,? extends java.lang.Object>) ,public Entry<java.lang.String,java.lang.Object> ceilingEntry(java.lang.String) ,public java.lang.String ceilingKey(java.lang.String) ,public void clear() ,public ConcurrentSkipListMap<java.lang.String,java.lang.Object> clone() ,public Comparator<? super java.lang.String> comparator() ,public java.lang.Object compute(java.lang.String, BiFunction<? super java.lang.String,? super java.lang.Object,? extends java.lang.Object>) ,public java.lang.Object computeIfAbsent(java.lang.String, Function<? super java.lang.String,? extends java.lang.Object>) ,public java.lang.Object computeIfPresent(java.lang.String, BiFunction<? super java.lang.String,? super java.lang.Object,? extends java.lang.Object>) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public NavigableSet<java.lang.String> descendingKeySet() ,public ConcurrentNavigableMap<java.lang.String,java.lang.Object> descendingMap() ,public Set<Entry<java.lang.String,java.lang.Object>> entrySet() ,public boolean equals(java.lang.Object) ,public Entry<java.lang.String,java.lang.Object> firstEntry() ,public java.lang.String firstKey() ,public Entry<java.lang.String,java.lang.Object> floorEntry(java.lang.String) ,public java.lang.String floorKey(java.lang.String) ,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 ConcurrentNavigableMap<java.lang.String,java.lang.Object> headMap(java.lang.String) ,public ConcurrentNavigableMap<java.lang.String,java.lang.Object> headMap(java.lang.String, boolean) ,public Entry<java.lang.String,java.lang.Object> higherEntry(java.lang.String) ,public java.lang.String higherKey(java.lang.String) ,public boolean isEmpty() ,public NavigableSet<java.lang.String> keySet() ,public Entry<java.lang.String,java.lang.Object> lastEntry() ,public java.lang.String lastKey() ,public Entry<java.lang.String,java.lang.Object> lowerEntry(java.lang.String) ,public java.lang.String lowerKey(java.lang.String) ,public java.lang.Object merge(java.lang.String, java.lang.Object, BiFunction<? super java.lang.Object,? super java.lang.Object,? extends java.lang.Object>) ,public NavigableSet<java.lang.String> navigableKeySet() ,public Entry<java.lang.String,java.lang.Object> pollFirstEntry() ,public Entry<java.lang.String,java.lang.Object> pollLastEntry() ,public java.lang.Object put(java.lang.String, java.lang.Object) ,public java.lang.Object putIfAbsent(java.lang.String, java.lang.Object) ,public java.lang.Object remove(java.lang.Object) ,public boolean remove(java.lang.Object, java.lang.Object) ,public java.lang.Object replace(java.lang.String, java.lang.Object) ,public boolean replace(java.lang.String, java.lang.Object, java.lang.Object) ,public void replaceAll(BiFunction<? super java.lang.String,? super java.lang.Object,? extends java.lang.Object>) ,public int size() ,public ConcurrentNavigableMap<java.lang.String,java.lang.Object> subMap(java.lang.String, java.lang.String) ,public ConcurrentNavigableMap<java.lang.String,java.lang.Object> subMap(java.lang.String, boolean, java.lang.String, boolean) ,public ConcurrentNavigableMap<java.lang.String,java.lang.Object> tailMap(java.lang.String) ,public ConcurrentNavigableMap<java.lang.String,java.lang.Object> tailMap(java.lang.String, boolean) ,public Collection<java.lang.Object> values() <variables>private static final java.lang.invoke.VarHandle ADDER,private static final int EQ,private static final int GT,private static final java.lang.invoke.VarHandle HEAD,private static final int LT,private static final java.lang.invoke.VarHandle NEXT,private static final java.lang.invoke.VarHandle RIGHT,private static final java.lang.invoke.VarHandle VAL,private transient java.util.concurrent.atomic.LongAdder adder,final Comparator<? super java.lang.String> comparator,private transient SubMap<java.lang.String,java.lang.Object> descendingMap,private transient EntrySet<java.lang.String,java.lang.Object> entrySet,private transient Index<java.lang.String,java.lang.Object> head,private transient KeySet<java.lang.String,java.lang.Object> keySet,private static final long serialVersionUID,private transient Values<java.lang.String,java.lang.Object> values
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/spring/PathSharingContext.java
|
PathSharingContext
|
getConfigurationFile
|
class PathSharingContext extends FileSystemXmlApplicationContext {
private static Logger LOGGER =
Logger.getLogger(PathSharingContext.class.getName());
public PathSharingContext(String configLocation) throws BeansException {
super(configLocation);
}
public PathSharingContext(String[] configLocations, ApplicationContext parent) throws BeansException {
super(configLocations, parent);
}
public PathSharingContext(String[] configLocations, boolean refresh, ApplicationContext parent) throws BeansException {
super(configLocations, refresh, parent);
}
public PathSharingContext(String[] configLocations, boolean refresh) throws BeansException {
super(configLocations, refresh);
}
public PathSharingContext(String[] configLocations) throws BeansException {
super(configLocations);
}
public String getPrimaryConfigurationPath() {
return getConfigLocations()[0];
}
//
// Cascading self-validation
//
protected HashMap<String,Errors> allErrors; // bean name -> Errors
public void validate() {
allErrors = new HashMap<String,Errors>();
for(Entry<String, HasValidator> entry : getBeansOfType(HasValidator.class).entrySet()) {
String name = entry.getKey();
HasValidator hv = entry.getValue();
Validator v = hv.getValidator();
Errors errors = new BeanPropertyBindingResult(hv,name);
v.validate(hv, errors);
if(errors.hasErrors()) {
allErrors.put(name,errors);
}
}
for(String name : allErrors.keySet()) {
for(Object obj : allErrors.get(name).getAllErrors()) {
LOGGER.fine("validation error for '"+name+"': "+obj);
}
}
}
@Override
public void start() {
initLaunchDir();
super.start();
}
public HashMap<String,Errors> getAllErrors() {
return allErrors;
}
protected transient String currentLaunchId;
protected void initLaunchId() {
currentLaunchId = ArchiveUtils.getUnique14DigitDate();
LOGGER.info("launch id " + currentLaunchId);
}
public String getCurrentLaunchId() {
return currentLaunchId;
}
protected transient File currentLaunchDir;
public File getCurrentLaunchDir() {
return currentLaunchDir;
}
protected File getConfigurationFile() {<FILL_FUNCTION_BODY>}
protected void initLaunchDir() {
initLaunchId();
try {
currentLaunchDir = new File(getConfigurationFile().getParentFile(), getCurrentLaunchId());
if (!currentLaunchDir.mkdir()) {
throw new IOException("failed to create directory " + currentLaunchDir);
}
// copy cxml to launch dir
FileUtils.copyFileToDirectory(getConfigurationFile(), currentLaunchDir);
// attempt to symlink "latest" to launch dir
File latestSymlink = new File(getConfigurationFile().getParentFile(), "latest");
latestSymlink.delete();
try {
Files.createSymbolicLink(latestSymlink.toPath(), Paths.get(currentLaunchDir.getName()));
} catch (IOException | UnsupportedOperationException e) {
LOGGER.log(Level.WARNING, "failed to create symlink from " + latestSymlink + " to " + currentLaunchDir, e);
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "failed to initialize launch directory: " + e);
currentLaunchDir = null;
}
}
/**
* Initialize the LifecycleProcessor.
* Uses HeritrixLifecycleProcessor, which prevents an automatic lifecycle
* start(), if none defined in the context.
* @see org.springframework.context.support.DefaultLifecycleProcessor
*/
protected void initLifecycleProcessor() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (!beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
HeritrixLifecycleProcessor obj = (HeritrixLifecycleProcessor)beanFactory.createBean(HeritrixLifecycleProcessor.class);
beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME,obj);
}
super.initLifecycleProcessor();
}
protected ConcurrentHashMap<Object, Object> data;
/**
* @return a shared map for arbitrary use during a crawl; for example, could
* be used for state persisting for the duration of the crawl,
* shared among ScriptedProcessor, scripting console, etc scripts
*/
public ConcurrentHashMap<Object, Object> getData() {
if (data == null) {
data = new ConcurrentHashMap<Object, Object>();
}
return data;
}
}
|
String primaryConfigurationPath = getPrimaryConfigurationPath();
if (primaryConfigurationPath.startsWith("file:")) {
// strip URI-scheme if present (as is usual)
try {
return new File(new URI(primaryConfigurationPath));
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
} else {
return new File(primaryConfigurationPath);
}
| 1,420
| 116
| 1,536
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/spring/Sheet.java
|
Sheet
|
prime
|
class Sheet implements BeanFactoryAware, BeanNameAware {
@SuppressWarnings("unused")
private static final long serialVersionUID = 9129011082185864377L;
/**
* unique name of this Sheet; if Sheet has a beanName from original
* configuration, that is always the name -- but the name might
* also be another string, in the case of Sheets added after
* initial container wiring
*/
protected String name;
protected BeanFactory beanFactory;
/** map of full property-paths (from BeanFactory to individual
* property) and their changed value when this Sheet of overrides
* is in effect
*/
protected Map<String,Object> map = new ConcurrentHashMap<String, Object>();
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
public void setBeanName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
/**
* Return map of full bean-path (starting with a target bean-name)
* to the alternate value for that targeted property
*/
public Map<String, Object> getMap() {
return map;
}
/**
* Set map of property full bean-path (starting with a target
* bean-name) to alternate values. Note: provided map is copied
* into a local concurrent map, rather than used directly.
* @param m
*/
@Required
public void setMap(Map<String, Object> m) {
this.map.clear();
this.map.putAll(m);
}
/**
* Ensure any properties targeted by this Sheet know to
* check the right property paths for overrides at lookup time,
* and that the override values are compatible types for their
* destination properties.
*
* Should be done as soon as all possible targets are
* constructed (ApplicationListener ContextRefreshedEvent)
*
* TODO: consider if an 'un-priming' also needs to occur to
* prevent confusing side-effects.
* TODO: consider if priming should move to another class
*/
public void prime() {<FILL_FUNCTION_BODY>}
}
|
for (String fullpath : map.keySet()) {
int lastDot = fullpath.lastIndexOf(".");
String beanPath = fullpath.substring(0,lastDot);
String terminalProp = fullpath.substring(lastDot+1);
Object value = map.get(fullpath);
int i = beanPath.indexOf(".");
Object bean;
HasKeyedProperties hkp;
if (i < 0) {
bean = beanFactory.getBean(beanPath);
} else {
String beanName = beanPath.substring(0,i);
String propPath = beanPath.substring(i+1);
BeanWrapperImpl wrapper = new BeanWrapperImpl(beanFactory.getBean(beanName));
bean = wrapper.getPropertyValue(propPath);
}
try {
hkp = (HasKeyedProperties) bean;
} catch (ClassCastException cce) {
// targeted bean has no overridable properties
throw new TypeMismatchException(bean,HasKeyedProperties.class,cce);
}
// install knowledge of this path
hkp.getKeyedProperties().addExternalPath(beanPath);
// verify type-compatibility
BeanWrapperImpl wrapper = new BeanWrapperImpl(hkp);
Class<?> requiredType = wrapper.getPropertyType(terminalProp);
try {
// convert for destination type
map.put(fullpath, wrapper.convertForProperty(value,terminalProp));
} catch(TypeMismatchException tme) {
TypeMismatchException tme2 =
new TypeMismatchException(
new PropertyChangeEvent(
hkp,
fullpath,
wrapper.getPropertyValue(terminalProp),
value), requiredType, tme);
throw tme2;
}
}
| 694
| 503
| 1,197
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/surt/SURTTokenizer.java
|
SURTTokenizer
|
nextSearch
|
class SURTTokenizer {
private final static String EXACT_SUFFIX = "\t";
private String remainder;
private boolean triedExact;
private boolean triedFull;
private boolean choppedArgs;
private boolean choppedPath;
private boolean choppedLogin;
private boolean choppedPort;
/**
* constructor
*
* @param url String URL
* @throws URIException
*/
public SURTTokenizer(final String url) throws URIException {
remainder = getKey(url,false);
}
/**
* update internal state and return the next smaller search string
* for the url
*
* @return string to lookup for prefix match for relevant information.
*/
public String nextSearch() {<FILL_FUNCTION_BODY>}
/**
* @param url
* @return String SURT which will match exactly argument url
* @throws URIException
*/
public static String exactKey(String url) throws URIException {
return getKey(url,false);
}
/**
* @param url
* @return String SURT which will match urls prefixed with the argument url
* @throws URIException
*/
public static String prefixKey(String url) throws URIException {
return getKey(url,true);
}
private static String getKey(String url, boolean prefix)
throws URIException {
String key = ArchiveUtils.addImpliedHttpIfNecessary(url);
UURI uuri = UURIFactory.getInstance(key);
key = uuri.getScheme() + "://" + uuri.getAuthority() +
uuri.getEscapedPathQuery();
key = SURT.fromURI(key);
int hashPos = key.indexOf('#');
if(hashPos != -1) {
key = key.substring(0,hashPos);
}
if(key.startsWith("http://")) {
key = key.substring(7);
}
if(prefix) {
if(key.endsWith(")/")) {
key = key.substring(0,key.length()-2);
}
}
return key;
}
}
|
if(!triedExact) {
triedExact = true;
//remainder = remainder.substring(0,remainder.length()-1);
return remainder + EXACT_SUFFIX;
}
if(!triedFull) {
triedFull = true;
return remainder;
}
if(!choppedArgs) {
choppedArgs = true;
int argStart = remainder.indexOf('?');
if(argStart != -1) {
remainder = remainder.substring(0,argStart);
return remainder;
}
}
if(!choppedPath) {
int lastSlash = remainder.lastIndexOf('/');
if(lastSlash != -1) {
remainder = remainder.substring(0,lastSlash);
if(remainder.endsWith(")")) {
remainder = remainder.substring(0,remainder.length()-1);
}
return remainder;
}
choppedPath = true;
}
if(!choppedLogin) {
choppedLogin = true;
int lastAt = remainder.lastIndexOf('@');
if(lastAt != -1) {
remainder = remainder.substring(0,lastAt);
if(remainder.endsWith(",")) {
remainder = remainder.substring(0,remainder.length()-1);
}
return remainder;
}
}
if(!choppedPort) {
choppedPort = true;
int lastColon = remainder.lastIndexOf(':');
if(lastColon != -1) {
remainder = remainder.substring(0,lastColon);
if(remainder.endsWith(",")) {
remainder = remainder.substring(0,remainder.length()-1);
}
return remainder;
}
}
// now just remove ','s
int lastComma = remainder.lastIndexOf(',');
if(lastComma == -1) {
return null;
}
remainder = remainder.substring(0,lastComma);
return remainder;
| 565
| 529
| 1,094
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/BloomFilter64bit.java
|
BloomFilter64bit
|
add
|
class BloomFilter64bit implements Serializable, BloomFilter {
private static final long serialVersionUID = 3L;
/** The expected number of inserts; determines calculated size */
private final long expectedInserts;
/** The number of elements currently in the filter. It may be
* smaller than the actual number of additions of distinct character
* sequences because of false positives.
*/
private int size;
private final com.google.common.hash.BloomFilter<CharSequence> delegate;
private final long bitSize;
private final int numHashFunctions;
/** Creates a new Bloom filter with given number of hash functions and
* expected number of elements.
*
* @param n the expected number of elements.
* @param d the number of hash functions; if the filter add not more
* than <code>n</code> elements, false positives will happen with
* probability 2<sup>-<var>d</var></sup>.
*/
public BloomFilter64bit( final long n, final int d) {
this(n,d, new SecureRandom(), false);
}
public BloomFilter64bit( final long n, final int d, boolean roundUp) {
this(n,d, new SecureRandom(), roundUp);
}
/** Creates a new Bloom filter with given number of hash functions and
* expected number of elements.
*
* @param n the expected number of elements.
* @param d the number of hash functions; if the filter add not more
* than <code>n</code> elements, false positives will happen with
* probability 2<sup>-<var>d</var></sup>.
* @param weightsGenerator may provide a seeded Random for reproducible
* internal universal hash function weighting
* @param roundUp if true, round bit size up to next-nearest-power-of-2
*/
public BloomFilter64bit(final long n, final int d, Random weightsGenerator, boolean roundUp ) {
delegate = com.google.common.hash.BloomFilter.create(Funnels.unencodedCharsFunnel(), Ints.saturatedCast(n), Math.pow(2, -d));
this.expectedInserts = n;
try {
Method bitSizeMethod = delegate.getClass().getDeclaredMethod("bitSize", new Class[] {});
bitSizeMethod.setAccessible(true);
bitSize = (long) bitSizeMethod.invoke(delegate, new Object[] {});
Field numHashFunctionField = delegate.getClass().getDeclaredField("numHashFunctions");
numHashFunctionField.setAccessible(true);
numHashFunctions = numHashFunctionField.getInt(delegate);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/** The number of character sequences in the filter.
*
* @return the number of character sequences in the filter (but
* see {@link #contains(CharSequence)}).
*/
public int size() {
return size;
}
/** Checks whether the given character sequence is in this filter.
*
* <P>Note that this method may return true on a character sequence that is has
* not been added to the filter. This will happen with probability 2<sub>-<var>d</var></sub>,
* where <var>d</var> is the number of hash functions specified at creation time, if
* the number of the elements in the filter is less than <var>n</var>, the number
* of expected elements specified at creation time.
*
* @param s a character sequence.
* @return true if the sequence is in the filter (or if a sequence with the
* same hash sequence is in the filter).
*/
public boolean contains( final CharSequence s ) {
return delegate.mightContain(s);
}
/** Adds a character sequence to the filter.
*
* @param s a character sequence.
* @return true if the character sequence was not in the filter (but see {@link #contains(CharSequence)}).
*/
public boolean add( final CharSequence s ) {<FILL_FUNCTION_BODY>}
/* (non-Javadoc)
* @see org.archive.util.BloomFilter#getSizeBytes()
*/
public long getSizeBytes() {
return bitSize / 8;
}
@Override
public long getExpectedInserts() {
return expectedInserts;
}
@Override
public long getHashCount() {
return numHashFunctions;
}
@VisibleForTesting
public boolean getBit(long bitIndex) {
try {
Field bitsField = delegate.getClass().getDeclaredField("bits");
bitsField.setAccessible(true);
Object bitarray = bitsField.get(delegate);
Method getBitMethod = bitarray.getClass().getDeclaredMethod("get", long.class);
getBitMethod.setAccessible(true);
return (boolean) getBitMethod.invoke(bitarray, bitIndex);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
|
boolean added = delegate.put(s);
if (added) {
size++;
}
return added;
| 1,320
| 34
| 1,354
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/Histotable.java
|
Histotable
|
getTotal
|
class Histotable<K> extends TreeMap<K,Long> {
private static final long serialVersionUID = 310306238032568623L;
/**
* Record one more occurrence of the given object key.
*
* @param key Object key.
*/
public void tally(K key) {
tally(key,1L);
}
/**
* Record <i>count</i> more occurrence(s) of the given object key.
*
* @param key Object key.
*/
public synchronized void tally(K key,long count) {
long tally = containsKey(key) ? get(key) : 0;
tally += count;
if(tally!=0) {
put(key,tally);
} else {
remove(key);
}
}
/**
* Get a SortedSet that, when filled with (String key)->(long count)
* Entry instances, sorts them by (count, key) descending, as is useful
* for most-frequent displays.
*
* Static to allow reuse elsewhere (TopNSet) until a better home for
* this utility method is found.
*
* @return TreeSet with suitable Comparator
*/
public static TreeSet<Map.Entry<?, Long>> getEntryByFrequencySortedSet() {
// sorted by count
TreeSet<Map.Entry<?,Long>> sorted =
new TreeSet<Map.Entry<?,Long>>(
new Comparator<Map.Entry<?,Long>>() {
public int compare(Map.Entry<?,Long> e1,
Map.Entry<?,Long> e2) {
long firstVal = e1.getValue();
long secondVal = e2.getValue();
if (firstVal < secondVal) { return 1; }
if (secondVal < firstVal) { return -1; }
// If the values are the same, sort by keys.
String firstKey = ((Map.Entry<?,Long>) e1).getKey().toString();
String secondKey = ((Map.Entry<?,Long>) e2).getKey().toString();
return firstKey.compareTo(secondKey);
}
});
return sorted;
}
/**
* @return Return an up-to-date count-descending sorted version of the totaled info.
*/
public TreeSet<Map.Entry<?,Long>> getSortedByCounts() {
TreeSet<java.util.Map.Entry<?, Long>> sorted = getEntryByFrequencySortedSet();
sorted.addAll(entrySet());
return sorted;
}
/**
* @return Return an up-to-date sorted version of the totaled info.
*/
public Set<Map.Entry<K,Long>> getSortedByKeys() {
return entrySet();
}
/**
* Return the largest value of any key that is larger than 0. If no
* values or no value larger than zero, return zero.
*
* @return long largest value or zero if none larger than zero
*/
public long getLargestValue() {
long largest = 0;
for (Long el : values()) {
if (el > largest) {
largest = el;
}
}
return largest;
}
/**
* Return the total of all tallies.
*
* @return long total of all tallies
*/
public long getTotal() {<FILL_FUNCTION_BODY>}
/**
* Utility method to convert a key->Long into
* the string "count key".
*
* @param e Map key.
* @return String 'count key'.
*/
@SuppressWarnings("unchecked")
public static String entryString(Object e) {
Map.Entry<?,Long> entry = (Map.Entry<?,Long>) e;
return entry.getValue() + " " + entry.getKey();
}
public long add(Histotable<K> ht) {
long net = 0;
for (K key : ht.keySet()) {
long change = ht.get(key);
net += change;
tally(key,change);
}
return net;
}
public long subtract(Histotable<K> ht) {
long net = 0;
for (K key : ht.keySet()) {
long change = ht.get(key);
net -= change;
tally(key,-change);
}
return net;
}
/** Return 0 instead of null for absent keys.
*
* @see java.util.TreeMap#get(java.lang.Object)
*/
@Override
public Long get(Object key) {
Long val = super.get(key);
return val == null ? 0 : val;
}
}
|
long total = 0;
for (Long el : values()) {
total += el;
}
return total;
| 1,286
| 36
| 1,322
|
<methods>public void <init>() ,public void <init>(Comparator<? super K>) ,public void <init>(Map<? extends K,? extends java.lang.Long>) ,public void <init>(SortedMap<K,? extends java.lang.Long>) ,public Entry<K,java.lang.Long> ceilingEntry(K) ,public K ceilingKey(K) ,public void clear() ,public java.lang.Object clone() ,public Comparator<? super K> comparator() ,public java.lang.Long compute(K, BiFunction<? super K,? super java.lang.Long,? extends java.lang.Long>) ,public java.lang.Long computeIfAbsent(K, Function<? super K,? extends java.lang.Long>) ,public java.lang.Long computeIfPresent(K, BiFunction<? super K,? super java.lang.Long,? extends java.lang.Long>) ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public NavigableSet<K> descendingKeySet() ,public NavigableMap<K,java.lang.Long> descendingMap() ,public Set<Entry<K,java.lang.Long>> entrySet() ,public Entry<K,java.lang.Long> firstEntry() ,public K firstKey() ,public Entry<K,java.lang.Long> floorEntry(K) ,public K floorKey(K) ,public void forEach(BiConsumer<? super K,? super java.lang.Long>) ,public java.lang.Long get(java.lang.Object) ,public SortedMap<K,java.lang.Long> headMap(K) ,public NavigableMap<K,java.lang.Long> headMap(K, boolean) ,public Entry<K,java.lang.Long> higherEntry(K) ,public K higherKey(K) ,public Set<K> keySet() ,public Entry<K,java.lang.Long> lastEntry() ,public K lastKey() ,public Entry<K,java.lang.Long> lowerEntry(K) ,public K lowerKey(K) ,public java.lang.Long merge(K, java.lang.Long, BiFunction<? super java.lang.Long,? super java.lang.Long,? extends java.lang.Long>) ,public NavigableSet<K> navigableKeySet() ,public Entry<K,java.lang.Long> pollFirstEntry() ,public Entry<K,java.lang.Long> pollLastEntry() ,public java.lang.Long put(K, java.lang.Long) ,public void putAll(Map<? extends K,? extends java.lang.Long>) ,public java.lang.Long putIfAbsent(K, java.lang.Long) ,public java.lang.Long remove(java.lang.Object) ,public java.lang.Long replace(K, java.lang.Long) ,public boolean replace(K, java.lang.Long, java.lang.Long) ,public void replaceAll(BiFunction<? super K,? super java.lang.Long,? extends java.lang.Long>) ,public int size() ,public SortedMap<K,java.lang.Long> subMap(K, K) ,public NavigableMap<K,java.lang.Long> subMap(K, boolean, K, boolean) ,public SortedMap<K,java.lang.Long> tailMap(K) ,public NavigableMap<K,java.lang.Long> tailMap(K, boolean) ,public Collection<java.lang.Long> values() <variables>private static final boolean BLACK,private static final boolean RED,private static final java.lang.Object UNBOUNDED,private final Comparator<? super K> comparator,private transient NavigableMap<K,java.lang.Long> descendingMap,private transient EntrySet entrySet,private transient int modCount,private transient KeySet<K> navigableKeySet,private transient Entry<K,java.lang.Long> root,private static final long serialVersionUID,private transient int size
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/JSONUtils.java
|
JSONUtils
|
putAllLongs
|
class JSONUtils {
@SuppressWarnings("unchecked")
public static void putAllLongs(Map<String,Long> targetMap, JSONObject sourceJson) throws JSONException {<FILL_FUNCTION_BODY>}
@SuppressWarnings("unchecked")
public static void putAllAtomicLongs(Map<String,AtomicLong> targetMap, JSONObject sourceJson) throws JSONException {
for(String k : new Iteratorable<String>(sourceJson.keys())) {
targetMap.put(k, new AtomicLong(sourceJson.getLong(k)));
}
}
}
|
for(String k : new Iteratorable<String>(sourceJson.keys())) {
targetMap.put(k, sourceJson.getLong(k));
}
| 165
| 48
| 213
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/JavaLiterals.java
|
JavaLiterals
|
escape
|
class JavaLiterals {
public static String escape(String raw) {<FILL_FUNCTION_BODY>}
public static String unescape(String escaped) {
StringBuffer raw = new StringBuffer();
for(int i = 0; i<escaped.length(); i++) {
char c = escaped.charAt(i);
if (c!='\\') {
raw.append(c);
} else {
i++;
if(i>=escaped.length()) {
// trailing '/'
raw.append(c);
continue;
}
c = escaped.charAt(i);
switch (c) {
case 'b':
raw.append('\b');
break;
case 't':
raw.append('\t');
break;
case 'n':
raw.append('\n');
break;
case 'f':
raw.append('\f');
break;
case 'r':
raw.append('r');
break;
case '"':
raw.append('\"');
break;
case '\'':
raw.append('\'');
break;
case '\\':
raw.append('\\');
break;
case 'u':
// unicode hex escape
try {
int unicode = Integer.parseInt(escaped.substring(i+1,i+5),16);
raw.append((char)unicode);
i = i + 4;
} catch (IndexOutOfBoundsException e) {
// err
raw.append("\\u");
}
break;
default:
if(Character.isDigit(c)) {
// octal escape
int end = Math.min(i+4,escaped.length());
int octal = Integer.parseInt(escaped.substring(i+1,end),8);
if(octal<256) {
raw.append((char)octal);
i = end - 1;
} else {
// err
raw.append('\\');
raw.append(c);
}
}
break;
}
}
}
return raw.toString();
}
}
|
StringBuffer escaped = new StringBuffer();
for(int i = 0; i<raw.length(); i++) {
char c = raw.charAt(i);
switch (c) {
case '\b':
escaped.append("\\b");
break;
case '\t':
escaped.append("\\t");
break;
case '\n':
escaped.append("\\n");
break;
case '\f':
escaped.append("\\f");
break;
case '\r':
escaped.append("\\r");
break;
case '\"':
escaped.append("\\\"");
break;
case '\'':
escaped.append("\\'");
break;
case '\\':
escaped.append("\\\\");
break;
default:
if(Character.getType(c)==Character.CONTROL) {
String unicode = Integer.toHexString((int)c);
while(unicode.length()<4) {
unicode = "0"+unicode;
}
escaped.append("\\u"+unicode);
} else {
escaped.append(c);
}
}
}
return escaped.toString();
| 564
| 314
| 878
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/JndiUtils.java
|
JndiUtils
|
getReference
|
class JndiUtils {
/**
* Syntax that will work with jmx ObjectNames (i.e. will escape '.' and
* will add treat ',' and '=' specially.
*/
private static final Properties COMPOUND_NAME_SYNTAX = new Properties();
static {
COMPOUND_NAME_SYNTAX.put("jndi.syntax.direction", "left_to_right");
COMPOUND_NAME_SYNTAX.put("jndi.syntax.separator", "+");
COMPOUND_NAME_SYNTAX.put("jndi.syntax.ignorecase", "false");
COMPOUND_NAME_SYNTAX.put("jndi.syntax.escape", "\\");
COMPOUND_NAME_SYNTAX.put("jndi.syntax.beginquote", "'");
COMPOUND_NAME_SYNTAX.put("jndi.syntax.trimblanks", "true");
COMPOUND_NAME_SYNTAX.put("jndi.syntax.separator.ava", ",");
COMPOUND_NAME_SYNTAX.put("jndi.syntax.separator.typeval", "=");
}
public static CompoundName getCompoundName(final String name)
throws InvalidNameException {
return new CompoundName(name, COMPOUND_NAME_SYNTAX);
}
/**
* Return name to use as jndi name.
* Used to do a subset of the ObjectName fields but not just
* let all through so its easy to just use the jndi name to
* find mbean.
* @param on ObjectName instance to work with.
* @return Returns a compound name to use as jndi key.
* @throws NullPointerException
* @throws InvalidNameException
*/
public static CompoundName getCompoundName(final ObjectName on)
throws NullPointerException,
InvalidNameException {
return getCompoundName(on.getCanonicalKeyPropertyListString());
}
/**
* @param on ObjectName instance to work with.
* @return A simple reference based on passed <code>on</code>
*/
public static Reference getReference(final ObjectName on) {<FILL_FUNCTION_BODY>}
/**
* Get subcontext. Only looks down one level.
* @param subContext Name of subcontext to return.
* @return Sub context.
* @throws NamingException
*/
public static Context getSubContext(final String subContext)
throws NamingException {
return getSubContext(getCompoundName(subContext));
}
/**
* Get subcontext. Only looks down one level.
* @param subContext Name of subcontext to return.
* @return Sub context.
* @throws NamingException
*/
public static Context getSubContext(final CompoundName subContext)
throws NamingException {
Context context = new InitialContext();
try {
context = (Context)context.lookup(subContext);
} catch (NameNotFoundException e) {
context = context.createSubcontext(subContext);
}
return context;
}
/**
*
* @param context A subcontext named for the <code>on.getDomain()</code>
* (Assumption is that caller already setup this subcontext).
* @param on The ObjectName we're to base our bind name on.
* @return Returns key we used binding this ObjectName.
* @throws NamingException
* @throws NullPointerException
*/
public static CompoundName bindObjectName(Context context,
final ObjectName on)
throws NamingException, NullPointerException {
// I can't call getNameInNamespace in tomcat. Complains about
// unsupported operation -- that I can't get absolute name.
// Therefore just skip this test below -- at least for now.
// Check that passed context has the passed ObjectNames' name.
//
// String name = getCompoundName(context.getNameInNamespace()).toString();
// if (!name.equals(on.getDomain())) {
// throw new NamingException("The current context is " + name +
// " but domain is " + on.getDomain() + " (Was expecting " +
// "them to be the same).");
// }
CompoundName key = getCompoundName(on);
context.rebind(key, getReference(on));
return key;
}
public static CompoundName unbindObjectName(final Context context,
final ObjectName on)
throws NullPointerException, NamingException {
CompoundName key = getCompoundName(on);
context.unbind(key);
return key;
}
/**
* Testing code.
* @param args Command line arguments.
* @throws NullPointerException
* @throws MalformedObjectNameException
* @throws NamingException
* @throws InvalidNameException
*/
public static void main(String[] args)
throws MalformedObjectNameException, NullPointerException,
InvalidNameException, NamingException {
final ObjectName on = new ObjectName("org.archive.crawler:" +
"type=Service,name=Heritrix00,host=debord.archive.org");
Context c = getSubContext(getCompoundName(on.getDomain()));
CompoundName key = bindObjectName(c, on);
Reference r = (Reference)c.lookup(key);
for (Enumeration<RefAddr> e = r.getAll(); e.hasMoreElements();) {
System.out.println(e.nextElement());
}
unbindObjectName(c, on);
}
}
|
Reference r = new Reference(String.class.getName());
Hashtable<String,String> ht = on.getKeyPropertyList();
r.add(new StringRefAddr("host", (String)ht.get("host")));
r.add(new StringRefAddr("name", (String)ht.get("name")));
// Put in a value to serve as a unique 'key'.
r.add(new StringRefAddr("key",
on.getCanonicalKeyPropertyListString()));
return r;
| 1,453
| 128
| 1,581
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/KeyTool.java
|
KeyTool
|
main
|
class KeyTool {
public static void main(String[] args) {<FILL_FUNCTION_BODY>}
}
|
try {
Class<?> cl;
try {
// java 6 and 7
cl = ClassLoader.getSystemClassLoader().loadClass("sun.security.tools.KeyTool");
} catch (ClassNotFoundException e) {
// java 8
cl = ClassLoader.getSystemClassLoader().loadClass("sun.security.tools.keytool.Main");
}
Method main = cl.getMethod("main", String[].class);
main.invoke(null, (Object) args);
} catch (IllegalAccessException e) {
// java 16
List<String> command = new ArrayList<>();
command.add(System.getProperty("java.home") + File.separator + "bin" + File.separator + "keytool");
command.addAll(Arrays.asList(args));
try {
new ProcessBuilder(command).inheritIO().start().waitFor();
} catch (IOException e2) {
throw new UncheckedIOException(e2);
} catch (InterruptedException e2) {
Thread.currentThread().interrupt();
}
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
} else {
throw new RuntimeException(e);
}
}
| 31
| 339
| 370
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/LongToIntConsistentHash.java
|
LongToIntConsistentHash
|
bucketFor
|
class LongToIntConsistentHash {
protected static final int DEFAULT_REPLICAS = 128;
protected TreeMap<Long,Integer> circle = new TreeMap<Long,Integer>();
protected int replicasInstalledUpTo=-1;
protected int numReplicas;
public LongToIntConsistentHash() {
this(DEFAULT_REPLICAS);
}
public LongToIntConsistentHash(int numReplicas) {
this.numReplicas = numReplicas;
installReplicas(0);
replicasInstalledUpTo=1;
}
/**
* Install necessary replicas, if not already present.
* @param upTo
*/
public void installReplicasUpTo(int upTo) {
if(replicasInstalledUpTo>upTo) {
return;
}
for(;replicasInstalledUpTo<upTo;replicasInstalledUpTo++) {
installReplicas(replicasInstalledUpTo);
}
}
private void installReplicas(int bucket) {
for(int i = 0; i < numReplicas; i++) {
circle.put(
replicaLocation(bucket,i),
bucket);
}
}
// SecureRandom rand = new SecureRandom();
protected long replicaLocation(int bucketNumber, int replicaNumber) {
// return rand.nextLong();
// return RandomUtils.nextLong();
// return ArchiveUtils.doubleMurmur(string.getBytes());
// return (new JenkinsHash()).hash(string.getBytes());
return FPGenerator.std64.fp(bucketNumber+"."+replicaNumber);
}
protected long hash(CharSequence cs) {
// return ArchiveUtils.doubleMurmur(string.getBytes());
// return (new JenkinsHash()).hash(string.getBytes());
return FPGenerator.std64.fp(cs);
}
/**
* Return the proper integer bucket-number for the given long hash,
* up to the given integer boundary (exclusive).
*
* @param longHash
* @param upTo
*/
public int bucketFor(long longHash, int upTo) {<FILL_FUNCTION_BODY>}
/**
* Convenience alternative which creates longHash from CharSequence
*/
public int bucketFor(CharSequence cs, int upTo) {
return bucketFor(hash(cs), upTo);
}
public int bucketFor(char[] chars, int upTo) {
return bucketFor(hash(new String(chars)), upTo);
}
}
|
installReplicasUpTo(upTo);
NavigableMap<Long, Integer> tailMap = circle.tailMap(longHash, true);
Map.Entry<Long,Integer> match = null;
for(Map.Entry<Long,Integer> candidate : tailMap.entrySet()) {
if(candidate.getValue() < upTo) {
match = candidate;
break;
}
}
if (match == null) {
return bucketFor(Long.MIN_VALUE,upTo);
}
return match.getValue();
| 756
| 161
| 917
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/ObjectIdentityMemCache.java
|
ObjectIdentityMemCache
|
getOrUse
|
class ObjectIdentityMemCache<V extends IdentityCacheable>
implements ObjectIdentityCache<V> {
protected ConcurrentHashMap<String, V> map;
public ObjectIdentityMemCache() {
map = new ConcurrentHashMap<String, V>();
}
public ObjectIdentityMemCache(int cap, float load, int conc) {
map = new ConcurrentHashMap<String, V>(cap, load, conc);
}
public void close() {
// do nothing
}
@Override
public V get(String key) {
// all gets are mutatable
return getOrUse(key,null);
}
public V getOrUse(String key, Supplier<V> supplierOrNull) {<FILL_FUNCTION_BODY>}
public int size() {
return map.size();
}
public Set<String> keySet() {
return map.keySet();
}
public void sync() {
// do nothing
}
@Override
public void dirtyKey(String key) {
// do nothing: memory is whole cache
}
/**
* Offer raw map access for convenience of checkpoint/recovery.
*/
public Map<String, V> getMap() {
return map;
}
}
|
V val = map.get(key);
if (val==null && supplierOrNull!=null) {
val = supplierOrNull.get();
V prevVal = map.putIfAbsent(key, val);
if(prevVal!=null) {
val = prevVal;
}
}
if (val != null) {
val.setIdentityCache(this);
}
return val;
| 383
| 126
| 509
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/OneLineSimpleLayout.java
|
OneLineSimpleLayout
|
format
|
class OneLineSimpleLayout extends Layout {
private OneLineSimpleLogger logger = new OneLineSimpleLogger();
@Override
public void activateOptions() {
}
@Override
public String format(LoggingEvent event) {<FILL_FUNCTION_BODY>}
protected java.util.logging.Level convertLevel(org.apache.log4j.Level log4jLevel) {
switch (log4jLevel.toInt()) {
case org.apache.log4j.Level.TRACE_INT:
return java.util.logging.Level.FINER;
case org.apache.log4j.Level.DEBUG_INT:
return java.util.logging.Level.FINE;
case org.apache.log4j.Level.INFO_INT:
return java.util.logging.Level.INFO;
case org.apache.log4j.Level.WARN_INT:
return java.util.logging.Level.WARNING;
case org.apache.log4j.Level.ERROR_INT:
return java.util.logging.Level.SEVERE;
case org.apache.log4j.Level.FATAL_INT:
return java.util.logging.Level.SEVERE;
default:
return java.util.logging.Level.ALL;
}
}
@Override
public boolean ignoresThrowable() {
return true;
}
}
|
java.util.logging.Level level = convertLevel(event.getLevel());
LogRecord logRecord = new LogRecord(level, event.getMessage().toString());
logRecord.setLoggerName(event.getLoggerName());
logRecord.setMillis(event.getTimeStamp());
logRecord.setSourceClassName(event.getLoggerName());
logRecord.setSourceMethodName(event.getLocationInformation().getMethodName());
logRecord.setThreadID((int) Thread.currentThread().getId());
return logger.format(logRecord);
| 353
| 138
| 491
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/OneLineSimpleLogger.java
|
OneLineSimpleLogger
|
format
|
class OneLineSimpleLogger extends SimpleFormatter {
/**
* Date instance.
*
* Keep around instance of date.
*/
private Date date = new Date();
/**
* Field position instance.
*
* Keep around this instance.
*/
private FieldPosition position = new FieldPosition(0);
/**
* MessageFormatter for date.
*/
private SimpleDateFormat formatter =
new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
/**
* Persistent buffer in which we conjure the log.
*/
private StringBuffer buffer = new StringBuffer();
public OneLineSimpleLogger() {
super();
}
public synchronized String format(LogRecord record) {<FILL_FUNCTION_BODY>}
public static Logger setConsoleHandler() {
Logger logger = Logger.getLogger("");
Handler [] hs = logger.getHandlers();
for (int i = 0; i < hs.length; i++) {
Handler h = hs[0];
if (h instanceof ConsoleHandler) {
h.setFormatter(new OneLineSimpleLogger());
}
}
return logger;
}
/**
* Test this logger.
*/
public static void main(String[] args) {
Logger logger = setConsoleHandler();
logger = Logger.getLogger("Test");
logger.severe("Does this come out?");
logger.severe("Does this come out?");
logger.severe("Does this come out?");
logger.log(Level.SEVERE, "hello", new RuntimeException("test"));
}
}
|
this.buffer.setLength(0);
this.date.setTime(record.getMillis());
this.position.setBeginIndex(0);
this.formatter.format(this.date, buffer, this.position);
buffer.append(' ');
buffer.append(record.getLevel().getLocalizedName());
buffer.append(" thread-");
buffer.append(record.getThreadID());
buffer.append(' ');
if (record.getSourceClassName() != null) {
buffer.append(record.getSourceClassName());
} else {
buffer.append(record.getLoggerName());
}
buffer.append('.');
String methodName = record.getSourceMethodName();
methodName = (methodName == null || methodName.length() <= 0)?
"-": methodName;
buffer.append(methodName);
buffer.append("() ");
buffer.append(formatMessage(record));
buffer.append(System.getProperty("line.separator"));
if (record.getThrown() != null) {
try {
StringWriter writer = new StringWriter();
PrintWriter printer = new PrintWriter(writer);
record.getThrown().printStackTrace(printer);
writer.close();
buffer.append(writer.toString());
} catch (Exception e) {
buffer.append("Failed to get stack trace: " + e.getMessage());
}
}
return buffer.toString();
| 437
| 373
| 810
|
<methods>public void <init>() ,public java.lang.String format(java.util.logging.LogRecord) <variables>private final java.lang.String format
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/PaddingStringBuffer.java
|
PaddingStringBuffer
|
append
|
class PaddingStringBuffer {
// The buffer.
protected StringBuffer buffer;
// Location in current line
protected int linePos;
/**
* Create a new PaddingStringBuffer
*
*/
public PaddingStringBuffer() {
buffer = new StringBuffer();
linePos=0;
}
/** append a string directly to the buffer
* @param string the string to append
* @return This wrapped buffer w/ the passed string appended.
*/
public PaddingStringBuffer append(String string) {<FILL_FUNCTION_BODY>}
/**
* Append a string, right-aligned to the given columm. If the buffer
* length is already greater than the column specified, it simply appends
* the string
*
* @param col the column to right-align to
* @param string the string, must not contain multiple lines.
* @return This wrapped buffer w/ append string, right-aligned to the
* given column.
*/
public PaddingStringBuffer raAppend(int col, String string) {
padTo(col-string.length());
append(string);
return this;
}
/** Pad to a given column. If the buffer size is already greater than the
* column, nothing is done.
* @param col
* @return The buffer padded to <code>i</code>.
*/
public PaddingStringBuffer padTo(int col) {
while(linePos<col) {
buffer.append(" ");
linePos++;
}
return this;
}
/** append an <code>int</code> to the buffer.
* @param i the int to append
* @return This wrapped buffer with <code>i</code> appended.
*/
public PaddingStringBuffer append(int i) {
append(Integer.toString(i));
return this;
}
/**
* Append an <code>int</code> right-aligned to the given column. If the
* buffer length is already greater than the column specified, it simply
* appends the <code>int</code>.
*
* @param col the column to right-align to
* @param i the int to append
* @return This wrapped buffer w/ appended int, right-aligned to the
* given column.
*/
public PaddingStringBuffer raAppend(int col, int i) {
return raAppend(col,Integer.toString(i));
}
/** append a <code>long</code> to the buffer.
* @param lo the <code>long</code> to append
* @return This wrapped buffer w/ appended long.
*/
public PaddingStringBuffer append(long lo) {
append(Long.toString(lo));
return this;
}
/**Append a <code>long</code>, right-aligned to the given column. If the
* buffer length is already greater than the column specified, it simply
* appends the <code>long</code>.
* @param col the column to right-align to
* @param lo the long to append
* @return This wrapped buffer w/ appended long, right-aligned to the
* given column.
*/
public PaddingStringBuffer raAppend(int col, long lo) {
return raAppend(col,Long.toString(lo));
}
/** reset the buffer back to empty */
public void reset() {
buffer = new StringBuffer();
linePos = 0;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString() {
return buffer.toString();
}
/**
* Forces a new line in the buffer.
*/
public PaddingStringBuffer newline() {
buffer.append("\n");
linePos = 0;
return this;
}
}
|
buffer.append(string);
if ( string.indexOf('\n') == -1 ){
linePos+=string.length();
} else {
while ( string.indexOf('\n') == -1 ){
string = string.substring(string.indexOf('\n'));
}
linePos=string.length();
}
return this;
| 991
| 94
| 1,085
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/PrefixFinder.java
|
PrefixFinder
|
find
|
class PrefixFinder {
/**
* Extracts prefixes of a given string from a SortedSet. If an element
* of the given set is a prefix of the given string, then that element
* is added to the result list.
*
* <p>Put another way, for every element in the result list, the following
* expression will be true: <tt>string.startsWith(element.getKey())</tt>.
*
* @param set the sorted set containing potential prefixes
* @param input the string whose prefixes to find
* @return the list of prefixes
*/
public static List<String> find(SortedSet<String> set, String input) {<FILL_FUNCTION_BODY>}
protected static SortedSet<String> headSetInclusive(SortedSet<String> set, String input) {
// use NavigableSet inclusive version if available
if(set instanceof NavigableSet) {
return ((NavigableSet<String>)set).headSet(input, true);
}
// use Stored*Set inclusive version if available
if(set instanceof StoredSortedKeySet) {
return ((StoredSortedKeySet<String>)set).headSet(input, true);
}
if(set instanceof StoredSortedValueSet) {
return ((StoredSortedValueSet<String>)set).headSet(input, true);
}
// Use synthetic "one above" trick
// NOTE: because '\0' sorts in the middle in "java modified UTF-8",
// used in the Stored* class StringBindings, this trick won't work
// there
return set.headSet(input+'\0');
}
private static String last(SortedSet<String> set) {
return set.isEmpty() ? null : set.last();
}
public static List<String> findKeys(SortedMap<String,?> map, String input) {
LinkedList<String> result = new LinkedList<String>();
map = headMapInclusive(map, input);
for (String last = last(map); last != null; last = last(map)) {
if (input.startsWith(last)) {
result.push(last);
map = map.headMap(last);
} else {
// Find the longest common prefix.
int p = StringUtils.indexOfDifference(input, last);
if (p <= 0) {
return result;
}
last = input.substring(0, p);
map = headMapInclusive(map, last);
}
}
return result;
}
private static SortedMap<String, ?> headMapInclusive(SortedMap<String, ?> map, String input) {
// use NavigableMap inclusive version if available
if(map instanceof NavigableMap) {
return ((NavigableMap<String, ?>)map).headMap(input, true);
}
// use StoredSortedMap inclusive version if available
if(map instanceof StoredSortedMap) {
return ((StoredSortedMap<String, ?>)map).headMap(input, true);
}
// Use synthetic "one above" trick
// NOTE: because '\0' sorts in the middle in "java modified UTF-8",
// used in the Stored* class StringBindings, this trick won't work
// there
return map.headMap(input+'\0');
}
private static String last(SortedMap<String,?> map) {
// TODO Auto-generated method stub
return map.isEmpty() ? null : map.lastKey();
}
}
|
LinkedList<String> result = new LinkedList<String>();
set = headSetInclusive(set, input);
for (String last = last(set); last != null; last = last(set)) {
if (input.startsWith(last)) {
result.push(last);
set = set.headSet(last);
} else {
// Find the longest common prefix.
int p = StringUtils.indexOfDifference(input, last);
if (p <= 0) {
return result;
}
last = input.substring(0, p);
set = headSetInclusive(set, last);
}
}
return result;
| 931
| 172
| 1,103
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/ReportUtils.java
|
ReportUtils
|
shortReportLine
|
class ReportUtils {
/**
* Utility method to get a String shortReportLine from Reporter
* @param rep Reporter to get shortReportLine from
* @return String of report
*/
public static String shortReportLine(Reporter rep) {<FILL_FUNCTION_BODY>}
}
|
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
try {
rep.shortReportLineTo(pw);
} catch (IOException e) {
// not really possible
e.printStackTrace();
}
pw.flush();
return sw.toString();
| 79
| 82
| 161
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/TestUtils.java
|
TestUtils
|
makeSuite
|
class TestUtils {
private static final Logger logger =
Logger.getLogger(TestUtils.class.getName());
/**
* Temporarily exhaust memory, forcing weak/soft references to
* be broken.
*/
public static void forceScarceMemory() {
// force soft references to be broken
LinkedList<SoftReference<byte[]>> hog = new LinkedList<SoftReference<byte[]>>();
long blocks = Runtime.getRuntime().maxMemory() / 1000000;
logger.info("forcing scarce memory via "+blocks+" 1MB blocks");
for(long l = 0; l <= blocks; l++) {
try {
hog.add(new SoftReference<byte[]>(new byte[1000000]));
} catch (OutOfMemoryError e) {
hog = null;
logger.info("OOME triggered");
break;
}
}
}
public static void testSerialization(Object proc) throws Exception {
byte[] first = serialize(proc);
ByteArrayInputStream binp = new ByteArrayInputStream(first);
ObjectInputStream oinp = new ObjectInputStream(binp);
Object o = oinp.readObject();
oinp.close();
TestCase.assertEquals(proc.getClass(), o.getClass());
byte[] second = serialize(o);
TestCase.assertTrue(Arrays.equals(first, second));
}
public static byte[] serialize(Object o) throws Exception {
ByteArrayOutputStream bout = new ByteArrayOutputStream();
ObjectOutputStream oout = new ObjectOutputStream(bout);
oout.writeObject(o);
oout.close();
return bout.toByteArray();
}
public static TestSuite makePackageSuite(Class<?> c)
throws ClassNotFoundException {
String cname = c.getName();
int p = cname.lastIndexOf('.');
String dir = cname.substring(0, p).replace('.', File.separatorChar);
String root = "heritrix/src/test/java/".replace('/', File.separatorChar);
File src = new File(root);
return makeSuite(src, new File(root + dir));
}
public static TestSuite makeSuite(File srcRoot, File dir)
throws ClassNotFoundException {<FILL_FUNCTION_BODY>}
private static void scanSuite(TestSuite suite, File start, File dir)
throws ClassNotFoundException {
for (File f: dir.listFiles()) {
if (f.isDirectory() && !f.getName().startsWith(".")) {
String prefix = start.getAbsolutePath();
String full = f.getAbsolutePath();
TestSuite sub = new TestSuite(full.substring(prefix.length()));
scanSuite(sub, start, f);
if (sub.testCount() > 0) {
suite.addTest(sub);
}
} else {
if (f.getName().endsWith("Test.java")) {
String full = f.getAbsolutePath();
String prefix = start.getAbsolutePath();
String cname = full.substring(prefix.length());
if (cname.startsWith(File.separator)) {
cname = cname.substring(1);
}
cname = cname.replace(File.separatorChar, '.');
cname = cname.substring(0, cname.length() - 5);
suite.addTestSuite((Class<? extends TestCase>) Class.forName(cname));
}
}
}
}
/*
* create a tmp dir for testing; copied nearly verbatim from TmpDirTestCase
*/
public static File tmpDir() throws IOException {
String tmpDirStr = System.getProperty(TmpDirTestCase.TEST_TMP_SYSTEM_PROPERTY_NAME);
tmpDirStr = (tmpDirStr == null)? TmpDirTestCase.DEFAULT_TEST_TMP_DIR: tmpDirStr;
File tmpDir = new File(tmpDirStr);
FileUtils.ensureWriteableDirectory(tmpDir);
if (!tmpDir.canWrite())
{
throw new IOException(tmpDir.getAbsolutePath() +
" is unwriteable.");
}
tmpDir.deleteOnExit();
return tmpDir;
}
}
|
TestSuite result = new TestSuite("All Tests");
if (!dir.exists()) {
throw new IllegalArgumentException(dir + " does not exist.");
}
scanSuite(result, srcRoot, dir);
return result;
| 1,119
| 63
| 1,182
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/bdbje/EnhancedEnvironment.java
|
EnhancedEnvironment
|
getClassCatalog
|
class EnhancedEnvironment extends Environment {
protected StoredClassCatalog classCatalog;
protected Database classCatalogDB;
/**
* Constructor
*
* @param envHome directory in which to open environment
* @param envConfig config options
* @throws DatabaseException
*/
public EnhancedEnvironment(File envHome, EnvironmentConfig envConfig) throws DatabaseException {
super(envHome, envConfig);
}
/**
* Return a StoredClassCatalog backed by a Database in this environment,
* either pre-existing or created (and cached) if necessary.
*
* @return the cached class catalog
*/
public StoredClassCatalog getClassCatalog() {<FILL_FUNCTION_BODY>}
@Override
public synchronized void close() throws DatabaseException {
if(classCatalogDB!=null) {
classCatalogDB.close();
}
super.close();
}
/**
* Create a temporary test environment in the given directory.
* @param dir target directory
* @return EnhancedEnvironment
*/
public static EnhancedEnvironment getTestEnvironment(File dir) {
EnvironmentConfig envConfig = new EnvironmentConfig();
envConfig.setAllowCreate(true);
envConfig.setTransactional(false);
EnhancedEnvironment env;
try {
env = new EnhancedEnvironment(dir, envConfig);
} catch (DatabaseException e) {
throw new RuntimeException(e);
}
return env;
}
}
|
if(classCatalog == null) {
DatabaseConfig dbConfig = new DatabaseConfig();
dbConfig.setAllowCreate(true);
dbConfig.setReadOnly(this.getConfig().getReadOnly());
try {
classCatalogDB = openDatabase(null, "classCatalog", dbConfig);
classCatalog = new StoredClassCatalog(classCatalogDB);
} catch (DatabaseException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
}
return classCatalog;
| 389
| 137
| 526
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/fingerprint/ArrayLongFPCache.java
|
ArrayLongFPCache
|
contains
|
class ArrayLongFPCache implements LongFPSet {
public static final int DEFAULT_CAPACITY = 1 << 20; // 1 million, 8MB
public static final int DEFAULT_SMEAR = 5;
protected long cache[] = new long[DEFAULT_CAPACITY];
protected int smear = DEFAULT_SMEAR;
protected int count = 0;
public void setCapacity(int newCapacity) {
long[] oldCache = cache;
cache = new long[newCapacity];
for(int i=0;i<oldCache.length;i++) {
add(oldCache[i]);
}
}
/* (non-Javadoc)
* @see org.archive.util.fingerprint.LongFPSet#add(long)
*/
public boolean add(long l) {
if(contains(l)) {
return false;
}
int index = (Math.abs((int) (l % cache.length)) + (count % smear)) % cache.length;
count++;
cache[index]=l;
return true;
}
/* (non-Javadoc)
* @see org.archive.util.fingerprint.LongFPSet#contains(long)
*/
public boolean contains(long l) {<FILL_FUNCTION_BODY>}
/* (non-Javadoc)
* @see org.archive.util.fingerprint.LongFPSet#remove(long)
*/
public boolean remove(long l) {
int index = Math.abs((int) (l % cache.length));
for(int i = index; i < index + smear; i++) {
if(cache[i%cache.length]==l) {
cache[i%cache.length]=0;
count = Math.min(count,cache.length);
count--;
return true;
}
}
return false;
}
/* (non-Javadoc)
* @see org.archive.util.fingerprint.LongFPSet#count()
*/
public long count() {
return Math.min(count,cache.length);
}
/* (non-Javadoc)
* @see org.archive.util.fingerprint.LongFPSet#quickContains(long)
*/
public boolean quickContains(long fp) {
return contains(fp);
}
public int cacheLength() {
return cache.length;
}
}
|
int index = Math.abs((int) (l % cache.length));
for(int i = index; i < index + smear; i++) {
if(cache[i%cache.length]==l) {
return true;
}
}
return false;
| 632
| 73
| 705
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/fingerprint/LongFPSetCache.java
|
LongFPSetCache
|
discard
|
class LongFPSetCache extends MemLongFPSet {
private static final long serialVersionUID = -5307436423975825566L;
long sweepHand = 0;
public LongFPSetCache() {
super();
}
public LongFPSetCache(int capacityPowerOfTwo, float loadFactor) {
super(capacityPowerOfTwo, loadFactor);
}
protected void noteAccess(long index) {
if(slots[(int)index]<Byte.MAX_VALUE) {
slots[(int)index]++;
}
}
protected void makeSpace() {
discard(1);
}
private void discard(int i) {<FILL_FUNCTION_BODY>}
}
|
int toDiscard = i;
while(toDiscard>0) {
if(slots[(int)sweepHand]==0) {
removeAt(sweepHand);
toDiscard--;
} else {
if (slots[(int)sweepHand]>0) {
slots[(int)sweepHand]--;
}
}
sweepHand++;
if (sweepHand==slots.length) {
sweepHand = 0;
}
}
| 202
| 129
| 331
|
<methods>public void <init>() ,public void <init>(int, float) ,public boolean quickContains(long) <variables>private static final int DEFAULT_CAPACITY_POWER_OF_TWO,private static final float DEFAULT_LOAD_FACTOR,private static java.util.logging.Logger logger,private static final long serialVersionUID,protected byte[] slots,protected long[] values
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/fingerprint/LongFPSetTestCase.java
|
LongFPSetTestCase
|
testContains
|
class LongFPSetTestCase extends TestCase {
/** the unerlying FPSet we wish to test */
private LongFPSet fpSet;
/**
* Create a new LongFPSetTest object
*
* @param testName the name of the test
*/
public LongFPSetTestCase(final String testName) {
super(testName);
}
public void setUp() {
fpSet = makeLongFPSet();
}
protected abstract LongFPSet makeLongFPSet();
/** check that we can add fingerprints */
public void testAdd() {
long l1 = (long)1234;
long l2 = (long)2345;
assertEquals("empty set to start", 0, fpSet.count());
assertTrue("set changed on addition of l1", fpSet.add(l1));
assertTrue("set changed on addition of l2", fpSet.add(l2));
assertFalse("set didn't change on re-addition of l1", fpSet.add(l1));
}
/** check we can call add/remove/contains() with 0 as a value */
public void testWithZero() {
long zero = (long)0;
assertEquals("empty set to start", 0, fpSet.count());
assertFalse("zero is not there", fpSet.contains(zero));
assertTrue("zero added", fpSet.add(zero));
// now one element
assertEquals("one fp in set", 1, fpSet.count());
assertTrue("zero is the element", fpSet.contains(zero));
// and remove
assertTrue("zero removed", fpSet.remove(zero));
assertEquals("empty set again", 0, fpSet.count());
}
/** check that contains() does what we expect */
public void testContains() {<FILL_FUNCTION_BODY>}
/** test remove() works as expected */
public void testRemove() {
long l1 = (long) 1234;
assertEquals("empty set to start", 0, fpSet.count());
// remove before it's there
assertFalse("fp not in set", fpSet.remove(l1));
// now add
fpSet.add(l1);
// and remove again
assertTrue("fp was in set", fpSet.remove(l1));
// check set is empty again
assertEquals("empty set again", 0, fpSet.count());
}
/** check count works ok */
public void testCount() {
final int NUM = 1000;
assertEquals("empty set to start", 0, fpSet.count());
for(int i = 1; i < NUM; ++i) {
fpSet.add((long)i);
assertEquals("correct num", i, fpSet.count());
}
for (int i = NUM - 1; i > 0; --i) {
fpSet.remove((long) i);
assertEquals("correct num", i -1, fpSet.count());
}
assertEquals("empty set to start", 0, fpSet.count());
}
}
|
long l1 = (long) 1234;
long l2 = (long) 2345;
long l3 = (long) 1334;
assertEquals("empty set to start", 0, fpSet.count());
fpSet.add(l1);
fpSet.add(l2);
assertTrue("contains l1", fpSet.contains(l1));
assertTrue("contains l2", fpSet.contains(l2));
assertFalse("does not contain l3", fpSet.contains(l3));
| 807
| 146
| 953
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/fingerprint/MemLongFPSet.java
|
MemLongFPSet
|
grow
|
class MemLongFPSet extends AbstractLongFPSet
implements LongFPSet, Serializable {
private static final long serialVersionUID = -4301879539092625698L;
private static Logger logger =
Logger.getLogger(MemLongFPSet.class.getName());
private static final int DEFAULT_CAPACITY_POWER_OF_TWO = 10;
private static final float DEFAULT_LOAD_FACTOR = 0.75f;
protected byte[] slots;
protected long[] values;
public MemLongFPSet() {
this(DEFAULT_CAPACITY_POWER_OF_TWO, DEFAULT_LOAD_FACTOR);
}
/**
* @param capacityPowerOfTwo The capacity as the exponent of a power of 2.
* e.g if the capacity is <code>4</code> this means <code>2^^4</code>
* entries.
* @param loadFactor The load factor as a fraction. This gives the amount
* of free space to keep in the Set.
*/
public MemLongFPSet(int capacityPowerOfTwo, float loadFactor) {
super(capacityPowerOfTwo, loadFactor);
slots = new byte[1 << capacityPowerOfTwo];
for(int i = 0; i < (1 << capacityPowerOfTwo); i++) {
slots[i] = EMPTY; // flag value for unused
}
values = new long[1 << capacityPowerOfTwo];
}
protected void setAt(long i, long val) {
slots[(int)i] = 1;
values[(int)i] = val;
}
protected long getAt(long i) {
return values[(int)i];
}
protected void makeSpace() {
grow();
}
private void grow() {<FILL_FUNCTION_BODY>}
protected void relocate(long val, long oldIndex, long newIndex) {
values[(int)newIndex] = values[(int)oldIndex];
slots[(int)newIndex] = slots[(int)oldIndex];
slots[(int)oldIndex] = EMPTY;
}
protected int getSlotState(long i) {
return slots[(int)i];
}
protected void clearAt(long index) {
slots[(int)index]=EMPTY;
values[(int)index]=0;
}
public boolean quickContains(long fp) {
return contains(fp);
}
}
|
// Catastrophic event. Log its occurrence.
logger.info("Doubling fingerprinting slots to "
+ (1 << this.capacityPowerOfTwo));
long[] oldValues = values;
byte[] oldSlots = slots;
capacityPowerOfTwo++;
values = new long[1 << capacityPowerOfTwo];
slots = new byte[1 << capacityPowerOfTwo];
for(int i = 0; i < (1 << capacityPowerOfTwo); i++) {
slots[i]=EMPTY; // flag value for unused
}
count=0;
for(int i = 0; i< oldValues.length; i++) {
if(oldSlots[i]>=0) {
add(oldValues[i]);
}
}
| 647
| 198
| 845
|
<methods>public void <init>() ,public void <init>(int, float) ,public boolean add(long) ,public boolean contains(long) ,public long count() ,public boolean quickContains(long) ,public boolean remove(long) <variables>protected static byte EMPTY,protected int capacityPowerOfTwo,protected long count,protected float loadFactor,private static java.util.logging.Logger logger
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/iterator/CompositeIterator.java
|
CompositeIterator
|
hasNext
|
class CompositeIterator<E> implements Iterator<E> {
protected ArrayList<Iterator<E>> iterators = new ArrayList<Iterator<E>>();
protected Iterator<E> currentIterator;
protected int indexOfCurrentIterator = -1;
/**
* Moves to the next (non empty) iterator. Returns false if there are no
* more (non empty) iterators, true otherwise.
* @return false if there are no more (non empty) iterators, true otherwise.
*/
private boolean nextIterator() {
if (++indexOfCurrentIterator < iterators.size()) {
currentIterator = iterators.get(indexOfCurrentIterator);
// If the new iterator was empty this will move us to the next one.
return hasNext();
} else {
currentIterator = null;
return false;
}
}
/* (non-Javadoc)
* @see java.util.Iterator#hasNext()
*/
public boolean hasNext() {<FILL_FUNCTION_BODY>}
/* (non-Javadoc)
* @see java.util.Iterator#next()
*/
public E next() {
if(hasNext()) {
return currentIterator.next();
} else {
throw new NoSuchElementException();
}
}
/* (non-Javadoc)
* @see java.util.Iterator#remove()
*/
public void remove() {
throw new UnsupportedOperationException();
}
/**
* Create an empty CompositeIterator. Internal
* iterators may be added later.
*/
public CompositeIterator() {
super();
}
/**
* Convenience method for concatenating together
* two iterators.
* @param i1
* @param i2
*/
public CompositeIterator(Iterator<E> i1, Iterator<E> i2) {
this();
add(i1);
add(i2);
}
/**
* Add an iterator to the internal chain.
*
* @param i an iterator to add.
*/
public void add(Iterator<E> i) {
iterators.add(i);
}
}
|
if(currentIterator!=null && currentIterator.hasNext()) {
// Got more
return true;
} else {
// Have got more if we can queue up a new iterator.
return nextIterator();
}
| 558
| 60
| 618
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/ms/BlockInputStream.java
|
BlockInputStream
|
read
|
class BlockInputStream extends SeekInputStream {
/**
* The starting block number.
*/
private int start;
/**
* The current block.
*/
private int block;
/**
* The BlockFileSystem that produced this stream.
*/
private BlockFileSystem bfs;
/**
* The raw input stream of the BlockFileSystem.
*/
private SeekInputStream raw;
/**
* The current logical position of this stream.
*/
private long position;
/**
* The current file pointer position of the raw input stream.
*/
private long expectedRawPosition;
/**
* The number of bytes read in the current block.
*/
private int blockBytesRead;
/**
* Constructor.
*
* @param bfs The block file system that owns this stream
* @param block The starting block number.
*/
public BlockInputStream(BlockFileSystem bfs, int block) throws IOException {
this.raw = bfs.getRawInput();
this.bfs = bfs;
this.start = block;
this.block = block;
this.position = 0;
seek(block, 0);
}
private void seek(long block, long rem) throws IOException {
assert rem < BLOCK_SIZE;
long pos = (block + 1) * BLOCK_SIZE + rem;
blockBytesRead = (int)rem;
expectedRawPosition = pos;
raw.position(pos);
}
private void ensureRawPosition() throws IOException {
if (raw.position() != expectedRawPosition) {
raw.position(expectedRawPosition);
}
}
private boolean ensureBuffer() throws IOException {
if (block < 0) {
return false;
}
ensureRawPosition();
if (blockBytesRead < BLOCK_SIZE) {
return true;
}
block = bfs.getNextBlock(block);
if (block < 0) {
return false;
}
seek(block, 0);
return true;
}
public long skip(long v) throws IOException {
// FIXME
int r = read();
return (r < 0) ? 0 : 1;
}
public int read() throws IOException {
if (!ensureBuffer()) {
return -1;
}
int r = raw.read();
position++;
expectedRawPosition++;
blockBytesRead++;
return r;
}
public int read(byte[] b, int ofs, int len) throws IOException {<FILL_FUNCTION_BODY>}
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
public long position() {
return position;
}
public void position(long v) throws IOException {
ensureRawPosition();
if (v == position) {
return;
}
// If new position is in same block, just seek.
if (v / BLOCK_SIZE == position / BLOCK_SIZE) {
long rem = v % BLOCK_SIZE;
seek(block, rem);
position = v;
return;
}
if (v > position) {
seekAfter(v);
} else {
seekBefore(v);
}
}
private void seekAfter(long v) throws IOException {
long currentBlock = position / BLOCK_SIZE;
long destBlock = v / BLOCK_SIZE;
long blockAdvance = destBlock - currentBlock;
for (int i = 0; i < blockAdvance; i++) {
block = bfs.getNextBlock(block);
}
seek(block, v % BLOCK_SIZE);
position = v;
}
private void seekBefore(long v) throws IOException {
long blockAdvance = (v - 1) / BLOCK_SIZE;
block = start;
for (int i = 0; i < blockAdvance; i++) {
block = bfs.getNextBlock(block);
}
seek(block, v % BLOCK_SIZE);
}
}
|
if (!ensureBuffer()) {
return 0;
}
int rem = BLOCK_SIZE - (int)(position % BLOCK_SIZE);
len = Math.min(len, rem);
int c = raw.read(b, ofs, len);
position += c;
expectedRawPosition += c;
blockBytesRead++;
return len;
| 1,097
| 94
| 1,191
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/ms/Cp1252.java
|
Cp1252
|
createTable
|
class Cp1252 {
/**
* The translation table. If x is an unsigned byte from a .doc
* text stream, then XLAT[x] is the Unicode character that byte
* represents.
*/
final private static char[] XLAT = createTable();
/**
* Static utility library, do not instantiate.
*/
private Cp1252() {
}
/**
* Generates the translation table. The Java String API is used for each
* possible byte to determine the corresponding Unicode character.
*
* @return the Cp1252 translation table
*/
private static char[] createTable() {<FILL_FUNCTION_BODY>}
/**
* Returns the Unicode character for the given Cp1252 byte.
*
* @param b an unsigned byte from 0 to 255
* @return the Unicode character corresponding to that byte
*/
public static char decode(int b) {
return XLAT[b];
}
}
|
char[] result = new char[256];
byte[] b = new byte[1];
for (int i = 0; i < 256; i++) try {
b[0] = (byte)i;
String s = new String(b, "Cp1252");
result[i] = s.charAt(0);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
return result;
| 281
| 120
| 401
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/ms/DefaultBlockFileSystem.java
|
DefaultBlockFileSystem
|
getNextBlock
|
class DefaultBlockFileSystem implements BlockFileSystem {
/**
* Pointers per BAT block.
*/
final private static int POINTERS_PER_BAT = 128;
/**
* Size of a BAT pointer in bytes. (In other words, 4).
*/
final private static int BAT_POINTER_SIZE = BLOCK_SIZE / POINTERS_PER_BAT;
/**
* The number of BAT pointers in the header block. After this many
* BAT blocks, the XBAT blocks must be consulted.
*/
final private static int HEADER_BAT_LIMIT = 109;
/**
* The size of an entry record in bytes.
*/
final private static int ENTRY_SIZE = 128;
/**
* The number of entries that can fit in a block.
*/
final private static int ENTRIES_PER_BLOCK = BLOCK_SIZE / ENTRY_SIZE;
/**
* The .doc file as a stream.
*/
private SeekInputStream input;
/**
* The header block.
*/
private HeaderBlock header;
/**
* Cache of BAT and XBAT blocks.
*/
private Map<Integer,ByteBuffer> cache;
/**
* Constructor.
*
* @param input the file to read from
* @param batCacheSize number of BAT and XBAT blocks to cache
* @throws IOException if an IO error occurs
*/
public DefaultBlockFileSystem(SeekInputStream input, int batCacheSize)
throws IOException {
this.input = input;
byte[] temp = new byte[BLOCK_SIZE];
ArchiveUtils.readFully(input, temp);
this.header = new HeaderBlock(ByteBuffer.wrap(temp));
this.cache = new LRU<Integer,ByteBuffer>(batCacheSize);
}
public Entry getRoot() throws IOException {
// Position to the first block of the entry list.
int block = header.getEntriesStart();
input.position((block + 1) * BLOCK_SIZE);
// The root entry is always entry #0.
return new DefaultEntry(this, input, 0);
}
/**
* Returns the entry with the given number.
*
* @param entryNumber the number of the entry to return
* @return that entry, or null if no such entry exists
* @throws IOException if an IO error occurs
*/
protected Entry getEntry(int entryNumber) throws IOException {
// Entry numbers < 0 typically indicate an end-of-stream.
if (entryNumber < 0) {
return null;
}
// It's impossible to check against the upper bound, because the
// upper bound is not recorded anywhere.
// Advance to the block containing the desired entry.
int blockCount = entryNumber / ENTRIES_PER_BLOCK;
int remainder = entryNumber % ENTRIES_PER_BLOCK;
int block = header.getEntriesStart();
for (int i = 0; i < blockCount; i++) {
block = getNextBlock(block);
}
if (block < 0) {
// Given entry number exceeded the number of available entries.
return null;
}
int filePos = (block + 1) * BLOCK_SIZE + remainder * ENTRY_SIZE;
input.position(filePos);
return new DefaultEntry(this, input, entryNumber);
}
public int getNextBlock(int block) throws IOException {<FILL_FUNCTION_BODY>}
/**
* Looks up the block number of a BAT block.
*
* @param headerIndex
* @return
* @throws IOException
*/
private int batLookup(int headerIndex) throws IOException {
if (headerIndex < HEADER_BAT_LIMIT + 1) {
return header.getBATBlockNumber(headerIndex);
}
// Find the XBAT block of interest
headerIndex -= HEADER_BAT_LIMIT;
int xbatBlockNumber = headerIndex / POINTERS_PER_BAT;
xbatBlockNumber += header.getExtendedBATStart();
ByteBuffer xbat = getBATBlock(xbatBlockNumber);
// Find the bat Block number inside the XBAT block
int xbatBlockIndex = headerIndex % POINTERS_PER_BAT;
return xbat.getInt(xbatBlockIndex * BAT_POINTER_SIZE);
}
/**
* Returns the BAT block with the given block number.
* If the BAT block were previously cached, then the cached version
* is returned. Otherwise, the file pointer is repositioned to
* the start of the given block, and the 512 bytes are read and
* stored in the cache.
*
* @param block the block number of the BAT block to return
* @return the BAT block
* @throws IOException
*/
private ByteBuffer getBATBlock(int block) throws IOException {
ByteBuffer r = cache.get(block);
if (r != null) {
return r;
}
byte[] buf = new byte[BLOCK_SIZE];
input.position((block + 1) * BLOCK_SIZE);
ArchiveUtils.readFully(input, buf);
r = ByteBuffer.wrap(buf);
r.order(ByteOrder.LITTLE_ENDIAN);
cache.put(block, r);
return r;
}
public SeekInputStream getRawInput() {
return input;
}
}
|
if (block < 0) {
return block;
}
// Index into the header array of BAT blocks.
int headerIndex = block / POINTERS_PER_BAT;
// Index within that BAT block of the block we're interested in.
int batBlockIndex = block % POINTERS_PER_BAT;
int batBlockNumber = batLookup(headerIndex);
ByteBuffer batBlock = getBATBlock(batBlockNumber);
return batBlock.getInt(batBlockIndex * BAT_POINTER_SIZE);
| 1,467
| 142
| 1,609
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/ms/DefaultEntry.java
|
DefaultEntry
|
list
|
class DefaultEntry implements Entry {
private DefaultBlockFileSystem origin;
private String name;
private EntryType type;
private int previous;
private int next;
private int child;
private int startBlock;
private int size;
private int index;
public DefaultEntry(DefaultBlockFileSystem origin, SeekInputStream input, int index)
throws IOException {
this.index = index;
// FIXME: Read directly from the stream
this.origin = origin;
byte[] temp = new byte[128];
ArchiveUtils.readFully(input, temp);
ByteBuffer buf = ByteBuffer.wrap(temp);
buf.order(ByteOrder.LITTLE_ENDIAN);
buf.position(0);
StringBuilder nameBuf = new StringBuilder();
char ch = buf.getChar();
while (ch != 0) {
nameBuf.append(ch);
ch = buf.getChar();
}
this.name = nameBuf.toString();
byte typeFlag = buf.get(0x42);
switch (typeFlag) {
case 1:
this.type = EntryType.DIRECTORY;
break;
case 2:
this.type = EntryType.FILE;
break;
case 5:
this.type = EntryType.ROOT;
break;
default:
throw new IllegalStateException("Invalid type: " + typeFlag);
}
this.previous = buf.getInt(0x44);
this.next = buf.getInt(0x48);
this.child = buf.getInt(0x4C);
this.startBlock = buf.getInt(0x74);
this.size = buf.getInt(0x78);
}
public String getName() {
return name;
}
public EntryType getType() {
return type;
}
public Entry getNext() throws IOException {
return origin.getEntry(next);
}
public Entry getPrevious() throws IOException {
return origin.getEntry(previous);
}
public Entry getChild() throws IOException {
return origin.getEntry(child);
}
public SeekInputStream open() throws IOException {
return new BlockInputStream(origin, startBlock);
}
public List<Entry> list() throws IOException {<FILL_FUNCTION_BODY>}
public static void list(List<Entry> list, Entry e) throws IOException {
if (e == null) {
return;
}
list.add(e);
list(list, e.getPrevious());
list(list, e.getNext());
}
public int getIndex() {
return index;
}
public String toString() {
StringBuilder result = new StringBuilder("Entry{");
result.append("name=").append(name);
result.append(" index=").append(index);
result.append(" type=").append(type);
result.append(" size=").append(size);
result.append(" prev=").append(previous);
result.append(" next=").append(next);
result.append(" child=").append(child);
result.append(" startBlock=").append(startBlock);
result.append("}");
return result.toString();
}
}
|
if (child < 0) {
throw new IllegalStateException("Can't list non-directory.");
}
Entry child = getChild();
ArrayList<Entry> r = new ArrayList<Entry>();
list(r, child);
return r;
| 874
| 66
| 940
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/ms/Doc.java
|
Doc
|
getText
|
class Doc {
final private static Logger LOGGER = Logger.getLogger(Doc.class.getName());
/**
* Static utility library, do not instantiate.
*/
private Doc() {
}
/**
* Returns the text of the .doc file with the given file name.
*
* @param docFilename the name of the file whose text to return
* @return the text of that file
* @throws IOException if an IO error occurs
*/
public static SeekReader getText(String docFilename) throws IOException {
return getText(new File(docFilename));
}
/**
* Returns the text of the given .doc file.
*
* @param doc the .doc file whose text to return
* @return the text of that file
* @throws IOException if an IO error occurs
*/
public static SeekReader getText(File doc) throws IOException {
RandomAccessFile raf = new RandomAccessFile(doc, "r");
RandomAccessInputStream rais = new RandomAccessInputStream(raf);
return getText(rais);
}
/**
* Returns the text of the given .doc file.
*
* @param doc the .doc file whose text to return
* @return the text of that file
* @throws IOException if an IO error occurs
*/
public static SeekReader getText(SeekInputStream doc) throws IOException {
BlockFileSystem bfs = new DefaultBlockFileSystem(doc, 16);
return getText(bfs, 20);
}
/**
* Returns the text for the given .doc file. The given cacheSize refers
* to the number of the .doc file's piece table entries to cache. Most
* .doc files only have 1 piece table entry; however, a "fast-saved"
* .doc file might have several. A cacheSize of 20 should be ample for
* most .doc files in the world. Since piece table entries are small --
* only 12 bytes each -- caching them prevents many otherwise necessary
* file pointer repositionings.
*
* @param wordDoc the .doc file as a BlockFileSystem
* @param cacheSize the number of piece table entries to cache
* @return a reader that will return the text in the file
* @throws IOException if an IO error occurs
*/
public static SeekReader getText(BlockFileSystem wordDoc, int cacheSize)
throws IOException {<FILL_FUNCTION_BODY>}
private static Entry find(List<Entry> entries, String name) {
for (Entry e: entries) {
if (e.getName().equals(name)) {
return e;
}
}
return null;
}
}
|
List<Entry> entries = wordDoc.getRoot().list();
Entry main = find(entries, "WordDocument");
SeekInputStream mainStream = main.open();
mainStream.position(10);
int flags = Endian.littleChar(mainStream);
boolean complex = (flags & 0x0004) == 0x0004;
boolean tableOne = (flags & 0x0200) == 0x0200;
String tableName = tableOne ? "1Table" : "0Table";
Entry table = find(entries, tableName);
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("Main entry: " + main);
LOGGER.finest("Table entry: " + table);
}
SeekInputStream tableStream = table.open();
mainStream.position(24);
int fcMin = Endian.littleInt(mainStream);
int fcMax = Endian.littleInt(mainStream);
mainStream.position(76);
int cppText = Endian.littleInt(mainStream);
mainStream.position(418);
int fcClx = Endian.littleInt(mainStream);
int fcSz = Endian.littleInt(mainStream);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("fcMin: " + fcMin);
LOGGER.fine("fcMax: " + fcMax);
LOGGER.fine("FcClx: " + fcClx);
LOGGER.fine("szClx: " + fcSz);
LOGGER.fine("complex: " + complex);
LOGGER.fine("cppText: " + cppText);
}
PieceTable pt = new PieceTable(tableStream, fcClx, fcMax - fcMin, cacheSize);
return new PieceReader(pt, mainStream);
| 713
| 508
| 1,221
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/ms/HeaderBlock.java
|
HeaderBlock
|
toString
|
class HeaderBlock {
private ByteBuffer buffer;
public HeaderBlock(ByteBuffer buffer) {
// FIXME: Read the fields we're interested in directly from stream
this.buffer = buffer;
buffer.order(ByteOrder.LITTLE_ENDIAN);
}
public long getFileType() {
return buffer.getLong(0);
}
public int getBATCount() {
return buffer.getInt(0x2C);
}
public int getEntriesStart() {
return buffer.getInt(0x30);
}
public int getSmallBATStart() {
return buffer.getInt(0x3C);
}
public int getSmallBATCount() {
return buffer.getInt(0x40);
}
public int getExtendedBATStart() {
return buffer.getInt(0x44);
}
public int getExtendedBATCount() {
return buffer.getInt(0x48);
}
public int getBATBlockNumber(int block) {
assert block < 110;
return buffer.getInt(0x4C + block * 4);
}
public String toString() {<FILL_FUNCTION_BODY>}
}
|
StringBuilder sb = new StringBuilder("HeaderBlock{");
sb.append("fileType=" + getFileType());
sb.append(" propertiesStart=" + getEntriesStart());
sb.append(" batCount=" + getBATCount());
sb.append(" extendedBATStart=" + getExtendedBATStart());
sb.append(" extendedBATCount=" + getExtendedBATCount());
sb.append(" smallBATStart=" + getSmallBATStart());
sb.append(" smallBATCount=" + getSmallBATCount());
sb.append("}");
return sb.toString();
| 364
| 157
| 521
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/ms/Piece.java
|
Piece
|
toString
|
class Piece {
private boolean unicode;
private int charPosStart;
private int charPosLimit;
private int filePos;
public Piece(int filePos, int start, int end, boolean unicode) {
this.filePos = filePos;
this.charPosStart = start;
this.charPosLimit = end;
this.unicode = unicode;
}
public int getFilePos() {
return filePos;
}
public int getCharPosLimit() {
return charPosLimit;
}
public int getCharPosStart() {
return charPosStart;
}
public boolean isUnicode() {
return unicode;
}
public String toString() {<FILL_FUNCTION_BODY>}
public boolean contains(int charPos) {
return (charPos >= charPosStart) && (charPos < charPosLimit);
}
}
|
StringBuilder sb = new StringBuilder();
sb.append("Piece{filePos=").append(filePos);
sb.append(" start=").append(charPosStart);
sb.append(" end=").append(charPosLimit);
sb.append(" unicode=").append(unicode);
sb.append("}");
return sb.toString();
| 241
| 91
| 332
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/ms/PieceReader.java
|
PieceReader
|
read
|
class PieceReader extends SeekReader {
private PieceTable table;
private SeekInputStream doc;
private boolean unicode;
private int charPos;
private int limit;
public PieceReader(PieceTable table, SeekInputStream doc)
throws IOException {
this.table = table;
this.doc = doc;
charPos = 0;
limit = -1;
}
private void seekIfNecessary() throws IOException {
if (doc == null) {
throw new IOException("Stream closed.");
}
if (charPos >= table.getMaxCharPos()) {
return;
}
if (charPos < limit) {
return;
}
Piece piece = table.next();
unicode = piece.isUnicode();
limit = piece.getCharPosLimit();
doc.position(piece.getFilePos());
}
public int read() throws IOException {
seekIfNecessary();
if (doc == null) {
throw new IOException("Stream closed.");
}
if (charPos >= table.getMaxCharPos()) {
return -1;
}
int ch;
if (unicode) {
ch = Endian.littleChar(doc);
} else {
ch = Cp1252.decode(doc.read());
}
charPos++;
return ch;
}
public int read(char[] buf, int ofs, int len) throws IOException {<FILL_FUNCTION_BODY>}
public void close() throws IOException {
doc.close();
table = null;
}
public long position() throws IOException {
return charPos;
}
public void position(long p) throws IOException {
if (p > Integer.MAX_VALUE) {
throw new IOException("File too large.");
}
int charPos = (int)p;
Piece piece = table.pieceFor(charPos);
if (piece == null) {
throw new IOException("Illegal position: " + p);
}
unicode = piece.isUnicode();
limit = piece.getCharPosLimit();
int ofs = charPos - piece.getCharPosStart();
this.charPos = charPos;
doc.position(piece.getFilePos() + ofs);
}
}
|
// FIXME: Think of a faster implementation that will work with
// both unicode and non-unicode.
seekIfNecessary();
if (doc == null) {
throw new IOException("Stream closed.");
}
if (charPos >= table.getMaxCharPos()) {
return 0;
}
for (int i = 0; i < len; i++) {
int ch = read();
if (ch < 0) {
return i;
}
buf[ofs + i] = (char)ch;
}
return len;
| 606
| 148
| 754
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/commons/src/main/java/org/archive/util/ms/PieceTable.java
|
PieceTable
|
next
|
class PieceTable {
private final static Logger LOGGER
= Logger.getLogger(PieceTable.class.getName());
/** The bit that indicates if a piece uses Cp1252 or unicode. */
protected final static int CP1252_INDICATOR = 1 << 30;
/** The mask to use to clear the Cp1252 flag bit. */
protected final static int CP1252_MASK = ~(3 << 30);
/** The total number of pieces in the table. */
private int count;
/** The total number of characters in the text stream. */
private int maxCharPos;
/** The index of the current piece. */
private int current;
/** The most recently returned piece from this table. */
private Piece currentPiece;
/** The buffered stream that provides character position information. */
private SeekInputStream charPos;
/** The buffered stream that provides file pointer information. */
private SeekInputStream filePos;
/**
* Constructor.
*
* @param tableStream the stream containing the piece table
* @param offset the starting offset of the piece table
* @param maxCharPos the total number of characters in the document
* @param cachedRecords the number of piece table entries to cache
* @throws IOException if an IO error occurs
*/
public PieceTable(SeekInputStream tableStream, int offset,
int maxCharPos, int cachedRecords) throws IOException {
tableStream.position(offset);
skipProperties(tableStream);
int sizeInBytes = Endian.littleInt(tableStream);
this.count = (sizeInBytes - 4) / 12;
cachedRecords = Math.min(cachedRecords, count);
long tp = tableStream.position() + 4;
long charPosStart = tp;
long filePosStart = tp + count * 4 + 2;
this.filePos = wrap(tableStream, filePosStart, cachedRecords * 8);
this.charPos = wrap(tableStream, charPosStart, cachedRecords * 4);
this.maxCharPos = maxCharPos;
if (LOGGER.isLoggable(Level.FINEST)) {
LOGGER.finest("Size in bytes: " + sizeInBytes);
LOGGER.finest("Piece table count: " + count);
for (Piece piece = next(); piece != null; piece = next()) {
LOGGER.finest("#" + current + ": " + piece.toString());
}
current = 0;
}
}
/**
* Wraps the raw table stream. This is used to create the charPos and
* filePos streams. The streams that this method returns are "safe",
* meaning that the charPos and filePos position() fields never clobber
* each other. They are buffered, meaning that up to <i>n</i> elements
* can be read before the disk is accessed again. And they are "origined",
* meaning result.position(0) actually positions the stream at the
* beginning of the piece table array, not the beginning of the file.
*
* @param input the stream to wrap
* @param pos the origin for the returned stream
* @param cache the number of bytes for the returned stream to buffer
* @return the wrapped stream
* @throws IOException if an IO error occurs
*/
private SeekInputStream wrap(SeekInputStream input, long pos, int cache)
throws IOException {
input.position(pos);
SeekInputStream r = new SafeSeekInputStream(input);
r = new OriginSeekInputStream(r, pos);
r = new BufferedSeekInputStream(r, cache);
return r;
}
/**
* Skips over any property information that may precede a piece table.
* These property structures contain stylesheet information that applies
* to the piece table. Since we're only interested in the text itself,
* we just ignore this property stuff. (I suppose a third buffered
* stream could be used to add style information to {@link Piece}, but
* we don't need it.)
*
* @param input the input stream containing the piece table
* @throws IOException if an IO error occurs
*/
private static void skipProperties(SeekInputStream input) throws IOException {
int tag = input.read();
while (tag == 1) {
int size = Endian.littleChar(input);
while (size > 0) {
size -= input.skip(size);
}
tag = input.read();
}
if (tag != 2) {
throw new IllegalStateException();
}
}
/**
* Returns the maximum character position. Put another way, returns the
* total number of characters in the document.
*
* @return the maximum character position
*/
public int getMaxCharPos() {
return maxCharPos;
}
/**
* Returns the next piece in the piece table.
*
* @return the next piece in the piece table, or null if there is no
* next piece
* @throws IOException if an IO error occurs
*/
public Piece next() throws IOException {<FILL_FUNCTION_BODY>}
/**
* Returns the piece containing the given character position.
*
* @param charPos the character position whose piece to return
* @return that piece, or null if no such piece exists (if charPos
* is greater than getMaxCharPos())
* @throws IOException if an IO error occurs
*/
public Piece pieceFor(int charPos) throws IOException {
if (currentPiece.contains(charPos)) {
return currentPiece;
}
// FIXME: Use binary search to find piece index
current = 0;
currentPiece = null;
next();
while (currentPiece != null) {
if (currentPiece.contains(charPos)) {
return currentPiece;
}
next();
}
return null;
}
}
|
if (current >= count) {
currentPiece = null;
return null;
}
int cp;
if (current == count - 1) {
cp = maxCharPos;
} else {
charPos.position(current * 4);
cp = Endian.littleInt(charPos);
}
filePos.position(current * 8);
int encoded = Endian.littleInt(filePos);
if (LOGGER.isLoggable(Level.FINEST)) {
StringBuffer sb = new StringBuffer(Integer.toBinaryString(encoded));
while (sb.length() < 32) {
sb.insert(0, '0');
}
LOGGER.finest("Encoded offset: " + sb.toString());
}
current++;
int start;
if (currentPiece == null) {
start = 0;
} else {
start = currentPiece.getCharPosLimit();
}
if ((encoded & CP1252_INDICATOR) == 0) {
Piece piece = new Piece(encoded, start, cp, true);
currentPiece = piece;
return piece;
} else {
int filePos = (encoded & CP1252_MASK) / 2;
Piece piece = new Piece(filePos, start, cp, false);
currentPiece = piece;
return piece;
}
| 1,573
| 367
| 1,940
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/crawler/frontier/AMQPUrlReceiver.java
|
StarterRestarter
|
run
|
class StarterRestarter extends Thread {
public StarterRestarter(String name) {
super(name);
}
@Override
public void run() {<FILL_FUNCTION_BODY>}
public void startConsumer() throws IOException, TimeoutException {
Consumer consumer = new UrlConsumer(channel());
channel().exchangeDeclare(getExchange(), "direct", true);
channel().queueDeclare(getQueueName(), durable,
false, autoDelete, null);
channel().queueBind(getQueueName(), getExchange(), getQueueName());
if (prefetchCount != null)
channel().basicQos(prefetchCount);
consumerTag = channel().basicConsume(getQueueName(), false, consumer);
logger.info("started AMQP consumer uri=" + getAmqpUri() + " exchange=" + getExchange() + " queueName=" + getQueueName() + " consumerTag=" + consumerTag);
}
}
|
while (!Thread.interrupted()) {
try {
lock.lockInterruptibly();
logger.finest("Checking consumerTag=" + consumerTag + " and pauseConsumer=" + pauseConsumer);
try {
if (consumerTag == null && !pauseConsumer) {
// start up again
try {
startConsumer();
} catch (IOException | TimeoutException e) {
logger.log(Level.SEVERE, "problem starting AMQP consumer (will try again after 10 seconds)", e);
}
}
if (consumerTag != null && pauseConsumer) {
try {
if (consumerTag != null) {
logger.info("Attempting to cancel URLConsumer with consumerTag=" + consumerTag);
channel().basicCancel(consumerTag);
consumerTag = null;
logger.info("Cancelled URLConsumer.");
}
} catch (IOException | TimeoutException e) {
logger.log(Level.SEVERE, "problem cancelling AMQP consumer (will try again after 10 seconds)", e);
}
}
} finally {
lock.unlock();
}
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
return;
}
}
| 244
| 328
| 572
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/crawler/prefetch/HostQuotaEnforcer.java
|
HostQuotaEnforcer
|
shouldProcess
|
class HostQuotaEnforcer extends Processor {
protected ServerCache serverCache;
public ServerCache getServerCache() {
return this.serverCache;
}
@Autowired
public void setServerCache(ServerCache serverCache) {
this.serverCache = serverCache;
}
protected String host;
public String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
protected boolean applyToSubdomains = false;
public boolean getApplyToSubdomains() {
return applyToSubdomains;
}
/**
* Whether to apply the quotas to each subdomain of {@link #host}
* (separately, not cumulatively).
*/
public void setApplyToSubdomains(boolean applyToSubdomains) {
this.applyToSubdomains = applyToSubdomains;
}
protected Map<String,Long> quotas = new HashMap<String, Long>();
public Map<String, Long> getQuotas() {
return quotas;
}
/**
* Keys can be any of the {@link FetchStats} keys.
*/
public void setQuotas(Map<String, Long> quotas) {
this.quotas = quotas;
}
@Override
protected boolean shouldProcess(CrawlURI curi) {<FILL_FUNCTION_BODY>}
@Override
protected void innerProcess(CrawlURI curi) throws InterruptedException {
throw new AssertionError();
}
@Override
protected ProcessResult innerProcessResult(CrawlURI curi) throws InterruptedException {
if (!shouldProcess(curi)) {
return ProcessResult.PROCEED;
}
final CrawlHost host = serverCache.getHostFor(curi.getUURI());
for (String k: quotas.keySet()) {
if (host.getSubstats().get(k) >= quotas.get(k)) {
curi.getAnnotations().add("hostQuota:" + k);
curi.setFetchStatus(FetchStatusCodes.S_BLOCKED_BY_QUOTA);
return ProcessResult.FINISH;
}
}
return ProcessResult.PROCEED;
}
}
|
String uriHostname = serverCache.getHostFor(curi.getUURI()).getHostName();
if (getApplyToSubdomains() && InternetDomainName.isValid(host) && InternetDomainName.isValid(uriHostname)) {
InternetDomainName h = InternetDomainName.from(host);
InternetDomainName uriHostOrAncestor = InternetDomainName.from(uriHostname);
while (true) {
if (uriHostOrAncestor.equals(h)) {
return true;
}
if (uriHostOrAncestor.hasParent()) {
uriHostOrAncestor = uriHostOrAncestor.parent();
} else {
break;
}
}
return false;
} else {
return serverCache.getHostFor(curi.getUURI()) == serverCache.getHostFor(host);
}
| 592
| 225
| 817
|
<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/contrib/src/main/java/org/archive/crawler/prefetch/SourceQuotaEnforcer.java
|
SourceQuotaEnforcer
|
innerProcessResult
|
class SourceQuotaEnforcer extends Processor {
protected String sourceTag;
public void setSourceTag(String sourceTag) {
this.sourceTag = sourceTag;
}
public String getSourceTag() {
return sourceTag;
}
protected Map<String, Long> quotas = new HashMap<String, Long>();
public Map<String, Long> getQuotas() {
return quotas;
}
/**
* Keys can be any of the {@link CrawledBytesHistotable} keys.
*/
public void setQuotas(Map<String, Long> quotas) {
this.quotas = quotas;
}
protected StatisticsTracker statisticsTracker;
public StatisticsTracker getStatisticsTracker() {
return this.statisticsTracker;
}
@Autowired
public void setStatisticsTracker(StatisticsTracker statisticsTracker) {
this.statisticsTracker = statisticsTracker;
}
@Override
protected boolean shouldProcess(CrawlURI curi) {
return curi.containsDataKey(CoreAttributeConstants.A_SOURCE_TAG)
&& sourceTag.equals(curi.getSourceTag())
&& statisticsTracker.getSourceStats(curi.getSourceTag()) != null;
}
protected void innerProcess(CrawlURI curi) {
throw new AssertionError();
}
protected ProcessResult innerProcessResult(CrawlURI curi) {<FILL_FUNCTION_BODY>}
}
|
if (!shouldProcess(curi)) {
return ProcessResult.PROCEED;
}
CrawledBytesHistotable stats = statisticsTracker.getSourceStats(curi.getSourceTag());
for (Entry<String, Long> quota: quotas.entrySet()) {
if (stats.get(quota.getKey()) >= quota.getValue()) {
curi.getAnnotations().add("sourceQuota:" + quota.getKey());
curi.setFetchStatus(FetchStatusCodes.S_BLOCKED_BY_QUOTA);
return ProcessResult.FINISH;
}
}
return ProcessResult.PROCEED;
| 390
| 173
| 563
|
<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/contrib/src/main/java/org/archive/crawler/reporting/XmlCrawlSummaryReport.java
|
XmlCrawlSummaryReport
|
write
|
class XmlCrawlSummaryReport extends Report {
private String scheduledDate;
public void setScheduledDate(String scheduledDate) {
this.scheduledDate = scheduledDate;
}
public String getScheduledDate() {
return this.scheduledDate;
}
@Override
public void write(PrintWriter writer, StatisticsTracker stats) {<FILL_FUNCTION_BODY>}
@Override
public String getFilename() {
return "crawl-report.xml";
}
}
|
Map<String,Object> info = new LinkedHashMap<String,Object>();
CrawlStatSnapshot snapshot = stats.getLastSnapshot();
info.put("crawlName",
((BaseWARCWriterProcessor) stats.appCtx.getBean("warcWriter")).getPrefix());
info.put("crawlJobShortName",
stats.getCrawlController().getMetadata().getJobName());
info.put("scheduledDate", this.scheduledDate);
info.put("crawlStatus",
stats.getCrawlController().getCrawlExitStatus().desc);
info.put("duration",
ArchiveUtils.formatMillisecondsToConventional(stats.getCrawlElapsedTime()));
stats.tallySeeds();
info.put("seedsCrawled", stats.seedsCrawled);
info.put("seedsUncrawled",stats.seedsTotal - stats.seedsCrawled);
info.put("hostsVisited",stats.serverCache.hostKeys().size() - 1);
info.put("urisProcessed", snapshot.finishedUriCount);
info.put("uriSuccesses", snapshot.downloadedUriCount);
info.put("uriFailures", snapshot.downloadFailures);
info.put("uriDisregards", snapshot.downloadDisregards);
info.put("novelUris", stats.crawledBytes.get("novelCount"));
long duplicateCount = stats.crawledBytes.containsKey("dupByHashCount") ? stats.crawledBytes
.get("dupByHashCount").longValue() : 0L;
info.put("duplicateByHashUris", duplicateCount);
long notModifiedCount = stats.crawledBytes
.containsKey("notModifiedCount") ? stats.crawledBytes.get(
"notModifiedCount").longValue() : 0L;
info.put("notModifiedUris", notModifiedCount);
info.put("totalCrawledBytes", snapshot.bytesProcessed);
info.put("novelCrawledBytes", stats.crawledBytes.get("novel"));
long duplicateByHashCrawledBytes = stats.crawledBytes
.containsKey("dupByHash") ? stats.crawledBytes.get("dupByHash")
.longValue() : 0L;
info.put("duplicateByHashCrawledBytes",duplicateByHashCrawledBytes);
long notModifiedCrawledBytes = stats.crawledBytes
.containsKey("notModified") ? stats.crawledBytes.get(
"notModified").longValue() : 0L;
info.put("notModifiedCrawledBytes",notModifiedCrawledBytes);
info.put("urisPerSec",
ArchiveUtils.doubleToString(snapshot.docsPerSecond, 2));
info.put("kbPerSec", snapshot.totalKiBPerSec);
try {
XmlMarshaller.marshalDocument(writer,
XmlCrawlSummaryReport.class.getCanonicalName(), info);
} catch (IOException e) {
e.printStackTrace();
}
| 138
| 811
| 949
|
<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/contrib/src/main/java/org/archive/modules/AMQPProducer.java
|
AMQPProducer
|
connect
|
class AMQPProducer {
static protected final Logger logger = Logger.getLogger(AMQPProducer.class.getName());
protected String amqpUri;
protected String exchange;
protected String routingKey;
public AMQPProducer(String amqpUri, String exchange, String routingKey) {
this.amqpUri = amqpUri;
this.exchange = exchange;
this.routingKey = routingKey;
}
transient protected Connection connection = null;
transient protected ThreadLocal<Channel> threadChannel =
new ThreadLocal<Channel>();
protected synchronized Channel channel() throws IOException {
if (threadChannel.get() != null && !threadChannel.get().isOpen()) {
threadChannel.set(null);
}
if (threadChannel.get() == null) {
if (connection == null || !connection.isOpen()) {
connect();
}
try {
if (connection != null) {
threadChannel.set(connection.createChannel());
}
} catch (IOException e) {
throw new IOException("Attempting to create channel for AMQP connection failed!", e);
}
}
return threadChannel.get();
}
private AtomicBoolean serverLooksDown = new AtomicBoolean(false);
private synchronized void connect() throws IOException {<FILL_FUNCTION_BODY>}
synchronized public void stop() {
try {
if (connection != null && connection.isOpen()) {
connection.close();
connection = null;
}
} catch (IOException e) {
logger.log(Level.SEVERE, "Attempting to close AMQP connection failed!", e);
}
}
/**
* Publish the message with the supplied properties. If this method returns
* without throwing an exception, the message was published successfully.
*
* @param message
* @param props
* @throws IOException
* if message is not published successfully for any reason
*/
public void publishMessage(byte[] message, BasicProperties props)
throws IOException {
Channel channel = channel();
channel.exchangeDeclare(exchange, "direct", true);
channel.basicPublish(exchange, routingKey, props, message);
}
}
|
ConnectionFactory factory = new ConnectionFactory();
try {
factory.setUri(amqpUri);
connection = factory.newConnection();
boolean wasDown = serverLooksDown.getAndSet(false);
if (wasDown) {
logger.info(amqpUri + " is back up, connected successfully!");
}
} catch (Exception e) {
connection = null;
serverLooksDown.getAndSet(true);
throw new IOException("Attempting to connect to AMQP server failed! " + amqpUri, e);
}
| 575
| 144
| 719
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/AMQPProducerProcessor.java
|
AMQPProducerProcessor
|
amqpProducer
|
class AMQPProducerProcessor extends Processor {
protected final Logger logger = Logger.getLogger(getClass().getName());
{
setAmqpUri("amqp://guest:guest@localhost:5672/%2f");
}
public String getAmqpUri() {
return (String) kp.get("amqpUri");
}
public void setAmqpUri(String uri) {
kp.put("amqpUri", uri);
}
public String getExchange() {
return (String) kp.get("exchange");
}
public void setExchange(String exchange) {
kp.put("exchange", exchange);
}
public String getRoutingKey() {
return (String) kp.get("routingKey");
}
public void setRoutingKey(String routingKey) {
kp.put("routingKey", routingKey);
}
transient protected AMQPProducer amqpProducer;
protected AMQPProducer amqpProducer() {<FILL_FUNCTION_BODY>}
@Override
synchronized public void stop() {
if (!isRunning) {
return;
}
super.stop();
if (amqpProducer != null) {
amqpProducer.stop();
}
}
@Override
protected ProcessResult innerProcessResult(CrawlURI curi)
throws InterruptedException {
byte[] message = null;
BasicProperties props = null;
message = buildMessage(curi);
props = amqpMessageProperties();
try {
amqpProducer().publishMessage(message, props);
success(curi, message, props);
} catch (IOException e) {
fail(curi, message, props, e);
}
return ProcessResult.PROCEED;
}
protected BasicProperties amqpMessageProperties() {
return null;
}
@Override
protected void innerProcess(CrawlURI uri) throws InterruptedException {
throw new RuntimeException("should never be called");
}
abstract protected byte[] buildMessage(CrawlURI curi);
protected void success(CrawlURI curi, byte[] message, BasicProperties props) {
if (logger.isLoggable(Level.FINE)) {
try {
logger.fine("sent to amqp exchange=" + getExchange()
+ " routingKey=" + getRoutingKey() + ": " + new String(message, "UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.fine("sent to amqp exchange=" + getExchange()
+ " routingKey=" + getRoutingKey() + ": " + message + " (" + message.length + " bytes)");
}
}
}
protected void fail(CrawlURI curi, byte[] message, BasicProperties props, Throwable e) {
logger.log(Level.SEVERE, "failed to send message to amqp for URI " + curi, e);
}
}
|
if (amqpProducer == null) {
amqpProducer = new AMQPProducer(getAmqpUri(), getExchange(), getRoutingKey());
}
return amqpProducer;
| 794
| 58
| 852
|
<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/contrib/src/main/java/org/archive/modules/AMQPPublishProcessor.java
|
AMQPPublishProcessor
|
buildJsonMessage
|
class AMQPPublishProcessor extends AMQPProducerProcessor implements Serializable, ApplicationContextAware {
private static final long serialVersionUID = 2L;
public static final String A_SENT_TO_AMQP = "sentToAMQP"; // annotation
protected ApplicationContext appCtx;
public void setApplicationContext(ApplicationContext appCtx) throws BeansException {
this.appCtx = appCtx;
}
public AMQPPublishProcessor() {
// set default values
setExchange("umbra");
setRoutingKey("urls");
}
{
setClientId("requests");
}
public String getClientId() {
return (String) kp.get("clientId");
}
/**
* Client id to include in the json payload. AMQPUrlReceiver queueName
* should have the same value, since umbra will route request urls based on
* this key.
*/
public void setClientId(String clientId) {
kp.put("clientId", clientId);
}
@SuppressWarnings("unchecked")
public Map<String, Object> getExtraInfo() {
return (Map<String, Object>) kp.get("extraInfo");
}
/**
* Arbitrary additional information to include in the json payload.
*/
public void setExtraInfo(Map<String, Object> extraInfo) {
kp.put("extraInfo", extraInfo);
}
/**
* @return true iff url is http or https, is not robots.txt, was not
* received via AMQP
*/
protected boolean shouldProcess(CrawlURI curi) {
try {
return !curi.getAnnotations().contains(AMQPUrlReceiver.A_RECEIVED_FROM_AMQP)
&& !"/robots.txt".equals(curi.getUURI().getPath())
&& (curi.getUURI().getScheme().equals(FetchHTTP.HTTP_SCHEME)
|| curi.getUURI().getScheme().equals(FetchHTTP.HTTPS_SCHEME));
} catch (URIException e) {
throw new RuntimeException(e);
}
}
/**
* Constructs the json to send via AMQP. This includes the url, and some
* metadata from the CrawlURI. The metadata should be passed back to
* heritrix with each url discovered from this url. (XXX need context in
* class javadoc)
*
* @return the message to send via AMQP
* @see CrawlURI#inheritFrom(CrawlURI)
*/
protected JSONObject buildJsonMessage(CrawlURI curi) {<FILL_FUNCTION_BODY>}
@Override
protected byte[] buildMessage(CrawlURI curi) {
try {
return buildJsonMessage(curi).toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
@Override
protected void success(CrawlURI curi, byte[] message, BasicProperties props) {
super.success(curi, message, props);
curi.getAnnotations().add(A_SENT_TO_AMQP);
appCtx.publishEvent(new AMQPUrlPublishedEvent(AMQPPublishProcessor.this, curi));
}
protected BasicProperties props = new AMQP.BasicProperties.Builder().
contentType("application/json").build();
@Override
protected BasicProperties amqpMessageProperties() {
return props;
}
}
|
JSONObject message = new JSONObject().put("url", curi.toString());
if (getClientId() != null) {
message.put("clientId", getClientId());
}
if (getExtraInfo() != null) {
for (String k: getExtraInfo().keySet()) {
message.put(k, getExtraInfo().get(k));
}
}
HashMap<String, Object> metadata = new HashMap<String,Object>();
metadata.put("pathFromSeed", curi.getPathFromSeed());
@SuppressWarnings("unchecked")
Set<String> heritableKeys = (Set<String>) curi.getData().get(A_HERITABLE_KEYS);
HashMap<String, Object> heritableData = new HashMap<String,Object>();
if (heritableKeys != null) {
for (String key: heritableKeys) {
heritableData.put(key, curi.getData().get(key));
}
}
metadata.put("heritableData", heritableData);
message.put("metadata", metadata);
return message;
| 929
| 293
| 1,222
|
<methods>public non-sealed void <init>() ,public java.lang.String getAmqpUri() ,public java.lang.String getExchange() ,public java.lang.String getRoutingKey() ,public void setAmqpUri(java.lang.String) ,public void setExchange(java.lang.String) ,public void setRoutingKey(java.lang.String) ,public synchronized void stop() <variables>protected transient org.archive.modules.AMQPProducer amqpProducer,protected final java.util.logging.Logger logger
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/AMQPUrlWaiter.java
|
AMQPUrlWaiter
|
checkAMQPUrlWait
|
class AMQPUrlWaiter implements ApplicationListener<ApplicationEvent> {
public AMQPUrlWaiter() {}
static protected final Logger logger = Logger.getLogger(AMQPUrlWaiter.class.getName());
protected int urlsPublished = 0;
protected int urlsReceived = 0;
protected CrawlController controller;
public CrawlController getCrawlController() {
return this.controller;
}
@Autowired
public void setCrawlController(CrawlController controller) {
this.controller = controller;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if (event instanceof AMQPUrlPublishedEvent) {
urlsPublished += 1;
} else if (event instanceof AMQPUrlReceivedEvent) {
urlsReceived += 1;
} else if (event instanceof StatSnapshotEvent) {
checkAMQPUrlWait();
}
}
protected void checkAMQPUrlWait() {<FILL_FUNCTION_BODY>}
}
|
if (controller.getState() == CrawlController.State.EMPTY && (urlsPublished == 0 || urlsReceived > 0)) {
logger.info("crawl controller state is empty and we have received " + urlsReceived +
" urls from AMQP, and published " + urlsPublished +
", stopping crawl with status " + CrawlStatus.FINISHED);
controller.requestCrawlStop(CrawlStatus.FINISHED);
}
| 266
| 124
| 390
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/deciderules/DecideRuleSequenceWithAMQPFeed.java
|
DecideRuleSequenceWithAMQPFeed
|
buildJson
|
class DecideRuleSequenceWithAMQPFeed extends DecideRuleSequence {
private static final long serialVersionUID = 1L;
private static final Logger logger =
Logger.getLogger(DecideRuleSequenceWithAMQPFeed.class.getName());
protected String amqpUri = "amqp://guest:guest@localhost:5672/%2f";
public String getAmqpUri() {
return this.amqpUri;
}
public void setAmqpUri(String uri) {
this.amqpUri = uri;
}
protected String exchange = "heritrix.realTimeFeed";
public String getExchange() {
return exchange;
}
public void setExchange(String exchange) {
this.exchange = exchange;
}
protected String routingKey = "scopeLog";
public String getRoutingKey() {
return routingKey;
}
public void setRoutingKey(String routingKey) {
this.routingKey = routingKey;
}
protected ServerCache serverCache;
public ServerCache getServerCache() {
return this.serverCache;
}
@Autowired
public void setServerCache(ServerCache serverCache) {
this.serverCache = serverCache;
}
transient protected AMQPProducer amqpProducer;
protected AMQPProducer amqpProducer() {
if (amqpProducer == null) {
amqpProducer = new AMQPProducer(getAmqpUri(), getExchange(), getRoutingKey());
}
return amqpProducer;
}
@Override
synchronized public void stop() {
if (!isRunning) {
return;
}
super.stop();
if (amqpProducer != null) {
amqpProducer.stop();
}
}
@Override
protected void decisionMade(CrawlURI curi, DecideRule decisiveRule,
int decisiveRuleNumber, DecideResult result) {
super.decisionMade(curi, decisiveRule, decisiveRuleNumber, result);
JSONObject jo = buildJson(curi, decisiveRuleNumber, decisiveRule,
result);
byte[] message;
try {
message = jo.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
try {
amqpProducer().publishMessage(message, props);
if (logger.isLoggable(Level.FINEST)) {
logger.log(Level.FINEST, "sent message to amqp: " + jo);
}
} catch (IOException e) {
logger.log(Level.WARNING, "failed to send message to amqp: " + jo, e);
}
}
protected BasicProperties props = new AMQP.BasicProperties.Builder().
contentType("application/json").build();
protected JSONObject buildJson(CrawlURI curi, int decisiveRuleNumber,
DecideRule decisiveRule, DecideResult result) {<FILL_FUNCTION_BODY>}
}
|
JSONObject jo = new JSONObject();
jo.put("timestamp", ArchiveUtils.getLog17Date(System.currentTimeMillis()));
jo.put("decisiveRuleNo", decisiveRuleNumber);
jo.put("decisiveRule", decisiveRule.getClass().getSimpleName());
jo.put("result", result.toString());
jo.put("url", curi.toString());
CrawlHost host = getServerCache().getHostFor(curi.getUURI());
if (host != null) {
jo.put("host", host.fixUpName());
} else {
jo.put("host", JSONObject.NULL);
}
jo.put("sourceSeed", curi.getSourceTag());
jo.put("via", curi.flattenVia());
return jo;
| 808
| 213
| 1,021
|
<methods>public non-sealed void <init>() ,public java.lang.String getBeanName() ,public boolean getLogExtraInfo() ,public boolean getLogToFile() ,public org.archive.modules.SimpleFileLoggerProvider getLoggerModule() ,public List<org.archive.modules.deciderules.DecideRule> getRules() ,public org.archive.modules.net.ServerCache getServerCache() ,public org.archive.modules.deciderules.DecideResult innerDecide(org.archive.modules.CrawlURI) ,public boolean isRunning() ,public void setBeanName(java.lang.String) ,public void setLogExtraInfo(boolean) ,public void setLogToFile(boolean) ,public void setLoggerModule(org.archive.modules.SimpleFileLoggerProvider) ,public void setRules(List<org.archive.modules.deciderules.DecideRule>) ,public void setServerCache(org.archive.modules.net.ServerCache) ,public void start() ,public void stop() <variables>private static final java.util.logging.Logger LOGGER,protected java.lang.String beanName,protected transient java.util.logging.Logger fileLogger,protected boolean isRunning,protected boolean logExtraInfo,protected org.archive.modules.SimpleFileLoggerProvider loggerModule,private static final long serialVersionUID,protected org.archive.modules.net.ServerCache serverCache
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/deciderules/ExpressionDecideRule.java
|
ExpressionDecideRule
|
evaluate
|
class ExpressionDecideRule extends PredicatedDecideRule {
private static final long serialVersionUID = 1L;
private static final Logger logger =
Logger.getLogger(ExpressionDecideRule.class.getName());
{
setGroovyExpression("");
}
public void setGroovyExpression(String groovyExpression) {
kp.put("groovyExpression", groovyExpression);
}
public String getGroovyExpression() {
return (String) kp.get("groovyExpression");
}
protected ConcurrentHashMap<String,Template> groovyTemplates = new ConcurrentHashMap<String, Template>();
protected Template groovyTemplate() {
Template groovyTemplate = groovyTemplates.get(getGroovyExpression());
if (groovyTemplate == null) {
try {
groovyTemplate = new SimpleTemplateEngine().createTemplate("${" + getGroovyExpression() + "}");
groovyTemplates.put(getGroovyExpression(), groovyTemplate);
} catch (Exception e) {
logger.log(Level.SEVERE, "problem with groovy expression " + getGroovyExpression(), e);
}
}
return groovyTemplate;
}
@Override
protected boolean evaluate(CrawlURI curi) {<FILL_FUNCTION_BODY>}
}
|
HashMap<String, Object> binding = new HashMap<String, Object>();
binding.put("curi", curi);
return String.valueOf(true).equals(groovyTemplate().make(binding).toString());
| 362
| 58
| 420
|
<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/contrib/src/main/java/org/archive/modules/extractor/ExtractorPDFContent.java
|
ExtractorPDFContent
|
innerExtract
|
class ExtractorPDFContent extends ContentExtractor {
@SuppressWarnings("unused")
private static final long serialVersionUID = 3L;
private static final Logger LOGGER =
Logger.getLogger(ExtractorPDFContent.class.getName());
public static final Pattern URLPattern = Pattern.compile(
"(?i)\\(?(https?):\\/\\/"+ // protocol
"(([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+"+ // username
"(:([a-z0-9$_\\.\\+!\\*\\'\\(\\),;\\?&=-]|%[0-9a-f]{2})+)?"+ // password
"@)?(?"+ // auth requires @
")((([a-z0-9]\\.|[a-z0-9][a-z0-9-]*[a-z0-9]\\.)*"+ // domain segments AND
"[a-z][a-z0-9-]*[a-z0-9]"+ // top level domain OR
"|((\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])\\.){3}"+
"(\\d|[1-9]\\d|1\\d{2}|2[0-4][0-9]|25[0-5])"+ // IP address
")(:\\d+)?)"+ // port
"(((\\/+([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)*"+ // path
"(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)?)?)?"+ // query string
"(\\n(?!http://)"+ // possible newline (seems to happen in pdfs)
"((\\/)?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)*"+ // continue possible path
"(\\?([a-z0-9$_\\.\\+!\\*\\'\\(\\),;:@&=-]|%[0-9a-f]{2})*)?"+ // or possible query
")?");
{
setMaxSizeToParse(10*1024*1024L); // 10MB
}
public long getMaxSizeToParse() {
return (Long) kp.get("maxSizeToParse");
}
/**
* The maximum size of PDF files to consider. PDFs larger than this
* maximum will not be searched for links.
*/
public void setMaxSizeToParse(long threshold) {
kp.put("maxSizeToParse",threshold);
}
public ExtractorPDFContent() {
}
protected boolean innerExtract(CrawlURI curi){<FILL_FUNCTION_BODY>}
@Override
protected boolean shouldExtract(CrawlURI uri) {
long max = getMaxSizeToParse();
if (uri.getRecorder().getRecordedInput().getSize() > max) {
return false;
}
String ct = uri.getContentType();
return (ct != null) && (ct.startsWith("application/pdf"));
}
}
|
ArrayList<String> uris = new ArrayList<String>();
File tempFile = null;
try {
tempFile = File.createTempFile("heritrix-ExtractorPDFContent", "tmp.pdf");
curi.getRecorder().copyContentBodyTo(tempFile);
try (PDDocument document = Loader.loadPDF(tempFile)) {
PDFTextStripper textStripper = new PDFTextStripper();
for (int i = 1; i <= document.getNumberOfPages(); i++) { //Page numbers start at 1
textStripper.setStartPage(i);
textStripper.setEndPage(i);
String pageParseText = textStripper.getText(document);
Matcher matcher = URLPattern.matcher(pageParseText);
while (matcher.find()) {
String prospectiveURL = pageParseText.substring(matcher.start(), matcher.end()).trim();
//handle URLs wrapped in parentheses
if (prospectiveURL.startsWith("(")) {
prospectiveURL = prospectiveURL.substring(1, prospectiveURL.length());
if (prospectiveURL.endsWith(")"))
prospectiveURL = prospectiveURL.substring(0, prospectiveURL.length() - 1);
}
uris.add(prospectiveURL);
//parsetext URLs tend to end in a '.' if they are in a sentence, queue without trailing '.'
if (prospectiveURL.endsWith(".") && prospectiveURL.length() > 2)
uris.add(prospectiveURL.substring(0, prospectiveURL.length() - 1));
//Full regex allows newlines which seem to be common, also add match without newline in case we are wrong
if (matcher.group(19) != null) {
String alternateURL = matcher.group(1) + "://" + (matcher.group(2) != null ? matcher.group(2) : "") + matcher.group(6) + matcher.group(13);
//Again, handle URLs wrapped in parentheses
if (prospectiveURL.startsWith("(") && alternateURL.endsWith(")"))
alternateURL = alternateURL.substring(0, alternateURL.length() - 1);
// Again, remove trailing '.'
if (alternateURL.endsWith(".") && alternateURL.length() > 2)
alternateURL = alternateURL.substring(0, alternateURL.length() - 1);
uris.add(alternateURL);
}
}
}
}
} catch (IOException e) {
curi.getNonFatalFailures().add(e);
return false;
} catch (RuntimeException e) {
curi.getNonFatalFailures().add(e);
return false;
} finally {
if (tempFile != null) {
tempFile.delete();
}
}
if (uris.size()<1) {
return true;
}
for (String uri: uris) {
addOutlink(curi, uri, LinkContext.NAVLINK_MISC, Hop.NAVLINK);
}
numberOfLinksExtracted.addAndGet(uris.size());
LOGGER.fine(curi+" has "+uris.size()+" links.");
// Set flag to indicate that link extraction is completed.
return true;
| 928
| 878
| 1,806
|
<methods>public non-sealed void <init>() <variables>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/extractor/ExtractorYoutubeChannelFormatStream.java
|
ExtractorYoutubeChannelFormatStream
|
extract
|
class ExtractorYoutubeChannelFormatStream extends
ExtractorYoutubeFormatStream {
private static Logger logger =
Logger.getLogger(ExtractorYoutubeChannelFormatStream.class.getName());
{
setExtractLimit(1);
}
@Override
protected boolean shouldProcess(CrawlURI uri) {
return uri.getContentLength() > 0
&& uri.getFetchStatus() == 200
&& TextUtils.matches("^https?://(?:www\\.)?youtube\\.com/user.*$",
uri.getUURI().toCustomString());
}
@Override
protected void extract(CrawlURI uri) {<FILL_FUNCTION_BODY>}
}
|
ReplayCharSequence cs;
try {
cs = uri.getRecorder().getContentReplayCharSequence();
} catch (IOException e) {
uri.getNonFatalFailures().add(e);
logger.log(Level.WARNING, "Failed get of replay char sequence in "
+ Thread.currentThread().getName(), e);
return;
}
Matcher matcher = TextUtils.getMatcher(
"data-swf-config=\"(\\{.*?\\}\")>", cs);
if (matcher.find()) {
String str = matcher.group(1);
String jsonStr = StringEscapeUtils.unescapeHtml(StringEscapeUtils.unescapeHtml(str));
// logger.fine("Just Extracted: "+jsonStr);
try {
JSONObject json = new JSONObject(jsonStr);
if (json.has("args")) {
JSONObject args = json.getJSONObject("args");
if (args.has("url_encoded_fmt_stream_map")) {
String streamMap = args.getString("url_encoded_fmt_stream_map");
// logger.info("Just Extracted: "+stream_map);
LinkedHashMap<String, String> parsedVideoMap = parseStreamMap(streamMap);
addPreferredOutlinks(uri, parsedVideoMap);
}
}
} catch (JSONException e) {
logger.log(Level.WARNING,
"Error parsing JSON object - Skipping extraction", e);
}
}
TextUtils.recycleMatcher(matcher);
| 193
| 401
| 594
|
<methods>public non-sealed void <init>() ,public java.lang.Integer getExtractLimit() ,public List<java.lang.String> getItagPriority() ,public void setExtractLimit(java.lang.Integer) ,public void setItagPriority(List<java.lang.String>) <variables>private static final List<java.lang.String> DEFAULT_ITAG_PRIORITY,private static final Set<java.lang.String> KNOWN_ITAGS,private static java.util.logging.Logger logger
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/extractor/KnowledgableExtractorJS.java
|
CustomizedCrawlURIFacade
|
considerStrings
|
class CustomizedCrawlURIFacade extends CrawlURI {
private static final long serialVersionUID = 1l;
protected CrawlURI wrapped;
protected UURI baseURI;
public CustomizedCrawlURIFacade(CrawlURI wrapped, UURI baseURI) {
super(wrapped.getUURI(), wrapped.getPathFromSeed(), wrapped.getVia(), wrapped.getViaContext());
this.wrapped = wrapped;
this.baseURI = baseURI;
}
/**
* @return value set in {@link #CustomizedCrawlURIFacade(CrawlURI, UURI)}
*/
@Override
public UURI getBaseURI() {
return baseURI;
}
/** Delegates to wrapped CrawlURI */
@Override
public CrawlURI createCrawlURI(UURI destination, LinkContext context,
Hop hop) throws URIException {
return wrapped.createCrawlURI(destination, context, hop);
}
/** Delegates to wrapped CrawlURI */
@Override
public Collection<CrawlURI> getOutLinks() {
return wrapped.getOutLinks();
}
/** Delegates to wrapped CrawlURI */
@Override
public void incrementDiscardedOutLinks() {
wrapped.incrementDiscardedOutLinks();
}
}
public long considerStrings(Extractor ext,
CrawlURI curi, CharSequence cs, boolean handlingJSFile) {<FILL_FUNCTION_BODY>
|
CrawlURI baseUri = curi;
Matcher m = TextUtils.getMatcher("jQuery\\.extend\\(Drupal\\.settings,[^'\"]*['\"]basePath['\"]:[^'\"]*['\"]([^'\"]+)['\"]", cs);
if (m.find()) {
String basePath = m.group(1);
try {
basePath = StringEscapeUtils.unescapeJavaScript(basePath);
} catch (NestableRuntimeException e) {
LOGGER.log(Level.WARNING, "problem unescaping purported drupal basePath '" + basePath + "'", e);
}
try {
UURI baseUURI = UURIFactory.getInstance(curi.getUURI(), basePath);
baseUri = new CustomizedCrawlURIFacade(curi, baseUURI);
} catch (URIException e) {
LOGGER.log(Level.WARNING, "problem creating UURI from drupal basePath '" + basePath + "'", e);
}
}
TextUtils.recycleMatcher(m);
// extract youtube videoid from youtube javascript embed and create link
// for watch page
m = TextUtils.getMatcher("new[\\s]+YT\\.Player\\(['\"][^'\"]+['\"],[\\s]+\\{[\\n\\s\\w:'\",]+videoId:[\\s]+['\"]([\\w-]+)['\"],", cs);
if (m.find()) {
String videoId = m.group(1);
String newUri = "https://www.youtube.com/watch?v=" + videoId;
try {
addRelativeToBase(curi, ext.getExtractorParameters().getMaxOutlinks(), newUri, LinkContext.INFERRED_MISC,
Hop.INFERRED);
} catch (URIException e) {
// no way this should happen
throw new IllegalStateException(newUri, e);
}
}
TextUtils.recycleMatcher(m);
return super.considerStrings(ext, baseUri, cs, handlingJSFile);
| 396
| 552
| 948
|
<methods>public non-sealed void <init>() ,public long considerStrings(org.archive.modules.extractor.Extractor, org.archive.modules.CrawlURI, java.lang.CharSequence) ,public long considerStrings(org.archive.modules.extractor.Extractor, org.archive.modules.CrawlURI, java.lang.CharSequence, boolean) <variables>protected static final java.lang.String JAVASCRIPT_STRING_EXTRACTOR,private static java.util.logging.Logger LOGGER,protected long numberOfCURIsHandled,private static final long serialVersionUID
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/postprocessor/AMQPCrawlLogFeed.java
|
AMQPCrawlLogFeed
|
stop
|
class AMQPCrawlLogFeed extends AMQPProducerProcessor implements Lifecycle {
protected Frontier frontier;
public Frontier getFrontier() {
return this.frontier;
}
/** Autowired frontier, needed to determine when a url is finished. */
@Autowired
public void setFrontier(Frontier frontier) {
this.frontier = frontier;
}
protected ServerCache serverCache;
public ServerCache getServerCache() {
return this.serverCache;
}
@Autowired
public void setServerCache(ServerCache serverCache) {
this.serverCache = serverCache;
}
protected Map<String,String> extraFields;
public Map<String, String> getExtraFields() {
return extraFields;
}
public void setExtraFields(Map<String, String> extraFields) {
this.extraFields = extraFields;
}
protected boolean dumpPendingAtClose = false;
public boolean getDumpPendingAtClose() {
return dumpPendingAtClose;
}
/**
* If true, publish all pending urls (i.e. queued urls still in the
* frontier) when crawl job is stopping. They are recognizable by the status
* field which has the value 0.
*
* @see BdbFrontier#setDumpPendingAtClose(boolean)
*/
public void setDumpPendingAtClose(boolean dumpPendingAtClose) {
this.dumpPendingAtClose = dumpPendingAtClose;
}
public AMQPCrawlLogFeed() {
// set default values
setExchange("heritrix.realTimeFeed");
setRoutingKey("crawlLog");
}
@Override
protected byte[] buildMessage(CrawlURI curi) {
JSONObject jo = CrawlLogJsonBuilder.buildJson(curi, getExtraFields(), getServerCache());
try {
return jo.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
@Override
protected boolean shouldProcess(CrawlURI curi) {
if (frontier instanceof AbstractFrontier) {
return !((AbstractFrontier) frontier).needsReenqueuing(curi);
} else {
return false;
}
}
private transient long pendingDumpedCount = 0l;
@Override
public synchronized void stop() {<FILL_FUNCTION_BODY>}
protected BasicProperties props = new AMQP.BasicProperties.Builder().
contentType("application/json").build();
@Override
protected BasicProperties amqpMessageProperties() {
return props;
}
}
|
if (!isRunning) {
return;
}
if (dumpPendingAtClose) {
if (frontier instanceof BdbFrontier) {
Closure closure = new Closure() {
public void execute(Object curi) {
try {
innerProcessResult((CrawlURI) curi);
pendingDumpedCount++;
} catch (InterruptedException e) {
}
}
};
logger.info("dumping " + frontier.queuedUriCount() + " queued urls to amqp feed");
((BdbFrontier) frontier).forAllPendingDo(closure);
logger.info("dumped " + pendingDumpedCount + " queued urls to amqp feed");
} else {
logger.warning("frontier is not a BdbFrontier, cannot dumpPendingAtClose");
}
}
// closes amqp connection
super.stop();
| 705
| 243
| 948
|
<methods>public non-sealed void <init>() ,public java.lang.String getAmqpUri() ,public java.lang.String getExchange() ,public java.lang.String getRoutingKey() ,public void setAmqpUri(java.lang.String) ,public void setExchange(java.lang.String) ,public void setRoutingKey(java.lang.String) ,public synchronized void stop() <variables>protected transient org.archive.modules.AMQPProducer amqpProducer,protected final java.util.logging.Logger logger
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/postprocessor/CrawlLogJsonBuilder.java
|
CrawlLogJsonBuilder
|
buildJson
|
class CrawlLogJsonBuilder {
protected static Object checkForNull(Object o) {
return o != null ? o : JSONObject.NULL;
}
public static JSONObject buildJson(CrawlURI curi, Map<String,String> extraFields, ServerCache serverCache) {<FILL_FUNCTION_BODY>}
}
|
JSONObject jo = new JSONObject();
jo.put("timestamp", ArchiveUtils.getLog17Date(System.currentTimeMillis()));
for (Entry<String, String> entry: extraFields.entrySet()) {
jo.put(entry.getKey(), entry.getValue());
}
jo.put("content_length", curi.isHttpTransaction() && curi.getContentLength() >= 0 ? curi.getContentLength() : JSONObject.NULL);
jo.put("size", curi.getContentSize() > 0 ? curi.getContentSize() : JSONObject.NULL);
jo.put("status_code", checkForNull(curi.getFetchStatus()));
jo.put("url", checkForNull(curi.getUURI().toString()));
jo.put("hop_path", checkForNull(curi.getPathFromSeed()));
jo.put("via", checkForNull(curi.flattenVia()));
jo.put("mimetype", checkForNull(MimetypeUtils.truncate(curi.getContentType())));
jo.put("thread", checkForNull(curi.getThreadNumber()));
if (curi.containsDataKey(CoreAttributeConstants.A_FETCH_COMPLETED_TIME)) {
long beganTime = curi.getFetchBeginTime();
String fetchBeginDuration = ArchiveUtils.get17DigitDate(beganTime)
+ "+" + (curi.getFetchCompletedTime() - beganTime);
jo.put("start_time_plus_duration", fetchBeginDuration);
} else {
jo.put("start_time_plus_duration", JSONObject.NULL);
}
jo.put("content_digest", checkForNull(curi.getContentDigestSchemeString()));
jo.put("seed", checkForNull(curi.getSourceTag()));
CrawlHost host = serverCache.getHostFor(curi.getUURI());
if (host != null) {
jo.put("host", host.fixUpName());
} else {
jo.put("host", JSONObject.NULL);
}
jo.put("annotations", checkForNull(StringUtils.join(curi.getAnnotations(), ",")));
JSONObject ei = curi.getExtraInfo();
if (ei == null) {
ei = new JSONObject();
}
// copy so we can remove unrolled fields
ei = new JSONObject(curi.getExtraInfo().toString());
ei.remove("contentSize"); // we get this value above
jo.put("warc_filename", checkForNull(ei.remove("warcFilename")));
jo.put("warc_offset", checkForNull(ei.remove("warcFileOffset")));
jo.put("extra_info", ei);
return jo;
| 88
| 712
| 800
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/postprocessor/KafkaCrawlLogFeed.java
|
KafkaCrawlLogFeed
|
kafkaProducer
|
class KafkaCrawlLogFeed extends Processor implements Lifecycle {
protected static final Logger logger = Logger.getLogger(KafkaCrawlLogFeed.class.getName());
protected Frontier frontier;
public Frontier getFrontier() {
return this.frontier;
}
/** Autowired frontier, needed to determine when a url is finished. */
@Autowired
public void setFrontier(Frontier frontier) {
this.frontier = frontier;
}
protected ServerCache serverCache;
public ServerCache getServerCache() {
return this.serverCache;
}
@Autowired
public void setServerCache(ServerCache serverCache) {
this.serverCache = serverCache;
}
protected Map<String,String> extraFields;
public Map<String, String> getExtraFields() {
return extraFields;
}
public void setExtraFields(Map<String, String> extraFields) {
this.extraFields = extraFields;
}
protected boolean dumpPendingAtClose = false;
public boolean getDumpPendingAtClose() {
return dumpPendingAtClose;
}
/**
* If true, publish all pending urls (i.e. queued urls still in the
* frontier) when crawl job is stopping. They are recognizable by the status
* field which has the value 0.
*
* @see BdbFrontier#setDumpPendingAtClose(boolean)
*/
public void setDumpPendingAtClose(boolean dumpPendingAtClose) {
this.dumpPendingAtClose = dumpPendingAtClose;
}
protected String brokerList = "localhost:9092";
/** Kafka broker list (kafka property "metadata.broker.list"). */
public void setBrokerList(String brokerList) {
this.brokerList = brokerList;
}
public String getBrokerList() {
return brokerList;
}
protected String topic = "heritrix-crawl-log";
public void setTopic(String topic) {
this.topic = topic;
}
public String getTopic() {
return topic;
}
protected byte[] buildMessage(CrawlURI curi) {
JSONObject jo = CrawlLogJsonBuilder.buildJson(curi, getExtraFields(), getServerCache());
try {
return jo.toString().getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
@Override
protected boolean shouldProcess(CrawlURI curi) {
if (frontier instanceof AbstractFrontier) {
return !((AbstractFrontier) frontier).needsReenqueuing(curi);
} else {
return false;
}
}
private transient long pendingDumpedCount = 0l;
@Override
public synchronized void stop() {
if (!isRunning) {
return;
}
if (dumpPendingAtClose) {
if (frontier instanceof BdbFrontier) {
Closure closure = new Closure() {
public void execute(Object curi) {
try {
innerProcess((CrawlURI) curi);
pendingDumpedCount++;
} catch (InterruptedException e) {
}
}
};
logger.info("dumping " + frontier.queuedUriCount() + " queued urls to kafka feed");
((BdbFrontier) frontier).forAllPendingDo(closure);
logger.info("dumped " + pendingDumpedCount + " queued urls to kafka feed");
} else {
logger.warning("frontier is not a BdbFrontier, cannot dumpPendingAtClose");
}
}
String rateStr = String.format("%1.1f", 0.01 * stats.errors / stats.total);
logger.info("final error count: " + stats.errors + "/" + stats.total + " (" + rateStr + "%)");
if (kafkaProducer != null) {
kafkaProducer.close();
kafkaProducer = null;
}
if (kafkaProducerThreads != null) {
kafkaProducerThreads.destroy();
kafkaProducerThreads = null;
}
super.stop();
}
private transient ThreadGroup kafkaProducerThreads;
transient protected KafkaProducer<String, byte[]> kafkaProducer;
protected KafkaProducer<String, byte[]> kafkaProducer() {<FILL_FUNCTION_BODY>}
protected final class StatsCallback implements Callback {
public long errors = 0l;
public long total = 0l;
@Override
public void onCompletion(RecordMetadata metadata, Exception exception) {
total++;
if (exception != null) {
errors++;
}
if (total % 10000 == 0) {
String rateStr = String.format("%1.1f", 0.01 * errors / total);
logger.info("error count so far: " + errors + "/" + total + " (" + rateStr + "%)");
}
}
}
protected StatsCallback stats = new StatsCallback();
@Override
protected void innerProcess(CrawlURI curi) throws InterruptedException {
byte[] message = buildMessage(curi);
ProducerRecord<String, byte[]> producerRecord = new ProducerRecord<String,byte[]>(getTopic(), message);
kafkaProducer().send(producerRecord, stats);
}
}
|
if (kafkaProducer == null) {
synchronized (this) {
if (kafkaProducer == null) {
final Properties props = new Properties();
props.put("bootstrap.servers", getBrokerList());
props.put("acks", "1");
props.put("producer.type", "async");
props.put("key.serializer", StringSerializer.class.getName());
props.put("value.serializer", ByteArraySerializer.class.getName());
/*
* XXX This mess here exists so that the kafka producer
* thread is in a thread group that is not the ToePool,
* so that it doesn't get interrupted at the end of the
* crawl in ToePool.cleanup().
*/
kafkaProducerThreads = new ThreadGroup(Thread.currentThread().getThreadGroup().getParent(), "KafkaProducerThreads");
ThreadFactory threadFactory = new ThreadFactory() {
public Thread newThread(Runnable r) {
return new Thread(kafkaProducerThreads, r);
}
};
Callable<KafkaProducer<String,byte[]>> task = new Callable<KafkaProducer<String,byte[]>>() {
public KafkaProducer<String, byte[]> call() throws InterruptedException {
return new KafkaProducer<String,byte[]>(props);
}
};
ExecutorService executorService = Executors.newFixedThreadPool(1, threadFactory);
Future<KafkaProducer<String, byte[]>> future = executorService.submit(task);
try {
kafkaProducer = future.get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
} finally {
executorService.shutdown();
}
}
}
}
return kafkaProducer;
| 1,456
| 491
| 1,947
|
<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/contrib/src/main/java/org/archive/modules/postprocessor/WARCLimitEnforcer.java
|
WARCLimitEnforcer
|
innerProcess
|
class WARCLimitEnforcer extends Processor {
private final static Logger log =
Logger.getLogger(WARCLimitEnforcer.class.getName());
protected Map<String, Map<String, Long>> limits = new HashMap<String, Map<String, Long>>();
/**
* Should match structure of {@link BaseWARCWriterProcessor#getStats()}
* @param limits
*/
public void setLimits(Map<String, Map<String, Long>> limits) {
this.limits = limits;
}
public Map<String, Map<String, Long>> getLimits() {
return limits;
}
protected BaseWARCWriterProcessor warcWriter;
@Autowired
public void setWarcWriter(BaseWARCWriterProcessor warcWriter) {
this.warcWriter = warcWriter;
}
public BaseWARCWriterProcessor getWarcWriter() {
return warcWriter;
}
{
setWarcWriters(new ArrayList<BaseWARCWriterProcessor>());
}
@SuppressWarnings("unchecked")
public List<BaseWARCWriterProcessor> getWarcWriters() {
return (List<BaseWARCWriterProcessor>) kp.get("warcWriters");
}
public void setWarcWriters(List<BaseWARCWriterProcessor> warcWriters) {
kp.put("warcWriters", warcWriters);
}
protected CrawlController controller;
public CrawlController getCrawlController() {
return this.controller;
}
@Autowired
public void setCrawlController(CrawlController controller) {
this.controller = controller;
}
@Override
protected boolean shouldProcess(CrawlURI uri) {
return true;
}
@Override
protected void innerProcess(CrawlURI uri) throws InterruptedException {<FILL_FUNCTION_BODY>}
}
|
for (String j: limits.keySet()) {
for (String k: limits.get(j).keySet()) {
Long limit = limits.get(j).get(k);
AtomicLong value = null;
if(getWarcWriters() !=null && getWarcWriters().size()>0) {
value = new AtomicLong(0);
for (BaseWARCWriterProcessor w: getWarcWriters()) {
Map<String, AtomicLong> valueBucket = w.getStats().get(j);
if(valueBucket != null) {
value.set(value.addAndGet(valueBucket.get(k).get()));
}
}
}
else {
Map<String, AtomicLong> valueBucket = warcWriter.getStats().get(j);
if(valueBucket != null) {
value = valueBucket.get(k);
}
}
if (value != null
&& value.get() >= limit) {
log.info("stopping crawl because warcwriter stats['" + j + "']['" + k + "']=" + value.get() + " exceeds limit " + limit);
controller.requestCrawlStop(CrawlStatus.FINISHED_WRITE_LIMIT);
}
}
}
| 511
| 339
| 850
|
<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/contrib/src/main/java/org/archive/modules/recrawl/FetchHistoryHelper.java
|
FetchHistoryHelper
|
getFetchHistory
|
class FetchHistoryHelper {
private static final Log logger = LogFactory.getLog(FetchHistoryHelper.class);
/**
* key for storing timestamp in crawl history map.
*/
public static final String A_TIMESTAMP = ".ts";
/**
* returns a Map to store recrawl data, positioned properly in CrawlURI's
* fetch history array, according to {@code timestamp}. this makes it possible
* to import crawl history data from multiple sources.
* @param uri target {@link CrawlURI}
* @param timestamp timestamp (in ms) of crawl history to be added.
* @return Map object to store recrawl data, or null if {@code timestamp} is older
* than existing crawl history entry and there's no room for it.
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> getFetchHistory(CrawlURI uri, long timestamp, int historyLength) {<FILL_FUNCTION_BODY>}
protected static final DateFormat HTTP_DATE_FORMAT = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz");
protected FetchHistoryHelper() {
}
/**
* converts time in HTTP Date format {@code dateStr} to seconds
* since epoch.
* @param dateStr time in HTTP Date format.
* @return seconds since epoch
*/
public static long parseHttpDate(String dateStr) {
synchronized (HTTP_DATE_FORMAT) {
try {
Date d = HTTP_DATE_FORMAT.parse(dateStr);
return d.getTime() / 1000;
} catch (ParseException ex) {
if (logger.isDebugEnabled())
logger.debug("bad HTTP DATE: " + dateStr);
return 0;
}
}
}
public static String formatHttpDate(long time) {
synchronized (HTTP_DATE_FORMAT) {
// format(Date) is not thread safe either
return HTTP_DATE_FORMAT.format(new Date(time * 1000));
}
}
}
|
Map<String, Object>[] history = uri.getFetchHistory();
if (history == null) {
// there's no history records at all.
// FetchHistoryProcessor assumes history is HashMap[], not Map[].
history = new HashMap[historyLength];
uri.setFetchHistory(history);
}
for (int i = 0; i < history.length; i++) {
if (history[i] == null) {
history[i] = new HashMap<String, Object>();
history[i].put(A_TIMESTAMP, timestamp);
return history[i];
}
Object ts = history[i].get(A_TIMESTAMP);
// no timestamp value is regarded as older than anything.
if (!(ts instanceof Long) || timestamp > (Long)ts) {
if (i < history.length - 2) {
System.arraycopy(history, i, history, i + 1, history.length - i - 1);
} else if (i == history.length - 2) {
history[i + 1] = history[i];
}
history[i] = new HashMap<String, Object>();
history[i].put(A_TIMESTAMP, timestamp);
return history[i];
}
}
return null;
| 532
| 328
| 860
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/recrawl/TroughContentDigestHistory.java
|
TroughContentDigestHistory
|
onApplicationEvent
|
class TroughContentDigestHistory extends AbstractContentDigestHistory implements HasKeyedProperties, ApplicationListener<CrawlStateEvent> {
private static final Logger logger = Logger.getLogger(TroughContentDigestHistory.class.getName());
protected KeyedProperties kp = new KeyedProperties();
public KeyedProperties getKeyedProperties() {
return kp;
}
public void setSegmentId(String segmentId) {
kp.put("segmentId", segmentId);
}
public String getSegmentId() {
return (String) kp.get("segmentId");
}
/**
* @param rethinkUrl url with schema rethinkdb:// pointing to
* trough configuration database
*/
public void setRethinkUrl(String rethinkUrl) {
kp.put("rethinkUrl", rethinkUrl);
}
public String getRethinkUrl() {
return (String) kp.get("rethinkUrl");
}
protected TroughClient troughClient = null;
protected TroughClient troughClient() throws MalformedURLException {
if (troughClient == null) {
troughClient = new TroughClient(getRethinkUrl(), 60 * 60);
troughClient.start();
}
return troughClient;
}
protected static final String SCHEMA_ID = "warcprox-dedup-v1";
protected static final String SCHEMA_SQL = "create table dedup (\n"
+ " digest_key varchar(100) primary key,\n"
+ " url varchar(2100) not null,\n"
+ " date varchar(100) not null,\n"
+ " id varchar(100));\n"; // warc record id
@Override
public void onApplicationEvent(CrawlStateEvent event) {<FILL_FUNCTION_BODY>}
@Override
public void load(CrawlURI curi) {
// make this call in all cases so that the value is initialized and
// WARCWriterProcessor knows it should put the info in there
HashMap<String, Object> contentDigestHistory = curi.getContentDigestHistory();
try {
String sql = "select * from dedup where digest_key = %s";
List<Map<String, Object>> results = troughClient().read(getSegmentId(), sql, new String[] {persistKeyFor(curi)});
if (!results.isEmpty()) {
Map<String,Object> hist = new HashMap<String, Object>();
hist.put(A_ORIGINAL_URL, results.get(0).get("url"));
hist.put(A_ORIGINAL_DATE, results.get(0).get("date"));
hist.put(A_WARC_RECORD_ID, results.get(0).get("id"));
if (logger.isLoggable(Level.FINER)) {
logger.finer("loaded history by digest " + persistKeyFor(curi)
+ " for uri " + curi + " - " + hist);
}
contentDigestHistory.putAll(hist);
}
} catch (TroughNoReadUrlException e) {
// this is totally normal at the beginning of the crawl, for example
logger.log(Level.FINE, "problem retrieving dedup info from trough segment " + getSegmentId() + " for url " + curi, e);
} catch (Exception e) {
logger.log(Level.WARNING, "problem retrieving dedup info from trough segment " + getSegmentId() + " for url " + curi, e);
}
}
protected static final String WRITE_SQL_TMPL =
"insert or ignore into dedup (digest_key, url, date, id) values (%s, %s, %s, %s);";
@Override
public void store(CrawlURI curi) {
if (!curi.hasContentDigestHistory() || curi.getContentDigestHistory().isEmpty()) {
return;
}
Map<String,Object> hist = curi.getContentDigestHistory();
try {
String digestKey = persistKeyFor(curi);
Object url = hist.get(A_ORIGINAL_URL);
Object date = hist.get(A_ORIGINAL_DATE);
Object recordId = hist.get(A_WARC_RECORD_ID);
Object[] values = new Object[] { digestKey, url, date, recordId };
troughClient().write(getSegmentId(), WRITE_SQL_TMPL, values, SCHEMA_ID);
} catch (Exception e) {
logger.log(Level.WARNING, "problem writing dedup info to trough segment " + getSegmentId() + " for url " + curi, e);
}
}
}
|
switch(event.getState()) {
case PREPARING:
try {
// initializes TroughClient and starts promoter thread as a side effect
troughClient().registerSchema(SCHEMA_ID, SCHEMA_SQL);
} catch (Exception e) {
// can happen. hopefully someone else has registered it
logger.log(Level.SEVERE, "will try to continue after problem registering schema " + SCHEMA_ID, e);
}
break;
case FINISHED:
/*
* We do this here at FINISHED rather than at STOPPING time to make
* sure every URL has had a chance to have its dedup info stored,
* before committing the trough segment to permanent storage.
*
* (When modules implement org.springframework.context.Lifecycle,
* stop() is called in the STOPPING phase, before all URLs are
* necessarily finished processing.)
*/
if (troughClient != null) {
troughClient.stop();
troughClient.promoteDirtySegments();
troughClient = null;
}
break;
default:
}
| 1,225
| 296
| 1,521
|
<methods>public non-sealed void <init>() ,public abstract void load(org.archive.modules.CrawlURI) ,public abstract void store(org.archive.modules.CrawlURI) <variables>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/recrawl/hbase/HBase.java
|
HBase
|
configuration
|
class HBase implements Lifecycle {
private static final Logger logger =
Logger.getLogger(HBase.class.getName());
protected Configuration conf = null;
private Map<String,String> properties;
public Map<String,String> getProperties() {
return properties;
}
public void setProperties(Map<String,String> properties) {
this.properties = properties;
if (conf == null) {
conf = HBaseConfiguration.create();
}
for (Entry<String, String> entry: getProperties().entrySet()) {
conf.set(entry.getKey(), entry.getValue());
}
}
public synchronized Configuration configuration() {<FILL_FUNCTION_BODY>}
// convenience setters
public void setZookeeperQuorum(String value) {
configuration().set("hbase.zookeeper.quorum", value);
}
public void setZookeeperClientPort(int port) {
configuration().setInt("hbase.zookeeper.property.clientPort", port);
}
protected transient HBaseAdmin admin;
public synchronized HBaseAdmin admin() throws IOException {
if (admin == null) {
admin = new HBaseAdmin(configuration());
}
return admin;
}
@Override
public synchronized void stop() {
isRunning = false;
if (admin != null) {
try {
admin.close();
} catch (IOException e) {
logger.warning("problem closing HBaseAdmin " + admin + " - " + e);
}
admin = null;
}
if (conf != null) {
// HConnectionManager.deleteConnection(conf); // XXX?
conf = null;
}
}
protected transient boolean isRunning = false;
@Override
public boolean isRunning() {
return isRunning;
}
@Override
public void start() {
isRunning = true;
}
public synchronized void reset() {
if (admin != null) {
try {
admin.close();
} catch (IOException e) {
logger.warning("problem closing HBaseAdmin " + admin + " - " + e);
}
admin = null;
}
}
}
|
if (conf == null) {
conf = HBaseConfiguration.create();
}
return conf;
| 582
| 31
| 613
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/recrawl/hbase/HBasePersistLoadProcessor.java
|
HBasePersistLoadProcessor
|
shouldProcess
|
class HBasePersistLoadProcessor extends HBasePersistProcessor {
private static final Logger logger =
Logger.getLogger(HBasePersistLoadProcessor.class.getName());
@Override
protected ProcessResult innerProcessResult(CrawlURI uri) throws InterruptedException {
byte[] key = rowKeyForURI(uri);
Get g = new Get(key);
try {
Result r = table.get(g);
// no data for uri is indicated by empty Result
if (r.isEmpty()) {
if (logger.isLoggable(Level.FINE)) {
logger.fine(uri + ": <no crawlinfo>");
}
return ProcessResult.PROCEED;
}
schema.load(r, uri);
if (uri.getFetchStatus() < 0) {
return ProcessResult.FINISH;
}
} catch (IOException e) {
logger.warning("problem retrieving persist data from hbase, proceeding without, for " + uri + " - " + e);
} catch (Exception ex) {
// get() throws RuntimeException upon ZooKeeper connection failures.
// no crawl history load failure should make fetch of URL fail.
logger.log(Level.WARNING, "Get failed for " + uri + ": ", ex);
}
return ProcessResult.PROCEED;
}
/**
* unused.
*/
@Override
protected void innerProcess(CrawlURI uri) throws InterruptedException {
}
@Override
protected boolean shouldProcess(CrawlURI uri) {<FILL_FUNCTION_BODY>}
}
|
// TODO: we want deduplicate robots.txt, too.
//if (uri.isPrerequisite()) return false;
String scheme = uri.getUURI().getScheme();
if (!(scheme.equals("http") || scheme.equals("https") || scheme.equals("ftp") || scheme.equals("sftp"))) {
return false;
}
return true;
| 405
| 101
| 506
|
<methods>public non-sealed void <init>() ,public org.archive.modules.recrawl.hbase.RecrawlDataSchema getSchema() ,public void setSchema(org.archive.modules.recrawl.hbase.RecrawlDataSchema) ,public void setTable(org.archive.modules.recrawl.hbase.HBaseTableBean) <variables>protected org.archive.modules.recrawl.hbase.RecrawlDataSchema schema,protected org.archive.modules.recrawl.hbase.HBaseTableBean table
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/recrawl/hbase/HBasePersistStoreProcessor.java
|
HBasePersistStoreProcessor
|
innerProcess
|
class HBasePersistStoreProcessor extends HBasePersistProcessor implements FetchStatusCodes, RecrawlAttributeConstants {
private static final Logger logger = Logger.getLogger(HBasePersistStoreProcessor.class.getName());
protected boolean addColumnFamily = false;
public boolean getAddColumnFamily() {
return addColumnFamily;
}
/**
* Add the expected column family
* {@link HBaseContentDigestHistory#COLUMN_FAMILY} to the HBase table if the
* table doesn't already have it.
*/
public void setAddColumnFamily(boolean addColumnFamily) {
this.addColumnFamily = addColumnFamily;
}
protected int retryIntervalMs = 10*1000;
public int getRetryIntervalMs() {
return retryIntervalMs;
}
public void setRetryIntervalMs(int retryIntervalMs) {
this.retryIntervalMs = retryIntervalMs;
}
protected int maxTries = 1;
public int getMaxTries() {
return maxTries;
}
public void setMaxTries(int maxTries) {
this.maxTries = maxTries;
}
protected synchronized void addColumnFamily() {
try {
HTableDescriptor oldDesc = table.getHtableDescriptor();
byte[] columnFamily = Bytes.toBytes(schema.getColumnFamily());
if (oldDesc.getFamily(columnFamily) == null) {
HTableDescriptor newDesc = new HTableDescriptor(oldDesc);
newDesc.addFamily(new HColumnDescriptor(columnFamily));
logger.info("table does not yet have expected column family, modifying descriptor to " + newDesc);
HBaseAdmin hbaseAdmin = table.getHbase().admin();
hbaseAdmin.disableTable(table.getName());
hbaseAdmin.modifyTable(Bytes.toBytes(table.getName()), newDesc);
hbaseAdmin.enableTable(table.getName());
}
} catch (IOException e) {
logger.warning("problem adding column family: " + e);
}
}
@Override
protected void innerProcess(CrawlURI uri) {<FILL_FUNCTION_BODY>}
@Override
protected boolean shouldProcess(CrawlURI curi) {
return super.shouldStore(curi);
}
}
|
Put p = schema.createPut(uri);
int tryCount = 0;
do {
tryCount++;
try {
table.put(p);
return;
} catch (RetriesExhaustedWithDetailsException e) {
if (e.getCause(0) instanceof NoSuchColumnFamilyException && getAddColumnFamily()) {
addColumnFamily();
tryCount--;
} else {
logger.warning("put failed " + "(try " + tryCount + " of "
+ getMaxTries() + ")" + " for " + uri + " - " + e);
}
} catch (IOException e) {
logger.warning("put failed " + "(try " + tryCount + " of "
+ getMaxTries() + ")" + " for " + uri + " - " + e);
} catch (NullPointerException e) {
// HTable.put() throws NullPointerException while connection is lost.
logger.warning("put failed " + "(try " + tryCount + " of "
+ getMaxTries() + ")" + " for " + uri + " - " + e);
}
if (tryCount > 0 && tryCount < getMaxTries() && isRunning()) {
try {
Thread.sleep(getRetryIntervalMs());
} catch (InterruptedException ex) {
logger.warning("thread interrupted. aborting retry for " + uri);
return;
}
}
} while (tryCount < getMaxTries() && isRunning());
if (isRunning()) {
logger.warning("giving up after " + tryCount + " tries on put for " + uri);
}
| 590
| 416
| 1,006
|
<methods>public non-sealed void <init>() ,public org.archive.modules.recrawl.hbase.RecrawlDataSchema getSchema() ,public void setSchema(org.archive.modules.recrawl.hbase.RecrawlDataSchema) ,public void setTable(org.archive.modules.recrawl.hbase.HBaseTableBean) <variables>protected org.archive.modules.recrawl.hbase.RecrawlDataSchema schema,protected org.archive.modules.recrawl.hbase.HBaseTableBean table
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/recrawl/hbase/HBaseTable.java
|
HBaseTable
|
start
|
class HBaseTable extends HBaseTableBean {
static final Logger logger =
Logger.getLogger(HBaseTable.class.getName());
protected boolean create = false;
protected HConnection hconn = null;
protected ThreadLocal<HTableInterface> htable = new ThreadLocal<HTableInterface>();
public boolean getCreate() {
return create;
}
/** Create the named table if it doesn't exist. */
public void setCreate(boolean create) {
this.create = create;
}
public HBaseTable() {
}
protected synchronized HConnection hconnection() throws IOException {
if (hconn == null) {
hconn = HConnectionManager.createConnection(hbase.configuration());
}
return hconn;
}
protected HTableInterface htable() throws IOException {
if (htable.get() == null) {
htable.set(hconnection().getTable(htableName));
}
return htable.get();
}
@Override
public void put(Put p) throws IOException {
try {
htable().put(p);
} catch (IOException e) {
reset();
throw e;
}
}
@Override
public Result get(Get g) throws IOException {
try {
return htable().get(g);
} catch (IOException e) {
reset();
throw e;
}
}
public HTableDescriptor getHtableDescriptor() throws IOException {
try {
return htable().getTableDescriptor();
} catch (IOException e) {
reset();
throw e;
}
}
@Override
public void start() {<FILL_FUNCTION_BODY>}
protected void reset() {
if (htable.get() != null) {
try {
htable.get().close();
} catch (IOException e) {
logger.log(Level.WARNING, "htablename='" + htableName + "' htable.close() threw " + e, e);
}
htable.remove();
}
if (hconn != null) {
try {
hconn.close();
} catch (IOException e) {
logger.log(Level.WARNING, "hconn.close() threw " + e, e);
}
// HConnectionManager.deleteStaleConnection(hconn);
hconn = null;
}
hbase.reset();
}
@Override
public synchronized void stop() {
super.stop();
reset();
}
}
|
if (getCreate()) {
int attempt = 1;
while (true) {
try {
HBaseAdmin admin = hbase.admin();
if (!admin.tableExists(htableName)) {
HTableDescriptor desc = new HTableDescriptor(TableName.valueOf(htableName));
logger.info("hbase table '" + htableName + "' does not exist, creating it... " + desc);
admin.createTable(desc);
}
break;
} catch (IOException e) {
logger.log(Level.WARNING, "(attempt " + attempt + ") problem creating hbase table " + htableName, e);
attempt++;
reset();
// back off up to 60 seconds between retries
try {
Thread.sleep(Math.min(attempt * 1000, 60000));
} catch (InterruptedException e1) {
}
}
}
}
super.start();
| 653
| 245
| 898
|
<methods>public void <init>() ,public abstract Result get(Get) throws java.io.IOException,public org.archive.modules.recrawl.hbase.HBase getHbase() ,public abstract HTableDescriptor getHtableDescriptor() throws java.io.IOException,public java.lang.String getHtableName() ,public java.lang.String getName() ,public boolean isRunning() ,public abstract void put(Put) throws java.io.IOException,public void setHbase(org.archive.modules.recrawl.hbase.HBase) ,public void setHtableName(java.lang.String) ,public void setName(java.lang.String) ,public void start() ,public synchronized void stop() <variables>protected org.archive.modules.recrawl.hbase.HBase hbase,protected java.lang.String htableName,protected transient boolean isRunning
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/recrawl/hbase/MultiColumnRecrawlDataSchema.java
|
MultiColumnRecrawlDataSchema
|
load
|
class MultiColumnRecrawlDataSchema extends RecrawlDataSchemaBase implements RecrawlDataSchema, RecrawlAttributeConstants {
static final Logger logger = Logger.getLogger(MultiColumnRecrawlDataSchema.class.getName());
public static final byte[] COLUMN_STATUS = Bytes.toBytes("s");
public static final byte[] COLUMN_CONTENT_DIGEST = Bytes.toBytes("d");
public static final byte[] COLUMN_ETAG = Bytes.toBytes("e");
public static final byte[] COLUMN_LAST_MODIFIED = Bytes.toBytes("m");
/* (non-Javadoc)
* @see org.archive.modules.hq.recrawl.RecrawlDataSchema#createPut()
*/
public Put createPut(CrawlURI uri) {
byte[] uriBytes = rowKeyForURI(uri);
byte[] key = uriBytes;
Put p = new Put(key);
String digest = uri.getContentDigestSchemeString();
if (digest != null) {
p.add(columnFamily, COLUMN_CONTENT_DIGEST, Bytes.toBytes(digest));
}
p.add(columnFamily, COLUMN_STATUS, Bytes.toBytes(Integer.toString(uri.getFetchStatus())));
if (uri.isHttpTransaction()) {
String etag = uri.getHttpResponseHeader(RecrawlAttributeConstants.A_ETAG_HEADER);
if (etag != null) {
// Etqg is usually quoted
if (etag.length() >= 2 && etag.charAt(0) == '"' && etag.charAt(etag.length() - 1) == '"')
etag = etag.substring(1, etag.length() - 1);
p.add(columnFamily, COLUMN_ETAG, Bytes.toBytes(etag));
}
String lastmod = uri.getHttpResponseHeader(RecrawlAttributeConstants.A_LAST_MODIFIED_HEADER);
if (lastmod != null) {
long lastmod_sec = FetchHistoryHelper.parseHttpDate(lastmod);
if (lastmod_sec == 0) {
try {
lastmod_sec = uri.getFetchCompletedTime();
} catch (NullPointerException ex) {
logger.warning("CrawlURI.getFetchCompletedTime():" + ex + " for " + uri.shortReportLine());
}
}
if (lastmod_sec != 0)
p.add(columnFamily, COLUMN_LAST_MODIFIED, Bytes.toBytes(lastmod_sec));
} else {
try {
long completed = uri.getFetchCompletedTime();
if (completed != 0)
p.add(columnFamily, COLUMN_LAST_MODIFIED, Bytes.toBytes(completed));
} catch (NullPointerException ex) {
logger.warning("CrawlURI.getFetchCompletedTime():" + ex + " for " + uri.shortReportLine());
}
}
}
return p;
}
/* (non-Javadoc)
* @see org.archive.modules.hq.recrawl.RecrawlDataSchema#load(java.util.Map, org.apache.hadoop.hbase.client.Result)
*/
public void load(Result result, CrawlURI curi) {<FILL_FUNCTION_BODY>}
}
|
// check for "do-not-crawl" flag - any non-empty data tells not to crawl this
// URL.
byte[] nocrawl = result.getValue(columnFamily, COLUMN_NOCRAWL);
if (nocrawl != null && nocrawl.length > 0) {
// fetch status set to S_DEEMED_CHAFF, because this do-not-crawl flag
// is primarily intended for preventing crawler from stepping on traps.
curi.setFetchStatus(FetchStatusCodes.S_DEEMED_CHAFF);
curi.getAnnotations().add("nocrawl");
return;
}
// all column should have identical timestamp.
KeyValue rkv = result.getColumnLatest(columnFamily, COLUMN_STATUS);
long timestamp = rkv.getTimestamp();
Map<String, Object> history = FetchHistoryHelper.getFetchHistory(curi, timestamp, historyLength);
// FetchHTTP ignores history with status <= 0
byte[] status = result.getValue(columnFamily, COLUMN_STATUS);
if (status != null) {
// Note that status is stored as integer text. It's typically three-chars
// that is less than 4-byte integer bits.
history.put(RecrawlAttributeConstants.A_STATUS, Integer.parseInt(Bytes.toString(status)));
byte[] etag = result.getValue(columnFamily, COLUMN_ETAG);
if (etag != null) {
history.put(RecrawlAttributeConstants.A_ETAG_HEADER, Bytes.toString(etag));
}
byte[] lastmod = result.getValue(columnFamily, COLUMN_LAST_MODIFIED);
if (lastmod != null) {
long lastmod_sec = Bytes.toLong(lastmod);
history.put(RecrawlAttributeConstants.A_LAST_MODIFIED_HEADER, FetchHistoryHelper.formatHttpDate(lastmod_sec));
}
byte[] digest = result.getValue(columnFamily, COLUMN_CONTENT_DIGEST);
if (digest != null) {
history.put(RecrawlAttributeConstants.A_CONTENT_DIGEST, Bytes.toString(digest));
}
}
| 881
| 580
| 1,461
|
<methods>public void <init>() ,public java.lang.String getColumnFamily() ,public int getHistoryLength() ,public org.archive.modules.canonicalize.CanonicalizationRule getKeyRule() ,public boolean isUseCanonicalString() ,public byte[] rowKeyForURI(org.archive.modules.CrawlURI) ,public void setColumnFamily(java.lang.String) ,public void setHistoryLength(int) ,public void setKeyRule(org.archive.modules.canonicalize.CanonicalizationRule) ,public void setUseCanonicalString(boolean) <variables>public static final byte[] COLUMN_NOCRAWL,public static final byte[] DEFAULT_COLUMN_FAMILY,public static boolean DEFAULT_USE_CANONICAL_STRING,protected byte[] columnFamily,protected int historyLength,private org.archive.modules.canonicalize.CanonicalizationRule keyRule,private static final java.util.logging.Logger logger,private boolean useCanonicalString
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/recrawl/hbase/RecrawlDataSchemaBase.java
|
RecrawlDataSchemaBase
|
rowKeyForURI
|
class RecrawlDataSchemaBase implements RecrawlDataSchema {
private static final Logger logger = Logger.getLogger(RecrawlDataSchemaBase.class.getName());
/**
* default value for {@link #columnFamily}.
*/
public static final byte[] DEFAULT_COLUMN_FAMILY = Bytes.toBytes("f");
protected byte[] columnFamily = DEFAULT_COLUMN_FAMILY;
public static final byte[] COLUMN_NOCRAWL = Bytes.toBytes("z");
/**
* default value for {@link #useCanonicalString}.
*/
public static boolean DEFAULT_USE_CANONICAL_STRING = true;
private boolean useCanonicalString = DEFAULT_USE_CANONICAL_STRING;
private CanonicalizationRule keyRule = null;
protected int historyLength = 2;
public RecrawlDataSchemaBase() {
super();
}
public void setColumnFamily(String colf) {
columnFamily = Bytes.toBytes(colf);
}
public boolean isUseCanonicalString() {
return useCanonicalString;
}
/**
* if set to true, canonicalized string will be used as row key, rather than URI
* @param useCanonicalString
*/
public void setUseCanonicalString(boolean useCanonicalString) {
this.useCanonicalString = useCanonicalString;
}
public String getColumnFamily() {
return Bytes.toString(columnFamily);
}
public CanonicalizationRule getKeyRule() {
return keyRule;
}
/**
* alternative canonicalization rule for generating row key from URI.
* TODO: currently unused.
* @param keyRule
*/
public void setKeyRule(CanonicalizationRule keyRule) {
this.keyRule = keyRule;
}
public int getHistoryLength() {
return historyLength;
}
/**
* maximum number of crawl history entries to retain in {@link CrawlURI}.
* when more than this number of crawl history entry is being added by
* {@link #getFetchHistory(CrawlURI, long)}, oldest entry will be discarded.
* {@code historyLength} should be the same number as
* {@link FetchHistoryProcessor#setHistoryLength(int)}, or FetchHistoryProcessor will
* reallocate the crawl history array.
* @param historyLength
* @see FetchHistoryProcessor#setHistoryLength(int)
*/
public void setHistoryLength(int historyLength) {
this.historyLength = historyLength;
}
/**
* calls {@link FetchHistoryHelper#getFetchHistory(CrawlURI, long, int)} with {@link #historyLength}.
* @param uri CrawlURI from which fetch history is obtained.
* @return Map object for storing re-crawl data (never null).
* @see FetchHistoryHelper#getFetchHistory(CrawlURI, long, int)
* @see FetchHistoryProcessor
*/
protected Map<String, Object> getFetchHistory(CrawlURI uri, long timestamp) {
return FetchHistoryHelper.getFetchHistory(uri, timestamp, historyLength);
}
/**
* return row key for {@code curi}.
* TODO: move this to HBasePersistProcessor by redesigning {@link RecrawlDataSchema}.
* @param curi {@link CrawlURI} for which a row is being fetched.
* @return row key
*/
public byte[] rowKeyForURI(CrawlURI curi) {<FILL_FUNCTION_BODY>}
}
|
if (useCanonicalString) {
// TODO: use keyRule if specified.
return Bytes.toBytes(PersistProcessor.persistKeyFor(curi));
} else {
return Bytes.toBytes(curi.toString());
}
| 915
| 67
| 982
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/modules/recrawl/hbase/SingleColumnJsonRecrawlDataSchema.java
|
SingleColumnJsonRecrawlDataSchema
|
load
|
class SingleColumnJsonRecrawlDataSchema extends RecrawlDataSchemaBase
implements RecrawlDataSchema {
static final Logger logger = Logger.getLogger(SingleColumnJsonRecrawlDataSchema.class.getName());
public static byte[] DEFAULT_COLUMN = Bytes.toBytes("r");
// JSON property names for re-crawl data properties
public static final String PROPERTY_STATUS = "s";
public static final String PROPERTY_CONTENT_DIGEST = "d";
public static final String PROPERTY_ETAG = "e";
public static final String PROPERTY_LAST_MODIFIED = "m";
// SHA1 scheme is assumed.
public static final String CONTENT_DIGEST_SCHEME = "sha1:";
// single column for storing JSON of re-crawl data
protected byte[] column = DEFAULT_COLUMN;
public void setColumn(String column) {
this.column = Bytes.toBytes(column);
}
public String getColumn() {
return Bytes.toString(column);
}
/* (non-Javadoc)
* @see org.archive.modules.hq.recrawl.RecrawlDataSchema#createPut(org.archive.modules.CrawlURI)
*/
public Put createPut(CrawlURI uri) {
byte[] key = rowKeyForURI(uri);
Put p = new Put(key);
JSONObject jo = new JSONObject();
try {
// TODO should we post warning message when scheme != "sha1"?
String digest = uri.getContentDigestString();
if (digest != null) {
jo.put(PROPERTY_CONTENT_DIGEST, digest);
}
jo.put(PROPERTY_STATUS, uri.getFetchStatus());
if (uri.isHttpTransaction()) {
String etag = uri.getHttpResponseHeader(RecrawlAttributeConstants.A_ETAG_HEADER);
if (etag != null) {
// Etag is usually quoted
if (etag.length() >= 2 && etag.charAt(0) == '"' && etag.charAt(etag.length() - 1) == '"')
etag = etag.substring(1, etag.length() - 1);
jo.put(PROPERTY_ETAG, etag);
}
String lastmod = uri.getHttpResponseHeader(RecrawlAttributeConstants.A_LAST_MODIFIED_HEADER);
if (lastmod != null) {
long lastmod_sec = FetchHistoryHelper.parseHttpDate(lastmod);
if (lastmod_sec == 0) {
try {
lastmod_sec = uri.getFetchCompletedTime();
} catch (NullPointerException ex) {
logger.warning("CrawlURI.getFetchCompletedTime():" + ex + " for " + uri.shortReportLine());
}
}
} else {
try {
long completed = uri.getFetchCompletedTime();
if (completed != 0)
jo.put(PROPERTY_LAST_MODIFIED, completed);
} catch (NullPointerException ex) {
logger.warning("CrawlURI.getFetchCompletedTime():" + ex + " for " + uri.shortReportLine());
}
}
}
} catch (JSONException ex) {
// should not happen - all values are either primitive or String.
logger.log(Level.SEVERE, "JSON translation failed", ex);
}
p.add(columnFamily, column, Bytes.toBytes(jo.toString()));
return p;
}
/* (non-Javadoc)
* @see org.archive.modules.hq.recrawl.RecrawlDataSchema#load(org.apache.hadoop.hbase.client.Result)
*/
public void load(Result result, CrawlURI curi) {<FILL_FUNCTION_BODY>}
}
|
// check for "do-not-crawl" flag - any non-empty data tells not to crawl this
// URL.
byte[] nocrawl = result.getValue(columnFamily, COLUMN_NOCRAWL);
if (nocrawl != null && nocrawl.length > 0) {
// fetch status set to S_DEEMED_CHAFF, because this do-not-crawl flag
// is primarily intended for preventing crawler from stepping on traps.
curi.setFetchStatus(FetchStatusCodes.S_DEEMED_CHAFF);
curi.getAnnotations().add("nocrawl");
return;
}
KeyValue rkv = result.getColumnLatest(columnFamily, column);
long timestamp = rkv.getTimestamp();
Map<String, Object> history = FetchHistoryHelper.getFetchHistory(curi, timestamp, historyLength);
if (history == null) {
// crawl history array is fully occupied by crawl history entries
// newer than timestamp.
return;
}
byte[] jsonBytes = rkv.getValue();
if (jsonBytes != null) {
JSONObject jo = null;
try {
jo = new JSONObject(Bytes.toString(jsonBytes));
} catch (JSONException ex) {
logger.warning(String.format("JSON parsing failed for key %1s: %2s",
result.getRow(), ex.getMessage()));
}
if (jo != null) {
int status = jo.optInt(PROPERTY_STATUS, -1);
if (status >= 0) {
history.put(RecrawlAttributeConstants.A_STATUS, status);
}
String digest = jo.optString(PROPERTY_CONTENT_DIGEST);
if (digest != null) {
history.put(RecrawlAttributeConstants.A_CONTENT_DIGEST, CONTENT_DIGEST_SCHEME + digest);
}
String etag = jo.optString(PROPERTY_ETAG);
if (etag != null) {
history.put(RecrawlAttributeConstants.A_ETAG_HEADER, etag);
}
long lastmod = jo.optLong(PROPERTY_LAST_MODIFIED);
if (lastmod > 0) {
history.put(RecrawlAttributeConstants.A_LAST_MODIFIED_HEADER, FetchHistoryHelper.formatHttpDate(lastmod));
}
}
}
| 1,008
| 635
| 1,643
|
<methods>public void <init>() ,public java.lang.String getColumnFamily() ,public int getHistoryLength() ,public org.archive.modules.canonicalize.CanonicalizationRule getKeyRule() ,public boolean isUseCanonicalString() ,public byte[] rowKeyForURI(org.archive.modules.CrawlURI) ,public void setColumnFamily(java.lang.String) ,public void setHistoryLength(int) ,public void setKeyRule(org.archive.modules.canonicalize.CanonicalizationRule) ,public void setUseCanonicalString(boolean) <variables>public static final byte[] COLUMN_NOCRAWL,public static final byte[] DEFAULT_COLUMN_FAMILY,public static boolean DEFAULT_USE_CANONICAL_STRING,protected byte[] columnFamily,protected int historyLength,private org.archive.modules.canonicalize.CanonicalizationRule keyRule,private static final java.util.logging.Logger logger,private boolean useCanonicalString
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/net/chrome/ChromeClient.java
|
ChromeClient
|
callInSession
|
class ChromeClient implements Closeable {
private static final Logger logger = Logger.getLogger(ChromeClient.class.getName());
private static final int RPC_TIMEOUT_SECONDS = 60;
private final DevtoolsSocket devtoolsSocket;
private final AtomicLong nextMessageId = new AtomicLong(0);
private final Map<Long, CompletableFuture<JSONObject>> responseFutures = new ConcurrentHashMap<>();
final ConcurrentHashMap<String, Consumer<JSONObject>> sessionEventHandlers = new ConcurrentHashMap<>();
public ChromeClient(String devtoolsUrl) {
devtoolsSocket = new DevtoolsSocket(URI.create(devtoolsUrl));
try {
devtoolsSocket.connectBlocking();
} catch (InterruptedException e) {
throw new ChromeException("Interrupted while connecting", e);
}
}
public JSONObject call(String method, Object... keysAndValues) {
return callInSession(null, method, keysAndValues);
}
public JSONObject callInSession(String sessionId, String method, Object... keysAndValues) {<FILL_FUNCTION_BODY>}
private JSONObject callInternal(String sessionId, String method, JSONObject params) {
long id = nextMessageId.getAndIncrement();
JSONObject message = new JSONObject();
message.put("id", id);
if (sessionId != null) {
message.put("sessionId", sessionId);
}
message.put("method", method);
message.put("params", params);
CompletableFuture<JSONObject> future = new CompletableFuture<>();
responseFutures.put(id, future);
devtoolsSocket.send(message.toString());
try {
return future.get(RPC_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e) {
throw new ChromeException("Call interrupted", e);
} catch (TimeoutException e) {
throw new ChromeException("Call timed out: " + message, e);
} catch (ExecutionException e) {
throw new ChromeException("Call failed: " + message + ": " + e.getMessage(), e.getCause());
}
}
private void handleResponse(JSONObject message) {
long id = message.getLong("id");
CompletableFuture<JSONObject> future = responseFutures.remove(id);
if (future == null) {
logger.log(WARNING, "Unexpected RPC response id {0}", id);
} else if (message.has("error")) {
future.completeExceptionally(new ChromeException(message.getJSONObject("error").getString("message")));
} else {
future.complete(message.getJSONObject("result"));
}
}
private void handleEvent(JSONObject message) {
if (message.has("sessionId")) {
String sessionId = message.getString("sessionId");
Consumer<JSONObject> handler = sessionEventHandlers.get(sessionId);
if (handler != null) {
handler.accept(message);
} else {
logger.log(WARNING, "Received event for unknown session {0}", sessionId);
}
}
}
public ChromeWindow createWindow(int width, int height) {
String targetId = call("Target.createTarget", "url", "about:blank",
"width", width, "height", height).getString("targetId");
return new ChromeWindow(this, targetId);
}
@Override
public void close() {
devtoolsSocket.close();
}
private class DevtoolsSocket extends WebSocketClient {
public DevtoolsSocket(URI uri) {
super(uri);
setConnectionLostTimeout(-1); // disable pings - Chromium doesn't support them
}
@Override
public void onOpen(ServerHandshake serverHandshake) {
}
@Override
public void onMessage(String messageString) {
try {
JSONObject message = new JSONObject(messageString);
if (message.has("method")) {
handleEvent(message);
} else {
handleResponse(message);
}
} catch (Throwable e) {
logger.log(WARNING, "Exception handling message from Chromium", e);
throw e;
}
}
@Override
public void onClose(int code, String reason, boolean remote) {
if (!remote) return;
logger.log(WARNING, "Websocket closed by browser: " + reason);
}
@Override
public void onError(Exception e) {
logger.log(Level.SEVERE, "Websocket error", e);
}
}
}
|
JSONObject params = new JSONObject();
if (keysAndValues.length % 2 != 0) {
throw new IllegalArgumentException("keysAndValues.length must even");
}
for (int i = 0; i < keysAndValues.length; i += 2) {
params.put((String)keysAndValues[i], keysAndValues[i + 1]);
}
return callInternal(sessionId, method, params);
| 1,174
| 108
| 1,282
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/net/chrome/ChromeProcess.java
|
ChromeProcess
|
readDevtoolsUriFromStderr
|
class ChromeProcess implements Closeable {
private static final Logger logger = Logger.getLogger(ExtractorChrome.class.getName());
private static final String[] DEFAULT_EXECUTABLES = {"chromium-browser", "chromium", "google-chrome",
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
"firefox"};
private static final int SHUTDOWN_TIMEOUT_SECONDS = 2;
private static final Set<Process> runningProcesses = Collections.newSetFromMap(new ConcurrentHashMap<>());
private static Thread shutdownHook;
private final Process process;
private final String devtoolsUrl;
public ChromeProcess(String executable, List<String> commandLineOptions) throws IOException {
process = executable == null ? launchAny(commandLineOptions) : launch(executable, commandLineOptions);
runningProcesses.add(process);
registerShutdownHook();
devtoolsUrl = readDevtoolsUriFromStderr(process);
}
private static Process launch(String executable, List<String> commandLineOptions) throws IOException {
List<String> command = new ArrayList<>();
command.add(executable);
command.add("--headless");
command.add("--remote-debugging-port=0");
// https://github.com/GoogleChrome/chrome-launcher/blob/master/docs/chrome-flags-for-tools.md
command.add("--disable-background-networking");
command.add("--disable-background-timer-throttling");
command.add("--disable-backgrounding-occluded-windows");
command.add("--disable-breakpad");
command.add("--disable-client-side-phishing-detection");
command.add("--disable-component-extensions-with-background-pages");
command.add("--disable-component-update");
command.add("--disable-crash-reporter");
command.add("--disable-default-apps");
command.add("--disable-extensions");
command.add("--disable-features=Translate");
command.add("--disable-ipc-flooding-protection");
command.add("--disable-popup-blocking");
command.add("--disable-prompt-on-repost");
command.add("--disable-renderer-backgrounding");
command.add("--disable-sync");
command.add("--metrics-recording-only");
command.add("--mute-audio");
command.add("--no-default-browser-check");
command.add("--no-first-run");
command.add("--password-store=basic");
command.add("--use-mock-keychain");
command.addAll(commandLineOptions);
return new ProcessBuilder(command)
.inheritIO()
.redirectError(ProcessBuilder.Redirect.PIPE)
.start();
}
/**
* Try to launch the browser process using each of DEFAUSLT_EXECUTABLES in turn until one succeeds.
*/
private static Process launchAny(List<String> extraCommandLineOptions) throws IOException {
IOException lastException = null;
for (String executable : DEFAULT_EXECUTABLES) {
try {
return launch(executable, extraCommandLineOptions);
} catch (IOException e) {
lastException = e;
}
}
throw new IOException("Failed to launch any of " + Arrays.asList(DEFAULT_EXECUTABLES), lastException);
}
@Override
public void close() {
destroyProcess(process);
runningProcesses.remove(process);
}
/**
* Register a shutdown hook that destroys all running browser processes before exiting in case stop() is never
* called. This can happen if the Heritrix exits abnormally.
*/
private static synchronized void registerShutdownHook() {
if (shutdownHook != null) return;
shutdownHook = new Thread(ChromeProcess::destroyAllRunningProcesses, "ChromiumClient shutdown hook");
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
private static void destroyAllRunningProcesses() {
for (Process process : runningProcesses) {
process.destroy();
}
for (Process process : runningProcesses) {
try {
if (!process.waitFor(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
break;
}
} catch (InterruptedException e) {
break;
}
}
for (Process process : runningProcesses) {
process.destroyForcibly();
}
}
private static void destroyProcess(Process process) {
process.destroy();
try {
process.waitFor(SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
} finally {
process.destroyForcibly();
}
}
/**
* Reads the stderr of a Chromium process and returns the DevTools URI. Once this method
* returns stderr will continue to be consumed and logged by a background thread.
*/
private static String readDevtoolsUriFromStderr(Process process) throws IOException {<FILL_FUNCTION_BODY>}
public String getDevtoolsUrl() {
return devtoolsUrl;
}
}
|
BufferedReader stderr = new BufferedReader(new InputStreamReader(process.getErrorStream(), ISO_8859_1));
CompletableFuture<String> future = new CompletableFuture<>();
Thread thread = new Thread(() -> {
String listenMsg = "DevTools listening on ";
try {
while (true) {
String line = stderr.readLine();
if (line == null) break;
if (!future.isDone() && line.startsWith(listenMsg)) {
future.complete(line.substring(listenMsg.length()));
}
logger.log(FINER, "Chromium STDERR: {0}", line);
}
} catch (IOException e) {
future.completeExceptionally(e);
}
});
thread.setName("Chromium stderr reader");
thread.setDaemon(true);
thread.start();
try {
return future.get(10, TimeUnit.SECONDS);
} catch (InterruptedException | ExecutionException | TimeoutException e) {
// unwrap the exception if we can to cut down on log noise
if (e.getCause() instanceof IOException) {
throw (IOException) e.getCause();
}
throw new IOException(e);
}
| 1,376
| 323
| 1,699
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/net/chrome/ChromeRequest.java
|
ChromeRequest
|
getResponseBody
|
class ChromeRequest {
private final ChromeWindow window;
private final String id;
private JSONObject requestJson;
private JSONObject rawRequestHeaders;
private JSONObject responseJson;
private JSONObject rawResponseHeaders;
private String responseHeadersText;
private final long beginTime = System.currentTimeMillis();
private boolean responseFulfilledByInterception;
public ChromeRequest(ChromeWindow window, String id) {
this.window = window;
this.id = id;
}
void setRawRequestHeaders(JSONObject rawRequestHeaders) {
this.rawRequestHeaders = rawRequestHeaders;
}
void setResponseJson(JSONObject responseJson) {
this.responseJson = responseJson;
}
void setRawResponseHeaders(JSONObject headers) {
this.rawResponseHeaders = headers;
}
void setResponseHeadersText(String responseHeadersText) {
this.responseHeadersText = responseHeadersText;
}
public String getUrl() {
return requestJson.getString("url");
}
public byte[] getResponseBody() {<FILL_FUNCTION_BODY>}
public String getRequestHeader() {
if (responseJson != null && responseJson.has("requestHeadersText")) {
return responseJson.getString("requestHeadersText");
}
StringBuilder builder = new StringBuilder();
builder.append(requestJson.getString("method"));
builder.append(' ');
builder.append(getUrl());
builder.append(" HTTP/1.1\r\n");
formatHeaders(builder, requestJson.getJSONObject("headers"), rawRequestHeaders);
return builder.toString();
}
public byte[] getRequestBody() {
if (requestJson.has("postData")) {
return requestJson.getString("postData").getBytes(StandardCharsets.UTF_8);
} else {
return new byte[0];
}
}
public String getResponseHeader() {
if (responseHeadersText != null) {
return responseHeadersText;
} else if (responseJson.has("headersText")) {
return responseJson.getString("headersText");
}
StringBuilder builder = new StringBuilder();
if (responseJson.getString("protocol").equals("http/1.0")) {
builder.append("HTTP/1.0");
} else {
builder.append("HTTP/1.1");
}
builder.append(getStatus());
builder.append(" ");
builder.append(responseJson.getString("statusText"));
builder.append("\r\n");
formatHeaders(builder, responseJson.getJSONObject("headers"), rawResponseHeaders);
return builder.toString();
}
private void formatHeaders(StringBuilder builder, JSONObject headers, JSONObject rawHeaders) {
if (rawHeaders != null) {
headers = rawHeaders;
}
for (Object key : headers.keySet()) {
builder.append(key);
builder.append(": ");
builder.append(headers.getString((String) key));
builder.append("\r\n");
}
builder.append("\r\n");
}
public String getMethod() {
return requestJson.getString("method");
}
public int getStatus() {
return responseJson.getInt("status");
}
public String getResponseContentType() {
return responseJson.getString("mimeType");
}
public long getBeginTime() {
return beginTime;
}
public String getRemoteIPAddress() {
if (responseJson.has("remoteIPAddress")) {
return responseJson.getString("remoteIPAddress");
} else {
return null;
}
}
void setRequestJson(JSONObject requestJson) {
this.requestJson = requestJson;
}
void setResponseFulfilledByInterception(boolean responseFulfilledByInterception) {
this.responseFulfilledByInterception = responseFulfilledByInterception;
}
public boolean isResponseFulfilledByInterception() {
return responseFulfilledByInterception;
}
}
|
JSONObject reply = window.call("Network.getResponseBody", "requestId", id);
byte[] body;
if (reply.getBoolean("base64Encoded")) {
body = Base64.getDecoder().decode(reply.getString("body"));
} else {
body = reply.getString("body").getBytes(StandardCharsets.UTF_8);
}
return body;
| 1,029
| 102
| 1,131
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/net/chrome/ChromeWindow.java
|
ChromeWindow
|
handleEvent
|
class ChromeWindow implements Closeable {
private static final Logger logger = Logger.getLogger(ChromeWindow.class.getName());
private final ChromeClient client;
private final String targetId;
private final String sessionId;
private boolean closed;
private CompletableFuture<Void> loadEventFuture;
private final Map<String,ChromeRequest> requestMap = new ConcurrentHashMap<>();
private Consumer<ChromeRequest> requestConsumer;
private Consumer<InterceptedRequest> requestInterceptor;
private final ExecutorService eventExecutor;
public ChromeWindow(ChromeClient client, String targetId) {
this.client = client;
this.targetId = targetId;
this.sessionId = client.call("Target.attachToTarget", "targetId", targetId,
"flatten", true).getString("sessionId");
eventExecutor = Executors.newSingleThreadExecutor(runnable ->
new Thread(runnable, "ChromeWindow (sessionId=" + sessionId +")"));
client.sessionEventHandlers.put(sessionId, this::handleEvent);
call("Page.enable"); // for loadEventFired
call("Page.setLifecycleEventsEnabled", "enabled", true); // for networkidle
call("Runtime.enable"); // required by Firefox for Runtime.evaluate to work
}
/**
* Call a devtools method in the session of this window.
*/
public JSONObject call(String method, Object... keysAndValues) {
return client.callInSession(sessionId, method, keysAndValues);
}
/**
* Evaluate a JavaScript expression.
*/
public JSONObject eval(String expression) {
return call("Runtime.evaluate", "expression", expression,
"returnByValue", true).getJSONObject("result");
}
/**
* Navigate this window to a new URL. Returns a future which will be fulfilled when the page finishes loading.
*/
public CompletableFuture<Void> navigateAsync(String url) {
if (loadEventFuture != null) {
loadEventFuture.cancel(false);
}
loadEventFuture = new CompletableFuture<>();
call("Page.navigate", "url", url);
return loadEventFuture;
}
private void handleEvent(JSONObject message) {<FILL_FUNCTION_BODY>}
private void handleEventOnEventThread(JSONObject message) {
JSONObject params = message.getJSONObject("params");
switch (message.getString("method")) {
case "Fetch.requestPaused":
handlePausedRequest(params);
break;
case "Network.requestWillBeSent":
handleRequestWillBeSent(params);
break;
case "Network.requestWillBeSentExtraInfo":
handleRequestWillBeSentExtraInfo(params);
break;
case "Network.responseReceived":
handleResponseReceived(params);
break;
case "Network.responseReceivedExtraInfo":
handleResponseReceivedExtraInfo(params);
break;
case "Network.loadingFinished":
handleLoadingFinished(params);
break;
case "Page.loadEventFired":
if (loadEventFuture != null) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
loadEventFuture.complete(null);
}
break;
default:
logger.log(FINE, "Unhandled event {0}", message);
break;
}
}
private void handlePausedRequest(JSONObject params) {
String networkId = params.getString("networkId");
ChromeRequest request = requestMap.computeIfAbsent(networkId, id -> new ChromeRequest(this, id));
request.setRequestJson(params.getJSONObject("request"));
String id = params.getString("requestId");
InterceptedRequest interceptedRequest = new InterceptedRequest(this, id, request);
try {
requestInterceptor.accept(interceptedRequest);
} catch (Exception e) {
logger.log(SEVERE, "Request interceptor threw", e);
}
if (!interceptedRequest.isHandled()) {
interceptedRequest.continueNormally();
}
}
private void handleRequestWillBeSent(JSONObject params) {
String requestId = params.getString("requestId");
ChromeRequest request = requestMap.computeIfAbsent(requestId, id -> new ChromeRequest(this, id));
request.setRequestJson(params.getJSONObject("request"));
}
private void handleRequestWillBeSentExtraInfo(JSONObject params) {
// it seems this event can arrive both before and after requestWillBeSent so we need to cope with that
String requestId = params.getString("requestId");
ChromeRequest request = requestMap.computeIfAbsent(requestId, id -> new ChromeRequest(this, id));
if (params.has("headers")) {
request.setRawRequestHeaders(params.getJSONObject("headers"));
}
}
private void handleResponseReceived(JSONObject params) {
ChromeRequest request = requestMap.get(params.getString("requestId"));
if (request == null) {
logger.log(WARNING, "Got responseReceived event without corresponding requestWillBeSent");
return;
}
request.setResponseJson(params.getJSONObject("response"));
}
private void handleResponseReceivedExtraInfo(JSONObject params) {
ChromeRequest request = requestMap.get(params.getString("requestId"));
if (request == null) {
logger.log(WARNING, "Got responseReceivedExtraInfo event without corresponding requestWillBeSent");
return;
}
if (params.has("headers")) {
request.setRawResponseHeaders(params.getJSONObject("headers"));
}
if (params.has("headersText")) {
request.setResponseHeadersText(params.getString("headersText"));
}
}
private void handleLoadingFinished(JSONObject params) {
ChromeRequest request = requestMap.get(params.getString("requestId"));
if (request == null) {
logger.log(WARNING, "Got loadingFinished event without corresponding requestWillBeSent");
return;
}
if (requestConsumer != null) {
requestConsumer.accept(request);
}
}
@Override
public void close() {
if (closed) return;
closed = true;
eventExecutor.shutdown();
try {
eventExecutor.awaitTermination(1, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
try {
client.call("Target.closeTarget", "targetId", targetId);
} catch (WebsocketNotConnectedException e) {
// no need to close the window if the browser has already exited
}
client.sessionEventHandlers.remove(sessionId);
}
public void captureRequests(Consumer<ChromeRequest> requestConsumer) {
this.requestConsumer = requestConsumer;
call("Network.enable");
}
public void interceptRequests(Consumer<InterceptedRequest> requestInterceptor) {
this.requestInterceptor = requestInterceptor;
call("Fetch.enable");
}
}
|
if (closed) return;
// Run event handlers on a different thread so we don't block the websocket receiving thread.
// That would cause a deadlock if an event handler itself made an RPC call as the response could
// never be processed.
// We use a single thread per window though as the order events are processed is important.
eventExecutor.submit(() -> {
try {
handleEventOnEventThread(message);
} catch (Throwable t) {
logger.log(WARNING, "Exception handling browser event " + message, t);
}
});
| 1,846
| 143
| 1,989
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/contrib/src/main/java/org/archive/net/chrome/InterceptedRequest.java
|
InterceptedRequest
|
fulfill
|
class InterceptedRequest {
private final String id;
private final ChromeRequest request;
private final ChromeWindow window;
private boolean handled;
public InterceptedRequest(ChromeWindow window, String id, ChromeRequest request) {
this.window = window;
this.id = id;
this.request = request;
}
public ChromeRequest getRequest() {
return request;
}
public void fulfill(int status, Collection<Map.Entry<String,String>> headers, byte[] body) {<FILL_FUNCTION_BODY>}
public void continueNormally() {
setHandled();
window.call("Fetch.continueRequest", "requestId", id);
}
public boolean isHandled() {
return handled;
}
private void setHandled() {
if (handled) {
throw new IllegalStateException("intercepted request already handled");
}
handled = true;
}
}
|
setHandled();
JSONArray headerArray = new JSONArray();
for (Map.Entry<String,String> entry : headers) {
JSONObject object = new JSONObject();
object.put("name", entry.getKey());
object.put("value", entry.getValue());
headerArray.put(object);
}
String encodedBody = Base64.getEncoder().encodeToString(body);
request.setResponseFulfilledByInterception(true);
window.call("Fetch.fulfillRequest",
"requestId", id,
"responseCode", status,
"responseHeaders", headerArray,
"body", encodedBody);
| 244
| 164
| 408
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/framework/BeanLookupBindings.java
|
BeanLookupBindings
|
get
|
class BeanLookupBindings extends SimpleBindings {
private final ApplicationContext appCtx;
public BeanLookupBindings(ApplicationContext appCtx) {
if (appCtx == null) throw new NullPointerException("appCtx");
this.appCtx = appCtx;
}
public BeanLookupBindings(ApplicationContext appCtx, Map<String, Object> m) {
super(m);
if (appCtx == null) throw new NullPointerException("appCtx");
this.appCtx = appCtx;
}
@Override
public Object get(Object key) {<FILL_FUNCTION_BODY>}
@Override
public boolean containsKey(Object key) {
try {
return super.containsKey(key) || appCtx.containsBean((String) key);
} catch (Exception e) {
return false;
}
}
}
|
Object ret = super.get(key);
if (ret == null && key instanceof String) {
try {
ret = appCtx.getBean((String) key);
} catch (BeansException e) {}
}
return ret;
| 236
| 65
| 301
|
<methods>public void <init>() ,public void <init>(Map<java.lang.String,java.lang.Object>) ,public void clear() ,public boolean containsKey(java.lang.Object) ,public boolean containsValue(java.lang.Object) ,public Set<Entry<java.lang.String,java.lang.Object>> entrySet() ,public java.lang.Object get(java.lang.Object) ,public boolean isEmpty() ,public Set<java.lang.String> keySet() ,public java.lang.Object put(java.lang.String, java.lang.Object) ,public void putAll(Map<? extends java.lang.String,? extends java.lang.Object>) ,public java.lang.Object remove(java.lang.Object) ,public int size() ,public Collection<java.lang.Object> values() <variables>private final Map<java.lang.String,java.lang.Object> map
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/framework/CheckpointValidator.java
|
CheckpointValidator
|
validate
|
class CheckpointValidator implements Validator {
@Override
public boolean supports(Class<?> cls) {
return Checkpoint.class.isAssignableFrom(cls);
}
@Override
public void validate(Object target, Errors errors) {<FILL_FUNCTION_BODY>}
}
|
Checkpoint cp = ((CheckpointService)target).getRecoveryCheckpoint();
if(cp==null) {
return;
}
if(!Checkpoint.hasValidStamp(cp.getCheckpointDir().getFile())) {
errors.rejectValue(
"recoveryCheckpoint.checkpointDir",
null,
"Configured recovery checkpoint "+cp.getName()
+" incomplete: lacks valid stamp file.");
}
| 81
| 116
| 197
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/framework/CrawlJob.java
|
JobLogFormatter
|
isLaunchable
|
class JobLogFormatter extends Formatter {
@Override
public String format(LogRecord record) {
StringBuilder sb = new StringBuilder();
sb
.append(new DateTime(record.getMillis()))
.append(" ")
.append(record.getLevel())
.append(" ")
.append(record.getMessage())
.append("\n");
return sb.toString();
}
}
/**
* Return all config files included via 'import' statements in the
* primary config (or other included configs).
*
* @param xml File to examine
* @return List<File> of all transitively-imported Files
*/
@SuppressWarnings("unchecked")
public List<File> getImportedConfigs(File xml) {
List<File> imports = new LinkedList<File>();
Document doc = getDomDocument(xml);
if(doc==null) {
return ListUtils.EMPTY_LIST;
}
NodeList importElements = doc.getElementsByTagName("import");
for(int i = 0; i < importElements.getLength(); i++) {
File imported = new File(
getJobDir(),
importElements.item(i).getAttributes().getNamedItem("resource").getTextContent());
imports.add(imported);
imports.addAll(getImportedConfigs(imported));
}
return imports;
}
/**
* Return all known ConfigPaths, as an aid to viewing or editing.
*
* @return all ConfigPaths known to the ApplicationContext, in a
* map by name, or an empty map if no ApplicationContext
*/
@SuppressWarnings("unchecked")
public synchronized Map<String, ConfigPath> getConfigPaths() {
if(ac==null) {
return MapUtils.EMPTY_MAP;
}
ConfigPathConfigurer cpc =
(ConfigPathConfigurer)ac.getBean("configPathConfigurer");
return cpc.getAllConfigPaths();
}
/**
* Compute a path relative to the job directory for all contained
* files, or null if the File is not inside the job directory.
*
* @param f File
* @return path relative to the job directory, or null if File not
* inside job dir
*/
public String jobDirRelativePath(File f) {
try {
String filePath = f.getCanonicalPath();
String jobPath = getJobDir().getCanonicalPath();
if(filePath.startsWith(jobPath)) {
String jobRelative = filePath.substring(jobPath.length()).replace(File.separatorChar, '/');
if(jobRelative.startsWith("/")) {
jobRelative = jobRelative.substring(1);
}
return jobRelative;
}
} catch (IOException e) {
getJobLogger().log(Level.WARNING,"bad file: "+f);
}
return null;
}
/**
* Log note of all ApplicationEvents.
*
* @see org.springframework.context.ApplicationListener#onApplicationEvent(org.springframework.context.ApplicationEvent)
*/
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof CrawlStateEvent) {
getJobLogger().log(Level.INFO, ((CrawlStateEvent)event).getState() +
(ac.getCurrentLaunchId() != null ? " " + ac.getCurrentLaunchId() : ""));
}
if (event instanceof StopCompleteEvent) {
synchronized (this) {
if (needTeardown) {
doTeardown();
}
}
}
if(event instanceof CheckpointSuccessEvent) {
getJobLogger().log(Level.INFO, "CHECKPOINTED "+((CheckpointSuccessEvent)event).getCheckpoint().getName());
}
}
/**
* Is it reasonable to offer a launch button
* @return true if launchable
*/
public boolean isLaunchable() {<FILL_FUNCTION_BODY>
|
if (!hasApplicationContext()) {
// ok to try launch if not yet built
return true;
}
if (!hasValidApplicationContext()) {
// never launch if specifically invalid
return false;
}
// launchable if cc not yet instantiated or not yet started
CrawlController cc = getCrawlController();
return cc == null || !cc.hasStarted();
| 1,167
| 114
| 1,281
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/framework/CrawlLimitEnforcer.java
|
CrawlLimitEnforcer
|
checkForLimitsExceeded
|
class CrawlLimitEnforcer implements ApplicationListener<ApplicationEvent> {
/**
* Maximum number of bytes to download. Once this number is exceeded
* the crawler will stop. A value of zero means no upper limit.
*/
protected long maxBytesDownload = 0L;
public long getMaxBytesDownload() {
return maxBytesDownload;
}
public void setMaxBytesDownload(long maxBytesDownload) {
this.maxBytesDownload = maxBytesDownload;
}
protected long maxNovelBytes = 0L;
public long getMaxNovelBytes() {
return maxNovelBytes;
}
/**
* Maximum number of uncompressed payload bytes to write to WARC response or
* resource records. Once this number is exceeded the crawler will stop. A
* value of zero means no upper limit.
*/
public void setMaxNovelBytes(long maxNovelBytes) {
this.maxNovelBytes = maxNovelBytes;
}
protected long maxNovelUrls = 0L;
public long getMaxNovelUrls() {
return maxNovelUrls;
}
/**
* Maximum number of novel (not deduplicated) urls to download. Once this
* number is exceeded the crawler will stop. A value of zero means no upper
* limit.
*/
public void setMaxNovelUrls(long maxNovelUrls) {
this.maxNovelUrls = maxNovelUrls;
}
protected long maxWarcNovelUrls = 0L;
public long getMaxWarcNovelUrls() {
return maxWarcNovelUrls;
}
/**
* Maximum number of urls to write to WARC response or resource records.
* Once this number is exceeded the crawler will stop. A value of zero means
* no upper limit.
*/
public void setMaxWarcNovelUrls(long maxWarcNovelUrls) {
this.maxWarcNovelUrls = maxWarcNovelUrls;
}
protected long maxWarcNovelBytes = 0L;
public long getMaxWarcNovelBytes() {
return maxWarcNovelBytes;
}
/**
* Maximum number of novel (not deduplicated) bytes to write to WARC
* response or resource records. Once this number is exceeded the crawler
* will stop. A value of zero means no upper limit.
*/
public void setMaxWarcNovelBytes(long maxWarcNovelBytes) {
this.maxWarcNovelBytes = maxWarcNovelBytes;
}
/**
* Maximum number of documents to download. Once this number is exceeded the
* crawler will stop. A value of zero means no upper limit.
*/
protected long maxDocumentsDownload = 0L;
public long getMaxDocumentsDownload() {
return maxDocumentsDownload;
}
public void setMaxDocumentsDownload(long maxDocumentsDownload) {
this.maxDocumentsDownload = maxDocumentsDownload;
}
/**
* Maximum amount of time to crawl (in seconds). Once this much time has
* elapsed the crawler will stop. A value of zero means no upper limit.
*/
protected long maxTimeSeconds = 0L;
public long getMaxTimeSeconds() {
return maxTimeSeconds;
}
public void setMaxTimeSeconds(long maxTimeSeconds) {
this.maxTimeSeconds = maxTimeSeconds;
}
protected CrawlController controller;
public CrawlController getCrawlController() {
return this.controller;
}
@Autowired
public void setCrawlController(CrawlController controller) {
this.controller = controller;
}
@Override
public void onApplicationEvent(ApplicationEvent event) {
if(event instanceof StatSnapshotEvent) {
CrawlStatSnapshot snapshot = ((StatSnapshotEvent)event).getSnapshot();
checkForLimitsExceeded(snapshot);
}
}
protected void checkForLimitsExceeded(CrawlStatSnapshot snapshot) {<FILL_FUNCTION_BODY>}
}
|
if (maxBytesDownload > 0 && snapshot.bytesProcessed >= maxBytesDownload) {
controller.requestCrawlStop(CrawlStatus.FINISHED_DATA_LIMIT);
} else if (maxNovelBytes > 0 && snapshot.novelBytes >= maxNovelBytes) {
controller.requestCrawlStop(CrawlStatus.FINISHED_DATA_LIMIT);
} else if (maxWarcNovelBytes > 0 && snapshot.warcNovelBytes >= maxWarcNovelBytes) {
controller.requestCrawlStop(CrawlStatus.FINISHED_DATA_LIMIT);
} else if (maxDocumentsDownload > 0
&& snapshot.downloadedUriCount >= maxDocumentsDownload) {
controller.requestCrawlStop(CrawlStatus.FINISHED_DOCUMENT_LIMIT);
} else if (maxNovelUrls > 0
&& snapshot.novelUriCount >= maxNovelUrls) {
controller.requestCrawlStop(CrawlStatus.FINISHED_DOCUMENT_LIMIT);
} else if (maxWarcNovelUrls > 0
&& snapshot.warcNovelUriCount >= maxWarcNovelUrls) {
controller.requestCrawlStop(CrawlStatus.FINISHED_DOCUMENT_LIMIT);
} else if (maxTimeSeconds > 0
&& snapshot.elapsedMilliseconds >= maxTimeSeconds * 1000) {
controller.requestCrawlStop(CrawlStatus.FINISHED_TIME_LIMIT);
}
| 1,161
| 415
| 1,576
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/framework/Scoper.java
|
Scoper
|
start
|
class Scoper extends Processor implements Lifecycle {
protected DecideRule scope;
public DecideRule getScope() {
return this.scope;
}
@Autowired
public void setScope(DecideRule scope) {
this.scope = scope;
}
protected 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] [decision] [uri]" where decision is 'ACCEPT' or 'REJECT'.
*/
public void setLogToFile(boolean enabled) {
kp.put("logToFile",enabled);
}
protected CrawlerLoggerModule loggerModule;
public CrawlerLoggerModule getLoggerModule() {
return this.loggerModule;
}
@Autowired
public void setLoggerModule(CrawlerLoggerModule loggerModule) {
this.loggerModule = loggerModule;
}
/**
* Constructor.
*/
public Scoper() {
super();
}
protected boolean isRunning = false;
public void start() {<FILL_FUNCTION_BODY>}
public boolean isRunning() {
return this.isRunning;
}
public void stop() {
isRunning = false;
}
/**
* Schedule the given {@link CrawlURI CrawlURI} with the Frontier.
* @param caUri The CrawlURI to be scheduled.
* @return true if CrawlURI was accepted by crawl scope, false
* otherwise.
*/
protected boolean isInScope(CrawlURI caUri) {
boolean result = false;
DecideResult dr = scope.decisionFor(caUri);
if (dr == DecideResult.ACCEPT) {
result = true;
if (fileLogger != null) {
fileLogger.info("ACCEPT " + caUri);
}
} else {
outOfScope(caUri);
}
return result;
}
/**
* Called when a CrawlURI is ruled out of scope.
* Override if you don't want logs as coming from this class.
* @param caUri CrawlURI that is out of scope.
*/
protected void outOfScope(CrawlURI caUri) {
if (fileLogger != null) {
fileLogger.info("REJECT " + caUri);
}
}
}
|
if(isRunning) {
return;
}
if (getLogToFile() && fileLogger == null) {
fileLogger = loggerModule.setupSimpleLog(getBeanName());
}
isRunning = true;
| 672
| 62
| 734
|
<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/frontier/AntiCalendarCostAssignmentPolicy.java
|
AntiCalendarCostAssignmentPolicy
|
costOf
|
class AntiCalendarCostAssignmentPolicy extends UnitCostAssignmentPolicy {
private static final long serialVersionUID = 3L;
public static String CALENDARISH =
"(?i)(calendar)|(year)|(month)|(day)|(date)|(viewcal)" +
"|(\\D19\\d\\d\\D)|(\\D20\\d\\d\\D)|(event)|(yr=)" +
"|(calendrier)|(jour)";
/* (non-Javadoc)
* @see org.archive.crawler.frontier.CostAssignmentPolicy#costOf(org.archive.crawler.datamodel.CrawlURI)
*/
public int costOf(CrawlURI curi) {<FILL_FUNCTION_BODY>}
}
|
int cost = super.costOf(curi);
Matcher m = TextUtils.getMatcher(CALENDARISH, curi.toString());
if (m.find()) {
cost++;
// TODO: consider if multiple occurrences should cost more
}
TextUtils.recycleMatcher(m);
return cost;
| 211
| 88
| 299
|
<methods>public non-sealed void <init>() ,public int costOf(org.archive.modules.CrawlURI) <variables>private static final long serialVersionUID
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/frontier/AssignmentLevelSurtQueueAssignmentPolicy.java
|
AssignmentLevelSurtQueueAssignmentPolicy
|
getClassKey
|
class AssignmentLevelSurtQueueAssignmentPolicy extends
SurtAuthorityQueueAssignmentPolicy {
private static final long serialVersionUID = -1533545293624791702L;
@Override
public String getClassKey(CrawlURI curi) {<FILL_FUNCTION_BODY>}
}
|
if(getDeferToPrevious() && !StringUtils.isEmpty(curi.getClassKey())) {
return curi.getClassKey();
}
UURI basis = curi.getPolicyBasisUURI();
String candidate = super.getClassKey(curi);
candidate = PublicSuffixes.reduceSurtToAssignmentLevel(candidate);
if(!StringUtils.isEmpty(getForceQueueAssignment())) {
candidate = getForceQueueAssignment();
}
// all whois urls in the same queue
if (curi.getUURI().getScheme().equals("whois")) {
return "whois...";
}
if(StringUtils.isEmpty(candidate)) {
return DEFAULT_CLASS_KEY;
}
if(getParallelQueues()>1) {
int subqueue = getSubqueue(basis,getParallelQueues());
if (subqueue>0) {
candidate += "+"+subqueue;
}
}
return candidate;
| 91
| 252
| 343
|
<methods>public non-sealed void <init>() <variables>private static final long serialVersionUID
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/frontier/BdbWorkQueue.java
|
BdbWorkQueue
|
insertItem
|
class BdbWorkQueue extends WorkQueue
implements Serializable {
private static final long serialVersionUID = 1L;
private static Logger LOGGER =
Logger.getLogger(BdbWorkQueue.class.getName());
/**
* All items in this queue have this same 'origin'
* prefix to their keys.
*/
private byte[] origin;
/**
* Create a virtual queue inside the given BdbMultipleWorkQueues
*
* @param classKey
*/
public BdbWorkQueue(String classKey, BdbFrontier frontier) {
super(classKey);
this.origin = BdbMultipleWorkQueues.calculateOriginKey(classKey);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine(getPrefixClassKey(this.origin) + " " + classKey);
}
// add the queue-front 'cap' entry; see...
// http://sourceforge.net/tracker/index.php?func=detail&aid=1262665&group_id=73833&atid=539102
frontier.getWorkQueues().addCap(origin);
}
protected long deleteMatchingFromQueue(final WorkQueueFrontier frontier,
final String match) throws IOException {
try {
final BdbMultipleWorkQueues queues = ((BdbFrontier) frontier)
.getWorkQueues();
return queues.deleteMatchingFromQueue(match, classKey,
new DatabaseEntry(origin));
} catch (DatabaseException e) {
throw new IOException(e);
}
}
protected void deleteItem(final WorkQueueFrontier frontier,
final CrawlURI peekItem) throws IOException {
try {
final BdbMultipleWorkQueues queues = ((BdbFrontier) frontier)
.getWorkQueues();
queues.delete(peekItem);
} catch (DatabaseException e) {
throw new IOException(e);
}
}
protected CrawlURI peekItem(final WorkQueueFrontier frontier)
throws IOException {
final BdbMultipleWorkQueues queues = ((BdbFrontier) frontier)
.getWorkQueues();
DatabaseEntry key = new DatabaseEntry(origin);
CrawlURI curi = null;
int tries = 1;
while(true) {
try {
curi = queues.get(key);
} catch (DatabaseException e) {
LOGGER.log(Level.SEVERE,"peekItem failure; retrying",e);
}
// ensure CrawlURI, if any, came from acceptable range:
if(!ArchiveUtils.startsWith(key.getData(),origin)) {
LOGGER.severe(
"inconsistency: "+classKey+"("+
getPrefixClassKey(origin)+") with " + getCount() + " items gave "
+ curi +"("+getPrefixClassKey(key.getData()));
// clear curi to allow retry
curi = null;
// reset key to original origin for retry
key.setData(origin);
}
if (curi!=null) {
// success
break;
}
if (tries>3) {
LOGGER.severe("no item where expected in queue "+classKey);
break;
}
tries++;
LOGGER.severe("Trying get #" + Integer.toString(tries)
+ " in queue " + classKey + " with " + getCount()
+ " items using key "
+ getPrefixClassKey(key.getData()));
}
return curi;
}
protected void insertItem(final WorkQueueFrontier frontier,
final CrawlURI curi, boolean overwriteIfPresent) throws IOException {<FILL_FUNCTION_BODY>}
/**
* @param byteArray Byte array to get hex string of.
* @return Hex string of passed in byte array (Used logging
* key-prefixes).
*/
protected static String getPrefixClassKey(final byte [] byteArray) {
int zeroIndex = 0;
while(byteArray[zeroIndex]!=0) {
zeroIndex++;
}
try {
return new String(byteArray,0,zeroIndex,"UTF-8");
} catch (UnsupportedEncodingException e) {
// should be impossible; UTF-8 always available
e.printStackTrace();
return e.getMessage();
}
}
// Kryo support
public static void autoregisterTo(AutoKryo kryo) {
kryo.register(BdbWorkQueue.class);
kryo.autoregister(FetchStats.class);
kryo.autoregister(HashSet.class);
kryo.autoregister(SimplePrecedenceProvider.class);
kryo.autoregister(byte[].class);
kryo.setRegistrationOptional(true);
}
}
|
try {
final BdbMultipleWorkQueues queues = ((BdbFrontier) frontier)
.getWorkQueues();
queues.put(curi, overwriteIfPresent);
if (LOGGER.isLoggable(Level.FINE)) {
LOGGER.fine("Inserted into " + getPrefixClassKey(this.origin) +
" (count " + Long.toString(getCount())+ "): " +
curi.toString());
}
} catch (DatabaseException e) {
throw new IOException(e);
}
| 1,293
| 144
| 1,437
|
<methods>public void <init>(java.lang.String) ,public final int compareTo(java.util.concurrent.Delayed) ,public synchronized void considerActive() ,public synchronized long deleteMatching(org.archive.crawler.frontier.WorkQueueFrontier, java.lang.String) ,public void expend(int) ,public java.lang.String getClassKey() ,public synchronized long getCount() ,public long getDelay(java.util.concurrent.TimeUnit) ,public java.lang.String getKey() ,public int getPrecedence() ,public org.archive.crawler.frontier.precedence.PrecedenceProvider getPrecedenceProvider() ,public int getSessionBudget() ,public org.archive.modules.fetcher.FetchStats getSubstats() ,public long getTotalExpenditure() ,public long getWakeTime() ,public boolean isManaged() ,public boolean isOverSessionBudget() ,public boolean isOverTotalBudget() ,public boolean isRetired() ,public void makeDirty() ,public synchronized void noteDeactivated() ,public void noteError(int) ,public synchronized void noteExhausted() ,public synchronized org.archive.modules.CrawlURI peek(org.archive.crawler.frontier.WorkQueueFrontier) ,public synchronized void reportTo(java.io.PrintWriter) ,public void setIdentityCache(ObjectIdentityCache<?>) ,public void setPrecedenceProvider(org.archive.crawler.frontier.precedence.PrecedenceProvider) ,public void setWakeTime(long) ,public java.lang.String shortReportLegend() ,public java.lang.String shortReportLine() ,public synchronized void shortReportLineTo(java.io.PrintWriter) ,public synchronized Map<java.lang.String,java.lang.Object> shortReportMap() ,public void tally(org.archive.modules.CrawlURI, org.archive.modules.fetcher.FetchStats.Stage) ,public java.lang.String toString() ,public synchronized void unpeek(org.archive.modules.CrawlURI) <variables>protected boolean active,private transient ObjectIdentityCache<?> cache,protected final non-sealed java.lang.String classKey,protected long costCount,protected long count,protected long enqueueCount,protected long errorCount,protected long expenditureAtLastActivation,protected boolean isManaged,protected int lastCost,protected long lastDequeueTime,protected java.lang.String lastPeeked,protected java.lang.String lastQueued,private static final java.util.logging.Logger logger,protected transient org.archive.modules.CrawlURI peekItem,protected org.archive.crawler.frontier.precedence.PrecedenceProvider precedenceProvider,protected boolean retired,private static final long serialVersionUID,protected int sessionBudget,protected org.archive.modules.fetcher.FetchStats substats,protected long totalBudget,protected long totalExpenditure,protected long wakeTime
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/frontier/BucketQueueAssignmentPolicy.java
|
BucketQueueAssignmentPolicy
|
getClassKey
|
class BucketQueueAssignmentPolicy extends QueueAssignmentPolicy {
private static final long serialVersionUID = 3L;
private static final int DEFAULT_NOIP_BITMASK = 1023;
private static final int DEFAULT_QUEUES_HOSTS_MODULO = 1021;
protected ServerCache serverCache;
public ServerCache getServerCache() {
return this.serverCache;
}
@Autowired
public void setServerCache(ServerCache serverCache) {
this.serverCache = serverCache;
}
public String getClassKey(final CrawlURI curi) {<FILL_FUNCTION_BODY>}
public int maximumNumberOfKeys() {
return DEFAULT_NOIP_BITMASK + DEFAULT_QUEUES_HOSTS_MODULO + 2;
}
}
|
CrawlHost host;
host = serverCache.getHostFor(curi.getUURI());
if(host == null) {
return "NO-HOST";
} else if(host.getIP() == null) {
return "NO-IP-".concat(Long.toString(Math.abs((long) host
.getHostName().hashCode()) & DEFAULT_NOIP_BITMASK));
} else {
return Long.toString(Math.abs((long) host.getIP().hashCode())
% DEFAULT_QUEUES_HOSTS_MODULO);
}
| 211
| 151
| 362
|
<methods>public non-sealed void <init>() ,public abstract java.lang.String getClassKey(org.archive.modules.CrawlURI) ,public java.lang.String getForceQueueAssignment() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public int maximumNumberOfKeys() ,public void setForceQueueAssignment(java.lang.String) <variables>protected org.archive.spring.KeyedProperties kp,private static final long serialVersionUID
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/frontier/DelayedWorkQueue.java
|
DelayedWorkQueue
|
compareTo
|
class DelayedWorkQueue implements Delayed, Serializable {
private static final long serialVersionUID = 1L;
public String classKey;
public long wakeTime;
/**
* Reference to the WorkQueue, perhaps saving a deserialization
* from allQueues.
*/
protected transient WorkQueue workQueue;
public DelayedWorkQueue(WorkQueue queue) {
this.classKey = queue.getClassKey();
this.wakeTime = queue.getWakeTime();
this.workQueue = queue;
}
// TODO: consider if this should be method on WorkQueueFrontier
public WorkQueue getWorkQueue(WorkQueueFrontier wqf) {
if (workQueue == null) {
// This is a recently deserialized DelayedWorkQueue instance
WorkQueue result = wqf.getQueueFor(classKey);
this.workQueue = result;
}
return workQueue;
}
public long getDelay(TimeUnit unit) {
return unit.convert(
wakeTime - System.currentTimeMillis(),
TimeUnit.MILLISECONDS);
}
public String getClassKey() {
return classKey;
}
public long getWakeTime() {
return wakeTime;
}
public void setWakeTime(long time) {
this.wakeTime = time;
}
public int compareTo(Delayed obj) {<FILL_FUNCTION_BODY>}
}
|
if (this == obj) {
return 0; // for exact identity only
}
DelayedWorkQueue other = (DelayedWorkQueue) obj;
if (wakeTime > other.getWakeTime()) {
return 1;
}
if (wakeTime < other.getWakeTime()) {
return -1;
}
// at this point, the ordering is arbitrary, but still
// must be consistent/stable over time
return this.classKey.compareTo(other.getClassKey());
| 386
| 135
| 521
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/frontier/HostnameQueueAssignmentPolicy.java
|
HostnameQueueAssignmentPolicy
|
getCoreKey
|
class HostnameQueueAssignmentPolicy
extends URIAuthorityBasedQueueAssignmentPolicy {
private static final long serialVersionUID = 3L;
@Override
protected String getCoreKey(UURI basis) {<FILL_FUNCTION_BODY>}
}
|
String scheme = basis.getScheme();
String candidate = null;
try {
candidate = basis.getAuthorityMinusUserinfo();
} catch (URIException ue) {}// let next line handle
if(StringUtils.isEmpty(candidate)) {
return null;
}
if (UURIFactory.HTTPS.equals(scheme)) {
// If https and no port specified, add default https port to
// distinguish https from http server without a port.
if (!candidate.matches(".+:[0-9]+")) {
candidate += UURIFactory.HTTPS_PORT;
}
}
// Ensure classKeys are safe as filenames on NTFS
return candidate.replace(':','#');
| 68
| 191
| 259
|
<methods>public non-sealed void <init>() ,public java.lang.String getClassKey(org.archive.modules.CrawlURI) ,public boolean getDeferToPrevious() ,public int getParallelQueues() ,public boolean getParallelQueuesRandomAssignment() ,public void setDeferToPrevious(boolean) ,public void setParallelQueues(int) ,public void setParallelQueuesRandomAssignment(boolean) <variables>protected static java.lang.String DEFAULT_CLASS_KEY,protected org.archive.util.LongToIntConsistentHash conhash,private static final long serialVersionUID
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/frontier/IPQueueAssignmentPolicy.java
|
IPQueueAssignmentPolicy
|
getClassKey
|
class IPQueueAssignmentPolicy
extends HostnameQueueAssignmentPolicy {
private static final long serialVersionUID = 3L;
protected ServerCache serverCache;
public ServerCache getServerCache() {
return this.serverCache;
}
@Autowired
public void setServerCache(ServerCache serverCache) {
this.serverCache = serverCache;
}
public String getClassKey(CrawlURI cauri) {<FILL_FUNCTION_BODY>}
}
|
CrawlHost host = serverCache.getHostFor(cauri.getUURI());
if (host == null || host.getIP() == null) {
// if no server or no IP, use superclass implementation
return super.getClassKey(cauri);
}
// use dotted-decimal IP address
return host.getIP().getHostAddress();
| 125
| 93
| 218
|
<methods>public non-sealed void <init>() <variables>private static final long serialVersionUID
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/frontier/RecyclingSerialBinding.java
|
RecyclingSerialBinding
|
objectToEntry
|
class RecyclingSerialBinding<K> extends SerialBinding<K> {
/**
* Thread-local cache of reusable FastOutputStream
*/
protected ThreadLocal<FastOutputStream> fastOutputStreamHolder
= new ThreadLocal<FastOutputStream>();
private ClassCatalog classCatalog;
private Class<K> baseClass;
/**
* Constructor. Save parameters locally, as superclass
* fields are private.
*
* @param classCatalog is the catalog to hold shared class information
*
* @param baseClass is the base class for serialized objects stored using
* this binding
*/
@SuppressWarnings("unchecked")
public RecyclingSerialBinding(ClassCatalog classCatalog, Class baseClass) {
super(classCatalog, baseClass);
this.classCatalog = classCatalog;
this.baseClass = baseClass;
}
/**
* Copies superclass simply to allow different source for FastOoutputStream.
*
* @see com.sleepycat.bind.serial.SerialBinding#entryToObject
*/
public void objectToEntry(Object object, DatabaseEntry entry) {<FILL_FUNCTION_BODY>}
/**
* Get the cached (and likely pre-grown to efficient size) FastOutputStream,
* creating it if necessary.
*
* @return FastOutputStream
*/
private FastOutputStream getFastOutputStream() {
FastOutputStream fo = (FastOutputStream) fastOutputStreamHolder.get();
if (fo == null) {
fo = new FastOutputStream();
fastOutputStreamHolder.set(fo);
}
fo.reset();
return fo;
}
}
|
if (baseClass != null && !baseClass.isInstance(object)) {
throw new IllegalArgumentException(
"Data object class (" + object.getClass() +
") not an instance of binding's base class (" +
baseClass + ')');
}
FastOutputStream fo = getFastOutputStream();
try {
SerialOutput jos = new SerialOutput(fo, classCatalog);
jos.writeObject(object);
} catch (IOException e) {
throw new RuntimeExceptionWrapper(e);
}
byte[] hdr = SerialOutput.getStreamHeader();
entry.setData(fo.getBufferBytes(), hdr.length,
fo.getBufferLength() - hdr.length);
| 421
| 180
| 601
|
<no_super_class>
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/frontier/SurtAuthorityQueueAssignmentPolicy.java
|
SurtAuthorityQueueAssignmentPolicy
|
getSurtAuthority
|
class SurtAuthorityQueueAssignmentPolicy
extends URIAuthorityBasedQueueAssignmentPolicy {
private static final long serialVersionUID = 3L;
@Override
protected String getCoreKey(UURI basis) {
String candidate = getSurtAuthority(basis.getSurtForm());
return candidate.replace(':','#');
}
protected String getSurtAuthority(String surt) {<FILL_FUNCTION_BODY>}
}
|
int indexOfOpen = surt.indexOf("://(");
int indexOfClose = surt.indexOf(")");
if (indexOfOpen == -1 || indexOfClose == -1
|| ((indexOfOpen + 4) >= indexOfClose)) {
return DEFAULT_CLASS_KEY;
}
return surt.substring(indexOfOpen + 4, indexOfClose);
| 118
| 93
| 211
|
<methods>public non-sealed void <init>() ,public java.lang.String getClassKey(org.archive.modules.CrawlURI) ,public boolean getDeferToPrevious() ,public int getParallelQueues() ,public boolean getParallelQueuesRandomAssignment() ,public void setDeferToPrevious(boolean) ,public void setParallelQueues(int) ,public void setParallelQueuesRandomAssignment(boolean) <variables>protected static java.lang.String DEFAULT_CLASS_KEY,protected org.archive.util.LongToIntConsistentHash conhash,private static final long serialVersionUID
|
internetarchive_heritrix3
|
heritrix3/engine/src/main/java/org/archive/crawler/frontier/URIAuthorityBasedQueueAssignmentPolicy.java
|
URIAuthorityBasedQueueAssignmentPolicy
|
getSubqueue
|
class URIAuthorityBasedQueueAssignmentPolicy
extends
QueueAssignmentPolicy
implements
HasKeyedProperties {
private static final long serialVersionUID = 3L;
//for when neat class-key fails us
protected static String DEFAULT_CLASS_KEY = "default...";
protected LongToIntConsistentHash conhash = new LongToIntConsistentHash();
/**
* Whether to always defer to a previously-assigned key inside
* the CrawlURI. If true, any key already in the CrawlURI will
* be returned as the classKey.
*/
public boolean getDeferToPrevious() {
return (Boolean) kp.get("deferToPrevious");
}
{
setDeferToPrevious(true);
}
public void setDeferToPrevious(boolean defer) {
kp.put("deferToPrevious",defer);
}
/**
* The number of parallel queues to split a core key into. By
* default is 1. If larger than 1, the non-authority-based portion
* of the URI will be used to distribute over that many separate
* queues.
*
*/
public int getParallelQueues() {
return (Integer) kp.get("parallelQueues");
}
{
setParallelQueues(1);
}
public void setParallelQueues(int count) {
kp.put("parallelQueues",count);
}
/**
* Whether to assign URIs to parallel queues in round-robin fashon.
* False by default. If true, URIs will be assigned to a queue randomly.
*/
public boolean getParallelQueuesRandomAssignment() {
return (Boolean) kp.get("parallelQueuesRandomAssignment");
}
{
setParallelQueuesRandomAssignment(false);
}
public void setParallelQueuesRandomAssignment(boolean doRandom) {
kp.put("parallelQueuesRandomAssignment",doRandom);
}
public String getClassKey(CrawlURI curi) {
if(getDeferToPrevious() && !StringUtils.isEmpty(curi.getClassKey())) {
return curi.getClassKey();
}
UURI basis = curi.getPolicyBasisUURI();
String candidate = getCoreKey(basis);
if(!StringUtils.isEmpty(getForceQueueAssignment())) {
candidate = getForceQueueAssignment();
}
// all whois urls in the same queue
if (curi.getUURI().getScheme().equals("whois")) {
return "whois...";
}
if(StringUtils.isEmpty(candidate)) {
return DEFAULT_CLASS_KEY;
}
if(getParallelQueues()>1) {
int subqueue = getSubqueue(basis,getParallelQueues());
if (subqueue>0) {
candidate += "+"+subqueue;
}
}
return candidate;
}
protected int getSubqueue(UURI basisUuri, int parallelQueues) {<FILL_FUNCTION_BODY>}
/**
* Base subqueue on first path-segment, if any. (Means unbalanced
* subqueues, but consistency for most-common case where fanout
* can be at first segment, and it's beneficial to keep similar
* URIs in same queue.)
* @param uuri
* @return
*/
protected String bucketBasis(UURI uuri) {
if(getParallelQueuesRandomAssignment()){
return uuri.getEscapedURI();
}
String path = new String(uuri.getRawPath());
int i = path.indexOf('/',1);
if(i<0) {
return null;
}
return path.substring(1,i);
}
protected abstract String getCoreKey(UURI basis);
}
|
String basis = bucketBasis(basisUuri);
if(StringUtils.isEmpty(basis)) {
return 0;
}
return conhash.bucketFor(basis, parallelQueues);
| 1,128
| 63
| 1,191
|
<methods>public non-sealed void <init>() ,public abstract java.lang.String getClassKey(org.archive.modules.CrawlURI) ,public java.lang.String getForceQueueAssignment() ,public org.archive.spring.KeyedProperties getKeyedProperties() ,public int maximumNumberOfKeys() ,public void setForceQueueAssignment(java.lang.String) <variables>protected org.archive.spring.KeyedProperties kp,private static final long serialVersionUID
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.